text
stringlengths
54
60.6k
<commit_before>// // Copyright © 2022 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include <GraphUtils.hpp> #include <TestUtils.hpp> #include <armnn/INetwork.hpp> #include <doctest/doctest.h> using namespace armnn; namespace { #if defined(ARMNNREF_ENABLED)||defined(ARMCOMPUTECL_ENABLED) void FoldPadIntoQuantizedAvgPoolTest(Compute backendId) { // Create a network INetworkPtr network = INetwork::Create(); const unsigned int inputShape[] = {1, 2, 2, 3}; const unsigned int paddedShape[] = {1, 4, 4, 3}; const unsigned int outputShape[] = {1, 2, 2, 3}; TensorInfo inputInfo(4, inputShape, DataType::QAsymmU8, 1.0f, 0.0f); TensorInfo paddedInfo(4, paddedShape, DataType::QAsymmU8, 1.0f, 0.0f); TensorInfo outputInfo(4, outputShape, DataType::QAsymmU8, 1.0f, 0.0f); IConnectableLayer* input = network->AddInputLayer(0, "input"); input->GetOutputSlot(0).SetTensorInfo(inputInfo); PadDescriptor padDescriptor({{0, 0}, {1, 1}, {1, 1}, {0, 0}}); IConnectableLayer* padLayer = network->AddPadLayer(padDescriptor, "pad"); padLayer->GetOutputSlot(0).SetTensorInfo(paddedInfo); Pooling2dDescriptor pooling2dDescriptor; pooling2dDescriptor.m_PoolType = PoolingAlgorithm::Average; pooling2dDescriptor.m_PoolWidth = 3; pooling2dDescriptor.m_PoolHeight = 3; pooling2dDescriptor.m_StrideX = 1; pooling2dDescriptor.m_StrideY = 1; pooling2dDescriptor.m_DataLayout = DataLayout::NHWC; IConnectableLayer* pool2dLayer = network->AddPooling2dLayer(pooling2dDescriptor, "pool2d"); pool2dLayer->GetOutputSlot(0).SetTensorInfo(outputInfo); IConnectableLayer* output = network->AddOutputLayer(0, "output"); // Connect up layers - input -> pad -> pool2d -> output input->GetOutputSlot(0).Connect(padLayer->GetInputSlot(0)); padLayer->GetOutputSlot(0).Connect(pool2dLayer->GetInputSlot(0)); pool2dLayer->GetOutputSlot(0).Connect(output->GetInputSlot(0)); // Create ArmNN runtime IRuntimePtr run = IRuntime::Create(IRuntime::CreationOptions()); // Optimise ArmNN network IOptimizedNetworkPtr optNet = Optimize(*network, {backendId}, run->GetDeviceSpec()); auto checkPadFoldedIntoPool2d = [&](const Layer* const layer) { if (!IsLayerOfType<Pooling2dLayer>(layer) || (layer->GetNameStr() != "folded-pad-into-pool2d")) { return false; } const auto pool2dLayer = static_cast<const Pooling2dLayer*>(layer); const Pooling2dDescriptor pool2dLayerParams = pool2dLayer->GetParameters(); Pooling2dDescriptor pool2dLayerParamsNoPad = pool2dLayerParams; pool2dLayerParamsNoPad.m_PadLeft = 0; pool2dLayerParamsNoPad.m_PadRight = 0; pool2dLayerParamsNoPad.m_PadTop = 0; pool2dLayerParamsNoPad.m_PadBottom = 0; // If we fold then PaddingMethod will be set to Ignore. The original will be Exclude. pool2dLayerParamsNoPad.m_PaddingMethod = PaddingMethod::Exclude; return (pool2dLayerParamsNoPad == pooling2dDescriptor) && (pool2dLayerParams.m_PadLeft == 1) && (pool2dLayerParams.m_PadRight == 1) && (pool2dLayerParams.m_PadTop == 1) && (pool2dLayerParams.m_PadBottom == 1) && (pool2dLayerParams.m_PaddingMethod == PaddingMethod::IgnoreValue); }; Graph& graph = GetGraphForTesting(optNet.get()); CHECK(CheckSequence(graph.cbegin(), graph.cend(), &IsLayerOfType<InputLayer>, checkPadFoldedIntoPool2d, &IsLayerOfType<OutputLayer>)); } #endif } TEST_SUITE("Optimizer_FoldPadIntoQuantizedAvgPoolCpuRef") { TEST_CASE("FoldPadIntoQuantizedAvgPoolCpuRefTest") { FoldPadIntoQuantizedAvgPoolTest(Compute::CpuRef); } } #if defined(ARMCOMPUTECL_ENABLED) TEST_SUITE("Optimizer_FoldPadIntoQuantizedAvgPoolGpuAcc") { TEST_CASE("FoldPadIntoQuantizedAvgPoolGpuAccTest") { FoldPadIntoQuantizedAvgPoolTest(Compute::GpuAcc); } } #endif <commit_msg>IVGCVSW-7149 FoldPadIntoQuantizedAvgPoolCpuRefTest test failing while running Arm NN Unittest<commit_after>// // Copyright © 2022 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include <GraphUtils.hpp> #include <TestUtils.hpp> #include <armnn/INetwork.hpp> #include <doctest/doctest.h> using namespace armnn; namespace { #if defined(ARMNNREF_ENABLED)||defined(ARMCOMPUTECL_ENABLED) void FoldPadIntoQuantizedAvgPoolTest(Compute backendId) { // Create a network INetworkPtr network = INetwork::Create(); const unsigned int inputShape[] = {1, 2, 2, 3}; const unsigned int paddedShape[] = {1, 4, 4, 3}; const unsigned int outputShape[] = {1, 2, 2, 3}; TensorInfo inputInfo(4, inputShape, DataType::QAsymmU8, 1.0f, 0.0f); TensorInfo paddedInfo(4, paddedShape, DataType::QAsymmU8, 1.0f, 0.0f); TensorInfo outputInfo(4, outputShape, DataType::QAsymmU8, 1.0f, 0.0f); IConnectableLayer* input = network->AddInputLayer(0, "input"); input->GetOutputSlot(0).SetTensorInfo(inputInfo); PadDescriptor padDescriptor({{0, 0}, {1, 1}, {1, 1}, {0, 0}}); IConnectableLayer* padLayer = network->AddPadLayer(padDescriptor, "pad"); padLayer->GetOutputSlot(0).SetTensorInfo(paddedInfo); Pooling2dDescriptor pooling2dDescriptor; pooling2dDescriptor.m_PoolType = PoolingAlgorithm::Average; pooling2dDescriptor.m_PoolWidth = 3; pooling2dDescriptor.m_PoolHeight = 3; pooling2dDescriptor.m_StrideX = 1; pooling2dDescriptor.m_StrideY = 1; pooling2dDescriptor.m_DataLayout = DataLayout::NHWC; IConnectableLayer* pool2dLayer = network->AddPooling2dLayer(pooling2dDescriptor, "pool2d"); pool2dLayer->GetOutputSlot(0).SetTensorInfo(outputInfo); IConnectableLayer* output = network->AddOutputLayer(0, "output"); // Connect up layers - input -> pad -> pool2d -> output input->GetOutputSlot(0).Connect(padLayer->GetInputSlot(0)); padLayer->GetOutputSlot(0).Connect(pool2dLayer->GetInputSlot(0)); pool2dLayer->GetOutputSlot(0).Connect(output->GetInputSlot(0)); // Create ArmNN runtime IRuntimePtr run = IRuntime::Create(IRuntime::CreationOptions()); // Optimise ArmNN network IOptimizedNetworkPtr optNet = Optimize(*network, {backendId}, run->GetDeviceSpec()); auto checkPadFoldedIntoPool2d = [&](const Layer* const layer) { if (!IsLayerOfType<Pooling2dLayer>(layer) || (layer->GetNameStr() != "folded-pad-into-pool2d")) { return false; } const auto pool2dLayer = static_cast<const Pooling2dLayer*>(layer); const Pooling2dDescriptor pool2dLayerParams = pool2dLayer->GetParameters(); Pooling2dDescriptor pool2dLayerParamsNoPad = pool2dLayerParams; pool2dLayerParamsNoPad.m_PadLeft = 0; pool2dLayerParamsNoPad.m_PadRight = 0; pool2dLayerParamsNoPad.m_PadTop = 0; pool2dLayerParamsNoPad.m_PadBottom = 0; // If we fold then PaddingMethod will be set to Ignore. The original will be Exclude. pool2dLayerParamsNoPad.m_PaddingMethod = PaddingMethod::Exclude; return (pool2dLayerParamsNoPad == pooling2dDescriptor) && (pool2dLayerParams.m_PadLeft == 1) && (pool2dLayerParams.m_PadRight == 1) && (pool2dLayerParams.m_PadTop == 1) && (pool2dLayerParams.m_PadBottom == 1) && (pool2dLayerParams.m_PaddingMethod == PaddingMethod::IgnoreValue); }; Graph& graph = GetGraphForTesting(optNet.get()); CHECK(CheckSequence(graph.cbegin(), graph.cend(), &IsLayerOfType<InputLayer>, checkPadFoldedIntoPool2d, &IsLayerOfType<OutputLayer>)); } #endif } #if defined(ARMNNREF_ENABLED) TEST_SUITE("Optimizer_FoldPadIntoQuantizedAvgPoolCpuRef") { TEST_CASE("FoldPadIntoQuantizedAvgPoolCpuRefTest") { FoldPadIntoQuantizedAvgPoolTest(Compute::CpuRef); } } #endif #if defined(ARMCOMPUTECL_ENABLED) TEST_SUITE("Optimizer_FoldPadIntoQuantizedAvgPoolGpuAcc") { TEST_CASE("FoldPadIntoQuantizedAvgPoolGpuAccTest") { FoldPadIntoQuantizedAvgPoolTest(Compute::GpuAcc); } } #endif <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Base class for a torsion-bar suspension system using linear dampers (template // definition). // // ============================================================================= #include "chrono/assets/ChCylinderShape.h" #include "chrono/assets/ChColorAsset.h" #include "chrono_vehicle/tracked_vehicle/suspension/ChLinearDamperRWAssembly.h" namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- ChLinearDamperRWAssembly::ChLinearDamperRWAssembly(const std::string& name, bool has_shock) : ChRoadWheelAssembly(name), m_has_shock(has_shock) { } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChLinearDamperRWAssembly::Initialize(ChSharedPtr<ChBodyAuxRef> chassis, const ChVector<>& location) { // Express the suspension reference frame in the absolute coordinate system. ChFrame<> susp_to_abs(location); susp_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs()); // Transform all points and directions to absolute frame. std::vector<ChVector<> > points(NUM_POINTS); for (int i = 0; i < NUM_POINTS; i++) { ChVector<> rel_pos = GetLocation(static_cast<PointId>(i)); points[i] = susp_to_abs.TransformPointLocalToParent(rel_pos); } // Sanity check. assert(points[ARM_WHEEL].x == 0 && points[ARM_WHEEL].z == 0); // Create the trailing arm body. The reference frame of the arm body has its // x-axis aligned with the line between the arm-chassis connection point and // the arm-wheel connection point. ChVector<> u = susp_to_abs.GetPos() - points[ARM_CHASSIS]; u.Normalize(); ChVector<> w = Vcross(u, susp_to_abs.GetA().Get_A_Yaxis()); w.Normalize(); ChVector<> v = Vcross(w, u); ChMatrix33<> rot; rot.Set_A_axis(u, v, w); m_arm = ChSharedPtr<ChBody>(new ChBody(chassis->GetSystem()->GetContactMethod())); m_arm->SetNameString(m_name + "_arm"); m_arm->SetPos(points[ARM]); m_arm->SetRot(rot); m_arm->SetMass(GetArmMass()); m_arm->SetInertiaXX(GetArmInertia()); AddVisualizationArm(susp_to_abs.GetPos(), points[ARM], points[ARM_WHEEL], points[ARM_CHASSIS], points[SHOCK_A]); chassis->GetSystem()->AddBody(m_arm); // Create and initialize the revolute joint between arm and chassis. // The axis of rotation is the y axis of the suspension reference frame. m_revolute = ChSharedPtr<ChLinkLockRevolute>(new ChLinkLockRevolute); m_revolute->SetNameString(m_name + "_revolute"); m_revolute->Initialize(chassis, m_arm, ChCoordsys<>(points[ARM_CHASSIS], susp_to_abs.GetRot() * Q_from_AngX(CH_C_PI_2))); // Add torsional spring associated with m_revolute m_revolute->SetForce_Rz(GetTorsionForceFunction()); chassis->GetSystem()->AddLink(m_revolute); // Create and initialize the shock force element. if (m_has_shock) { m_shock = ChSharedPtr<ChLinkSpringCB>(new ChLinkSpringCB); m_shock->SetNameString(m_name + "_shock"); m_shock->Initialize(chassis, m_arm, false, points[SHOCK_C], points[SHOCK_A]); m_shock->Set_SpringCallback(GetShockForceCallback()); chassis->GetSystem()->AddLink(m_shock); } // Invoke the base class implementation. This initializes the associated road wheel. // Note: we must call this here, after the m_arm body is created. ChRoadWheelAssembly::Initialize(chassis, location); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChLinearDamperRWAssembly::AddVisualizationArm(const ChVector<>& pt_O, const ChVector<>& pt_A, const ChVector<>& pt_AW, const ChVector<>& pt_AC, const ChVector<>& pt_AS) { static const double threshold2 = 1e-6; double radius = GetArmVisRadius(); // Express hardpoint locations in body frame. ChVector<> p_O = m_arm->TransformPointParentToLocal(pt_O); ChVector<> p_A = m_arm->TransformPointParentToLocal(pt_A); ChVector<> p_AC = m_arm->TransformPointParentToLocal(pt_AC); ChVector<> p_AW = m_arm->TransformPointParentToLocal(pt_AW); ChVector<> p_AS = m_arm->TransformPointParentToLocal(pt_AS); if ((p_A - p_AW).Length2() > threshold2) { ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape); cyl->GetCylinderGeometry().p1 = p_A; cyl->GetCylinderGeometry().p2 = p_AW; cyl->GetCylinderGeometry().rad = radius; m_arm->AddAsset(cyl); } if ((p_A - p_AC).Length2() > threshold2) { ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape); cyl->GetCylinderGeometry().p1 = p_A; cyl->GetCylinderGeometry().p2 = p_AC; cyl->GetCylinderGeometry().rad = radius; m_arm->AddAsset(cyl); } if ((p_A - p_AS).Length2() > threshold2) { ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape); cyl->GetCylinderGeometry().p1 = p_A; cyl->GetCylinderGeometry().p2 = p_AS; cyl->GetCylinderGeometry().rad = 0.75 * radius; m_arm->AddAsset(cyl); } if ((p_O - p_AW).Length2() > threshold2) { ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape); double len = (p_O - p_AW).Length(); cyl->GetCylinderGeometry().p1 = p_O; cyl->GetCylinderGeometry().p2 = p_AW + (p_AW - p_O) * radius/len; cyl->GetCylinderGeometry().rad = radius; m_arm->AddAsset(cyl); } ChSharedPtr<ChColorAsset> col(new ChColorAsset); col->SetColor(ChColor(0.2f, 0.6f, 0.3f)); m_arm->AddAsset(col); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChLinearDamperRWAssembly::LogConstraintViolations() { ChMatrix<>* C = m_revolute->GetC(); GetLog() << " Arm-chassis revolute\n"; GetLog() << " " << C->GetElement(0, 0) << " "; GetLog() << " " << C->GetElement(1, 0) << " "; GetLog() << " " << C->GetElement(2, 0) << " "; GetLog() << " " << C->GetElement(3, 0) << " "; GetLog() << " " << C->GetElement(4, 0) << "\n"; m_road_wheel->LogConstraintViolations(); } } // end namespace vehicle } // end namespace chrono <commit_msg>Fix incorrect assert<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Base class for a torsion-bar suspension system using linear dampers (template // definition). // // ============================================================================= #include "chrono/assets/ChCylinderShape.h" #include "chrono/assets/ChColorAsset.h" #include "chrono_vehicle/tracked_vehicle/suspension/ChLinearDamperRWAssembly.h" namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- ChLinearDamperRWAssembly::ChLinearDamperRWAssembly(const std::string& name, bool has_shock) : ChRoadWheelAssembly(name), m_has_shock(has_shock) { } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChLinearDamperRWAssembly::Initialize(ChSharedPtr<ChBodyAuxRef> chassis, const ChVector<>& location) { // Express the suspension reference frame in the absolute coordinate system. ChFrame<> susp_to_abs(location); susp_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs()); // Transform all points and directions to absolute frame. std::vector<ChVector<> > points(NUM_POINTS); for (int i = 0; i < NUM_POINTS; i++) { ChVector<> rel_pos = GetLocation(static_cast<PointId>(i)); points[i] = susp_to_abs.TransformPointLocalToParent(rel_pos); } // Sanity check. assert(points[ARM_WHEEL].x == susp_to_abs.GetPos().x && points[ARM_WHEEL].z == susp_to_abs.GetPos().z); // Create the trailing arm body. The reference frame of the arm body has its // x-axis aligned with the line between the arm-chassis connection point and // the arm-wheel connection point. ChVector<> u = susp_to_abs.GetPos() - points[ARM_CHASSIS]; u.Normalize(); ChVector<> w = Vcross(u, susp_to_abs.GetA().Get_A_Yaxis()); w.Normalize(); ChVector<> v = Vcross(w, u); ChMatrix33<> rot; rot.Set_A_axis(u, v, w); m_arm = ChSharedPtr<ChBody>(new ChBody(chassis->GetSystem()->GetContactMethod())); m_arm->SetNameString(m_name + "_arm"); m_arm->SetPos(points[ARM]); m_arm->SetRot(rot); m_arm->SetMass(GetArmMass()); m_arm->SetInertiaXX(GetArmInertia()); AddVisualizationArm(susp_to_abs.GetPos(), points[ARM], points[ARM_WHEEL], points[ARM_CHASSIS], points[SHOCK_A]); chassis->GetSystem()->AddBody(m_arm); // Create and initialize the revolute joint between arm and chassis. // The axis of rotation is the y axis of the suspension reference frame. m_revolute = ChSharedPtr<ChLinkLockRevolute>(new ChLinkLockRevolute); m_revolute->SetNameString(m_name + "_revolute"); m_revolute->Initialize(chassis, m_arm, ChCoordsys<>(points[ARM_CHASSIS], susp_to_abs.GetRot() * Q_from_AngX(CH_C_PI_2))); // Add torsional spring associated with m_revolute m_revolute->SetForce_Rz(GetTorsionForceFunction()); chassis->GetSystem()->AddLink(m_revolute); // Create and initialize the shock force element. if (m_has_shock) { m_shock = ChSharedPtr<ChLinkSpringCB>(new ChLinkSpringCB); m_shock->SetNameString(m_name + "_shock"); m_shock->Initialize(chassis, m_arm, false, points[SHOCK_C], points[SHOCK_A]); m_shock->Set_SpringCallback(GetShockForceCallback()); chassis->GetSystem()->AddLink(m_shock); } // Invoke the base class implementation. This initializes the associated road wheel. // Note: we must call this here, after the m_arm body is created. ChRoadWheelAssembly::Initialize(chassis, location); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChLinearDamperRWAssembly::AddVisualizationArm(const ChVector<>& pt_O, const ChVector<>& pt_A, const ChVector<>& pt_AW, const ChVector<>& pt_AC, const ChVector<>& pt_AS) { static const double threshold2 = 1e-6; double radius = GetArmVisRadius(); // Express hardpoint locations in body frame. ChVector<> p_O = m_arm->TransformPointParentToLocal(pt_O); ChVector<> p_A = m_arm->TransformPointParentToLocal(pt_A); ChVector<> p_AC = m_arm->TransformPointParentToLocal(pt_AC); ChVector<> p_AW = m_arm->TransformPointParentToLocal(pt_AW); ChVector<> p_AS = m_arm->TransformPointParentToLocal(pt_AS); if ((p_A - p_AW).Length2() > threshold2) { ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape); cyl->GetCylinderGeometry().p1 = p_A; cyl->GetCylinderGeometry().p2 = p_AW; cyl->GetCylinderGeometry().rad = radius; m_arm->AddAsset(cyl); } if ((p_A - p_AC).Length2() > threshold2) { ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape); cyl->GetCylinderGeometry().p1 = p_A; cyl->GetCylinderGeometry().p2 = p_AC; cyl->GetCylinderGeometry().rad = radius; m_arm->AddAsset(cyl); } if ((p_A - p_AS).Length2() > threshold2) { ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape); cyl->GetCylinderGeometry().p1 = p_A; cyl->GetCylinderGeometry().p2 = p_AS; cyl->GetCylinderGeometry().rad = 0.75 * radius; m_arm->AddAsset(cyl); } if ((p_O - p_AW).Length2() > threshold2) { ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape); double len = (p_O - p_AW).Length(); cyl->GetCylinderGeometry().p1 = p_O; cyl->GetCylinderGeometry().p2 = p_AW + (p_AW - p_O) * radius/len; cyl->GetCylinderGeometry().rad = radius; m_arm->AddAsset(cyl); } ChSharedPtr<ChColorAsset> col(new ChColorAsset); col->SetColor(ChColor(0.2f, 0.6f, 0.3f)); m_arm->AddAsset(col); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChLinearDamperRWAssembly::LogConstraintViolations() { ChMatrix<>* C = m_revolute->GetC(); GetLog() << " Arm-chassis revolute\n"; GetLog() << " " << C->GetElement(0, 0) << " "; GetLog() << " " << C->GetElement(1, 0) << " "; GetLog() << " " << C->GetElement(2, 0) << " "; GetLog() << " " << C->GetElement(3, 0) << " "; GetLog() << " " << C->GetElement(4, 0) << "\n"; m_road_wheel->LogConstraintViolations(); } } // end namespace vehicle } // end namespace chrono <|endoftext|>
<commit_before>/* * Copyright (C) 2022 The Android Open Source Project * * 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. */ // This example demonstrates startup tracing with a custom data source. // Startup tracing can work only with kSystemBackend. Before running // this example, `traced` must already be running in a separate process. // Run system tracing: ninja -C out/default/ traced && ./out/default/traced // And then run this example: ninja -C out/default example_startup_trace && // ./out/default/example_startup_trace #if defined(PERFETTO_SDK_EXAMPLE_USE_INTERNAL_HEADERS) #include "perfetto/tracing.h" #include "perfetto/tracing/core/data_source_descriptor.h" #include "perfetto/tracing/core/trace_config.h" #include "perfetto/tracing/data_source.h" #include "perfetto/tracing/tracing.h" #include "protos/perfetto/trace/test_event.pbzero.h" #else #include <perfetto.h> #endif #include <unistd.h> #include <fstream> #include <iostream> #include <thread> namespace { // The definition of our custom data source. Instances of this class will be // automatically created and destroyed by Perfetto. class CustomDataSource : public perfetto::DataSource<CustomDataSource> {}; void InitializePerfetto() { perfetto::TracingInitArgs args; // The backends determine where trace events are recorded. For this example we // are going to use the system-wide tracing service, because the in-process // backend doesn't support startup tracing. args.backends = perfetto::kSystemBackend; perfetto::Tracing::Initialize(args); // Register our custom data source. Only the name is required, but other // properties can be advertised too. perfetto::DataSourceDescriptor dsd; dsd.set_name("com.example.startup_trace"); CustomDataSource::Register(dsd); } // The trace config defines which types of data sources are enabled for // recording. perfetto::TraceConfig GetTraceConfig() { perfetto::TraceConfig cfg; cfg.add_buffers()->set_size_kb(1024); auto* ds_cfg = cfg.add_data_sources()->mutable_config(); ds_cfg->set_name("com.example.startup_trace"); return cfg; } void StartStartupTracing() { perfetto::Tracing::SetupStartupTracingOpts args; args.backend = perfetto::kSystemBackend; perfetto::Tracing::SetupStartupTracingBlocking(GetTraceConfig(), args); } std::unique_ptr<perfetto::TracingSession> StartTracing() { auto tracing_session = perfetto::Tracing::NewTrace(); tracing_session->Setup(GetTraceConfig()); tracing_session->StartBlocking(); return tracing_session; } void StopTracing(std::unique_ptr<perfetto::TracingSession> tracing_session) { // Flush to make sure the last written event ends up in the trace. CustomDataSource::Trace( [](CustomDataSource::TraceContext ctx) { ctx.Flush(); }); // Stop tracing and read the trace data. tracing_session->StopBlocking(); std::vector<char> trace_data(tracing_session->ReadTraceBlocking()); // Write the result into a file. // Note: To save memory with longer traces, you can tell Perfetto to write // directly into a file by passing a file descriptor into Setup() above. std::ofstream output; const char* filename = "example_startup_trace.pftrace"; output.open(filename, std::ios::out | std::ios::binary); output.write(&trace_data[0], static_cast<std::streamsize>(trace_data.size())); output.close(); PERFETTO_LOG( "Trace written in %s file. To read this trace in " "text form, run `./tools/traceconv text %s`", filename, filename); } } // namespace PERFETTO_DECLARE_DATA_SOURCE_STATIC_MEMBERS(CustomDataSource); PERFETTO_DEFINE_DATA_SOURCE_STATIC_MEMBERS(CustomDataSource); int main(int, const char**) { InitializePerfetto(); StartStartupTracing(); // Write an event using our custom data source before starting tracing // session. CustomDataSource::Trace([](CustomDataSource::TraceContext ctx) { auto packet = ctx.NewTracePacket(); packet->set_timestamp(41); packet->set_for_testing()->set_str("Startup Event"); }); auto tracing_session = StartTracing(); // Write an event using our custom data source. CustomDataSource::Trace([](CustomDataSource::TraceContext ctx) { auto packet = ctx.NewTracePacket(); packet->set_timestamp(42); packet->set_for_testing()->set_str("Main Event"); }); StopTracing(std::move(tracing_session)); return 0; } <commit_msg>Fix example_startup_trace build on windows<commit_after>/* * Copyright (C) 2022 The Android Open Source Project * * 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. */ // This example demonstrates startup tracing with a custom data source. // Startup tracing can work only with kSystemBackend. Before running // this example, `traced` must already be running in a separate process. // Run system tracing: ninja -C out/default/ traced && ./out/default/traced // And then run this example: ninja -C out/default example_startup_trace && // ./out/default/example_startup_trace #if defined(PERFETTO_SDK_EXAMPLE_USE_INTERNAL_HEADERS) #include "perfetto/tracing.h" #include "perfetto/tracing/core/data_source_descriptor.h" #include "perfetto/tracing/core/trace_config.h" #include "perfetto/tracing/data_source.h" #include "perfetto/tracing/tracing.h" #include "protos/perfetto/trace/test_event.pbzero.h" #else #include <perfetto.h> #endif #include <fstream> #include <iostream> #include <thread> namespace { // The definition of our custom data source. Instances of this class will be // automatically created and destroyed by Perfetto. class CustomDataSource : public perfetto::DataSource<CustomDataSource> {}; void InitializePerfetto() { perfetto::TracingInitArgs args; // The backends determine where trace events are recorded. For this example we // are going to use the system-wide tracing service, because the in-process // backend doesn't support startup tracing. args.backends = perfetto::kSystemBackend; perfetto::Tracing::Initialize(args); // Register our custom data source. Only the name is required, but other // properties can be advertised too. perfetto::DataSourceDescriptor dsd; dsd.set_name("com.example.startup_trace"); CustomDataSource::Register(dsd); } // The trace config defines which types of data sources are enabled for // recording. perfetto::TraceConfig GetTraceConfig() { perfetto::TraceConfig cfg; cfg.add_buffers()->set_size_kb(1024); auto* ds_cfg = cfg.add_data_sources()->mutable_config(); ds_cfg->set_name("com.example.startup_trace"); return cfg; } void StartStartupTracing() { perfetto::Tracing::SetupStartupTracingOpts args; args.backend = perfetto::kSystemBackend; perfetto::Tracing::SetupStartupTracingBlocking(GetTraceConfig(), args); } std::unique_ptr<perfetto::TracingSession> StartTracing() { auto tracing_session = perfetto::Tracing::NewTrace(); tracing_session->Setup(GetTraceConfig()); tracing_session->StartBlocking(); return tracing_session; } void StopTracing(std::unique_ptr<perfetto::TracingSession> tracing_session) { // Flush to make sure the last written event ends up in the trace. CustomDataSource::Trace( [](CustomDataSource::TraceContext ctx) { ctx.Flush(); }); // Stop tracing and read the trace data. tracing_session->StopBlocking(); std::vector<char> trace_data(tracing_session->ReadTraceBlocking()); // Write the result into a file. // Note: To save memory with longer traces, you can tell Perfetto to write // directly into a file by passing a file descriptor into Setup() above. std::ofstream output; const char* filename = "example_startup_trace.pftrace"; output.open(filename, std::ios::out | std::ios::binary); output.write(trace_data.data(), static_cast<std::streamsize>(trace_data.size())); output.close(); PERFETTO_LOG( "Trace written in %s file. To read this trace in " "text form, run `./tools/traceconv text %s`", filename, filename); } } // namespace PERFETTO_DECLARE_DATA_SOURCE_STATIC_MEMBERS(CustomDataSource); PERFETTO_DEFINE_DATA_SOURCE_STATIC_MEMBERS(CustomDataSource); int main(int, const char**) { InitializePerfetto(); StartStartupTracing(); // Write an event using our custom data source before starting tracing // session. CustomDataSource::Trace([](CustomDataSource::TraceContext ctx) { auto packet = ctx.NewTracePacket(); packet->set_timestamp(41); packet->set_for_testing()->set_str("Startup Event"); }); auto tracing_session = StartTracing(); // Write an event using our custom data source. CustomDataSource::Trace([](CustomDataSource::TraceContext ctx) { auto packet = ctx.NewTracePacket(); packet->set_timestamp(42); packet->set_for_testing()->set_str("Main Event"); }); StopTracing(std::move(tracing_session)); return 0; } <|endoftext|>
<commit_before><commit_msg>Shuffle: make sure not to fail if getClipPreferences was not called<commit_after><|endoftext|>
<commit_before>// @(#)root/reflex:$Id$ // Author: Stefan Roiser 2004 // Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved. // // Permission to use, copy, modify, and distribute this software for any // purpose is hereby granted without fee, provided that this copyright and // permissions notice appear in all copies and derivatives. // // This software is provided "as is" without express or implied warranty. #ifndef REFLEX_BUILD # define REFLEX_BUILD #endif #include "Reflex/internal/MemberBase.h" #include "Reflex/internal/OwnedMember.h" #include "Reflex/Scope.h" #include "Reflex/Type.h" #include "Reflex/Base.h" #include "Reflex/Object.h" #include "Reflex/internal/OwnedPropertyList.h" #include "Reflex/DictionaryGenerator.h" #include "Reflex/Tools.h" #include "Class.h" //------------------------------------------------------------------------------- Reflex::MemberBase::MemberBase(const char* name, const Type& type, TYPE memberType, unsigned int modifiers) //------------------------------------------------------------------------------- : fType(type, modifiers & (CONST | VOLATILE | REFERENCE), Type::APPEND), fModifiers(modifiers), fName(name), fScope(Scope()), fMemberType(memberType), fPropertyList(OwnedPropertyList(new PropertyListImpl())) { // Construct the dictionary info for a member fThisMember = new Member(this); } //------------------------------------------------------------------------------- Reflex::MemberBase::~MemberBase() { //------------------------------------------------------------------------------- // Destructor. delete fThisMember; fPropertyList.Delete(); } //------------------------------------------------------------------------------- Reflex::MemberBase::operator Reflex::Member() const { //------------------------------------------------------------------------------- // Conversion operator to Member. return *fThisMember; } //------------------------------------------------------------------------------- void* Reflex::MemberBase::CalculateBaseObject(const Object& obj) const { //------------------------------------------------------------------------------- // Return the object address a member lives in. char* mem = (char*) obj.Address(); // check if its a dummy object Type cl = obj.TypeOf(); while (cl && cl.IsTypedef()) { cl = cl.ToType(); } // if the object type is not implemented return the Address of the object if (!cl) { return mem; } if (cl.IsClass()) { if (DeclaringScope() && (cl.Id() != (dynamic_cast<const Class*>(DeclaringScope().ToScopeBase()))->ThisType().Id())) { // now we know that the Member type is an inherited one std::vector<OffsetFunction> basePath = (dynamic_cast<const Class*>(cl.ToTypeBase()))->PathToBase(DeclaringScope()); if (basePath.size()) { // there is a path described from the object to the class containing the Member std::vector<OffsetFunction>::iterator pIter; for (pIter = basePath.begin(); pIter != basePath.end(); ++pIter) { mem += (*pIter)(mem); } } else { throw RuntimeError(std::string(": ERROR: There is no path available from class ") + cl.Name(SCOPED) + " to " + Name(SCOPED)); } } } else { throw RuntimeError(std::string("Object ") + cl.Name(SCOPED) + " does not represent a class"); } return (void*) mem; } // CalculateBaseObject //------------------------------------------------------------------------------- Reflex::Scope Reflex::MemberBase::DeclaringScope() const { //------------------------------------------------------------------------------- // Return the scope the member lives in. return fScope; } //------------------------------------------------------------------------------- Reflex::Type Reflex::MemberBase::DeclaringType() const { //------------------------------------------------------------------------------- // Return the type the member lives in. return DeclaringScope(); } //------------------------------------------------------------------------------- std::string Reflex::MemberBase::MemberTypeAsString() const { //------------------------------------------------------------------------------- // Remember type of the member as a string. switch (fMemberType) { case DATAMEMBER: return "DataMember"; break; case FUNCTIONMEMBER: return "FunctionMember"; break; default: return Reflex::Argv0() + ": ERROR: Member " + Name() + " has no Species associated"; } } //------------------------------------------------------------------------------- Reflex::PropertyList Reflex::MemberBase::Properties() const { //------------------------------------------------------------------------------- // Return the property list attached to this member. return fPropertyList; } //------------------------------------------------------------------------------- Reflex::Type Reflex::MemberBase::TemplateArgumentAt(size_t /* nth */) const { //------------------------------------------------------------------------------- // Return the nth template argument (in FunMemTemplInstance) return Dummy::Type(); } //------------------------------------------------------------------------------- void Reflex::MemberBase::GenerateDict(DictionaryGenerator& /* generator */) const { //------------------------------------------------------------------------------- // Generate Dictionary information about itself. } <commit_msg>Fix Cov CID 10240, check dyn_cast != 0<commit_after>// @(#)root/reflex:$Id$ // Author: Stefan Roiser 2004 // Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved. // // Permission to use, copy, modify, and distribute this software for any // purpose is hereby granted without fee, provided that this copyright and // permissions notice appear in all copies and derivatives. // // This software is provided "as is" without express or implied warranty. #ifndef REFLEX_BUILD # define REFLEX_BUILD #endif #include "Reflex/internal/MemberBase.h" #include "Reflex/internal/OwnedMember.h" #include "Reflex/Scope.h" #include "Reflex/Type.h" #include "Reflex/Base.h" #include "Reflex/Object.h" #include "Reflex/internal/OwnedPropertyList.h" #include "Reflex/DictionaryGenerator.h" #include "Reflex/Tools.h" #include "Class.h" //------------------------------------------------------------------------------- Reflex::MemberBase::MemberBase(const char* name, const Type& type, TYPE memberType, unsigned int modifiers) //------------------------------------------------------------------------------- : fType(type, modifiers & (CONST | VOLATILE | REFERENCE), Type::APPEND), fModifiers(modifiers), fName(name), fScope(Scope()), fMemberType(memberType), fPropertyList(OwnedPropertyList(new PropertyListImpl())) { // Construct the dictionary info for a member fThisMember = new Member(this); } //------------------------------------------------------------------------------- Reflex::MemberBase::~MemberBase() { //------------------------------------------------------------------------------- // Destructor. delete fThisMember; fPropertyList.Delete(); } //------------------------------------------------------------------------------- Reflex::MemberBase::operator Reflex::Member() const { //------------------------------------------------------------------------------- // Conversion operator to Member. return *fThisMember; } //------------------------------------------------------------------------------- void* Reflex::MemberBase::CalculateBaseObject(const Object& obj) const { //------------------------------------------------------------------------------- // Return the object address a member lives in. char* mem = (char*) obj.Address(); // check if its a dummy object Type cl = obj.TypeOf(); while (cl && cl.IsTypedef()) { cl = cl.ToType(); } // if the object type is not implemented return the Address of the object if (!cl) { return mem; } if (cl.IsClass()) { const Class* clTB = 0; if (DeclaringScope() && (cl.Id() != (dynamic_cast<const Class*>(DeclaringScope().ToScopeBase()))->ThisType().Id())) { // now we know that the Member type is an inherited one clTB = dynamic_cast<const Class*>(cl.ToTypeBase()); } if (clTB) { std::vector<OffsetFunction> basePath = clTB->PathToBase(DeclaringScope()); if (basePath.size()) { // there is a path described from the object to the class containing the Member std::vector<OffsetFunction>::iterator pIter; for (pIter = basePath.begin(); pIter != basePath.end(); ++pIter) { mem += (*pIter)(mem); } } else { throw RuntimeError(std::string(": ERROR: There is no path available from class ") + cl.Name(SCOPED) + " to " + Name(SCOPED)); } } } else { throw RuntimeError(std::string("Object ") + cl.Name(SCOPED) + " does not represent a class"); } return (void*) mem; } // CalculateBaseObject //------------------------------------------------------------------------------- Reflex::Scope Reflex::MemberBase::DeclaringScope() const { //------------------------------------------------------------------------------- // Return the scope the member lives in. return fScope; } //------------------------------------------------------------------------------- Reflex::Type Reflex::MemberBase::DeclaringType() const { //------------------------------------------------------------------------------- // Return the type the member lives in. return DeclaringScope(); } //------------------------------------------------------------------------------- std::string Reflex::MemberBase::MemberTypeAsString() const { //------------------------------------------------------------------------------- // Remember type of the member as a string. switch (fMemberType) { case DATAMEMBER: return "DataMember"; break; case FUNCTIONMEMBER: return "FunctionMember"; break; default: return Reflex::Argv0() + ": ERROR: Member " + Name() + " has no Species associated"; } } //------------------------------------------------------------------------------- Reflex::PropertyList Reflex::MemberBase::Properties() const { //------------------------------------------------------------------------------- // Return the property list attached to this member. return fPropertyList; } //------------------------------------------------------------------------------- Reflex::Type Reflex::MemberBase::TemplateArgumentAt(size_t /* nth */) const { //------------------------------------------------------------------------------- // Return the nth template argument (in FunMemTemplInstance) return Dummy::Type(); } //------------------------------------------------------------------------------- void Reflex::MemberBase::GenerateDict(DictionaryGenerator& /* generator */) const { //------------------------------------------------------------------------------- // Generate Dictionary information about itself. } <|endoftext|>
<commit_before><commit_msg>ENH: Added fractional diffs<commit_after><|endoftext|>
<commit_before>/** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Configuration. */ #include "zone.hpp" #include "conf.hpp" #include "pid/controller.hpp" #include "pid/ec/pid.hpp" #include "pid/fancontroller.hpp" #include "pid/stepwisecontroller.hpp" #include "pid/thermalcontroller.hpp" #include <algorithm> #include <chrono> #include <cstring> #include <fstream> #include <iostream> #include <memory> using tstamp = std::chrono::high_resolution_clock::time_point; using namespace std::literals::chrono_literals; double PIDZone::getMaxRPMRequest(void) const { return _maximumRPMSetPt; } bool PIDZone::getManualMode(void) const { return _manualMode; } void PIDZone::setManualMode(bool mode) { _manualMode = mode; } bool PIDZone::getFailSafeMode(void) const { // If any keys are present at least one sensor is in fail safe mode. return !_failSafeSensors.empty(); } int64_t PIDZone::getZoneID(void) const { return _zoneId; } void PIDZone::addRPMSetPoint(double setpoint) { _RPMSetPoints.push_back(setpoint); } void PIDZone::clearRPMSetPoints(void) { _RPMSetPoints.clear(); } double PIDZone::getFailSafePercent(void) const { return _failSafePercent; } double PIDZone::getMinThermalRPMSetpoint(void) const { return _minThermalRpmSetPt; } void PIDZone::addFanPID(std::unique_ptr<Controller> pid) { _fans.push_back(std::move(pid)); } void PIDZone::addThermalPID(std::unique_ptr<Controller> pid) { _thermals.push_back(std::move(pid)); } double PIDZone::getCachedValue(const std::string& name) { return _cachedValuesByName.at(name); } void PIDZone::addFanInput(const std::string& fan) { _fanInputs.push_back(fan); } void PIDZone::addThermalInput(const std::string& therm) { _thermalInputs.push_back(therm); } void PIDZone::determineMaxRPMRequest(void) { double max = 0; std::vector<double>::iterator result; if (_RPMSetPoints.size() > 0) { result = std::max_element(_RPMSetPoints.begin(), _RPMSetPoints.end()); max = *result; } /* * If the maximum RPM setpoint output is below the minimum RPM * setpoint, set it to the minimum. */ max = std::max(getMinThermalRPMSetpoint(), max); #ifdef __TUNING_LOGGING__ /* * We received no setpoints from thermal sensors. * This is a case experienced during tuning where they only specify * fan sensors and one large fan PID for all the fans. */ static constexpr auto setpointpath = "/etc/thermal.d/setpoint"; try { std::ifstream ifs; ifs.open(setpointpath); if (ifs.good()) { int value; ifs >> value; /* expecting RPM setpoint, not pwm% */ max = static_cast<double>(value); } } catch (const std::exception& e) { /* This exception is uninteresting. */ std::cerr << "Unable to read from '" << setpointpath << "'\n"; } #endif _maximumRPMSetPt = max; return; } #ifdef __TUNING_LOGGING__ void PIDZone::initializeLog(void) { /* Print header for log file: * epoch_ms,setpt,fan1,fan2,fanN,sensor1,sensor2,sensorN,failsafe */ _log << "epoch_ms,setpt"; for (const auto& f : _fanInputs) { _log << "," << f; } for (const auto& t : _thermalInputs) { _log << "," << t; } _log << ",failsafe"; _log << std::endl; return; } std::ofstream& PIDZone::getLogHandle(void) { return _log; } #endif /* * TODO(venture) This is effectively updating the cache and should check if the * values they're using to update it are new or old, or whatnot. For instance, * if we haven't heard from the host in X time we need to detect this failure. * * I haven't decided if the Sensor should have a lastUpdated method or whether * that should be for the ReadInterface or etc... */ /** * We want the PID loop to run with values cached, so this will get all the * fan tachs for the loop. */ void PIDZone::updateFanTelemetry(void) { /* TODO(venture): Should I just make _log point to /dev/null when logging * is disabled? I think it's a waste to try and log things even if the * data is just being dropped though. */ #ifdef __TUNING_LOGGING__ tstamp now = std::chrono::high_resolution_clock::now(); _log << std::chrono::duration_cast<std::chrono::milliseconds>( now.time_since_epoch()) .count(); _log << "," << _maximumRPMSetPt; #endif for (const auto& f : _fanInputs) { auto sensor = _mgr.getSensor(f); ReadReturn r = sensor->read(); _cachedValuesByName[f] = r.value; /* * TODO(venture): We should check when these were last read. * However, these are the fans, so if I'm not getting updated values * for them... what should I do? */ #ifdef __TUNING_LOGGING__ _log << "," << r.value; #endif } #ifdef __TUNING_LOGGING__ for (const auto& t : _thermalInputs) { _log << "," << _cachedValuesByName[t]; } #endif return; } void PIDZone::updateSensors(void) { using namespace std::chrono; /* margin and temp are stored as temp */ tstamp now = high_resolution_clock::now(); for (const auto& t : _thermalInputs) { auto sensor = _mgr.getSensor(t); ReadReturn r = sensor->read(); int64_t timeout = sensor->getTimeout(); _cachedValuesByName[t] = r.value; tstamp then = r.updated; if (sensor->getFailed()) { _failSafeSensors.insert(t); } /* Only go into failsafe if the timeout is set for * the sensor. */ else if (timeout > 0) { auto duration = duration_cast<std::chrono::seconds>(now - then).count(); auto period = std::chrono::seconds(timeout).count(); if (duration >= period) { // std::cerr << "Entering fail safe mode.\n"; _failSafeSensors.insert(t); } else { // Check if it's in there: remove it. auto kt = _failSafeSensors.find(t); if (kt != _failSafeSensors.end()) { _failSafeSensors.erase(kt); } } } } return; } void PIDZone::initializeCache(void) { for (const auto& f : _fanInputs) { _cachedValuesByName[f] = 0; } for (const auto& t : _thermalInputs) { _cachedValuesByName[t] = 0; // Start all sensors in fail-safe mode. _failSafeSensors.insert(t); } } void PIDZone::dumpCache(void) { std::cerr << "Cache values now: \n"; for (const auto& k : _cachedValuesByName) { std::cerr << k.first << ": " << k.second << "\n"; } } void PIDZone::processFans(void) { for (auto& p : _fans) { p->process(); } } void PIDZone::processThermals(void) { for (auto& p : _thermals) { p->process(); } } Sensor* PIDZone::getSensor(const std::string& name) { return _mgr.getSensor(name); } bool PIDZone::manual(bool value) { std::cerr << "manual: " << value << std::endl; setManualMode(value); return ModeObject::manual(value); } bool PIDZone::failSafe() const { return getFailSafeMode(); } <commit_msg>Allow removal from failsafe if timeout=0<commit_after>/** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Configuration. */ #include "zone.hpp" #include "conf.hpp" #include "pid/controller.hpp" #include "pid/ec/pid.hpp" #include "pid/fancontroller.hpp" #include "pid/stepwisecontroller.hpp" #include "pid/thermalcontroller.hpp" #include <algorithm> #include <chrono> #include <cstring> #include <fstream> #include <iostream> #include <memory> using tstamp = std::chrono::high_resolution_clock::time_point; using namespace std::literals::chrono_literals; double PIDZone::getMaxRPMRequest(void) const { return _maximumRPMSetPt; } bool PIDZone::getManualMode(void) const { return _manualMode; } void PIDZone::setManualMode(bool mode) { _manualMode = mode; } bool PIDZone::getFailSafeMode(void) const { // If any keys are present at least one sensor is in fail safe mode. return !_failSafeSensors.empty(); } int64_t PIDZone::getZoneID(void) const { return _zoneId; } void PIDZone::addRPMSetPoint(double setpoint) { _RPMSetPoints.push_back(setpoint); } void PIDZone::clearRPMSetPoints(void) { _RPMSetPoints.clear(); } double PIDZone::getFailSafePercent(void) const { return _failSafePercent; } double PIDZone::getMinThermalRPMSetpoint(void) const { return _minThermalRpmSetPt; } void PIDZone::addFanPID(std::unique_ptr<Controller> pid) { _fans.push_back(std::move(pid)); } void PIDZone::addThermalPID(std::unique_ptr<Controller> pid) { _thermals.push_back(std::move(pid)); } double PIDZone::getCachedValue(const std::string& name) { return _cachedValuesByName.at(name); } void PIDZone::addFanInput(const std::string& fan) { _fanInputs.push_back(fan); } void PIDZone::addThermalInput(const std::string& therm) { _thermalInputs.push_back(therm); } void PIDZone::determineMaxRPMRequest(void) { double max = 0; std::vector<double>::iterator result; if (_RPMSetPoints.size() > 0) { result = std::max_element(_RPMSetPoints.begin(), _RPMSetPoints.end()); max = *result; } /* * If the maximum RPM setpoint output is below the minimum RPM * setpoint, set it to the minimum. */ max = std::max(getMinThermalRPMSetpoint(), max); #ifdef __TUNING_LOGGING__ /* * We received no setpoints from thermal sensors. * This is a case experienced during tuning where they only specify * fan sensors and one large fan PID for all the fans. */ static constexpr auto setpointpath = "/etc/thermal.d/setpoint"; try { std::ifstream ifs; ifs.open(setpointpath); if (ifs.good()) { int value; ifs >> value; /* expecting RPM setpoint, not pwm% */ max = static_cast<double>(value); } } catch (const std::exception& e) { /* This exception is uninteresting. */ std::cerr << "Unable to read from '" << setpointpath << "'\n"; } #endif _maximumRPMSetPt = max; return; } #ifdef __TUNING_LOGGING__ void PIDZone::initializeLog(void) { /* Print header for log file: * epoch_ms,setpt,fan1,fan2,fanN,sensor1,sensor2,sensorN,failsafe */ _log << "epoch_ms,setpt"; for (const auto& f : _fanInputs) { _log << "," << f; } for (const auto& t : _thermalInputs) { _log << "," << t; } _log << ",failsafe"; _log << std::endl; return; } std::ofstream& PIDZone::getLogHandle(void) { return _log; } #endif /* * TODO(venture) This is effectively updating the cache and should check if the * values they're using to update it are new or old, or whatnot. For instance, * if we haven't heard from the host in X time we need to detect this failure. * * I haven't decided if the Sensor should have a lastUpdated method or whether * that should be for the ReadInterface or etc... */ /** * We want the PID loop to run with values cached, so this will get all the * fan tachs for the loop. */ void PIDZone::updateFanTelemetry(void) { /* TODO(venture): Should I just make _log point to /dev/null when logging * is disabled? I think it's a waste to try and log things even if the * data is just being dropped though. */ #ifdef __TUNING_LOGGING__ tstamp now = std::chrono::high_resolution_clock::now(); _log << std::chrono::duration_cast<std::chrono::milliseconds>( now.time_since_epoch()) .count(); _log << "," << _maximumRPMSetPt; #endif for (const auto& f : _fanInputs) { auto sensor = _mgr.getSensor(f); ReadReturn r = sensor->read(); _cachedValuesByName[f] = r.value; /* * TODO(venture): We should check when these were last read. * However, these are the fans, so if I'm not getting updated values * for them... what should I do? */ #ifdef __TUNING_LOGGING__ _log << "," << r.value; #endif } #ifdef __TUNING_LOGGING__ for (const auto& t : _thermalInputs) { _log << "," << _cachedValuesByName[t]; } #endif return; } void PIDZone::updateSensors(void) { using namespace std::chrono; /* margin and temp are stored as temp */ tstamp now = high_resolution_clock::now(); for (const auto& t : _thermalInputs) { auto sensor = _mgr.getSensor(t); ReadReturn r = sensor->read(); int64_t timeout = sensor->getTimeout(); _cachedValuesByName[t] = r.value; tstamp then = r.updated; auto duration = duration_cast<std::chrono::seconds>(now - then).count(); auto period = std::chrono::seconds(timeout).count(); if (sensor->getFailed()) { _failSafeSensors.insert(t); } else if (timeout != 0 && duration >= period) { // std::cerr << "Entering fail safe mode.\n"; _failSafeSensors.insert(t); } else { // Check if it's in there: remove it. auto kt = _failSafeSensors.find(t); if (kt != _failSafeSensors.end()) { _failSafeSensors.erase(kt); } } } return; } void PIDZone::initializeCache(void) { for (const auto& f : _fanInputs) { _cachedValuesByName[f] = 0; } for (const auto& t : _thermalInputs) { _cachedValuesByName[t] = 0; // Start all sensors in fail-safe mode. _failSafeSensors.insert(t); } } void PIDZone::dumpCache(void) { std::cerr << "Cache values now: \n"; for (const auto& k : _cachedValuesByName) { std::cerr << k.first << ": " << k.second << "\n"; } } void PIDZone::processFans(void) { for (auto& p : _fans) { p->process(); } } void PIDZone::processThermals(void) { for (auto& p : _thermals) { p->process(); } } Sensor* PIDZone::getSensor(const std::string& name) { return _mgr.getSensor(name); } bool PIDZone::manual(bool value) { std::cerr << "manual: " << value << std::endl; setManualMode(value); return ModeObject::manual(value); } bool PIDZone::failSafe() const { return getFailSafeMode(); } <|endoftext|>
<commit_before>// // Created by Miguel Rentes on 11/01/2017. // #include "introduction.h" using namespace std; int main(void) { unsigned int n, q; string line; getline(cin, line); n = (unsigned int) stoi(line.substr(0, 1)); q = (unsigned int) stoi(line.substr(2, 1)); unsigned int* array[n]; // array with n pointers to the array indexes unsigned int queries[n*q]; // array with all queries for (int i = 0; i < n; i++) { std::getline(cin, line); unsigned int index_size = (unsigned int) stoi(line.substr(0, 1)); unsigned int array_indexes[index_size]; for (int j = 0; j < index_size; j++) { array_indexes[j] = (unsigned int) stoi(line.substr(2*(j+1), 1)); } array[i] = array_indexes; } for (int i = 0; i < q; i++) { std::getline(cin, line); queries[2*i] = (unsigned int) stoi(line.substr(0, 1)); queries[2*i+1] = (unsigned int) stoi(line.substr(2, 1)); } for (int i = 0; i < q; i++) { cout << array[queries[2*i]][queries[2*i+1]]; } return EXIT_SUCCESS; } <commit_msg>Starts solution for the Variable Sized Arrays challenge.<commit_after>// // Created by Miguel Rentes on 11/01/2017. // #include "introduction.h" using namespace std; int main(void) { unsigned int n, q; string line; getline(cin, line); n = (unsigned int) stoi(line.substr(0, 1)); q = (unsigned int) stoi(line.substr(2, 1)); unsigned int* array[n]; // array with n pointers to the array indexes unsigned int queries[n*q]; // array with all queries unsigned int* array_indexes = nullptr; for (int i = 0; i < n; i++) { std::getline(cin, line); unsigned int index_size = (unsigned int) stoi(line.substr(0, 1)); array_indexes = (unsigned int*) calloc(1, index_size); for (int j = 0; j < index_size; j++) { array_indexes[j] = (unsigned int) stoi(line.substr(2*(j+1), 1)); } array[i] = array_indexes; } for (int i = 0; i < q; i++) { std::getline(cin, line); queries[2*i] = (unsigned int) stoi(line.substr(0, 1)); queries[2*i+1] = (unsigned int) stoi(line.substr(2, 1)); } for (int i = 0; i < q; i++) { cout << array[queries[2*i]][queries[2*i+1]] << endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez. // All rights reserved. // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software // Foundation; either version 2 of the License, or (at your option) any later // version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // this program; if not, write to the // // Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, // Boston, MA // 02110-1301 // USA // //////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <sstream> #include <Context.h> #include <Permission.h> #include <main.h> #include <text.h> #include <i18n.h> #include <CmdModify.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdModify::CmdModify () { _keyword = "modify"; _usage = "task <filter> modify <modifications>\n" "task <sequence> <modifications>"; _description = "Modifies the existing task with provided arguments.\n" "The 'modify' keyword is optional."; _read_only = false; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdModify::execute (std::string& output) { int count = 0; std::stringstream out; std::vector <Task> tasks; context.tdb.lock (context.config.getBoolean ("locking")); context.tdb.loadPending (tasks); // Apply filter. std::vector <Task> filtered; filter (tasks, filtered); if (filtered.size () == 0) { context.footnote (STRING_FEEDBACK_NO_TASKS_SP); return 1; } // Apply the command line modifications to the new task. A3 modifications = context.a3.extract_modifications (); Permission permission; if (filtered.size () > (size_t) context.config.getInteger ("bulk")) permission.bigSequence (); std::vector <Task>::iterator task; for (task = filtered.begin (); task != filtered.end (); ++task) { Task before (*task); modify_task_annotate (*task, modifications); apply_defaults (*task); // Perform some logical consistency checks. // TODO Shouldn't these tests be in Task::validate? if (task->has ("recur") && !task->has ("due") && !before.has ("due")) throw std::string ("You cannot specify a recurring task without a due date."); if (task->has ("until") && !task->has ("recur") && !before.has ("recur")) throw std::string ("You cannot specify an until date for a non-recurring task."); if (before.has ("recur") && before.has ("due") && task->has ("due") && task->get ("due") == "") throw std::string ("You cannot remove the due date from a recurring task."); if (before.has ("recur") && task->has ("recur") && task->get ("recur") == "") throw std::string ("You cannot remove the recurrence from a recurring task."); // Make all changes. bool warned = false; std::vector <Task>::iterator other; for (other = tasks.begin (); other != tasks.end (); ++other) { // Skip wait: modification to a parent task, and other child tasks. Too // difficult to achieve properly without losing 'waiting' as a status. // Soon... if (other->id == task->id || // Self (! task->has ("wait") && // skip waits before.has ("parent") && // is recurring before.get ("parent") == other->get ("parent")) || // Sibling other->get ("uuid") == before.get ("parent")) // Parent { if (before.has ("parent") && !warned) { warned = true; std::cout << "Task " << before.id << " is a recurring task, and all other instances of this" << " task will be modified.\n"; } Task alternate (*other); // If a task is being made recurring, there are other cascading // changes. if (!before.has ("recur") && task->has ("recur")) { other->setStatus (Task::recurring); other->set ("mask", ""); std::cout << "Task " << other->id << " is now a recurring task.\n"; } // Apply other deltas. modify_task_description_replace (*other, modifications); apply_defaults (*other); if (taskDiff (alternate, *other)) { // Only allow valid tasks. other->validate (); if (permission.confirmed (alternate, taskDifferences (alternate, *other) + "Proceed with change?")) { // TODO Are dependencies being explicitly removed? // Either we scan context.task for negative IDs "depends:-n" // or we ask deltaAttributes (above) to record dependency // removal. dependencyChainOnModify (alternate, *other); context.tdb.update (*other); ++count; if (alternate.get ("project") != other->get ("project")) context.footnote (onProjectChange (alternate, *other)); } } } } } if (count) context.tdb.commit (); context.tdb.unlock (); if (context.config.getBoolean ("echo.command")) out << "Modified " << count << " task" << (count == 1 ? ".\n" : "s.\n"); output = out.str (); return 0; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Commands - modify<commit_after>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez. // All rights reserved. // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software // Foundation; either version 2 of the License, or (at your option) any later // version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // this program; if not, write to the // // Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, // Boston, MA // 02110-1301 // USA // //////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <sstream> #include <Context.h> #include <Permission.h> #include <main.h> #include <text.h> #include <i18n.h> #include <CmdModify.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdModify::CmdModify () { _keyword = "modify"; _usage = "task <filter> modify <modifications>\n" "task <sequence> <modifications>"; _description = "Modifies the existing task with provided arguments.\n" "The 'modify' keyword is optional."; _read_only = false; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdModify::execute (std::string& output) { int count = 0; std::stringstream out; // Apply filter. std::vector <Task> filtered; filter (filtered); if (filtered.size () == 0) { context.footnote (STRING_FEEDBACK_NO_TASKS_SP); return 1; } // Apply the command line modifications to the new task. A3 modifications = context.a3.extract_modifications (); if (!modifications.size ()) throw std::string (STRING_CMD_XPEND_NEED_TEXT); Permission permission; if (filtered.size () > (size_t) context.config.getInteger ("bulk")) permission.bigSequence (); std::vector <Task>::iterator task; for (task = filtered.begin (); task != filtered.end (); ++task) { Task before (*task); modify_task_description_replace (*task, modifications); ++count; context.tdb2.modify (*task); // Perform some logical consistency checks. // TODO Shouldn't these tests be in Task::validate? if (task->has ("recur") && !task->has ("due") && !before.has ("due")) throw std::string ("You cannot specify a recurring task without a due date."); if (task->has ("until") && !task->has ("recur") && !before.has ("recur")) throw std::string ("You cannot specify an until date for a non-recurring task."); if (before.has ("recur") && before.has ("due") && task->has ("due") && task->get ("due") == "") throw std::string ("You cannot remove the due date from a recurring task."); if (before.has ("recur") && task->has ("recur") && task->get ("recur") == "") throw std::string ("You cannot remove the recurrence from a recurring task."); // Make all changes. bool warned = false; std::vector <Task> siblings = context.tdb2.siblings (*task); std::vector <Task>::iterator sibling; for (sibling = siblings.begin (); sibling != siblings.end (); ++sibling) { if (before.has ("parent") && !warned) { warned = true; std::cout << "Task " << before.id << " is a recurring task, and all other instances of this" << " task will be modified.\n"; } Task alternate (*sibling); // If a task is being made recurring, there are other cascading // changes. if (!before.has ("recur") && task->has ("recur")) { sibling->setStatus (Task::recurring); sibling->set ("mask", ""); std::cout << "Task " << sibling->id << " is now a recurring task.\n"; } // Apply other deltas. modify_task_description_replace (*sibling, modifications); if (taskDiff (alternate, *sibling)) { if (permission.confirmed (alternate, taskDifferences (alternate, *sibling) + "Proceed with change?")) { // TODO Are dependencies being explicitly removed? // Either we scan context.task for negative IDs "depends:-n" // or we ask deltaAttributes (above) to record dependency // removal. dependencyChainOnModify (alternate, *sibling); context.tdb2.modify (*sibling); ++count; if (alternate.get ("project") != sibling->get ("project")) context.footnote (onProjectChange (alternate, *sibling)); } } } } context.tdb2.commit (); if (context.config.getBoolean ("echo.command")) out << "Modified " << count << " task" << (count == 1 ? ".\n" : "s.\n"); output = out.str (); return 0; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // 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 https://mozilla.org/MPL/2.0/. #include "GeometricFilterMatrix_HGrowing.hpp" #include "dependencies/vectorGraphics/svgDrawer.hpp" namespace aliceVision { namespace matchingImageCollection { bool GeometricFilterMatrix_HGrowing::getMatches(const feature::EImageDescriberType &descType, const IndexT homographyId, matching::IndMatches &matches) const { matches.clear(); if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end()) return false; if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1) return false; matches = _HsAndMatchesPerDesc.at(descType).at(homographyId).second; return !matches.empty(); } std::size_t GeometricFilterMatrix_HGrowing::getNbHomographies(const feature::EImageDescriberType &descType) const { if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end()) return 0; return _HsAndMatchesPerDesc.at(descType).size(); } std::size_t GeometricFilterMatrix_HGrowing::getNbVerifiedMatches(const feature::EImageDescriberType &descType, const IndexT homographyId) const { if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end()) return 0; if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1) return 0; return _HsAndMatchesPerDesc.at(descType).at(homographyId).second.size(); } std::size_t GeometricFilterMatrix_HGrowing::getNbAllVerifiedMatches() const { std::size_t counter = 0; for (const auto & HnMs : _HsAndMatchesPerDesc) { for (const std::pair<Mat3, matching::IndMatches> & HnM : HnMs.second) { counter += HnM.second.size(); } } return counter; } bool growHomography(const std::vector<feature::SIOPointFeature> &featuresI, const std::vector<feature::SIOPointFeature> &featuresJ, const matching::IndMatches &matches, const IndexT &seedMatchId, std::set<IndexT> &planarMatchesIndices, Mat3 &transformation, const GrowParameters& param) { assert(seedMatchId <= matches.size()); planarMatchesIndices.clear(); transformation = Mat3::Identity(); const matching::IndMatch & seedMatch = matches.at(seedMatchId); const feature::SIOPointFeature & seedFeatureI = featuresI.at(seedMatch._i); const feature::SIOPointFeature & seedFeatureJ = featuresJ.at(seedMatch._j); double currTolerance; for (IndexT iRefineStep = 0; iRefineStep < param._nbRefiningIterations; ++iRefineStep) { if (iRefineStep == 0) { computeSimilarity(seedFeatureI, seedFeatureJ, transformation); currTolerance = param._similarityTolerance; } else if (iRefineStep <= 4) { estimateAffinity(featuresI, featuresJ, matches, transformation, planarMatchesIndices); currTolerance = param._affinityTolerance; } else { estimateHomography(featuresI, featuresJ, matches, transformation, planarMatchesIndices); currTolerance = param._homographyTolerance; } findTransformationInliers(featuresI, featuresJ, matches, transformation, currTolerance, planarMatchesIndices); if (planarMatchesIndices.size() < param._minInliersToRefine) return false; // Note: the following statement is present in the MATLAB code but not implemented in YASM // if (planarMatchesIndices.size() >= param._maxFractionPlanarMatches * matches.size()) // break; } return !transformation.isIdentity(); } void filterMatchesByHGrowing(const std::vector<feature::SIOPointFeature>& siofeatures_I, const std::vector<feature::SIOPointFeature>& siofeatures_J, const matching::IndMatches& putativeMatches, std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches, matching::IndMatches& outGeometricInliers, const HGrowingFilteringParam& param) { using namespace aliceVision::feature; using namespace aliceVision::matching; IndMatches remainingMatches = putativeMatches; GeometricFilterMatrix_HGrowing dummy; for(IndexT iH = 0; iH < param._maxNbHomographies; ++iH) { std::set<IndexT> usedMatchesId, bestMatchesId; Mat3 bestHomography; // -- Estimate H using homography-growing approach #pragma omp parallel for // (huge optimization but modify results a little) for(int iMatch = 0; iMatch < remainingMatches.size(); ++iMatch) { // Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20) // each match is used once only per homography estimation (increases computation time) [1st improvement ([F.Srajer, 2016] p. 20) ] if (usedMatchesId.find(iMatch) != usedMatchesId.end()) continue; std::set<IndexT> planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector. Mat3 homography; if (!growHomography(siofeatures_I, siofeatures_J, remainingMatches, iMatch, planarMatchesId, homography, param._growParam)) { continue; } #pragma omp critical usedMatchesId.insert(planarMatchesId.begin(), planarMatchesId.end()); if (planarMatchesId.size() > bestMatchesId.size()) { #pragma omp critical { if(iH == 3) std::cout << "best iMatch" << iMatch << std::endl; bestMatchesId = planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector. bestHomography = homography; } } } // 'iMatch' // -- Refine H using Ceres minimizer refineHomography(siofeatures_I, siofeatures_J, remainingMatches, bestHomography, bestMatchesId, param._growParam._homographyTolerance); // stop when the models get too small if (bestMatchesId.size() < param._minNbMatchesPerH) break; // Store validated results: { IndMatches matches; Mat3 H = bestHomography; for (IndexT id : bestMatchesId) { matches.push_back(remainingMatches.at(id)); } homographiesAndMatches.emplace_back(H, matches); } // -- Update not used matches & Save geometrically verified matches for (IndexT id : bestMatchesId) { outGeometricInliers.push_back(remainingMatches.at(id)); } // update remaining matches (/!\ Keep ordering) std::size_t cpt = 0; for (IndexT id : bestMatchesId) { remainingMatches.erase(remainingMatches.begin() + id - cpt); ++cpt; } // stop when the number of remaining matches is too small if (remainingMatches.size() < param._minNbMatchesPerH) break; } // 'iH' } void drawHomographyMatches(const std::string& outFilename, const sfm::View & viewI, const sfm::View & viewJ, const std::vector<feature::SIOPointFeature>& siofeatures_I, const std::vector<feature::SIOPointFeature>& siofeatures_J, const std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches, const matching::IndMatches& putativeMatches) { const std::vector<std::string> colors{"red", "cyan", "purple", "green", "black", "brown", "blue", "pink", "grey"}; svg::svgDrawer svgStream(viewI.getWidth() + viewJ.getWidth() , std::max(viewI.getHeight(), viewJ.getHeight())); const std::size_t offset{viewI.getWidth()}; svgStream.drawImage(viewI.getImagePath(), viewI.getWidth(), viewI.getHeight()); svgStream.drawImage(viewJ.getImagePath(), viewJ.getWidth(), viewJ.getHeight(), offset); // draw little white dots representing putative matches for (const auto& match : putativeMatches) { const float radius{1.f}; const float strokeSize{2.f}; const feature::SIOPointFeature &fI = siofeatures_I.at(match._i); const feature::SIOPointFeature &fJ = siofeatures_J.at(match._j); const svg::svgStyle style = svg::svgStyle().stroke("white", strokeSize); svgStream.drawCircle(fI.x(), fI.y(), radius, style); svgStream.drawCircle(fJ.x() + offset, fJ.y(), radius, style); } { // for each homography draw the associated matches in a different color std::size_t iH{0}; const float radius{5.f}; const float strokeSize{5.f}; for (const auto &currRes : homographiesAndMatches) { const auto &bestMatchesId = currRes.second; // 0 < iH <= 8: colored; iH > 8 are white (not enough colors) const std::string color = (iH < colors.size()) ? colors.at(iH) : "grey"; for (const auto &match : bestMatchesId) { const feature::SIOPointFeature &fI = siofeatures_I.at(match._i); const feature::SIOPointFeature &fJ = siofeatures_J.at(match._j); const svg::svgStyle style = svg::svgStyle().stroke(color, strokeSize); svgStream.drawCircle(fI.x(), fI.y(), radius, style); svgStream.drawCircle(fJ.x() + offset, fJ.y(), radius, style); } ++iH; } } std::ofstream svgFile(outFilename); if(!svgFile.is_open()) { ALICEVISION_CERR("Unable to open file "+outFilename); return; } svgFile << svgStream.closeSvgFile().str(); if(!svgFile.good()) { ALICEVISION_CERR("Something wrong happened while writing file "+outFilename); return; } svgFile.close(); } } }<commit_msg>[matchingImageCollection] using color const<commit_after>// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // 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 https://mozilla.org/MPL/2.0/. #include <aliceVision/feature/svgVisualization.hpp> #include "GeometricFilterMatrix_HGrowing.hpp" #include "dependencies/vectorGraphics/svgDrawer.hpp" namespace aliceVision { namespace matchingImageCollection { bool GeometricFilterMatrix_HGrowing::getMatches(const feature::EImageDescriberType &descType, const IndexT homographyId, matching::IndMatches &matches) const { matches.clear(); if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end()) return false; if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1) return false; matches = _HsAndMatchesPerDesc.at(descType).at(homographyId).second; return !matches.empty(); } std::size_t GeometricFilterMatrix_HGrowing::getNbHomographies(const feature::EImageDescriberType &descType) const { if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end()) return 0; return _HsAndMatchesPerDesc.at(descType).size(); } std::size_t GeometricFilterMatrix_HGrowing::getNbVerifiedMatches(const feature::EImageDescriberType &descType, const IndexT homographyId) const { if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end()) return 0; if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1) return 0; return _HsAndMatchesPerDesc.at(descType).at(homographyId).second.size(); } std::size_t GeometricFilterMatrix_HGrowing::getNbAllVerifiedMatches() const { std::size_t counter = 0; for (const auto & HnMs : _HsAndMatchesPerDesc) { for (const std::pair<Mat3, matching::IndMatches> & HnM : HnMs.second) { counter += HnM.second.size(); } } return counter; } bool growHomography(const std::vector<feature::SIOPointFeature> &featuresI, const std::vector<feature::SIOPointFeature> &featuresJ, const matching::IndMatches &matches, const IndexT &seedMatchId, std::set<IndexT> &planarMatchesIndices, Mat3 &transformation, const GrowParameters& param) { assert(seedMatchId <= matches.size()); planarMatchesIndices.clear(); transformation = Mat3::Identity(); const matching::IndMatch & seedMatch = matches.at(seedMatchId); const feature::SIOPointFeature & seedFeatureI = featuresI.at(seedMatch._i); const feature::SIOPointFeature & seedFeatureJ = featuresJ.at(seedMatch._j); double currTolerance; for (IndexT iRefineStep = 0; iRefineStep < param._nbRefiningIterations; ++iRefineStep) { if (iRefineStep == 0) { computeSimilarity(seedFeatureI, seedFeatureJ, transformation); currTolerance = param._similarityTolerance; } else if (iRefineStep <= 4) { estimateAffinity(featuresI, featuresJ, matches, transformation, planarMatchesIndices); currTolerance = param._affinityTolerance; } else { estimateHomography(featuresI, featuresJ, matches, transformation, planarMatchesIndices); currTolerance = param._homographyTolerance; } findTransformationInliers(featuresI, featuresJ, matches, transformation, currTolerance, planarMatchesIndices); if (planarMatchesIndices.size() < param._minInliersToRefine) return false; // Note: the following statement is present in the MATLAB code but not implemented in YASM // if (planarMatchesIndices.size() >= param._maxFractionPlanarMatches * matches.size()) // break; } return !transformation.isIdentity(); } void filterMatchesByHGrowing(const std::vector<feature::SIOPointFeature>& siofeatures_I, const std::vector<feature::SIOPointFeature>& siofeatures_J, const matching::IndMatches& putativeMatches, std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches, matching::IndMatches& outGeometricInliers, const HGrowingFilteringParam& param) { using namespace aliceVision::feature; using namespace aliceVision::matching; IndMatches remainingMatches = putativeMatches; GeometricFilterMatrix_HGrowing dummy; for(IndexT iH = 0; iH < param._maxNbHomographies; ++iH) { std::set<IndexT> usedMatchesId, bestMatchesId; Mat3 bestHomography; // -- Estimate H using homography-growing approach #pragma omp parallel for // (huge optimization but modify results a little) for(int iMatch = 0; iMatch < remainingMatches.size(); ++iMatch) { // Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20) // each match is used once only per homography estimation (increases computation time) [1st improvement ([F.Srajer, 2016] p. 20) ] if (usedMatchesId.find(iMatch) != usedMatchesId.end()) continue; std::set<IndexT> planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector. Mat3 homography; if (!growHomography(siofeatures_I, siofeatures_J, remainingMatches, iMatch, planarMatchesId, homography, param._growParam)) { continue; } #pragma omp critical usedMatchesId.insert(planarMatchesId.begin(), planarMatchesId.end()); if (planarMatchesId.size() > bestMatchesId.size()) { #pragma omp critical { if(iH == 3) std::cout << "best iMatch" << iMatch << std::endl; bestMatchesId = planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector. bestHomography = homography; } } } // 'iMatch' // -- Refine H using Ceres minimizer refineHomography(siofeatures_I, siofeatures_J, remainingMatches, bestHomography, bestMatchesId, param._growParam._homographyTolerance); // stop when the models get too small if (bestMatchesId.size() < param._minNbMatchesPerH) break; // Store validated results: { IndMatches matches; Mat3 H = bestHomography; for (IndexT id : bestMatchesId) { matches.push_back(remainingMatches.at(id)); } homographiesAndMatches.emplace_back(H, matches); } // -- Update not used matches & Save geometrically verified matches for (IndexT id : bestMatchesId) { outGeometricInliers.push_back(remainingMatches.at(id)); } // update remaining matches (/!\ Keep ordering) std::size_t cpt = 0; for (IndexT id : bestMatchesId) { remainingMatches.erase(remainingMatches.begin() + id - cpt); ++cpt; } // stop when the number of remaining matches is too small if (remainingMatches.size() < param._minNbMatchesPerH) break; } // 'iH' } void drawHomographyMatches(const std::string& outFilename, const sfm::View & viewI, const sfm::View & viewJ, const std::vector<feature::SIOPointFeature>& siofeatures_I, const std::vector<feature::SIOPointFeature>& siofeatures_J, const std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches, const matching::IndMatches& putativeMatches) { const auto& colors = feature::sixteenColors; svg::svgDrawer svgStream(viewI.getWidth() + viewJ.getWidth() , std::max(viewI.getHeight(), viewJ.getHeight())); const std::size_t offset{viewI.getWidth()}; svgStream.drawImage(viewI.getImagePath(), viewI.getWidth(), viewI.getHeight()); svgStream.drawImage(viewJ.getImagePath(), viewJ.getWidth(), viewJ.getHeight(), offset); // draw little white dots representing putative matches for (const auto& match : putativeMatches) { const float radius{1.f}; const float strokeSize{2.f}; const feature::SIOPointFeature &fI = siofeatures_I.at(match._i); const feature::SIOPointFeature &fJ = siofeatures_J.at(match._j); const svg::svgStyle style = svg::svgStyle().stroke("white", strokeSize); svgStream.drawCircle(fI.x(), fI.y(), radius, style); svgStream.drawCircle(fJ.x() + offset, fJ.y(), radius, style); } { // for each homography draw the associated matches in a different color std::size_t iH{0}; const float radius{5.f}; const float strokeSize{5.f}; for (const auto &currRes : homographiesAndMatches) { const auto &bestMatchesId = currRes.second; // 0 < iH <= 8: colored; iH > 8 are white (not enough colors) const std::string color = (iH < colors.size()) ? colors.at(iH) : "grey"; for (const auto &match : bestMatchesId) { const feature::SIOPointFeature &fI = siofeatures_I.at(match._i); const feature::SIOPointFeature &fJ = siofeatures_J.at(match._j); const svg::svgStyle style = svg::svgStyle().stroke(color, strokeSize); svgStream.drawCircle(fI.x(), fI.y(), radius, style); svgStream.drawCircle(fJ.x() + offset, fJ.y(), radius, style); } ++iH; } } std::ofstream svgFile(outFilename); if(!svgFile.is_open()) { ALICEVISION_CERR("Unable to open file "+outFilename); return; } svgFile << svgStream.closeSvgFile().str(); if(!svgFile.good()) { ALICEVISION_CERR("Something wrong happened while writing file "+outFilename); return; } svgFile.close(); } } }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: bitmapaction.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2005-04-18 09:58:44 $ * * 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 <bitmapaction.hxx> #include <outdevstate.hxx> #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif #ifndef _COM_SUN_STAR_RENDERING_XBITMAP_HPP__ #include <com/sun/star/rendering/XBitmap.hpp> #endif #ifndef _COM_SUN_STAR_RENDERING_REPAINTRESULT_HPP_ #include <com/sun/star/rendering/RepaintResult.hpp> #endif #ifndef _COM_SUN_STAR_RENDERING_XCACHEDPRIMITIVE_HPP_ #include <com/sun/star/rendering/XCachedPrimitive.hpp> #endif #ifndef _SV_BITMAPEX_HXX #include <vcl/bitmapex.hxx> #endif #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #ifndef _VCL_CANVASTOOLS_HXX #include <vcl/canvastools.hxx> #endif #ifndef _CANVAS_CANVASTOOLS_HXX #include <canvas/canvastools.hxx> #endif #ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX #include <basegfx/matrix/b2dhommatrix.hxx> #endif #ifndef _BGFX_VECTOR_B2DSIZE_HXX #include <basegfx/vector/b2dsize.hxx> #endif #ifndef _BGFX_RANGE_B2DRANGE_HXX #include <basegfx/range/b2drange.hxx> #endif #ifndef _BGFX_TOOLS_CANVASTOOLS_HXX #include <basegfx/tools/canvastools.hxx> #endif #include <boost/utility.hpp> #include <mtftools.hxx> using namespace ::com::sun::star; namespace cppcanvas { namespace internal { namespace { class BitmapAction : public Action, private ::boost::noncopyable { public: BitmapAction( const ::BitmapEx&, const ::Point& rDstPoint, const CanvasSharedPtr&, const OutDevState& ); BitmapAction( const ::BitmapEx&, const ::Point& rDstPoint, const ::Size& rDstSize, const CanvasSharedPtr&, const OutDevState& ); virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual sal_Int32 getActionCount() const; private: uno::Reference< rendering::XBitmap > mxBitmap; mutable uno::Reference< rendering::XCachedPrimitive > mxCachedBitmap; mutable ::basegfx::B2DHomMatrix maLastTransformation; CanvasSharedPtr mpCanvas; rendering::RenderState maState; }; BitmapAction::BitmapAction( const ::BitmapEx& rBmpEx, const ::Point& rDstPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) : mxBitmap( ::vcl::unotools::xBitmapFromBitmapEx( rCanvas->getUNOCanvas()->getDevice(), rBmpEx ) ), mxCachedBitmap(), maLastTransformation(), mpCanvas( rCanvas ), maState() { tools::initRenderState(maState,rState); // Setup transformation such that the next render call is // moved rPoint away. ::basegfx::B2DHomMatrix aLocalTransformation; aLocalTransformation.translate( rDstPoint.X(), rDstPoint.Y() ); ::canvas::tools::appendToRenderState( maState, aLocalTransformation ); // correct clip (which is relative to original transform) tools::modifyClip( maState, rState, rCanvas, rDstPoint, NULL ); } BitmapAction::BitmapAction( const ::BitmapEx& rBmpEx, const ::Point& rDstPoint, const ::Size& rDstSize, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) : mxBitmap( ::vcl::unotools::xBitmapFromBitmapEx( rCanvas->getUNOCanvas()->getDevice(), rBmpEx ) ), mxCachedBitmap(), maLastTransformation(), mpCanvas( rCanvas ), maState() { tools::initRenderState(maState,rState); // Setup transformation such that the next render call is // moved rPoint away, and scaled according to the ratio // given by src and dst size. const ::Size aBmpSize( rBmpEx.GetSizePixel() ); ::basegfx::B2DHomMatrix aLocalTransformation; const ::basegfx::B2DSize aScale( static_cast<double>(rDstSize.Width()) / aBmpSize.Width(), static_cast<double>(rDstSize.Height()) / aBmpSize.Height() ); aLocalTransformation.scale( aScale.getX(), aScale.getY() ); aLocalTransformation.translate( rDstPoint.X(), rDstPoint.Y() ); ::canvas::tools::appendToRenderState( maState, aLocalTransformation ); // correct clip (which is relative to original transform) tools::modifyClip( maState, rState, rCanvas, rDstPoint, &aScale ); } bool BitmapAction::render( const ::basegfx::B2DHomMatrix& rTransformation ) const { RTL_LOGFILE_CONTEXT( aLog, "::cppcanvas::internal::BitmapAction::render()" ); RTL_LOGFILE_CONTEXT_TRACE1( aLog, "::cppcanvas::internal::BitmapAction: 0x%X", this ); rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); const rendering::ViewState& rViewState( mpCanvas->getViewState() ); // can we use the cached bitmap? if( mxCachedBitmap.is() && maLastTransformation == rTransformation ) { if( mxCachedBitmap->redraw( rViewState ) == rendering::RepaintResult::REDRAWN ) { // cached repaint succeeded, done. return true; } } maLastTransformation = rTransformation; mxCachedBitmap = mpCanvas->getUNOCanvas()->drawBitmap( mxBitmap, rViewState, aLocalState ); return true; } bool BitmapAction::render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // bitmap only contains a single action, fail if subset // requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return false; return render( rTransformation ); } ::basegfx::B2DRange BitmapAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const { rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); const geometry::IntegerSize2D aSize( mxBitmap->getSize() ); return tools::calcDevicePixelBounds( ::basegfx::B2DRange( 0,0, aSize.Width, aSize.Height ), mpCanvas->getViewState(), aLocalState ); } ::basegfx::B2DRange BitmapAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // bitmap only contains a single action, empty bounds // if subset requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return ::basegfx::B2DRange(); return getBounds( rTransformation ); } sal_Int32 BitmapAction::getActionCount() const { return 1; } } ActionSharedPtr BitmapActionFactory::createBitmapAction( const ::BitmapEx& rBmpEx, const ::Point& rDstPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) { return ActionSharedPtr( new BitmapAction(rBmpEx, rDstPoint, rCanvas, rState ) ); } ActionSharedPtr BitmapActionFactory::createBitmapAction( const ::BitmapEx& rBmpEx, const ::Point& rDstPoint, const ::Size& rDstSize, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) { return ActionSharedPtr( new BitmapAction(rBmpEx, rDstPoint, rDstSize, rCanvas, rState ) ); } } } <commit_msg>INTEGRATION: CWS ooo19126 (1.6.14); FILE MERGED 2005/09/05 18:40:57 rt 1.6.14.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bitmapaction.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 08:17:43 $ * * 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 * ************************************************************************/ #include <bitmapaction.hxx> #include <outdevstate.hxx> #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif #ifndef _COM_SUN_STAR_RENDERING_XBITMAP_HPP__ #include <com/sun/star/rendering/XBitmap.hpp> #endif #ifndef _COM_SUN_STAR_RENDERING_REPAINTRESULT_HPP_ #include <com/sun/star/rendering/RepaintResult.hpp> #endif #ifndef _COM_SUN_STAR_RENDERING_XCACHEDPRIMITIVE_HPP_ #include <com/sun/star/rendering/XCachedPrimitive.hpp> #endif #ifndef _SV_BITMAPEX_HXX #include <vcl/bitmapex.hxx> #endif #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #ifndef _VCL_CANVASTOOLS_HXX #include <vcl/canvastools.hxx> #endif #ifndef _CANVAS_CANVASTOOLS_HXX #include <canvas/canvastools.hxx> #endif #ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX #include <basegfx/matrix/b2dhommatrix.hxx> #endif #ifndef _BGFX_VECTOR_B2DSIZE_HXX #include <basegfx/vector/b2dsize.hxx> #endif #ifndef _BGFX_RANGE_B2DRANGE_HXX #include <basegfx/range/b2drange.hxx> #endif #ifndef _BGFX_TOOLS_CANVASTOOLS_HXX #include <basegfx/tools/canvastools.hxx> #endif #include <boost/utility.hpp> #include <mtftools.hxx> using namespace ::com::sun::star; namespace cppcanvas { namespace internal { namespace { class BitmapAction : public Action, private ::boost::noncopyable { public: BitmapAction( const ::BitmapEx&, const ::Point& rDstPoint, const CanvasSharedPtr&, const OutDevState& ); BitmapAction( const ::BitmapEx&, const ::Point& rDstPoint, const ::Size& rDstSize, const CanvasSharedPtr&, const OutDevState& ); virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual sal_Int32 getActionCount() const; private: uno::Reference< rendering::XBitmap > mxBitmap; mutable uno::Reference< rendering::XCachedPrimitive > mxCachedBitmap; mutable ::basegfx::B2DHomMatrix maLastTransformation; CanvasSharedPtr mpCanvas; rendering::RenderState maState; }; BitmapAction::BitmapAction( const ::BitmapEx& rBmpEx, const ::Point& rDstPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) : mxBitmap( ::vcl::unotools::xBitmapFromBitmapEx( rCanvas->getUNOCanvas()->getDevice(), rBmpEx ) ), mxCachedBitmap(), maLastTransformation(), mpCanvas( rCanvas ), maState() { tools::initRenderState(maState,rState); // Setup transformation such that the next render call is // moved rPoint away. ::basegfx::B2DHomMatrix aLocalTransformation; aLocalTransformation.translate( rDstPoint.X(), rDstPoint.Y() ); ::canvas::tools::appendToRenderState( maState, aLocalTransformation ); // correct clip (which is relative to original transform) tools::modifyClip( maState, rState, rCanvas, rDstPoint, NULL ); } BitmapAction::BitmapAction( const ::BitmapEx& rBmpEx, const ::Point& rDstPoint, const ::Size& rDstSize, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) : mxBitmap( ::vcl::unotools::xBitmapFromBitmapEx( rCanvas->getUNOCanvas()->getDevice(), rBmpEx ) ), mxCachedBitmap(), maLastTransformation(), mpCanvas( rCanvas ), maState() { tools::initRenderState(maState,rState); // Setup transformation such that the next render call is // moved rPoint away, and scaled according to the ratio // given by src and dst size. const ::Size aBmpSize( rBmpEx.GetSizePixel() ); ::basegfx::B2DHomMatrix aLocalTransformation; const ::basegfx::B2DSize aScale( static_cast<double>(rDstSize.Width()) / aBmpSize.Width(), static_cast<double>(rDstSize.Height()) / aBmpSize.Height() ); aLocalTransformation.scale( aScale.getX(), aScale.getY() ); aLocalTransformation.translate( rDstPoint.X(), rDstPoint.Y() ); ::canvas::tools::appendToRenderState( maState, aLocalTransformation ); // correct clip (which is relative to original transform) tools::modifyClip( maState, rState, rCanvas, rDstPoint, &aScale ); } bool BitmapAction::render( const ::basegfx::B2DHomMatrix& rTransformation ) const { RTL_LOGFILE_CONTEXT( aLog, "::cppcanvas::internal::BitmapAction::render()" ); RTL_LOGFILE_CONTEXT_TRACE1( aLog, "::cppcanvas::internal::BitmapAction: 0x%X", this ); rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); const rendering::ViewState& rViewState( mpCanvas->getViewState() ); // can we use the cached bitmap? if( mxCachedBitmap.is() && maLastTransformation == rTransformation ) { if( mxCachedBitmap->redraw( rViewState ) == rendering::RepaintResult::REDRAWN ) { // cached repaint succeeded, done. return true; } } maLastTransformation = rTransformation; mxCachedBitmap = mpCanvas->getUNOCanvas()->drawBitmap( mxBitmap, rViewState, aLocalState ); return true; } bool BitmapAction::render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // bitmap only contains a single action, fail if subset // requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return false; return render( rTransformation ); } ::basegfx::B2DRange BitmapAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const { rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); const geometry::IntegerSize2D aSize( mxBitmap->getSize() ); return tools::calcDevicePixelBounds( ::basegfx::B2DRange( 0,0, aSize.Width, aSize.Height ), mpCanvas->getViewState(), aLocalState ); } ::basegfx::B2DRange BitmapAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // bitmap only contains a single action, empty bounds // if subset requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return ::basegfx::B2DRange(); return getBounds( rTransformation ); } sal_Int32 BitmapAction::getActionCount() const { return 1; } } ActionSharedPtr BitmapActionFactory::createBitmapAction( const ::BitmapEx& rBmpEx, const ::Point& rDstPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) { return ActionSharedPtr( new BitmapAction(rBmpEx, rDstPoint, rCanvas, rState ) ); } ActionSharedPtr BitmapActionFactory::createBitmapAction( const ::BitmapEx& rBmpEx, const ::Point& rDstPoint, const ::Size& rDstSize, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) { return ActionSharedPtr( new BitmapAction(rBmpEx, rDstPoint, rDstSize, rCanvas, rState ) ); } } } <|endoftext|>
<commit_before>#ifndef VG_MAPPER_HPP_INCLUDED #define VG_MAPPER_HPP_INCLUDED #include <iostream> #include <map> #include <chrono> #include <ctime> #include "omp.h" #include "xg.hpp" #include "alignment.hpp" #include "path.hpp" #include "position.hpp" #include "json2pb.h" #include "graph.hpp" #include "gcsa/internal.h" #include "xg_position.hpp" #include "utility.hpp" namespace vg { using namespace sdsl; class Packer { public: Packer(void); Packer(xg::XG* xidx, size_t bin_size); ~Packer(void); xg::XG* xgidx; void merge_from_files(const vector<string>& file_names); void merge_from_dynamic(vector<Packer*>& packers); void load_from_file(const string& file_name); void save_to_file(const string& file_name); void load(istream& in); size_t serialize(std::ostream& out, sdsl::structure_tree_node* s = NULL, std::string name = ""); void make_compact(void); void make_dynamic(void); void add(const Alignment& aln, bool record_edits = true); size_t graph_length(void) const; size_t position_in_basis(const Position& pos) const; string pos_key(size_t i) const; string edit_value(const Edit& edit, bool revcomp) const; vector<Edit> edits_at_position(size_t i) const; size_t coverage_at_position(size_t i) const; void collect_coverage(const Packer& c); ostream& as_table(ostream& out, bool show_edits = true); ostream& show_structure(ostream& out); // debugging void write_edits(vector<ofstream*>& out) const; // for merge void write_edits(ostream& out, size_t bin) const; // for merge size_t get_bin_size(void) const; size_t get_n_bins(void) const; bool is_dynamic(void); private: void ensure_edit_tmpfiles_open(void); void close_edit_tmpfiles(void); void remove_edit_tmpfiles(void); bool is_compacted; // dynamic model gcsa::CounterArray coverage_dynamic; vector<string> edit_tmpfile_names; vector<ofstream*> tmpfstreams; // which bin should we use size_t bin_for_position(size_t i) const; size_t n_bins = 1; size_t bin_size = 0; size_t edit_length; size_t edit_count; dac_vector<> coverage_civ; // graph coverage (compacted coverage_dynamic) // vector<csa_sada<enc_vector<>, 32, 32, sa_order_sa_sampling<>, isa_sampling<>, succinct_byte_alphabet<> > > edit_csas; // make separators that are somewhat unusual, as we escape these char delim1 = '\xff'; char delim2 = '\xfe'; // double the delimiter in the string string escape_delim(const string& s, char d) const; string escape_delims(const string& s) const; // take each double delimiter back to a single string unescape_delim(const string& s, char d) const; string unescape_delims(const string& s) const; }; // for making a combined matrix output and maybe doing other fun operations class Packers : public vector<Packer> { void load(const vector<string>& file_names); ostream& as_table(ostream& out); }; } #endif <commit_msg>Don't leave important packer fields uninitialized<commit_after>#ifndef VG_MAPPER_HPP_INCLUDED #define VG_MAPPER_HPP_INCLUDED #include <iostream> #include <map> #include <chrono> #include <ctime> #include "omp.h" #include "xg.hpp" #include "alignment.hpp" #include "path.hpp" #include "position.hpp" #include "json2pb.h" #include "graph.hpp" #include "gcsa/internal.h" #include "xg_position.hpp" #include "utility.hpp" namespace vg { using namespace sdsl; class Packer { public: Packer(void); Packer(xg::XG* xidx, size_t bin_size); ~Packer(void); xg::XG* xgidx; void merge_from_files(const vector<string>& file_names); void merge_from_dynamic(vector<Packer*>& packers); void load_from_file(const string& file_name); void save_to_file(const string& file_name); void load(istream& in); size_t serialize(std::ostream& out, sdsl::structure_tree_node* s = NULL, std::string name = ""); void make_compact(void); void make_dynamic(void); void add(const Alignment& aln, bool record_edits = true); size_t graph_length(void) const; size_t position_in_basis(const Position& pos) const; string pos_key(size_t i) const; string edit_value(const Edit& edit, bool revcomp) const; vector<Edit> edits_at_position(size_t i) const; size_t coverage_at_position(size_t i) const; void collect_coverage(const Packer& c); ostream& as_table(ostream& out, bool show_edits = true); ostream& show_structure(ostream& out); // debugging void write_edits(vector<ofstream*>& out) const; // for merge void write_edits(ostream& out, size_t bin) const; // for merge size_t get_bin_size(void) const; size_t get_n_bins(void) const; bool is_dynamic(void); private: void ensure_edit_tmpfiles_open(void); void close_edit_tmpfiles(void); void remove_edit_tmpfiles(void); bool is_compacted = false; // dynamic model gcsa::CounterArray coverage_dynamic; vector<string> edit_tmpfile_names; vector<ofstream*> tmpfstreams; // which bin should we use size_t bin_for_position(size_t i) const; size_t n_bins = 1; size_t bin_size = 0; size_t edit_length = 0; size_t edit_count = 0; dac_vector<> coverage_civ; // graph coverage (compacted coverage_dynamic) // vector<csa_sada<enc_vector<>, 32, 32, sa_order_sa_sampling<>, isa_sampling<>, succinct_byte_alphabet<> > > edit_csas; // make separators that are somewhat unusual, as we escape these char delim1 = '\xff'; char delim2 = '\xfe'; // double the delimiter in the string string escape_delim(const string& s, char d) const; string escape_delims(const string& s) const; // take each double delimiter back to a single string unescape_delim(const string& s, char d) const; string unescape_delims(const string& s) const; }; // for making a combined matrix output and maybe doing other fun operations class Packers : public vector<Packer> { void load(const vector<string>& file_names); ostream& as_table(ostream& out); }; } #endif <|endoftext|>
<commit_before>#include <Arduino.h> #include <IRremote.h> #include <IRremoteInt.h> #include "MagicRemoteIrCommunication.h" MagicRemoteIrCommunication::MagicRemoteIrCommunication() { timeLastSend = 0; } void MagicRemoteIrCommunication::sendColorCode(byte colorCode) { timeLastSend = millis(); irSendColorCode(colorCode); } void MagicRemoteIrCommunication::resendColorCode(int delay) { if(millisPassed(delay)) { irSendColorCode(colorCode); } } void MagicRemoteIrCommunication::irSendColorCode(byte colorCode) { if(colorCode != 0) { irsend.sendNEC(createNecCommand(rgbLedBulbAddress, colorCode), NEC_BITS); } } long MagicRemoteIrCommunication::createNecCommand(byte address, byte command) { long result = address; result <<= 8; result |= invertByte(address); result <<= 8; result |= command; result <<= 8; result |= invertByte(command); return result; } byte MagicRemoteIrCommunication::invertByte(byte b) { return b ^ 0xFF; } boolean MagicRemoteIrCommunication::millisPassed(int delay) { unsigned long now = millis(); if(now < timeLastSend) // overflow occured { timeLastSend = 0; } if(now > timeLastSend + delay) { timeLastSend = now; return true; } return false; } <commit_msg>Removed unnecessary includes<commit_after>#include "MagicRemoteIrCommunication.h" MagicRemoteIrCommunication::MagicRemoteIrCommunication() { timeLastSend = 0; } void MagicRemoteIrCommunication::sendColorCode(byte colorCode) { timeLastSend = millis(); irSendColorCode(colorCode); } void MagicRemoteIrCommunication::resendColorCode(int delay) { if(millisPassed(delay)) { irSendColorCode(colorCode); } } void MagicRemoteIrCommunication::irSendColorCode(byte colorCode) { if(colorCode != 0) { irsend.sendNEC(createNecCommand(rgbLedBulbAddress, colorCode), NEC_BITS); } } long MagicRemoteIrCommunication::createNecCommand(byte address, byte command) { long result = address; result <<= 8; result |= invertByte(address); result <<= 8; result |= command; result <<= 8; result |= invertByte(command); return result; } byte MagicRemoteIrCommunication::invertByte(byte b) { return b ^ 0xFF; } boolean MagicRemoteIrCommunication::millisPassed(int delay) { unsigned long now = millis(); if(now < timeLastSend) // overflow occured { timeLastSend = 0; } if(now > timeLastSend + delay) { timeLastSend = now; return true; } return false; } <|endoftext|>
<commit_before>#ifndef _BAYES_FILTER_EXCEPTION #define _BAYES_FILTER_EXCEPTION /* * Bayes++ the Bayesian Filtering Library * Copyright (c) 2004 Michael Stevens * See accompanying Bayes++.html for terms and conditions of use. * * $Header$ * $NoKeywords: $ */ /* * Exception types: Exception heirarchy for Bayesian filtering */ // Common headers required for declerations #include <exception> /* Filter namespace */ namespace Bayesian_filter { class Filter_exception : virtual public std::exception /* * Base class for all exception produced by filter heirachy */ { public: const char *what() const throw() { return error_description; } protected: Filter_exception (const char* description) { error_description = description; }; private: const char* error_description; }; class Logic_exception : virtual public Filter_exception /* * Logic Exception */ { public: Logic_exception (const char* description) : Filter_exception (description) {}; }; class Numeric_exception : virtual public Filter_exception /* * Numeric Exception */ { public: Numeric_exception (const char* description) : Filter_exception (description) {}; }; }//namespace #endif <commit_msg>MIINOR remove trailing ;<commit_after>#ifndef _BAYES_FILTER_EXCEPTION #define _BAYES_FILTER_EXCEPTION /* * Bayes++ the Bayesian Filtering Library * Copyright (c) 2004 Michael Stevens * See accompanying Bayes++.html for terms and conditions of use. * * $Header$ * $NoKeywords: $ */ /* * Exception types: Exception heirarchy for Bayesian filtering */ // Common headers required for declerations #include <exception> /* Filter namespace */ namespace Bayesian_filter { class Filter_exception : virtual public std::exception /* * Base class for all exception produced by filter heirachy */ { public: const char *what() const throw() { return error_description; } protected: Filter_exception (const char* description) { error_description = description; } private: const char* error_description; }; class Logic_exception : virtual public Filter_exception /* * Logic Exception */ { public: Logic_exception (const char* description) : Filter_exception (description) {} }; class Numeric_exception : virtual public Filter_exception /* * Numeric Exception */ { public: Numeric_exception (const char* description) : Filter_exception (description) {} }; }//namespace #endif <|endoftext|>
<commit_before>#ifndef NANOCV_THREAD_LOOP_H #define NANOCV_THREAD_LOOP_H #include "thread_pool.h" namespace ncv { /// /// \brief split a loop computation of the given size using a thread pool /// template < typename tsize, class toperator > void thread_loop(tsize N, toperator op, thread_pool_t& pool) { const tsize n_tasks = static_cast<tsize>(pool.n_workers()); const tsize task_size = N / n_tasks + 1; for (tsize t = 0; t < n_tasks; t ++) { pool.enqueue([=,&op]() { for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++) { op(i); } }); } pool.wait(); } /// /// \brief split a loop computation of the given size using multiple threads /// template < typename tsize, class toperator > void thread_loop(tsize N, toperator op, tsize nthreads = tsize(0)) { thread_pool_t pool(nthreads); thread_loop(N, op, pool); } /// /// \brief split a loop computation of the given size using a thread pool and cumulate partial results /// template < typename tdata, typename tsize, class toperator_init, class toperator, class toperator_cumulate > void thread_loop_cumulate( tsize N, toperator_init op_init, toperator op, toperator_cumulate op_cumulate, thread_pool_t& pool) { const tsize n_tasks = static_cast<tsize>(pool.n_workers()); const tsize task_size = N / n_tasks + 1; std::vector<tdata> data(n_tasks); for (tsize t = 0; t < n_tasks; t ++) { op_init(data[t]); } for (tsize t = 0; t < n_tasks; t ++) { pool.enqueue([=,&data,&op]() { for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++) { op(i, data[t]); } }); } pool.wait(); for (tsize t = 0; t < n_tasks; t ++) { op_cumulate(data[t]); } } /// /// \brief split a loop computation of the given size using multiple threads and cumulate partial results /// template < typename tdata, typename tsize, class toperator_init, class toperator, class toperator_cumulate > void thread_loop_cumulate( tsize N, toperator_init op_init, toperator op, toperator_cumulate op_cumulate, tsize nthreads = tsize(0)) { thread_pool_t pool(nthreads); thread_loop_cumulate<tdata, tsize, toperator_init, toperator, toperator_cumulate>(N, op_init, op, op_cumulate, pool); } } #endif // NANOCV_THREAD_LOOP_H <commit_msg>refactor accumulator<commit_after>#ifndef NANOCV_THREAD_LOOP_H #define NANOCV_THREAD_LOOP_H #include "thread_pool.h" namespace ncv { /// /// \brief split a loop computation of the given size using a thread pool /// template < typename tsize, class toperator > void thread_loopi(tsize N, toperator op, thread_pool_t& pool) { const tsize n_tasks = static_cast<tsize>(pool.n_workers()); const tsize task_size = N / n_tasks + 1; for (tsize t = 0; t < n_tasks; t ++) { pool.enqueue([=,&op]() { for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++) { op(i); } }); } pool.wait(); } /// /// \brief split a loop computation of the given size using a thread pool /// template < typename tsize, class toperator > void thread_loopit(tsize N, toperator op, thread_pool_t& pool) { const tsize n_tasks = static_cast<tsize>(pool.n_workers()); const tsize task_size = N / n_tasks + 1; for (tsize t = 0; t < n_tasks; t ++) { pool.enqueue([=,&op]() { for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++) { op(i, t); } }); } pool.wait(); } /// /// \brief split a loop computation of the given size using multiple threads /// template < typename tsize, class toperator > void thread_loopi(tsize N, toperator op, tsize nthreads = tsize(0)) { thread_pool_t pool(nthreads); thread_loopi(N, op, pool); } /// /// \brief split a loop computation of the given size using multiple threads /// template < typename tsize, class toperator > void thread_loopit(tsize N, toperator op, tsize nthreads = tsize(0)) { thread_pool_t pool(nthreads); thread_loopit(N, op, pool); } } #endif // NANOCV_THREAD_LOOP_H <|endoftext|>
<commit_before>#include "jnif.h" #include <erl_driver.h> static jclass NIF_class; static jmethodID m_NIF__get_erts_version; static jmethodID m_NIF__get_otp_release; static jmethodID m_NIF__get_num_async_threads; static jmethodID m_NIF__get_num_scheduler_threads; static JavaVM *jvm; void enif_system_info(ErlNifSysInfo* info, size_t si_size) { JNIEnv *je; if (jvm->AttachCurrentThreadAsDaemon((void**)&je, NULL) == JNI_OK) { info->driver_major_version = ERL_DRV_EXTENDED_MAJOR_VERSION; info->driver_minor_version = ERL_DRV_EXTENDED_MINOR_VERSION; jstring erts_version = (jstring) je->CallStaticObjectMethod(NIF_class, m_NIF__get_erts_version); if (erts_version == NULL) { info->erts_version = NULL; } else { info->erts_version = strdup(je->GetStringUTFChars(erts_version, NULL)); } jstring otp_release = (jstring) je->CallStaticObjectMethod(NIF_class, m_NIF__get_otp_release); if (otp_release == NULL) { info->otp_release = NULL; } else { info->otp_release = strdup(je->GetStringUTFChars(otp_release, NULL)); } info->thread_support = 1; info->smp_support = 1; info->async_threads = je->CallStaticIntMethod(NIF_class, m_NIF__get_num_async_threads); info->scheduler_threads = je->CallStaticIntMethod(NIF_class, m_NIF__get_num_scheduler_threads); info->nif_major_version = ERL_NIF_MAJOR_VERSION; info->nif_major_version = ERL_NIF_MINOR_VERSION; } } void initialize_jnif_sys(JavaVM* vm, JNIEnv *je) { jvm = vm; NIF_class = je->FindClass("erjang/NIF"); NIF_class = (jclass) je->NewGlobalRef(NIF_class); m_NIF__get_erts_version = je->GetStaticMethodID(NIF_class, "get_erts_version", "()Ljava/lang/String;"); m_NIF__get_otp_release = je->GetStaticMethodID(NIF_class, "get_otp_release", "()Ljava/lang/String;"); m_NIF__get_num_async_threads = je->GetStaticMethodID(NIF_class, "get_num_async_threads", "()I"); m_NIF__get_num_scheduler_threads = je->GetStaticMethodID(NIF_class, "get_num_scheduler_threads", "()I"); } <commit_msg>Yield meaningful result for old NIF callers<commit_after>#include "jnif.h" #include <erl_driver.h> static jclass NIF_class; static jmethodID m_NIF__get_erts_version; static jmethodID m_NIF__get_otp_release; static jmethodID m_NIF__get_num_async_threads; static jmethodID m_NIF__get_num_scheduler_threads; static JavaVM *jvm; void enif_system_info(ErlNifSysInfo* info, size_t si_size) { if (sizeof(*info) >= si_size) { memset(info, 0, si_size); info->driver_major_version = ERL_DRV_EXTENDED_MAJOR_VERSION; info->driver_minor_version = ERL_DRV_EXTENDED_MINOR_VERSION; return; } JNIEnv *je; if (jvm->AttachCurrentThreadAsDaemon((void**)&je, NULL) == JNI_OK) { info->driver_major_version = ERL_DRV_EXTENDED_MAJOR_VERSION; info->driver_minor_version = ERL_DRV_EXTENDED_MINOR_VERSION; jstring erts_version = (jstring) je->CallStaticObjectMethod(NIF_class, m_NIF__get_erts_version); if (erts_version == NULL) { info->erts_version = NULL; } else { info->erts_version = strdup(je->GetStringUTFChars(erts_version, NULL)); } jstring otp_release = (jstring) je->CallStaticObjectMethod(NIF_class, m_NIF__get_otp_release); if (otp_release == NULL) { info->otp_release = NULL; } else { info->otp_release = strdup(je->GetStringUTFChars(otp_release, NULL)); } info->thread_support = 1; info->smp_support = 1; info->async_threads = je->CallStaticIntMethod(NIF_class, m_NIF__get_num_async_threads); info->scheduler_threads = je->CallStaticIntMethod(NIF_class, m_NIF__get_num_scheduler_threads); info->nif_major_version = ERL_NIF_MAJOR_VERSION; info->nif_major_version = ERL_NIF_MINOR_VERSION; } } void initialize_jnif_sys(JavaVM* vm, JNIEnv *je) { jvm = vm; NIF_class = je->FindClass("erjang/NIF"); NIF_class = (jclass) je->NewGlobalRef(NIF_class); m_NIF__get_erts_version = je->GetStaticMethodID(NIF_class, "get_erts_version", "()Ljava/lang/String;"); m_NIF__get_otp_release = je->GetStaticMethodID(NIF_class, "get_otp_release", "()Ljava/lang/String;"); m_NIF__get_num_async_threads = je->GetStaticMethodID(NIF_class, "get_num_async_threads", "()I"); m_NIF__get_num_scheduler_threads = je->GetStaticMethodID(NIF_class, "get_num_scheduler_threads", "()I"); } <|endoftext|>
<commit_before>#include "parser.hpp" ////////////// // Includes // #include <istream> #include <string> #include <vector> #include <tuple> #include "json.hpp" ////////// // Code // // Creating a parse exception. ParseException::ParseException(std::string type) { this->type = type; } // Returning a string to refer to this exception. const char* ParseException::what() const throw() { return ("Failed to parse a " + this->type + " piece of JSON.").c_str(); } // Checking if a given string is whitespace. bool isWhitespace(char c) { switch (c) { case ' ': case '\t': case '\r': case '\n': return true; default: break; } return false; } // Returns the strings before and after a delimiter character. std::tuple<std::string, std::string> untilChar(const std::string& str, char delim) { int n; for (n = 0; n < str.size(); n++) if (str[n] == delim) break; if (n + 1 >= str.size()) return std::make_tuple(str, ""); return std::make_tuple(str.substr(0, n), str.substr(n + 1, str.size() - 1)); } // Checking if a character is a quote. bool isQuote(char c) { return c == '"' || c == '\''; } // Stripping the whitespace out of a string. Unless it's within a pair of quote // characters. Then it doesn't. :) std::string stripWhitespace(const std::string& str) { std::string ret; bool mode = true; char quoteChar = '\0'; for (auto it = str.begin(); it != str.end(); it++) { if (isQuote(*it) && (quoteChar == '\0' || *it == quoteChar)) { mode = !mode; quoteChar = *it; } if (!mode) ret.push_back(*it); else if (mode && !isWhitespace(*it)) ret.push_back(*it); } return ret; } // Trying to specifically parse out a JSON object. JValue parseJSONObject(const std::string& str) { return JValue(); } // Trying to specifically parse out a JSON array. JValue parseJSONArray(const std::string& str) { if (str[0] == '[' && str[str.size() - 1] == ']') { std::string useStr = str.substr(1, str.size() - 2); if (useStr.compare("") == 0) return JValue(); std::vector<JValue> jValues; std::tuple<std::string, std::string> tup; for (tup = untilChar(useStr, ','); std::get<0>(tup).compare("") != 0; tup = untilChar(std::get<1>(tup), ',')) jValues.push_back(parseJSON(stripWhitespace(std::get<0>(tup)))); return JValue(jValues); } throw ParseException("parseJSONArray"); } // Trying to specifically parse out a JSON number. JValue parseJSONNumber(const std::string& str) { try { return JValue(stod(str)); } catch (const std::invalid_argument& ia) { throw ParseException("parseJSONNumber"); } } // Trying to specifically parse out a JSON string. JValue parseJSONString(const std::string& str) { if (isQuote(*str.begin()) && isQuote(*(str.end() - 1))) { char fq = *str.begin(); bool ok = false; std::string accum; for (auto it = str.begin() + 1; it != str.end() - 1; it++) { if (!ok && *it == fq) return JValue(); else if ((*it) == '\\') ok = true; else ok = false; accum.push_back(*it); } return JValue(accum); } throw ParseException("parseJSONString"); } // Trying to specifically parse out a JSON boolean. JValue parseJSONBool(const std::string& str) { if (str.compare("true") == 0) return JValue(true); else if (str.compare("false") == 0) return JValue(false); throw ParseException("parseJSONBool"); } // Trying to specifically parse out the null JSON value. JValue parseJSONNull(const std::string& str) { if (str.compare("null") == 0) return JValue(); throw ParseException("parseJSONNull"); } // Parsing out a block of JSON from a string. JValue parseJSON(const std::string& str) throw (ParseException) { std::vector<JValue (*)(const std::string&)> fns; fns.push_back(&parseJSONObject); fns.push_back(&parseJSONArray); fns.push_back(&parseJSONNumber); fns.push_back(&parseJSONString); fns.push_back(&parseJSONBool); fns.push_back(&parseJSONNull); JValue val; for (auto it = fns.begin(); it != fns.end(); it++) { val = (*it)(str); if (!val.isNull()) return val; } throw ParseException("parseJSON"); } // Parsing out a block of JSON from an istream. JValue parseJSON(std::istream& stream) throw(ParseException) { std::string line, all; while (!stream.eof()) { std::getline(stream, line); all += line; } return parseJSON(all); } <commit_msg>Stopped it from failing all of everything.<commit_after>#include "parser.hpp" ////////////// // Includes // #include <istream> #include <string> #include <vector> #include <tuple> #include "json.hpp" ////////// // Code // // Creating a parse exception. ParseException::ParseException(std::string type) { this->type = type; } // Returning a string to refer to this exception. const char* ParseException::what() const throw() { return ("Failed to parse a " + this->type + " piece of JSON.").c_str(); } // Checking if a given string is whitespace. bool isWhitespace(char c) { switch (c) { case ' ': case '\t': case '\r': case '\n': return true; default: break; } return false; } // Returns the strings before and after a delimiter character. std::tuple<std::string, std::string> untilChar(const std::string& str, char delim) { int n; for (n = 0; n < str.size(); n++) if (str[n] == delim) break; if (n + 1 >= str.size()) return std::make_tuple(str, ""); return std::make_tuple(str.substr(0, n), str.substr(n + 1, str.size() - 1)); } // Checking if a character is a quote. bool isQuote(char c) { return c == '"' || c == '\''; } // Stripping the whitespace out of a string. Unless it's within a pair of quote // characters. Then it doesn't. :) std::string stripWhitespace(const std::string& str) { std::string ret; bool mode = true; char quoteChar = '\0'; for (auto it = str.begin(); it != str.end(); it++) { if (isQuote(*it) && (quoteChar == '\0' || *it == quoteChar)) { mode = !mode; quoteChar = *it; } if (!mode) ret.push_back(*it); else if (mode && !isWhitespace(*it)) ret.push_back(*it); } return ret; } // Trying to specifically parse out a JSON object. JValue parseJSONObject(const std::string& str) throw(ParseException) { throw ParseException("JObject"); } // Trying to specifically parse out a JSON array. JValue parseJSONArray(const std::string& str) throw(ParseException) { if (str[0] == '[' && str[str.size() - 1] == ']') { std::string useStr = str.substr(1, str.size() - 2); if (useStr.compare("") == 0) return JValue(); std::vector<JValue> jValues; std::tuple<std::string, std::string> tup; for (tup = untilChar(useStr, ','); std::get<0>(tup).compare("") != 0; tup = untilChar(std::get<1>(tup), ',')) jValues.push_back(parseJSON(stripWhitespace(std::get<0>(tup)))); return JValue(jValues); } throw ParseException("parseJSONArray"); } // Trying to specifically parse out a JSON number. JValue parseJSONNumber(const std::string& str) throw(ParseException) { try { return JValue(stod(str)); } catch (const std::invalid_argument& ia) { throw ParseException("parseJSONNumber"); } } // Trying to specifically parse out a JSON string. JValue parseJSONString(const std::string& str) throw(ParseException) { if (isQuote(*str.begin()) && isQuote(*(str.end() - 1))) { char fq = *str.begin(); bool ok = false; std::string accum; for (auto it = str.begin() + 1; it != str.end() - 1; it++) { if (!ok && *it == fq) return JValue(); else if ((*it) == '\\') ok = true; else ok = false; accum.push_back(*it); } return JValue(accum); } throw ParseException("parseJSONString"); } // Trying to specifically parse out a JSON boolean. JValue parseJSONBool(const std::string& str) throw(ParseException) { if (str.compare("true") == 0) return JValue(true); else if (str.compare("false") == 0) return JValue(false); throw ParseException("parseJSONBool"); } // Trying to specifically parse out the null JSON value. JValue parseJSONNull(const std::string& str) throw(ParseException) { if (str.compare("null") == 0) return JValue(); throw ParseException("parseJSONNull"); } #include <iostream> // Parsing out a block of JSON from a string. JValue parseJSON(const std::string& str) throw(ParseException) { std::vector<JValue (*)(const std::string&)> fns; fns.push_back(&parseJSONObject); fns.push_back(&parseJSONArray); fns.push_back(&parseJSONNumber); fns.push_back(&parseJSONString); fns.push_back(&parseJSONBool); fns.push_back(&parseJSONNull); JValue val; for (auto it = fns.begin(); it != fns.end(); it++) { try { return (*it)(str); } catch (const ParseException& e) { } } throw ParseException("parseJSON"); } // Parsing out a block of JSON from an istream. JValue parseJSON(std::istream& stream) throw(ParseException) { std::string line, all; while (!stream.eof()) { std::getline(stream, line); all += line; } return parseJSON(all); } <|endoftext|>
<commit_before>/* * The main spawn screen */ #include "spawnDialog_defines.hpp" class spawnDialog { idd = spawn_dialog; movingEnable = false; enableSimulation = true; onLoad = "uiNamespace setVariable [""UK_SpawnDialog"", _this select 0]"; class Controls { class spawnScreen: RscFrame { idc = spawn_screen; text = "Spawn Selection"; #define screenW (0.7 * 3/4) #define screenH 0.5 #define screenX CENTER(1, screenW) #define screenY CENTER(1, screenH) w = screenW; h = screenH; x = screenX; y = screenY; }; class randomSpawnButton: RscButton { idc = random_spawn_button; text = "Random"; #define randomButtonW scaleFix(0.15) #define bottomButtonH (0.055) #define bottomButtonY ((screenY + screenH) - (bottomButtonH + edgeOffsetY)) #define randomButtonX ((screenX + screenW) - randomButtonW - edgeOffsetX) x = randomButtonX; y = bottomButtonY; w = randomButtonW; h = bottomButtonH; }; class spawnLocationsList: RscListBox { idc = spawn_locations_list; #define locationslistW (screenW - (edgeOffsetX * 2)) #define locationslistH ((screenH - bottomButtonH) - (edgeOffsetY * 4)) #define locationslistY (screenY + (edgeOffsetY * 2)) #define locationslistX (screenX + edgeOffsetX) x = locationslistX; y = locationslistY; w = locationslistW; h = locationslistH; }; class spawnLocationsButton: RscButton { idc = spawn_locations_button; text = "Spawn"; #define spawnButtonW scaleFix(0.15) #define spawnButtonX (screenX + edgeOffsetX) x = spawnButtonX; y = bottomButtonY; w = spawnButtonW; h = bottomButtonH; }; }; }; <commit_msg>add abort button to spawn dialog<commit_after>/* * The main spawn screen */ #include "spawnDialog_defines.hpp" class spawnDialog { idd = spawn_dialog; movingEnable = false; enableSimulation = true; onLoad = "uiNamespace setVariable [""UK_SpawnDialog"", _this select 0]"; class Controls { class spawnScreen: RscFrame { idc = spawn_screen; text = "Spawn Selection"; #define screenW (0.7 * 3/4) #define screenH 0.5 #define screenX CENTER(1, screenW) #define screenY CENTER(1, screenH) w = screenW; h = screenH; x = screenX; y = screenY; }; #define bottomButtonH (0.055) #define bottomButtonY ((screenY + screenH) - (bottomButtonH + edgeOffsetY)) class spawnLocationsList: RscListBox { idc = spawn_locations_list; #define locationslistW (screenW - (edgeOffsetX * 2)) #define locationslistH ((screenH - bottomButtonH) - (edgeOffsetY * 4)) #define locationslistY (screenY + (edgeOffsetY * 2)) #define locationslistX (screenX + edgeOffsetX) x = locationslistX; y = locationslistY; w = locationslistW; h = locationslistH; }; class spawnLocationsButton: RscButton { idc = spawn_locations_button; text = "Spawn"; #define spawnButtonW scaleFix(0.15) #define spawnButtonX (screenX + edgeOffsetX) x = spawnButtonX; y = bottomButtonY; w = spawnButtonW; h = bottomButtonH; }; class randomSpawnButton: RscButton { idc = random_spawn_button; text = "Random"; #define randomButtonW scaleFix(0.15) #define randomButtonX (screenX + (edgeOffsetX * 2) + spawnButtonW) x = randomButtonX; y = bottomButtonY; w = randomButtonW; h = bottomButtonH; }; class abortButton: RscButton { idc = -1; text = "Abort"; onButtonClick = "endMission 'LOSER'"; #define abortButtonW scaleFix(0.15) #define abortButtonX ((screenX + screenW) - abortButtonW - edgeOffsetX) x = abortButtonX; y = bottomButtonY; w = abortButtonW; h = bottomButtonH; }; }; }; <|endoftext|>
<commit_before>/* * Copyright 2016-2017 deepstreamHub 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. */ #include <cstdlib> #include <cstring> #include <message.hpp> #include <parser.h> #include <parser.hpp> #include <scope_guard.hpp> #include <use.hpp> #include <cassert> bool is_header_token(enum deepstream_token token) { int min_event_num = TOKEN_A_A; return token >= min_event_num; } deepstream_parser_state::deepstream_parser_state(const char* p, std::size_t sz): buffer_(p), buffer_size_(sz), tokenizing_header_(true), offset_(0) { assert(buffer_); } int deepstream_parser_handle( deepstream::parser::State* p_state, deepstream_token token, const char* text, std::size_t textlen) { assert( p_state ); assert( token != TOKEN_MAXVAL ); return p_state->handle_token(token, text, textlen); } int deepstream_parser_state::handle_token( deepstream_token token, const char* text, std::size_t textlen) { assert( token != TOKEN_MAXVAL ); assert( text ); assert( textlen > 0 ); assert( token != TOKEN_EOF || *text == '\0' ); assert( token != TOKEN_EOF || textlen == 1 ); assert( token != TOKEN_EOF || offset_ + textlen == buffer_size_ + 1 ); assert( token == TOKEN_EOF || offset_ + textlen <= buffer_size_ ); assert( token == TOKEN_EOF || !std::memcmp(buffer_+offset_, text, textlen)); assert( messages_.size() <= offset_ ); assert( errors_.size() <= offset_ ); DEEPSTREAM_ON_EXIT([this, textlen] () { this->offset_ += textlen; } ); if(token == TOKEN_UNKNOWN) handle_error(token, text, textlen); else if(token == TOKEN_EOF) { assert(offset_ == buffer_size_); if(!tokenizing_header_) handle_error(token, text, textlen); } else if(token == TOKEN_PAYLOAD) handle_payload(token, text, textlen); else if(token == TOKEN_MESSAGE_SEPARATOR) handle_message_separator(token, text, textlen); else if( is_header_token(token) ) handle_header(token, text, textlen); else { assert(0); } return token; } void deepstream_parser_state::handle_error( deepstream_token token, const char*, std::size_t textlen) { using deepstream::parser::Error; assert( token == TOKEN_EOF || token == TOKEN_UNKNOWN ); assert( textlen > 0 || (textlen == 0 && token == EOF) ); DEEPSTREAM_ON_EXIT( [this] () { this->tokenizing_header_ = true; // reset parser status on exit } ); if( token == TOKEN_EOF ) { assert( !tokenizing_header_ ); assert( !messages_.empty() ); messages_.pop_back(); errors_.emplace_back(offset_, textlen, Error::UNEXPECTED_EOF); } if( token == TOKEN_UNKNOWN && tokenizing_header_ ) { errors_.emplace_back(offset_, textlen, Error::UNEXPECTED_TOKEN); } if( token == TOKEN_UNKNOWN && !tokenizing_header_ ) { assert( !messages_.empty() ); std::size_t msg_start = messages_.back().offset(); std::size_t msg_size = messages_.back().size(); messages_.pop_back(); assert( msg_start + msg_size == offset_ ); errors_.emplace_back( msg_start, msg_size+textlen, Error::CORRUPT_MESSAGE); } } #define DS_ADD_MSG(...) \ do { \ assert( textlen==deepstream::Message::Header::size(__VA_ARGS__) ); \ messages_.emplace_back(buffer_, offset_, __VA_ARGS__); \ } while(false) void deepstream_parser_state::handle_header( deepstream_token token, const char*, std::size_t textlen) { using deepstream::Topic; using deepstream::Action; assert( is_header_token(token) ); assert( tokenizing_header_ ); DEEPSTREAM_ON_EXIT( [this] () { this->tokenizing_header_ = false; } ); switch(token) { // avoid compiler warnings [-Wswitch] case TOKEN_EOF: case TOKEN_UNKNOWN: case TOKEN_PAYLOAD: case TOKEN_MESSAGE_SEPARATOR: case TOKEN_MAXVAL: assert(0); break; case TOKEN_A_A: DS_ADD_MSG(Topic::AUTH, Action::REQUEST, true); break; case TOKEN_A_E_IAD: DS_ADD_MSG(Topic::AUTH, Action::ERROR_INVALID_AUTH_DATA, true); break; case TOKEN_A_E_TMAA: DS_ADD_MSG(Topic::AUTH, Action::ERROR_TOO_MANY_AUTH_ATTEMPTS); break; case TOKEN_A_REQ: DS_ADD_MSG(Topic::AUTH, Action::REQUEST); break; case TOKEN_C_A: DS_ADD_MSG(Topic::CONNECTION, Action::CHALLENGE_RESPONSE, true); break; case TOKEN_C_CH: DS_ADD_MSG(Topic::CONNECTION, Action::CHALLENGE); break; case TOKEN_C_CHR: DS_ADD_MSG(Topic::CONNECTION, Action::CHALLENGE_RESPONSE); break; case TOKEN_C_RED: DS_ADD_MSG(Topic::CONNECTION, Action::REDIRECT); break; case TOKEN_C_REJ: DS_ADD_MSG(Topic::CONNECTION, Action::REJECT); case TOKEN_E_A_L: DS_ADD_MSG(Topic::EVENT, Action::LISTEN, true); break; case TOKEN_E_A_S: DS_ADD_MSG(Topic::EVENT, Action::SUBSCRIBE, true); break; case TOKEN_E_L: DS_ADD_MSG(Topic::EVENT, Action::LISTEN); break; case TOKEN_E_S: DS_ADD_MSG(Topic::EVENT, Action::SUBSCRIBE); break; case TOKEN_E_US: DS_ADD_MSG(Topic::EVENT, Action::UNSUBSCRIBE); break; } } void deepstream_parser_state::handle_payload( deepstream_token token, const char* text, std::size_t textlen) { using namespace deepstream::parser; assert( token == TOKEN_PAYLOAD ); assert( text ); assert( textlen > 0 ); assert( text[0] == ASCII_UNIT_SEPARATOR ); assert( !messages_.empty() ); deepstream::use(token); deepstream::use(text); auto& msg = messages_.back(); msg.arguments_.emplace_back(offset_+1, textlen-1); msg.size_ += textlen; } void deepstream_parser_state::handle_message_separator( deepstream_token token, const char* text, std::size_t textlen) { using namespace deepstream::parser; assert( token == TOKEN_MESSAGE_SEPARATOR ); assert( text ); assert( textlen == 1 ); assert( text[0] == ASCII_RECORD_SEPARATOR ); assert( !messages_.empty() ); deepstream::use(token); deepstream::use(text); DEEPSTREAM_ON_EXIT( [this] () { this->tokenizing_header_ = true; } ); auto& msg = messages_.back(); msg.size_ += textlen; std::size_t msg_offset = msg.offset(); std::size_t msg_size = msg.size(); std::size_t num_args = msg.arguments_.size(); const auto& expected_num_args = msg.num_arguments(); std::size_t min_num_args = expected_num_args.first; std::size_t max_num_args = expected_num_args.second; if( num_args >= min_num_args && num_args <= max_num_args ) return; messages_.pop_back(); errors_.emplace_back( msg_offset, msg_size, Error::INVALID_NUMBER_OF_ARGUMENTS); } <commit_msg>Test: check parsed message headers<commit_after>/* * Copyright 2016-2017 deepstreamHub 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. */ #include <cstdlib> #include <cstring> #include <message.hpp> #include <parser.h> #include <parser.hpp> #include <scope_guard.hpp> #include <use.hpp> #include <cassert> bool is_header_token(enum deepstream_token token) { int min_event_num = TOKEN_A_A; return token >= min_event_num; } deepstream_parser_state::deepstream_parser_state(const char* p, std::size_t sz): buffer_(p), buffer_size_(sz), tokenizing_header_(true), offset_(0) { assert(buffer_); } int deepstream_parser_handle( deepstream::parser::State* p_state, deepstream_token token, const char* text, std::size_t textlen) { assert( p_state ); assert( token != TOKEN_MAXVAL ); return p_state->handle_token(token, text, textlen); } int deepstream_parser_state::handle_token( deepstream_token token, const char* text, std::size_t textlen) { assert( token != TOKEN_MAXVAL ); assert( text ); assert( textlen > 0 ); assert( token != TOKEN_EOF || *text == '\0' ); assert( token != TOKEN_EOF || textlen == 1 ); assert( token != TOKEN_EOF || offset_ + textlen == buffer_size_ + 1 ); assert( token == TOKEN_EOF || offset_ + textlen <= buffer_size_ ); assert( token == TOKEN_EOF || !std::memcmp(buffer_+offset_, text, textlen)); assert( messages_.size() <= offset_ ); assert( errors_.size() <= offset_ ); DEEPSTREAM_ON_EXIT([this, textlen] () { this->offset_ += textlen; } ); if(token == TOKEN_UNKNOWN) handle_error(token, text, textlen); else if(token == TOKEN_EOF) { assert(offset_ == buffer_size_); if(!tokenizing_header_) handle_error(token, text, textlen); } else if(token == TOKEN_PAYLOAD) handle_payload(token, text, textlen); else if(token == TOKEN_MESSAGE_SEPARATOR) handle_message_separator(token, text, textlen); else if( is_header_token(token) ) handle_header(token, text, textlen); else { assert(0); } return token; } void deepstream_parser_state::handle_error( deepstream_token token, const char*, std::size_t textlen) { using deepstream::parser::Error; assert( token == TOKEN_EOF || token == TOKEN_UNKNOWN ); assert( textlen > 0 || (textlen == 0 && token == EOF) ); DEEPSTREAM_ON_EXIT( [this] () { this->tokenizing_header_ = true; // reset parser status on exit } ); if( token == TOKEN_EOF ) { assert( !tokenizing_header_ ); assert( !messages_.empty() ); messages_.pop_back(); errors_.emplace_back(offset_, textlen, Error::UNEXPECTED_EOF); } if( token == TOKEN_UNKNOWN && tokenizing_header_ ) { errors_.emplace_back(offset_, textlen, Error::UNEXPECTED_TOKEN); } if( token == TOKEN_UNKNOWN && !tokenizing_header_ ) { assert( !messages_.empty() ); std::size_t msg_start = messages_.back().offset(); std::size_t msg_size = messages_.back().size(); messages_.pop_back(); assert( msg_start + msg_size == offset_ ); errors_.emplace_back( msg_start, msg_size+textlen, Error::CORRUPT_MESSAGE); } } #define DS_ADD_MSG(...) \ do { \ messages_.emplace_back(buffer_, offset_, __VA_ARGS__); \ } while(false) void deepstream_parser_state::handle_header( deepstream_token token, const char* text, std::size_t textlen) { using deepstream::Topic; using deepstream::Action; assert( is_header_token(token) ); assert( tokenizing_header_ ); DEEPSTREAM_ON_EXIT( [this] () { this->tokenizing_header_ = false; } ); switch(token) { // avoid compiler warnings [-Wswitch] case TOKEN_EOF: case TOKEN_UNKNOWN: case TOKEN_PAYLOAD: case TOKEN_MESSAGE_SEPARATOR: case TOKEN_MAXVAL: assert(0); break; case TOKEN_A_A: DS_ADD_MSG(Topic::AUTH, Action::REQUEST, true); break; case TOKEN_A_E_IAD: DS_ADD_MSG(Topic::AUTH, Action::ERROR_INVALID_AUTH_DATA, true); break; case TOKEN_A_E_TMAA: DS_ADD_MSG(Topic::AUTH, Action::ERROR_TOO_MANY_AUTH_ATTEMPTS); break; case TOKEN_A_REQ: DS_ADD_MSG(Topic::AUTH, Action::REQUEST); break; case TOKEN_C_A: DS_ADD_MSG(Topic::CONNECTION, Action::CHALLENGE_RESPONSE, true); break; case TOKEN_C_CH: DS_ADD_MSG(Topic::CONNECTION, Action::CHALLENGE); break; case TOKEN_C_CHR: DS_ADD_MSG(Topic::CONNECTION, Action::CHALLENGE_RESPONSE); break; case TOKEN_C_RED: DS_ADD_MSG(Topic::CONNECTION, Action::REDIRECT); break; case TOKEN_C_REJ: DS_ADD_MSG(Topic::CONNECTION, Action::REJECT); case TOKEN_E_A_L: DS_ADD_MSG(Topic::EVENT, Action::LISTEN, true); break; case TOKEN_E_A_S: DS_ADD_MSG(Topic::EVENT, Action::SUBSCRIBE, true); break; case TOKEN_E_L: DS_ADD_MSG(Topic::EVENT, Action::LISTEN); break; case TOKEN_E_S: DS_ADD_MSG(Topic::EVENT, Action::SUBSCRIBE); break; case TOKEN_E_US: DS_ADD_MSG(Topic::EVENT, Action::UNSUBSCRIBE); break; } #ifndef NDEBUG const auto& msg = messages_.back(); const char* p = msg.header().to_string(); std::vector<char> bin = deepstream::Message::Header::from_human_readable(p); assert( textlen == msg.header().size() ); assert( textlen == bin.size() ); assert( std::equal(bin.cbegin(), bin.cend(), text) ); #endif } void deepstream_parser_state::handle_payload( deepstream_token token, const char* text, std::size_t textlen) { using namespace deepstream::parser; assert( token == TOKEN_PAYLOAD ); assert( text ); assert( textlen > 0 ); assert( text[0] == ASCII_UNIT_SEPARATOR ); assert( !messages_.empty() ); deepstream::use(token); deepstream::use(text); auto& msg = messages_.back(); msg.arguments_.emplace_back(offset_+1, textlen-1); msg.size_ += textlen; } void deepstream_parser_state::handle_message_separator( deepstream_token token, const char* text, std::size_t textlen) { using namespace deepstream::parser; assert( token == TOKEN_MESSAGE_SEPARATOR ); assert( text ); assert( textlen == 1 ); assert( text[0] == ASCII_RECORD_SEPARATOR ); assert( !messages_.empty() ); deepstream::use(token); deepstream::use(text); DEEPSTREAM_ON_EXIT( [this] () { this->tokenizing_header_ = true; } ); auto& msg = messages_.back(); msg.size_ += textlen; std::size_t msg_offset = msg.offset(); std::size_t msg_size = msg.size(); std::size_t num_args = msg.arguments_.size(); const auto& expected_num_args = msg.num_arguments(); std::size_t min_num_args = expected_num_args.first; std::size_t max_num_args = expected_num_args.second; if( num_args >= min_num_args && num_args <= max_num_args ) return; messages_.pop_back(); errors_.emplace_back( msg_offset, msg_size, Error::INVALID_NUMBER_OF_ARGUMENTS); } <|endoftext|>
<commit_before>// Copyright (c) 2009 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 "native_client/src/include/portability.h" #if NACL_OSX #include <crt_externs.h> #endif #ifdef _WIN64 /* TODO(gregoryd): remove this when win64 issues are fixed */ #define NACL_NO_INLINE #endif EXTERN_C_BEGIN #include "native_client/src/shared/platform/nacl_sync.h" #include "native_client/src/shared/platform/nacl_sync_checked.h" #include "native_client/src/trusted/service_runtime/nacl_globals.h" #include "native_client/src/trusted/service_runtime/expiration.h" #include "native_client/src/trusted/service_runtime/nacl_app.h" #include "native_client/src/trusted/service_runtime/nacl_all_modules.h" #include "native_client/src/trusted/service_runtime/sel_ldr.h" #include "native_client/src/trusted/platform_qualify/nacl_os_qualify.h" EXTERN_C_END int verbosity = 0; #ifdef __GNUC__ /* * GDB's canonical overlay managment routine. * We need its symbol in the symbol table so don't inline it. * Note: _ovly_debug_event has to be an unmangled 'C' style symbol. * TODO(dje): add some explanation for the non-GDB person. */ EXTERN_C_BEGIN static void __attribute__ ((noinline)) _ovly_debug_event (void) { /* * The asm volatile is here as instructed by the GCC docs. * It's not enough to declare a function noinline. * GCC will still look inside the function to see if it's worth calling. */ asm volatile (""); } EXTERN_C_END #endif static void StopForDebuggerInit(const struct NaClApp *state) { /* Put xlate_base in a place where gdb can find it. */ nacl_global_xlate_base = state->mem_start; #ifdef __GNUC__ _ovly_debug_event(); #endif } int SelMain(const int desc, const NaClHandle handle) { char *av[1]; int ac = 1; char **envp; struct NaClApp state; int main_thread_only = 1; int export_addr_to = -2; struct NaClApp *nap; NaClErrorCode errcode; int ret_code = 1; #if NACL_OSX // Mac dynamic libraries cannot access the environ variable directly. envp = *_NSGetEnviron(); #else extern char **environ; envp = environ; #endif NaClAllModulesInit(); /* used to be -P */ NaClSrpcFileDescriptor = desc; /* used to be -X */ export_addr_to = desc; /* to be passed to NaClMain, eventually... */ av[0] = const_cast<char*>("NaClMain"); if (!NaClAppCtor(&state)) { fprintf(stderr, "Error while constructing app state\n"); goto done; } state.restrict_to_main_thread = main_thread_only; nap = &state; errcode = LOAD_OK; /* import IMC handle - used to be "-i" */ NaClAddImcHandle(nap, handle, desc); /* * in order to report load error to the browser plugin through the * secure command channel, we do not immediate jump to cleanup code * on error. rather, we continue processing (assuming earlier * errors do not make it inappropriate) until the secure command * channel is set up, and then bail out. */ /* * Ensure this operating system platform is supported. */ if (!NaClOsIsSupported()) { errcode = LOAD_UNSUPPORTED_OS_PLATFORM; nap->module_load_status = errcode; fprintf(stderr, "Error while loading in SelMain: %s\n", NaClErrorString(errcode)); } /* Give debuggers a well known point at which xlate_base is known. */ StopForDebuggerInit(&state); /* * If export_addr_to is set to a non-negative integer, we create a * bound socket and socket address pair and bind the former to * descriptor 3 and the latter to descriptor 4. The socket address * is written out to the export_addr_to descriptor. * * The service runtime also accepts a connection on the bound socket * and spawns a secure command channel thread to service it. * * If export_addr_to is -1, we only create the bound socket and * socket address pair, and we do not export to an IMC socket. This * use case is typically only used in testing, where we only "dump" * the socket address to stdout or similar channel. */ if (-2 < export_addr_to) { NaClCreateServiceSocket(nap); if (0 <= export_addr_to) { NaClSendServiceAddressTo(nap, export_addr_to); /* * NB: spawns a thread that uses the command channel. we do * this after NaClAppLoadFile so that NaClApp object is more * fully populated. Hereafter any changes to nap should be done * while holding locks. */ NaClSecureCommandChannel(nap); } } NaClXMutexLock(&nap->mu); nap->module_load_status = LOAD_OK; NaClXCondVarBroadcast(&nap->cv); NaClXMutexUnlock(&nap->mu); if (NULL != nap->secure_channel) { /* * wait for start_module RPC call on secure channel thread. */ NaClWaitForModuleStartStatusCall(nap); } /* * error reporting done; can quit now if there was an error earlier. */ if (LOAD_OK != errcode) { goto done; } /* * only nap->ehdrs.e_entry is usable, no symbol table is * available. */ if (!NaClCreateMainThread(nap, ac, av, envp)) { fprintf(stderr, "creating main thread failed\n"); goto done; } ret_code = NaClWaitForMainThreadToExit(nap); /* * exit_group or equiv kills any still running threads while module * addr space is still valid. otherwise we'd have to kill threads * before we clean up the address space. */ return ret_code; done: fflush(stdout); NaClAllModulesFini(); return ret_code; } <commit_msg>Remove unnecessary EXTERN_C_BEGIN and EXTERN_C_END BUG=46024 TEST=None<commit_after>// Copyright (c) 2009 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 "native_client/src/include/portability.h" #if NACL_OSX #include <crt_externs.h> #endif #ifdef _WIN64 /* TODO(gregoryd): remove this when win64 issues are fixed */ #define NACL_NO_INLINE #endif #include "native_client/src/shared/platform/nacl_sync.h" #include "native_client/src/shared/platform/nacl_sync_checked.h" #include "native_client/src/trusted/service_runtime/nacl_globals.h" #include "native_client/src/trusted/service_runtime/expiration.h" #include "native_client/src/trusted/service_runtime/nacl_app.h" #include "native_client/src/trusted/service_runtime/nacl_all_modules.h" #include "native_client/src/trusted/service_runtime/sel_ldr.h" #include "native_client/src/trusted/platform_qualify/nacl_os_qualify.h" int verbosity = 0; #ifdef __GNUC__ /* * GDB's canonical overlay managment routine. * We need its symbol in the symbol table so don't inline it. * Note: _ovly_debug_event has to be an unmangled 'C' style symbol. * TODO(dje): add some explanation for the non-GDB person. */ EXTERN_C_BEGIN static void __attribute__ ((noinline)) _ovly_debug_event (void) { /* * The asm volatile is here as instructed by the GCC docs. * It's not enough to declare a function noinline. * GCC will still look inside the function to see if it's worth calling. */ asm volatile (""); } EXTERN_C_END #endif static void StopForDebuggerInit(const struct NaClApp *state) { /* Put xlate_base in a place where gdb can find it. */ nacl_global_xlate_base = state->mem_start; #ifdef __GNUC__ _ovly_debug_event(); #endif } int SelMain(const int desc, const NaClHandle handle) { char *av[1]; int ac = 1; char **envp; struct NaClApp state; int main_thread_only = 1; int export_addr_to = -2; struct NaClApp *nap; NaClErrorCode errcode; int ret_code = 1; #if NACL_OSX // Mac dynamic libraries cannot access the environ variable directly. envp = *_NSGetEnviron(); #else extern char **environ; envp = environ; #endif NaClAllModulesInit(); /* used to be -P */ NaClSrpcFileDescriptor = desc; /* used to be -X */ export_addr_to = desc; /* to be passed to NaClMain, eventually... */ av[0] = const_cast<char*>("NaClMain"); if (!NaClAppCtor(&state)) { fprintf(stderr, "Error while constructing app state\n"); goto done; } state.restrict_to_main_thread = main_thread_only; nap = &state; errcode = LOAD_OK; /* import IMC handle - used to be "-i" */ NaClAddImcHandle(nap, handle, desc); /* * in order to report load error to the browser plugin through the * secure command channel, we do not immediate jump to cleanup code * on error. rather, we continue processing (assuming earlier * errors do not make it inappropriate) until the secure command * channel is set up, and then bail out. */ /* * Ensure this operating system platform is supported. */ if (!NaClOsIsSupported()) { errcode = LOAD_UNSUPPORTED_OS_PLATFORM; nap->module_load_status = errcode; fprintf(stderr, "Error while loading in SelMain: %s\n", NaClErrorString(errcode)); } /* Give debuggers a well known point at which xlate_base is known. */ StopForDebuggerInit(&state); /* * If export_addr_to is set to a non-negative integer, we create a * bound socket and socket address pair and bind the former to * descriptor 3 and the latter to descriptor 4. The socket address * is written out to the export_addr_to descriptor. * * The service runtime also accepts a connection on the bound socket * and spawns a secure command channel thread to service it. * * If export_addr_to is -1, we only create the bound socket and * socket address pair, and we do not export to an IMC socket. This * use case is typically only used in testing, where we only "dump" * the socket address to stdout or similar channel. */ if (-2 < export_addr_to) { NaClCreateServiceSocket(nap); if (0 <= export_addr_to) { NaClSendServiceAddressTo(nap, export_addr_to); /* * NB: spawns a thread that uses the command channel. we do * this after NaClAppLoadFile so that NaClApp object is more * fully populated. Hereafter any changes to nap should be done * while holding locks. */ NaClSecureCommandChannel(nap); } } NaClXMutexLock(&nap->mu); nap->module_load_status = LOAD_OK; NaClXCondVarBroadcast(&nap->cv); NaClXMutexUnlock(&nap->mu); if (NULL != nap->secure_channel) { /* * wait for start_module RPC call on secure channel thread. */ NaClWaitForModuleStartStatusCall(nap); } /* * error reporting done; can quit now if there was an error earlier. */ if (LOAD_OK != errcode) { goto done; } /* * only nap->ehdrs.e_entry is usable, no symbol table is * available. */ if (!NaClCreateMainThread(nap, ac, av, envp)) { fprintf(stderr, "creating main thread failed\n"); goto done; } ret_code = NaClWaitForMainThreadToExit(nap); /* * exit_group or equiv kills any still running threads while module * addr space is still valid. otherwise we'd have to kill threads * before we clean up the address space. */ return ret_code; done: fflush(stdout); NaClAllModulesFini(); return ret_code; } <|endoftext|>
<commit_before><commit_msg>Revert 32626 - Remove the expiration check from Chrome code<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestLinePlot.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkChartMatrix.h" #include "vtkRenderWindow.h" #include "vtkChartXY.h" #include "vtkPlot.h" #include "vtkTable.h" #include "vtkFloatArray.h" #include "vtkContextView.h" #include "vtkContextScene.h" #include "vtkRenderWindowInteractor.h" #include "vtkNew.h" //---------------------------------------------------------------------------- int TestChartMatrix( int, char * [] ) { // Set up a 2D scene, add an XY chart to it vtkNew<vtkContextView> view; view->GetRenderWindow()->SetSize(400, 300); vtkNew<vtkChartMatrix> matrix; view->GetScene()->AddItem(matrix.GetPointer()); matrix->SetSize(vtkVector2i(2, 2)); vtkChart *chart = matrix->GetChart(vtkVector2i(0, 0)); // Create a table with some points in it... vtkNew<vtkTable> table; vtkNew<vtkFloatArray> arrX; arrX->SetName("X Axis"); table->AddColumn(arrX.GetPointer()); vtkNew<vtkFloatArray> arrC; arrC->SetName("Cosine"); table->AddColumn(arrC.GetPointer()); vtkNew<vtkFloatArray> arrS; arrS->SetName("Sine"); table->AddColumn(arrS.GetPointer()); vtkNew<vtkFloatArray> arrS2; arrS2->SetName("Sine2"); table->AddColumn(arrS2.GetPointer()); vtkNew<vtkFloatArray> tangent; tangent->SetName("Tangent"); table->AddColumn(tangent.GetPointer()); // Test charting with a few more points... int numPoints = 69; float inc = 7.5 / (numPoints-1); table->SetNumberOfRows(numPoints); for (int i = 0; i < numPoints; ++i) { table->SetValue(i, 0, i * inc); table->SetValue(i, 1, cos(i * inc)); table->SetValue(i, 2, sin(i * inc)); table->SetValue(i, 3, sin(i * inc) + 0.5); table->SetValue(i, 4, tan(i * inc)); } // Add multiple line plots, setting the colors etc vtkPlot *line = chart->AddPlot(vtkChart::POINTS); line->SetInput(table.GetPointer(), 0, 1); line->SetColor(0, 255, 0, 255); chart = matrix->GetChart(vtkVector2i(0, 1)); line = chart->AddPlot(vtkChart::POINTS); line->SetInput(table.GetPointer(), 0, 2); line->SetColor(255, 0, 0, 255); chart = matrix->GetChart(vtkVector2i(1, 0)); line = chart->AddPlot(vtkChart::LINE); line->SetInput(table.GetPointer(), 0, 3); line->SetColor(0, 0, 255, 255); chart = matrix->GetChart(vtkVector2i(1, 1)); line = chart->AddPlot(vtkChart::POINTS); line->SetInput(table.GetPointer(), 0, 4); //Finally render the scene and compare the image to a reference image view->GetRenderWindow()->SetMultiSamples(0); view->GetInteractor()->Initialize(); view->GetInteractor()->Start(); return EXIT_SUCCESS; } <commit_msg>ENH: Use less points, make tan a bar chart.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestLinePlot.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkChartMatrix.h" #include "vtkRenderWindow.h" #include "vtkChartXY.h" #include "vtkPlot.h" #include "vtkTable.h" #include "vtkFloatArray.h" #include "vtkContextView.h" #include "vtkContextScene.h" #include "vtkRenderWindowInteractor.h" #include "vtkNew.h" //---------------------------------------------------------------------------- int TestChartMatrix( int, char * [] ) { // Set up a 2D scene, add an XY chart to it vtkNew<vtkContextView> view; view->GetRenderWindow()->SetSize(400, 300); vtkNew<vtkChartMatrix> matrix; view->GetScene()->AddItem(matrix.GetPointer()); matrix->SetSize(vtkVector2i(2, 2)); vtkChart *chart = matrix->GetChart(vtkVector2i(0, 0)); // Create a table with some points in it... vtkNew<vtkTable> table; vtkNew<vtkFloatArray> arrX; arrX->SetName("X Axis"); table->AddColumn(arrX.GetPointer()); vtkNew<vtkFloatArray> arrC; arrC->SetName("Cosine"); table->AddColumn(arrC.GetPointer()); vtkNew<vtkFloatArray> arrS; arrS->SetName("Sine"); table->AddColumn(arrS.GetPointer()); vtkNew<vtkFloatArray> arrS2; arrS2->SetName("Sine2"); table->AddColumn(arrS2.GetPointer()); vtkNew<vtkFloatArray> tangent; tangent->SetName("Tangent"); table->AddColumn(tangent.GetPointer()); // Test charting with a few more points... int numPoints = 42; float inc = 7.5 / (numPoints-1); table->SetNumberOfRows(numPoints); for (int i = 0; i < numPoints; ++i) { table->SetValue(i, 0, i * inc); table->SetValue(i, 1, cos(i * inc)); table->SetValue(i, 2, sin(i * inc)); table->SetValue(i, 3, sin(i * inc) + 0.5); table->SetValue(i, 4, tan(i * inc)); } // Add multiple line plots, setting the colors etc vtkPlot *line = chart->AddPlot(vtkChart::POINTS); line->SetInput(table.GetPointer(), 0, 1); line->SetColor(0, 255, 0, 255); chart = matrix->GetChart(vtkVector2i(0, 1)); line = chart->AddPlot(vtkChart::POINTS); line->SetInput(table.GetPointer(), 0, 2); line->SetColor(255, 0, 0, 255); chart = matrix->GetChart(vtkVector2i(1, 0)); line = chart->AddPlot(vtkChart::LINE); line->SetInput(table.GetPointer(), 0, 3); line->SetColor(0, 0, 255, 255); chart = matrix->GetChart(vtkVector2i(1, 1)); line = chart->AddPlot(vtkChart::BAR); line->SetInput(table.GetPointer(), 0, 4); //Finally render the scene and compare the image to a reference image view->GetRenderWindow()->SetMultiSamples(0); view->GetInteractor()->Initialize(); view->GetInteractor()->Start(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkStandardFileLocations.h" #include "mitkTestingMacros.h" #include "mitkPointSetDifferenceStatisticsCalculator.h" //#include <QtCore> /** * \brief Test class for mitkPointSetDifferenceStatisticsCalculator */ class mitkPointSetDifferenceStatisticsCalculatorTestClass { public: static void TestInstantiation() { // let's create an object of our class mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator = mitk::PointSetDifferenceStatisticsCalculator::New(); MITK_TEST_CONDITION_REQUIRED(myPointSetDifferenceStatisticsCalculator.IsNotNull(),"Testing instantiation with constructor 1."); mitk::PointSet::Pointer myTestPointSet1 = mitk::PointSet::New(); mitk::PointSet::Pointer myTestPointSet2 = mitk::PointSet::New(); mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator2 = mitk::PointSetDifferenceStatisticsCalculator::New(myTestPointSet1,myTestPointSet2); MITK_TEST_CONDITION_REQUIRED(myPointSetDifferenceStatisticsCalculator2.IsNotNull(),"Testing instantiation with constructor 2."); } static void TestSimpleCase() { MITK_TEST_OUTPUT(<< "Starting simple test case..."); mitk::Point3D test; mitk::PointSet::Pointer testPointSet1 = mitk::PointSet::New(); mitk::FillVector3D(test,0,0,0); testPointSet1->InsertPoint(0,test); mitk::FillVector3D(test,1,1,1); testPointSet1->InsertPoint(1,test); mitk::PointSet::Pointer testPointSet2 = mitk::PointSet::New(); mitk::FillVector3D(test,0.5,0.5,0.5); testPointSet2->InsertPoint(0,test); mitk::FillVector3D(test,2,2,2); testPointSet2->InsertPoint(1,test); double mean = (sqrt(0.75)+sqrt(3))/2; double variance = ((sqrt(0.75)-mean)*(sqrt(0.75)-mean)+(sqrt(3)-mean)*(sqrt(3)-mean))/2; double sd = sqrt(variance); double rms = sqrt(3.75/2); double min = sqrt(0.75); double max = sqrt(3); double median = (min + max)/2; mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator = mitk::PointSetDifferenceStatisticsCalculator::New(testPointSet1,testPointSet2); MITK_TEST_CONDITION_REQUIRED((myPointSetDifferenceStatisticsCalculator->GetNumberOfPoints()==testPointSet1->GetSize()),".. Testing GetNumberOfPoints"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetMean(),mean),".. Testing GetMean"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetSD(),sd),".. Testing GetSD"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetVariance(),variance),".. Testing GetVariance"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetRMS(),rms),".. Testing GetRMS"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetMin(),min),".. Testing GetMin"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetMax(),max),".. Testing GetMax"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetMedian(),median),".. Testing GetMedian"); testPointSet2->InsertPoint(2,test); myPointSetDifferenceStatisticsCalculator->SetPointSets(testPointSet1,testPointSet2); MITK_TEST_OUTPUT(<<"Test for exception when using differently sized point sets"); MITK_TEST_FOR_EXCEPTION(itk::ExceptionObject,myPointSetDifferenceStatisticsCalculator->GetMean()); mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator2 = mitk::PointSetDifferenceStatisticsCalculator::New(); MITK_TEST_OUTPUT(<<"Test for exception when using point sets with size 0"); MITK_TEST_FOR_EXCEPTION(itk::ExceptionObject,myPointSetDifferenceStatisticsCalculator2->GetMean()); } }; int mitkPointSetDifferenceStatisticsCalculatorTest(int argc, char* argv[]) { // always start with this! MITK_TEST_BEGIN("mitkPointSetDifferenceStatisticsCalculatorTest") // let's create an object of our class mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator = mitk::PointSetDifferenceStatisticsCalculator::New(); MITK_TEST_CONDITION_REQUIRED(myPointSetDifferenceStatisticsCalculator.IsNotNull(),"Testing instantiation with constructor 1."); mitk::PointSet::Pointer myTestPointSet1 = mitk::PointSet::New(); mitk::PointSet::Pointer myTestPointSet2 = mitk::PointSet::New(); mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator2 = mitk::PointSetDifferenceStatisticsCalculator::New(myTestPointSet1,myTestPointSet2); MITK_TEST_CONDITION_REQUIRED(myPointSetDifferenceStatisticsCalculator2.IsNotNull(),"Testing instantiation with constructor 2."); mitkPointSetDifferenceStatisticsCalculatorTestClass::TestInstantiation(); mitkPointSetDifferenceStatisticsCalculatorTestClass::TestSimpleCase(); MITK_TEST_END() } <commit_msg>COMP: fixed ambiguous calls to sqrt()<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkStandardFileLocations.h" #include "mitkTestingMacros.h" #include "mitkPointSetDifferenceStatisticsCalculator.h" //#include <QtCore> /** * \brief Test class for mitkPointSetDifferenceStatisticsCalculator */ class mitkPointSetDifferenceStatisticsCalculatorTestClass { public: static void TestInstantiation() { // let's create an object of our class mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator = mitk::PointSetDifferenceStatisticsCalculator::New(); MITK_TEST_CONDITION_REQUIRED(myPointSetDifferenceStatisticsCalculator.IsNotNull(),"Testing instantiation with constructor 1."); mitk::PointSet::Pointer myTestPointSet1 = mitk::PointSet::New(); mitk::PointSet::Pointer myTestPointSet2 = mitk::PointSet::New(); mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator2 = mitk::PointSetDifferenceStatisticsCalculator::New(myTestPointSet1,myTestPointSet2); MITK_TEST_CONDITION_REQUIRED(myPointSetDifferenceStatisticsCalculator2.IsNotNull(),"Testing instantiation with constructor 2."); } static void TestSimpleCase() { MITK_TEST_OUTPUT(<< "Starting simple test case..."); mitk::Point3D test; mitk::PointSet::Pointer testPointSet1 = mitk::PointSet::New(); mitk::FillVector3D(test,0,0,0); testPointSet1->InsertPoint(0,test); mitk::FillVector3D(test,1,1,1); testPointSet1->InsertPoint(1,test); mitk::PointSet::Pointer testPointSet2 = mitk::PointSet::New(); mitk::FillVector3D(test,0.5,0.5,0.5); testPointSet2->InsertPoint(0,test); mitk::FillVector3D(test,2,2,2); testPointSet2->InsertPoint(1,test); double squaredDistance1 = 0.75; double squaredDistance2 = 3; double mean = (sqrt(squaredDistance1)+sqrt(squaredDistance2))/2; double variance = ((sqrt(squaredDistance1)-mean)*(sqrt(squaredDistance1)-mean)+(sqrt(squaredDistance2)-mean)*(sqrt(squaredDistance2)-mean))/2; double sd = sqrt(variance); double ms = 3.75/2; double rms = sqrt(ms); double min = sqrt(squaredDistance1); double max = sqrt(squaredDistance2); double median = (min + max)/2; mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator = mitk::PointSetDifferenceStatisticsCalculator::New(testPointSet1,testPointSet2); MITK_TEST_CONDITION_REQUIRED((myPointSetDifferenceStatisticsCalculator->GetNumberOfPoints()==testPointSet1->GetSize()),".. Testing GetNumberOfPoints"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetMean(),mean),".. Testing GetMean"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetSD(),sd),".. Testing GetSD"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetVariance(),variance),".. Testing GetVariance"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetRMS(),rms),".. Testing GetRMS"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetMin(),min),".. Testing GetMin"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetMax(),max),".. Testing GetMax"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(myPointSetDifferenceStatisticsCalculator->GetMedian(),median),".. Testing GetMedian"); testPointSet2->InsertPoint(2,test); myPointSetDifferenceStatisticsCalculator->SetPointSets(testPointSet1,testPointSet2); MITK_TEST_OUTPUT(<<"Test for exception when using differently sized point sets"); MITK_TEST_FOR_EXCEPTION(itk::ExceptionObject,myPointSetDifferenceStatisticsCalculator->GetMean()); mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator2 = mitk::PointSetDifferenceStatisticsCalculator::New(); MITK_TEST_OUTPUT(<<"Test for exception when using point sets with size 0"); MITK_TEST_FOR_EXCEPTION(itk::ExceptionObject,myPointSetDifferenceStatisticsCalculator2->GetMean()); } }; int mitkPointSetDifferenceStatisticsCalculatorTest(int argc, char* argv[]) { // always start with this! MITK_TEST_BEGIN("mitkPointSetDifferenceStatisticsCalculatorTest") // let's create an object of our class mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator = mitk::PointSetDifferenceStatisticsCalculator::New(); MITK_TEST_CONDITION_REQUIRED(myPointSetDifferenceStatisticsCalculator.IsNotNull(),"Testing instantiation with constructor 1."); mitk::PointSet::Pointer myTestPointSet1 = mitk::PointSet::New(); mitk::PointSet::Pointer myTestPointSet2 = mitk::PointSet::New(); mitk::PointSetDifferenceStatisticsCalculator::Pointer myPointSetDifferenceStatisticsCalculator2 = mitk::PointSetDifferenceStatisticsCalculator::New(myTestPointSet1,myTestPointSet2); MITK_TEST_CONDITION_REQUIRED(myPointSetDifferenceStatisticsCalculator2.IsNotNull(),"Testing instantiation with constructor 2."); mitkPointSetDifferenceStatisticsCalculatorTestClass::TestInstantiation(); mitkPointSetDifferenceStatisticsCalculatorTestClass::TestSimpleCase(); MITK_TEST_END() } <|endoftext|>
<commit_before>/*============================================================================= Copyright (c) 2012-2013 Richard Otis Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // declaration for functions related to EZD global minimization // Reference: Maria Emelianenko, Zi-Kui Liu, and Qiang Du. // "A new algorithm for the automation of phase diagram calculation." Computational Materials Science 35.1 (2006): 61-74. #ifndef INCLUDED_EZD_MINIMIZATION #define INCLUDED_EZD_MINIMIZATION #include "libgibbs/include/models.hpp" #include "libgibbs/include/compositionset.hpp" #include "libgibbs/include/constraint.hpp" #include "libgibbs/include/conditions.hpp" #include <boost/bimap.hpp> #include <vector> namespace Optimizer { template <typename T> struct Domain { std::vector<std::vector<T> > lower_left_corner; std::vector<std::vector<T> > upper_right_corner; }; void LocateMinima( CompositionSet const &phase, sublattice_set const &sublset, evalconditions const& conditions, const std::size_t depth = 1 ); } #endif <commit_msg>Remove Domain object<commit_after>/*============================================================================= Copyright (c) 2012-2013 Richard Otis Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // declaration for functions related to EZD global minimization // Reference: Maria Emelianenko, Zi-Kui Liu, and Qiang Du. // "A new algorithm for the automation of phase diagram calculation." Computational Materials Science 35.1 (2006): 61-74. #ifndef INCLUDED_EZD_MINIMIZATION #define INCLUDED_EZD_MINIMIZATION #include "libgibbs/include/models.hpp" #include "libgibbs/include/compositionset.hpp" #include "libgibbs/include/constraint.hpp" #include "libgibbs/include/conditions.hpp" #include <boost/bimap.hpp> #include <vector> namespace Optimizer { void LocateMinima( CompositionSet const &phase, sublattice_set const &sublset, evalconditions const& conditions, const std::size_t depth = 1 ); } #endif <|endoftext|>
<commit_before>/* WiFiServerBearSSL.cpp - SSL server for esp8266, mostly compatible with Arduino WiFi shield library Copyright (c) 2018 Earle F. Philhower, III 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 */ #define LWIP_INTERNAL extern "C" { #include "osapi.h" #include "ets_sys.h" } #include <StackThunk.h> #include "debug.h" #include "ESP8266WiFi.h" #include "WiFiClient.h" #include "WiFiServer.h" #include "lwip/opt.h" #include "lwip/tcp.h" #include "lwip/inet.h" #include <include/ClientContext.h> #include "WiFiServerSecureBearSSL.h" namespace BearSSL { // Only need to call the standard server constructor WiFiServerSecure::WiFiServerSecure(IPAddress addr, uint16_t port) : WiFiServer(addr, port) { stack_thunk_add_ref(); } // Only need to call the standard server constructor WiFiServerSecure::WiFiServerSecure(uint16_t port) : WiFiServer(port) { stack_thunk_add_ref(); } // Destructor only checks if we need to delete compatibilty cert/key WiFiServerSecure::~WiFiServerSecure() { stack_thunk_del_ref(); if (_deleteChainAndKey) { delete _chain; delete _sk; } } // Specify a RSA-signed certificate and key for the server. Only copies the pointer, the // caller needs to preserve this chain and key for the life of the object. void WiFiServerSecure::setRSACert(const X509List *chain, const PrivateKey *sk) { _chain = chain; _sk = sk; } // Specify a EC-signed certificate and key for the server. Only copies the pointer, the // caller needs to preserve this chain and key for the life of the object. void WiFiServerSecure::setECCert(const X509List *chain, unsigned cert_issuer_key_type, const PrivateKey *sk) { _chain = chain; _cert_issuer_key_type = cert_issuer_key_type; _sk = sk; } // Return a client if there's an available connection waiting. If one is returned, // then any validation (i.e. client cert checking) will have succeeded. WiFiClientSecure WiFiServerSecure::available(uint8_t* status) { (void) status; // Unused if (_unclaimed) { if (_sk && _sk->isRSA()) { WiFiClientSecure result(_unclaimed, _chain, _sk, _iobuf_in_size, _iobuf_out_size, _client_CA_ta); _unclaimed = _unclaimed->next(); result.setNoDelay(_noDelay); DEBUGV("WS:av\r\n"); return result; } else if (_sk && _sk->isEC()) { WiFiClientSecure result(_unclaimed, _chain, _cert_issuer_key_type, _sk, _iobuf_in_size, _iobuf_out_size, _client_CA_ta); _unclaimed = _unclaimed->next(); result.setNoDelay(_noDelay); DEBUGV("WS:av\r\n"); return result; } else { // No key was defined, so we can't actually accept and attempt accept() and SSL handshake. DEBUGV("WS:nokey\r\n"); } } // Something weird, return a no-op object optimistic_yield(1000); return WiFiClientSecure(); } void WiFiServerSecure::setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen) { X509List *chain = new X509List(cert, certLen); PrivateKey *sk = new PrivateKey(key, keyLen); if (!chain || !key) { // OOM, fail gracefully delete chain; delete sk; return; } _deleteChainAndKey = true; setRSACert(chain, sk); } void WiFiServerSecure::setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen) { setServerKeyAndCert(key, keyLen, cert, certLen); } }; <commit_msg>Fix BearSSL Server WDT (#5702)<commit_after>/* WiFiServerBearSSL.cpp - SSL server for esp8266, mostly compatible with Arduino WiFi shield library Copyright (c) 2018 Earle F. Philhower, III 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 */ #define LWIP_INTERNAL extern "C" { #include "osapi.h" #include "ets_sys.h" } #include <StackThunk.h> #include "debug.h" #include "ESP8266WiFi.h" #include "WiFiClient.h" #include "WiFiServer.h" #include "lwip/opt.h" #include "lwip/tcp.h" #include "lwip/inet.h" #include <include/ClientContext.h> #include "WiFiServerSecureBearSSL.h" namespace BearSSL { // Only need to call the standard server constructor WiFiServerSecure::WiFiServerSecure(IPAddress addr, uint16_t port) : WiFiServer(addr, port) { stack_thunk_add_ref(); } // Only need to call the standard server constructor WiFiServerSecure::WiFiServerSecure(uint16_t port) : WiFiServer(port) { stack_thunk_add_ref(); } // Destructor only checks if we need to delete compatibilty cert/key WiFiServerSecure::~WiFiServerSecure() { stack_thunk_del_ref(); if (_deleteChainAndKey) { delete _chain; delete _sk; } } // Specify a RSA-signed certificate and key for the server. Only copies the pointer, the // caller needs to preserve this chain and key for the life of the object. void WiFiServerSecure::setRSACert(const X509List *chain, const PrivateKey *sk) { _chain = chain; _sk = sk; } // Specify a EC-signed certificate and key for the server. Only copies the pointer, the // caller needs to preserve this chain and key for the life of the object. void WiFiServerSecure::setECCert(const X509List *chain, unsigned cert_issuer_key_type, const PrivateKey *sk) { _chain = chain; _cert_issuer_key_type = cert_issuer_key_type; _sk = sk; } // Return a client if there's an available connection waiting. If one is returned, // then any validation (i.e. client cert checking) will have succeeded. WiFiClientSecure WiFiServerSecure::available(uint8_t* status) { WiFiClientSecure client; (void) status; // Unused if (_unclaimed) { if (_sk && _sk->isRSA()) { WiFiClientSecure result(_unclaimed, _chain, _sk, _iobuf_in_size, _iobuf_out_size, _client_CA_ta); _unclaimed = _unclaimed->next(); result.setNoDelay(_noDelay); DEBUGV("WS:av\r\n"); client = result; } else if (_sk && _sk->isEC()) { WiFiClientSecure result(_unclaimed, _chain, _cert_issuer_key_type, _sk, _iobuf_in_size, _iobuf_out_size, _client_CA_ta); _unclaimed = _unclaimed->next(); result.setNoDelay(_noDelay); DEBUGV("WS:av\r\n"); client = result; } else { // No key was defined, so we can't actually accept and attempt accept() and SSL handshake. DEBUGV("WS:nokey\r\n"); } } else { optimistic_yield(1000); } return client; } void WiFiServerSecure::setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen) { X509List *chain = new X509List(cert, certLen); PrivateKey *sk = new PrivateKey(key, keyLen); if (!chain || !key) { // OOM, fail gracefully delete chain; delete sk; return; } _deleteChainAndKey = true; setRSACert(chain, sk); } void WiFiServerSecure::setServerKeyAndCert_P(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen) { setServerKeyAndCert(key, keyLen, cert, certLen); } }; <|endoftext|>
<commit_before>/********************************************************************* * * Condor ClassAd library * Copyright (C) 1990-2003, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI and Rajesh Raman. * * This source code is covered by the Condor Public License, which can * be found in the accompanying LICENSE file, or online at * www.condorproject.org. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS, * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY * RIGHT. * *********************************************************************/ #if defined( CLASSAD_DISTRIBUTION ) #include "classad_distribution.h" #else #include "condor_classad.h" #endif #include "lexerSource.h" #include "xmlSink.h" #include <fstream> #include <iostream> #include <ctype.h> #include <assert.h> #include "tester.h" using namespace std; #ifdef WANT_NAMESPACES using namespace classad; #endif typedef map<string, Variable *> VariableMap; /*-------------------------------------------------------------------- * * Private Data Types * *--------------------------------------------------------------------*/ enum Command { cmd_NoCommand, cmd_InvalidCommand, cmd_Let, cmd_Eval, cmd_Print, cmd_Same, cmd_Diff, cmd_Help }; class Parameters { public: bool debug; bool verbose; bool interactive; string input_file; void ParseCommandLine(int argc, char **argv); }; typedef map<string, Variable *> VariableMap; /*-------------------------------------------------------------------- * * Private Functions * *--------------------------------------------------------------------*/ bool read_line(string &line, Parameters &parameters); bool replace_variables(string &line, string &error, Parameters &parameters); Command get_command(string &line, Parameters &parameters); void get_variable_name(string &line, bool swallow_equals, string &variable_name, Parameters &parameters); ExprTree *get_expr(string &line, Parameters &parameters); void get_two_exprs(string &line, ExprTree *&tree1, ExprTree *&tree2, string &error, Parameters &parameters); void print_expr(ExprTree *tree, Parameters &parameters); bool evaluate_expr(ExprTree *tree, Value &value, Parameters &parameters); void shorten_line(string &line, int offset); /********************************************************************* * * Function: Parameters::ParseCommandLine * Purpose: This parses the command line. Note that it will exit * if there are any problems. * *********************************************************************/ void Parameters::ParseCommandLine(int argc, char **argv) { // First we set up the defaults. debug = false; verbose = false; interactive = true; input_file = ""; // Then we parse to see what the user wants. for (int arg_index = 1; arg_index < argc; arg_index++) { if ( !strcmp(argv[arg_index], "-d") || !strcmp(argv[arg_index], "-debug")) { debug = true; } else if ( !strcmp(argv[arg_index], "-v") || !strcmp(argv[arg_index], "-verbose")) { verbose = true; } else { if (!input_file.compare("")) { input_file = argv[arg_index]; interactive = false; } } } return; } Variable::Variable(string &name, ExprTree *tree) { _name = name; _tree = tree; _is_tree = true; return; } Variable::Variable(string &name, Value &value) { _name = name; _value = value; _is_tree = false; _tree = NULL; return; } Variable::~Variable() { if (_is_tree && _tree != NULL) { delete _tree; _tree = NULL; } return; } void Variable::GetStringRepresentation(string &representation) { ClassAdUnParser unparser; if (_is_tree) { unparser.Unparse(representation, _tree); } else { unparser.Unparse(representation, _value); } return; } VariableMap variables; /********************************************************************* * * Function: * Purpose: * *********************************************************************/ int main(int argc, char **argv) { string line; Parameters parameters; /* --- */ Value value; Variable *var; string name = "alain"; value.SetIntegerValue(33); var = new Variable(name, value); variables[name] = var; /* --- */ parameters.ParseCommandLine(argc, argv); while (read_line(line, parameters) == true) { bool good_line; string error; Command command; string variable_name; ExprTree *tree, *tree2; Variable *variable; good_line = replace_variables(line, error, parameters); if (!good_line) { cout << "Error: " << error << endl; } else { command = get_command(line, parameters); switch (command) { case cmd_NoCommand: cout << "Error: No command on line.\n"; break; case cmd_InvalidCommand: cout << "Unknown command on line.\n"; break; case cmd_Let: get_variable_name(line, true, variable_name, parameters); tree = get_expr(line, parameters); if (tree == NULL) { cout << "Couldn't parse rvalue.\n"; } else { variable = new Variable(variable_name, tree); variables[variable_name] = variable; print_expr(tree, parameters); } break; case cmd_Eval: get_variable_name(line, true, variable_name, parameters); tree = get_expr(line, parameters); if (tree == NULL) { cout << "Couldn't parse rvalue.\n"; } else { Value value; if (!evaluate_expr(tree, value, parameters)) { cout << "Couldn't evaluate rvalue.\n"; } else { variable = new Variable(variable_name, value); variables[variable_name] = variable; cout << value << endl; } } break; case cmd_Print: tree = get_expr(line, parameters); print_expr(tree, parameters); break; case cmd_Same: get_two_exprs(line, tree, tree2, error, parameters); if (tree == NULL || tree2 == NULL) { cout << "Error: " << error << endl; } else { if (tree->SameAs(tree2)) { cout << "Same.\n"; } else { cout << "Different.\n"; } } break; case cmd_Diff: break; case cmd_Help: break; } } } cout << endl; return 0; } /********************************************************************* * * Function: read_line * Purpose: * *********************************************************************/ bool read_line(string &line, Parameters &parameters) { bool have_input; line = ""; have_input = true; if (cin.eof()) { have_input = false; } else { cout << "> "; getline(cin, line, '\n'); if (cin.eof() && line.size() == 0) { have_input = false; } else { have_input = true; } } return have_input; } /********************************************************************* * * Function: replace_variables * Purpose: * *********************************************************************/ bool replace_variables(string &line, string &error, Parameters &parameters) { bool good_line; good_line = true; error = ""; for (;;) { int dollar, current_position; string variable_name; string variable_value; Variable *var; current_position = 0; dollar = line.find('$', current_position); if (dollar == -1) { break; } current_position = dollar + 1; if (!isalpha(line[current_position])){ good_line = false; error = "Bad variable name."; break; } current_position++; while (isalnum(line[current_position]) || line[current_position] == '_') { current_position++; } variable_name = line.substr(dollar + 1, current_position - (dollar + 1)); var = variables[variable_name]; if (var == NULL) { good_line = false; error = "Unknown variable '$"; error += variable_name; error += "'"; break; } var->GetStringRepresentation(variable_value); // We have to be careful with substr() because with gcc 2.96, it likes to // assert/except if you give it values that are too large. string end; if (current_position < (int) line.size()) { end = line.substr(current_position); } else { end = ""; } line = line.substr(0, dollar) + variable_value + end; } if (parameters.debug) { cerr << "after replacement: " << line << endl; } return good_line; } /********************************************************************* * * Function: get_command * Purpose: * *********************************************************************/ Command get_command(string &line, Parameters &parameters) { int current_position; int length; string command_name; Command command; current_position = 0; length = line.size(); command_name = ""; command = cmd_NoCommand; // Skip whitespace while (current_position < length && isspace(line[current_position])) { current_position++; } // Find command name while (current_position < length && isalpha(line[current_position])) { command_name += line[current_position]; current_position++; } // Figure out what the command is. if (command_name.size() == 0) { command = cmd_NoCommand; } else if (command_name == "let") { command = cmd_Let; } else if (command_name == "eval") { command = cmd_Eval; } else if (command_name == "print") { command = cmd_Print; } else if (command_name == "same") { command = cmd_Same; } else if (command_name == "diff") { command = cmd_Diff; } else if (command_name == "help") { command = cmd_Help; } else { command = cmd_InvalidCommand; } shorten_line(line, current_position); return command; } /********************************************************************* * * Function: get_variable_name * Purpose: * *********************************************************************/ void get_variable_name(string &line, bool swallow_equals, string &variable_name, Parameters &parameters) { int current_position; int length; current_position = 0; length = line.size(); variable_name = ""; // Skip whitespace while (current_position < length && isspace(line[current_position])) { current_position++; } // Find variable name while (current_position < length && isalpha(line[current_position])) { variable_name += line[current_position]; current_position++; } if (swallow_equals) { // Skip whitespace while (current_position < length && isspace(line[current_position])) { current_position++; } if (line[current_position] == '=') { current_position++; } // We should probably report an error if we didn't find an equal sign. // Maybe later. } shorten_line(line, current_position); return; } /********************************************************************* * * Function: get_expr * Purpose: * *********************************************************************/ ExprTree *get_expr(string &line, Parameters &parameters) { int offset; ExprTree *tree; ClassAdParser parser; StringLexerSource lexer_source(&line); tree = parser.ParseExpression(&lexer_source, false); offset = lexer_source.GetCurrentLocation(); shorten_line(line, offset); return tree; } void get_two_exprs(string &line, ExprTree *&tree1, ExprTree *&tree2, string &error, Parameters &parameters) { int offset; ClassAdParser parser; StringLexerSource lexer_source(&line); tree1 = parser.ParseExpression(&lexer_source, false); if (tree1 == NULL) { error = "Couldn't parse first expression."; } else { if (parameters.debug) { cout << "Tree1: "; print_expr(tree1, parameters); cout << endl; } if (parser.PeekToken() != Lexer::LEX_COMMA) { error = "Missing comma.\n"; delete tree1; tree1 = NULL; tree2 = NULL; } else { parser.ConsumeToken(); tree2 = parser.ParseNextExpression(); offset = lexer_source.GetCurrentLocation(); shorten_line(line, offset); if (tree2 == NULL) { error = "Couldn't parse second expression."; delete tree1; tree1 = NULL; } else if (parameters.debug){ cout << "Tree2: "; print_expr(tree2, parameters); cout << endl; } } } return; } void print_expr(ExprTree *tree, Parameters &parameters) { string output; ClassAdUnParser unparser; unparser.Unparse(output, tree); cout << output << endl; return; } bool evaluate_expr(ExprTree *tree, Value &value, Parameters &parameters) { ClassAd classad; bool success; classad.Insert("internal___", tree); success = classad.EvaluateAttr("internal___", value); classad.Remove("internal___"); return success; } void shorten_line(string &line, int offset) { // We have to be careful with substr() because with gcc 2.96, it likes to // assert/except if you give it values that are too large. if (offset < (int) line.size()) { line = line.substr(offset); } else { line = ""; } return; } <commit_msg>Added basic help.<commit_after>/********************************************************************* * * Condor ClassAd library * Copyright (C) 1990-2003, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI and Rajesh Raman. * * This source code is covered by the Condor Public License, which can * be found in the accompanying LICENSE file, or online at * www.condorproject.org. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS, * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY * RIGHT. * *********************************************************************/ #if defined(CLASSAD_DISTRIBUTION) #include "classad_distribution.h" #else #include "condor_classad.h" #endif #include "lexerSource.h" #include "xmlSink.h" #include <fstream> #include <iostream> #include <ctype.h> #include <assert.h> #include "tester.h" using namespace std; #ifdef WANT_NAMESPACES using namespace classad; #endif typedef map<string, Variable *> VariableMap; /*-------------------------------------------------------------------- * * Private Data Types * *--------------------------------------------------------------------*/ enum Command { cmd_NoCommand, cmd_InvalidCommand, cmd_Let, cmd_Eval, cmd_Print, cmd_Same, cmd_Diff, cmd_Help }; class Parameters { public: bool debug; bool verbose; bool interactive; string input_file; void ParseCommandLine(int argc, char **argv); }; typedef map<string, Variable *> VariableMap; /*-------------------------------------------------------------------- * * Private Functions * *--------------------------------------------------------------------*/ bool read_line(string &line, Parameters &parameters); bool replace_variables(string &line, string &error, Parameters &parameters); Command get_command(string &line, Parameters &parameters); void get_variable_name(string &line, bool swallow_equals, string &variable_name, Parameters &parameters); ExprTree *get_expr(string &line, Parameters &parameters); void get_two_exprs(string &line, ExprTree *&tree1, ExprTree *&tree2, string &error, Parameters &parameters); void print_expr(ExprTree *tree, Parameters &parameters); bool evaluate_expr(ExprTree *tree, Value &value, Parameters &parameters); void shorten_line(string &line, int offset); void print_help(void); void print_version(void); /********************************************************************* * * Function: Parameters::ParseCommandLine * Purpose: This parses the command line. Note that it will exit * if there are any problems. * *********************************************************************/ void Parameters::ParseCommandLine(int argc, char **argv) { // First we set up the defaults. debug = false; verbose = false; interactive = true; input_file = ""; // Then we parse to see what the user wants. for (int arg_index = 1; arg_index < argc; arg_index++) { if ( !strcmp(argv[arg_index], "-d") || !strcmp(argv[arg_index], "-debug")) { debug = true; } else if ( !strcmp(argv[arg_index], "-v") || !strcmp(argv[arg_index], "-verbose")) { verbose = true; } else { if (!input_file.compare("")) { input_file = argv[arg_index]; interactive = false; } } } return; } Variable::Variable(string &name, ExprTree *tree) { _name = name; _tree = tree; _is_tree = true; return; } Variable::Variable(string &name, Value &value) { _name = name; _value = value; _is_tree = false; _tree = NULL; return; } Variable::~Variable() { if (_is_tree && _tree != NULL) { delete _tree; _tree = NULL; } return; } void Variable::GetStringRepresentation(string &representation) { ClassAdUnParser unparser; if (_is_tree) { unparser.Unparse(representation, _tree); } else { unparser.Unparse(representation, _value); } return; } VariableMap variables; /********************************************************************* * * Function: * Purpose: * *********************************************************************/ int main(int argc, char **argv) { string line; Parameters parameters; print_version(); parameters.ParseCommandLine(argc, argv); while (read_line(line, parameters) == true) { bool good_line; string error; Command command; string variable_name; ExprTree *tree, *tree2; Variable *variable; good_line = replace_variables(line, error, parameters); if (!good_line) { cout << "Error: " << error << endl; } else { command = get_command(line, parameters); switch (command) { case cmd_NoCommand: cout << "Error: No command on line.\n"; break; case cmd_InvalidCommand: cout << "Unknown command on line.\n"; break; case cmd_Let: get_variable_name(line, true, variable_name, parameters); tree = get_expr(line, parameters); if (tree == NULL) { cout << "Couldn't parse rvalue.\n"; } else { variable = new Variable(variable_name, tree); variables[variable_name] = variable; print_expr(tree, parameters); } break; case cmd_Eval: get_variable_name(line, true, variable_name, parameters); tree = get_expr(line, parameters); if (tree == NULL) { cout << "Couldn't parse rvalue.\n"; } else { Value value; if (!evaluate_expr(tree, value, parameters)) { cout << "Couldn't evaluate rvalue.\n"; } else { variable = new Variable(variable_name, value); variables[variable_name] = variable; cout << value << endl; } } break; case cmd_Print: tree = get_expr(line, parameters); print_expr(tree, parameters); break; case cmd_Same: get_two_exprs(line, tree, tree2, error, parameters); if (tree == NULL || tree2 == NULL) { cout << "Error: " << error << endl; } else { if (tree->SameAs(tree2)) { cout << "Same.\n"; } else { cout << "Different.\n"; } } break; case cmd_Diff: break; case cmd_Help: print_help(); break; } } } cout << endl; return 0; } /********************************************************************* * * Function: read_line * Purpose: * *********************************************************************/ bool read_line(string &line, Parameters &parameters) { bool have_input; line = ""; have_input = true; if (cin.eof()) { have_input = false; } else { cout << "> "; getline(cin, line, '\n'); if (cin.eof() && line.size() == 0) { have_input = false; } else { have_input = true; } } return have_input; } /********************************************************************* * * Function: replace_variables * Purpose: * *********************************************************************/ bool replace_variables(string &line, string &error, Parameters &parameters) { bool good_line; good_line = true; error = ""; for (;;) { int dollar, current_position; string variable_name; string variable_value; Variable *var; current_position = 0; dollar = line.find('$', current_position); if (dollar == -1) { break; } current_position = dollar + 1; if (!isalpha(line[current_position])){ good_line = false; error = "Bad variable name."; break; } current_position++; while (isalnum(line[current_position]) || line[current_position] == '_') { current_position++; } variable_name = line.substr(dollar + 1, current_position - (dollar + 1)); var = variables[variable_name]; if (var == NULL) { good_line = false; error = "Unknown variable '$"; error += variable_name; error += "'"; break; } var->GetStringRepresentation(variable_value); // We have to be careful with substr() because with gcc 2.96, it likes to // assert/except if you give it values that are too large. string end; if (current_position < (int) line.size()) { end = line.substr(current_position); } else { end = ""; } line = line.substr(0, dollar) + variable_value + end; } if (parameters.debug) { cerr << "after replacement: " << line << endl; } return good_line; } /********************************************************************* * * Function: get_command * Purpose: * *********************************************************************/ Command get_command(string &line, Parameters &parameters) { int current_position; int length; string command_name; Command command; current_position = 0; length = line.size(); command_name = ""; command = cmd_NoCommand; // Skip whitespace while (current_position < length && isspace(line[current_position])) { current_position++; } // Find command name while (current_position < length && isalpha(line[current_position])) { command_name += line[current_position]; current_position++; } // Figure out what the command is. if (command_name.size() == 0) { command = cmd_NoCommand; } else if (command_name == "let") { command = cmd_Let; } else if (command_name == "eval") { command = cmd_Eval; } else if (command_name == "print") { command = cmd_Print; } else if (command_name == "same") { command = cmd_Same; } else if (command_name == "diff") { command = cmd_Diff; } else if (command_name == "help") { command = cmd_Help; } else { command = cmd_InvalidCommand; } shorten_line(line, current_position); return command; } /********************************************************************* * * Function: get_variable_name * Purpose: * *********************************************************************/ void get_variable_name(string &line, bool swallow_equals, string &variable_name, Parameters &parameters) { int current_position; int length; current_position = 0; length = line.size(); variable_name = ""; // Skip whitespace while (current_position < length && isspace(line[current_position])) { current_position++; } // Find variable name while (current_position < length && isalpha(line[current_position])) { variable_name += line[current_position]; current_position++; } if (swallow_equals) { // Skip whitespace while (current_position < length && isspace(line[current_position])) { current_position++; } if (line[current_position] == '=') { current_position++; } // We should probably report an error if we didn't find an equal sign. // Maybe later. } shorten_line(line, current_position); return; } /********************************************************************* * * Function: get_expr * Purpose: * *********************************************************************/ ExprTree *get_expr(string &line, Parameters &parameters) { int offset; ExprTree *tree; ClassAdParser parser; StringLexerSource lexer_source(&line); tree = parser.ParseExpression(&lexer_source, false); offset = lexer_source.GetCurrentLocation(); shorten_line(line, offset); return tree; } void get_two_exprs(string &line, ExprTree *&tree1, ExprTree *&tree2, string &error, Parameters &parameters) { int offset; ClassAdParser parser; StringLexerSource lexer_source(&line); tree1 = parser.ParseExpression(&lexer_source, false); if (tree1 == NULL) { error = "Couldn't parse first expression."; } else { if (parameters.debug) { cout << "Tree1: "; print_expr(tree1, parameters); cout << endl; } if (parser.PeekToken() != Lexer::LEX_COMMA) { error = "Missing comma.\n"; delete tree1; tree1 = NULL; tree2 = NULL; } else { parser.ConsumeToken(); tree2 = parser.ParseNextExpression(); offset = lexer_source.GetCurrentLocation(); shorten_line(line, offset); if (tree2 == NULL) { error = "Couldn't parse second expression."; delete tree1; tree1 = NULL; } else if (parameters.debug){ cout << "Tree2: "; print_expr(tree2, parameters); cout << endl; } } } return; } void print_expr(ExprTree *tree, Parameters &parameters) { string output; ClassAdUnParser unparser; unparser.Unparse(output, tree); cout << output << endl; return; } bool evaluate_expr(ExprTree *tree, Value &value, Parameters &parameters) { ClassAd classad; bool success; classad.Insert("internal___", tree); success = classad.EvaluateAttr("internal___", value); classad.Remove("internal___"); return success; } void shorten_line(string &line, int offset) { // We have to be careful with substr() because with gcc 2.96, it likes to // assert/except if you give it values that are too large. if (offset < (int) line.size()) { line = line.substr(offset); } else { line = ""; } return; } void print_help(void) { print_version(); cout << "Commands:\n"; cout << "let name = expr Set a variable to an unevaluated expression.\n"; cout << "eval name = expr Set a variable to an evaluated expression.\n"; cout << "same expr1 expr2 Prints a message only if expr1 and expr2 are different.\n"; cout << "diff expr1 expr2 Prints a message only if expr1 and expr2 are the same.\n"; cout << "quit Exit this program.\n"; cout << "help Print this message.\n"; } void print_version(void) { string classad_version; ClassAdLibraryVersion(classad_version); cout << "ClassAd Tester v" << classad_version << endl; return; } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg 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 author 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. */ #ifdef TORRENT_DEBUG #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <string> #include <cstring> #include <stdlib.h> // uClibc++ doesn't have cxxabi.h #if defined __GNUC__ && __GNUC__ >= 3 \ && !defined __UCLIBCXX_MAJOR__ #include <cxxabi.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #else std::string demangle(char const* name) { return name; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> #include "libtorrent/version.hpp" // execinfo.h is available in the MacOS X 10.5 SDK. #if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) #include <execinfo.h> void print_backtrace(char* out, int len) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 1; i < size && len > 0; ++i) { int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str()); out += ret; len -= ret; } free(symbols); } #else void print_backtrace(FILE* out, char const* label) {} #endif #if TORRENT_PRODUCTION_ASSERTS char const* libtorrent_assert_log = "asserts.log"; #endif void assert_fail(char const* expr, int line, char const* file, char const* function, char const* value) { #if TORRENT_PRODUCTION_ASSERTS FILE* out = fopen(libtorrent_assert_log, "a+"); if (out == 0) out = stderr; #else FILE* out = stderr; #endif char stack[8192]; print_backtrace(stack, sizeof(stack)); fprintf(out, "assertion failed. Please file a bugreport at " "http://code.rasterbar.com/libtorrent/newticket\n" "Please include the following information:\n\n" "version: " LIBTORRENT_VERSION "\n" "%s\n" "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "%s%s\n" "stack:\n" "%s\n" , LIBTORRENT_REVISION, file, line, function, expr , value ? value : "", value ? "\n" : "" , stack); // if production asserts are defined, don't abort, just print the error #if TORRENT_PRODUCTION_ASSERTS if (out != stderr) fclose(out); #else // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); #endif } #else void assert_fail(char const* expr, int line, char const* file, char const* function) {} #endif <commit_msg>we need backtraces for asio-debugging as well<commit_after>/* Copyright (c) 2007, Arvid Norberg 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 author 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. */ #if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <string> #include <cstring> #include <stdlib.h> // uClibc++ doesn't have cxxabi.h #if defined __GNUC__ && __GNUC__ >= 3 \ && !defined __UCLIBCXX_MAJOR__ #include <cxxabi.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #else std::string demangle(char const* name) { return name; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> #include "libtorrent/version.hpp" // execinfo.h is available in the MacOS X 10.5 SDK. #if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) #include <execinfo.h> void print_backtrace(char* out, int len) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 1; i < size && len > 0; ++i) { int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str()); out += ret; len -= ret; } free(symbols); } #else void print_backtrace(FILE* out, char const* label) {} #endif #if TORRENT_PRODUCTION_ASSERTS char const* libtorrent_assert_log = "asserts.log"; #endif void assert_fail(char const* expr, int line, char const* file, char const* function, char const* value) { #if TORRENT_PRODUCTION_ASSERTS FILE* out = fopen(libtorrent_assert_log, "a+"); if (out == 0) out = stderr; #else FILE* out = stderr; #endif char stack[8192]; print_backtrace(stack, sizeof(stack)); fprintf(out, "assertion failed. Please file a bugreport at " "http://code.rasterbar.com/libtorrent/newticket\n" "Please include the following information:\n\n" "version: " LIBTORRENT_VERSION "\n" "%s\n" "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "%s%s\n" "stack:\n" "%s\n" , LIBTORRENT_REVISION, file, line, function, expr , value ? value : "", value ? "\n" : "" , stack); // if production asserts are defined, don't abort, just print the error #if TORRENT_PRODUCTION_ASSERTS if (out != stderr) fclose(out); #else // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); #endif } #else void assert_fail(char const* expr, int line, char const* file, char const* function) {} #endif <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2015 ARM Limited * * 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 <stdio.h> #include "TestHarness.h" #include "mbed.h" /* Serial asynch cross */ #if !DEVICE_SERIAL || !DEVICE_SERIAL_ASYNCH #error serial_asynch requires asynch Serial #endif // Device config #if defined(TARGET_K64F) #define TEST_SERIAL_ONE_TX_PIN PTC17 // uart3 #define TEST_SERIAL_TWO_RX_PIN PTD2 // uart2 #elif defined(TARGET_K66F) #define TEST_SERIAL_ONE_TX_PIN PTD3 // uart2 #define TEST_SERIAL_TWO_RX_PIN PTC16 // uart3 #elif defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32GG_STK3700) || defined(TARGET_EFM32WG_STK3800) #define TEST_SERIAL_ONE_TX_PIN PD0 // usart1 #define TEST_SERIAL_TWO_RX_PIN PC3 // usart2 #elif defined(TARGET_EFM32ZG_STK3200) #error "Target not supported (only 2 serial ports available, need 3)" #elif defined(TARGET_EFM32HG_STK3400) #define TEST_SERIAL_ONE_TX_PIN PE10 // usart0 #define TEST_SERIAL_TWO_RX_PIN PC1 // usart1 #elif defined(TARGET_B96B_F446VE) #define TEST_SERIAL_ONE_TX_PIN D1 // UART2 #define TEST_SERIAL_TWO_RX_PIN D4 // UART5 #elif defined(TARGET_NUCLEO_L152RE) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_NUCLEO_F103RB) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_NUCLEO_F207ZG) #define TEST_SERIAL_ONE_TX_PIN PC_12 // UART5 #define TEST_SERIAL_TWO_RX_PIN PC_11 // UART4 #elif defined(TARGET_DISCO_F334C8) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_NUCLEO_F302R8) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_NUCLEO_F303RE) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_NUCLEO_F334R8) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_DISCO_F429ZI) #define TEST_SERIAL_ONE_TX_PIN PD_5 // UART2 #define TEST_SERIAL_TWO_RX_PIN PG_9 // UART6 #elif defined(TARGET_NUCLEO_F401RE) #define TEST_SERIAL_ONE_TX_PIN PB_6 // UART1 #define TEST_SERIAL_TWO_RX_PIN PC_7 // UART6 #elif defined(TARGET_NUCLEO_F411RE) #define TEST_SERIAL_ONE_TX_PIN PB_6 // UART1 #define TEST_SERIAL_TWO_RX_PIN PC_7 // UART6 #elif defined(TARGET_NUCLEO_F446RE) #define TEST_SERIAL_ONE_TX_PIN PB_6 // UART1 #define TEST_SERIAL_TWO_RX_PIN PC_7 // UART6 #elif defined(TARGET_NUCLEO_F410RB) #define TEST_SERIAL_ONE_TX_PIN PB_6 // UART1 #define TEST_SERIAL_TWO_RX_PIN PC_7 // UART6 #elif defined(TARGET_NUCLEO_F429ZI) #define TEST_SERIAL_ONE_TX_PIN PE_8 // UART7 #define TEST_SERIAL_TWO_RX_PIN PG_9 // UART6 #elif defined(TARGET_NUCLEO_F446ZE) #define TEST_SERIAL_ONE_TX_PIN PB_6 // UART1 #define TEST_SERIAL_TWO_RX_PIN PG_9 // UART6 #elif defined(TARGET_NUCLEO_L476RG) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_RZ_A1H) #define TEST_SERIAL_ONE_TX_PIN P8_14 // UART4 #define TEST_SERIAL_TWO_RX_PIN P8_11 // UART5 #else #error Target not supported #endif // Test config #define SHORT_XFR 3 #define LONG_XFR 16 #define TEST_BYTE_TX_BASE 0x5555 #define TEST_BYTE_RX 0x5A5A volatile int tx_event_flag; volatile bool tx_complete; volatile int rx_event_flag; volatile bool rx_complete; void cb_tx_done(int event) { tx_complete = true; tx_event_flag = event; } void cb_rx_done(int event) { rx_complete = true; rx_event_flag = event; } TEST_GROUP(Serial_Asynchronous) { uint8_t tx_buf[LONG_XFR]; uint8_t rx_buf[LONG_XFR]; Serial *serial_tx; Serial *serial_rx; event_callback_t tx_callback; event_callback_t rx_callback; void setup() { serial_tx = new Serial(TEST_SERIAL_ONE_TX_PIN, NC); serial_rx = new Serial(NC, TEST_SERIAL_TWO_RX_PIN); tx_complete = false; tx_event_flag = 0; rx_complete = false; rx_event_flag = 0; tx_callback.attach(cb_tx_done); rx_callback.attach(cb_rx_done); // Set the default value of tx_buf for (uint32_t i = 0; i < sizeof(tx_buf); i++) { tx_buf[i] = i + TEST_BYTE_TX_BASE; } memset(rx_buf, TEST_BYTE_RX, sizeof(rx_buf)); } void teardown() { delete serial_tx; serial_tx = NULL; delete serial_rx; serial_rx = NULL; } uint32_t cmpnbufc(uint8_t expect, uint8_t *actual, uint32_t offset, uint32_t end, const char *file, uint32_t line) { uint32_t i; for (i = offset; i < end; i++){ if (expect != actual[i]) { break; } } if (i < end) { CHECK_EQUAL_LOCATION((int)expect, (int)actual[i], file, line); } CHECK_EQUAL_LOCATION(end, i, file, line); return i; } uint32_t cmpnbuf(uint8_t *expect, uint8_t *actual, uint32_t offset, uint32_t end, const char *file, uint32_t line) { uint32_t i; for (i = offset; i < end; i++){ if (expect[i] != actual[i]) { break; } } if (i < end) { CHECK_EQUAL_LOCATION((int)expect[i], (int)actual[i], file, line); } CHECK_EQUAL_LOCATION(end, i, file, line); return i; } }; TEST(Serial_Asynchronous, short_tx_0_rx) { int rc; rc = serial_tx->write(tx_buf, SHORT_XFR, tx_callback, -1); CHECK_EQUAL(0, rc); while (!tx_complete); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); // rx buffer unchanged cmpnbufc(TEST_BYTE_RX, rx_buf, 0, sizeof(rx_buf), __FILE__, __LINE__); } TEST(Serial_Asynchronous, short_tx_short_rx) { int rc; serial_rx->read(rx_buf, SHORT_XFR, rx_callback, -1); rc = serial_tx->write(tx_buf, SHORT_XFR, tx_callback, -1); CHECK_EQUAL(0, rc); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_COMPLETE, rx_event_flag); // Check that the receive buffer contains the fill byte. cmpnbuf(tx_buf, rx_buf, 0, SHORT_XFR, __FILE__, __LINE__); // Check that remaining portion of the receive buffer contains the rx test byte cmpnbufc(TEST_BYTE_RX, rx_buf, SHORT_XFR, sizeof(rx_buf), __FILE__, __LINE__); } TEST(Serial_Asynchronous, long_tx_long_rx) { int rc; serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1); rc = serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); CHECK_EQUAL(0, rc); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_COMPLETE, rx_event_flag); // Check that the receive buffer contains the fill byte. cmpnbuf(tx_buf, rx_buf, 0, LONG_XFR, __FILE__, __LINE__); // Check that remaining portion of the receive buffer contains the rx test byte cmpnbufc(TEST_BYTE_RX, rx_buf, LONG_XFR, sizeof(rx_buf), __FILE__, __LINE__); } TEST(Serial_Asynchronous, rx_parity_error) { int rc; // Set different parity for RX and TX serial_rx->format(8, SerialBase::Even, 1); serial_tx->format(8, SerialBase::Odd, 1); serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1); rc = serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); CHECK_EQUAL(0, rc); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_PARITY_ERROR, rx_event_flag); } TEST(Serial_Asynchronous, rx_framing_error) { int rc; serial_tx->baud(4800); serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1); rc = serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); CHECK_EQUAL(0, rc); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_FRAMING_ERROR, rx_event_flag); } TEST(Serial_Asynchronous, char_matching_success) { // match found serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1, (uint8_t)(TEST_BYTE_TX_BASE+5)); serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_CHARACTER_MATCH, rx_event_flag); cmpnbufc(TEST_BYTE_RX, rx_buf, 5, sizeof(rx_buf), __FILE__, __LINE__); } TEST(Serial_Asynchronous, char_matching_failed) { // no match found (specified match char is not in tx buffer) serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1, (uint8_t)(TEST_BYTE_TX_BASE + sizeof(tx_buf))); serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_COMPLETE, rx_event_flag); cmpnbuf(tx_buf, rx_buf, 0, LONG_XFR, __FILE__, __LINE__); } TEST(Serial_Asynchronous, char_matching_with_complete) { serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1, (uint8_t)(TEST_BYTE_TX_BASE + sizeof(tx_buf) - 1)); serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL((SERIAL_EVENT_RX_COMPLETE | SERIAL_EVENT_RX_CHARACTER_MATCH), rx_event_flag); cmpnbuf(tx_buf, rx_buf, 0, LONG_XFR, __FILE__, __LINE__); } <commit_msg>STM32F7 - Add tests for asynchronous serial<commit_after>/* mbed Microcontroller Library * Copyright (c) 2015 ARM Limited * * 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 <stdio.h> #include "TestHarness.h" #include "mbed.h" /* Serial asynch cross */ #if !DEVICE_SERIAL || !DEVICE_SERIAL_ASYNCH #error serial_asynch requires asynch Serial #endif // Device config #if defined(TARGET_K64F) #define TEST_SERIAL_ONE_TX_PIN PTC17 // uart3 #define TEST_SERIAL_TWO_RX_PIN PTD2 // uart2 #elif defined(TARGET_K66F) #define TEST_SERIAL_ONE_TX_PIN PTD3 // uart2 #define TEST_SERIAL_TWO_RX_PIN PTC16 // uart3 #elif defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32GG_STK3700) || defined(TARGET_EFM32WG_STK3800) #define TEST_SERIAL_ONE_TX_PIN PD0 // usart1 #define TEST_SERIAL_TWO_RX_PIN PC3 // usart2 #elif defined(TARGET_EFM32ZG_STK3200) #error "Target not supported (only 2 serial ports available, need 3)" #elif defined(TARGET_EFM32HG_STK3400) #define TEST_SERIAL_ONE_TX_PIN PE10 // usart0 #define TEST_SERIAL_TWO_RX_PIN PC1 // usart1 #elif defined(TARGET_B96B_F446VE) #define TEST_SERIAL_ONE_TX_PIN D1 // UART2 #define TEST_SERIAL_TWO_RX_PIN D4 // UART5 #elif defined(TARGET_NUCLEO_L152RE) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_NUCLEO_F103RB) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_NUCLEO_F207ZG) #define TEST_SERIAL_ONE_TX_PIN PC_12 // UART5 #define TEST_SERIAL_TWO_RX_PIN PC_11 // UART4 #elif defined(TARGET_DISCO_F334C8) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_NUCLEO_F302R8) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_NUCLEO_F303RE) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_NUCLEO_F334R8) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_DISCO_F429ZI) #define TEST_SERIAL_ONE_TX_PIN PD_5 // UART2 #define TEST_SERIAL_TWO_RX_PIN PG_9 // UART6 #elif defined(TARGET_NUCLEO_F401RE) #define TEST_SERIAL_ONE_TX_PIN PB_6 // UART1 #define TEST_SERIAL_TWO_RX_PIN PC_7 // UART6 #elif defined(TARGET_NUCLEO_F411RE) #define TEST_SERIAL_ONE_TX_PIN PB_6 // UART1 #define TEST_SERIAL_TWO_RX_PIN PC_7 // UART6 #elif defined(TARGET_NUCLEO_F446RE) #define TEST_SERIAL_ONE_TX_PIN PB_6 // UART1 #define TEST_SERIAL_TWO_RX_PIN PC_7 // UART6 #elif defined(TARGET_NUCLEO_F410RB) #define TEST_SERIAL_ONE_TX_PIN PB_6 // UART1 #define TEST_SERIAL_TWO_RX_PIN PC_7 // UART6 #elif defined(TARGET_NUCLEO_F429ZI) #define TEST_SERIAL_ONE_TX_PIN PE_8 // UART7 #define TEST_SERIAL_TWO_RX_PIN PG_9 // UART6 #elif defined(TARGET_NUCLEO_F446ZE) #define TEST_SERIAL_ONE_TX_PIN PB_6 // UART1 #define TEST_SERIAL_TWO_RX_PIN PG_9 // UART6 #elif defined(TARGET_DISCO_F746NG) #define TEST_SERIAL_ONE_TX_PIN PC_6 // UART6 #define TEST_SERIAL_TWO_RX_PIN PF_6 // UART7 #elif defined(TARGET_NUCLEO_F746ZG) #define TEST_SERIAL_ONE_TX_PIN PC_12 // UART5 #define TEST_SERIAL_TWO_RX_PIN PC_11 // UART4 #elif defined(TARGET_NUCLEO_F767ZI) #define TEST_SERIAL_ONE_TX_PIN PC_12 // UART5 #define TEST_SERIAL_TWO_RX_PIN PC_11 // UART4 #elif defined(TARGET_NUCLEO_L476RG) #define TEST_SERIAL_ONE_TX_PIN PB_10 // UART3 #define TEST_SERIAL_TWO_RX_PIN PA_10 // UART1 #elif defined(TARGET_RZ_A1H) #define TEST_SERIAL_ONE_TX_PIN P8_14 // UART4 #define TEST_SERIAL_TWO_RX_PIN P8_11 // UART5 #else #error Target not supported #endif // Test config #define SHORT_XFR 3 #define LONG_XFR 16 #define TEST_BYTE_TX_BASE 0x5555 #define TEST_BYTE_RX 0x5A5A volatile int tx_event_flag; volatile bool tx_complete; volatile int rx_event_flag; volatile bool rx_complete; void cb_tx_done(int event) { tx_complete = true; tx_event_flag = event; } void cb_rx_done(int event) { rx_complete = true; rx_event_flag = event; } TEST_GROUP(Serial_Asynchronous) { uint8_t tx_buf[LONG_XFR]; uint8_t rx_buf[LONG_XFR]; Serial *serial_tx; Serial *serial_rx; event_callback_t tx_callback; event_callback_t rx_callback; void setup() { serial_tx = new Serial(TEST_SERIAL_ONE_TX_PIN, NC); serial_rx = new Serial(NC, TEST_SERIAL_TWO_RX_PIN); tx_complete = false; tx_event_flag = 0; rx_complete = false; rx_event_flag = 0; tx_callback.attach(cb_tx_done); rx_callback.attach(cb_rx_done); // Set the default value of tx_buf for (uint32_t i = 0; i < sizeof(tx_buf); i++) { tx_buf[i] = i + TEST_BYTE_TX_BASE; } memset(rx_buf, TEST_BYTE_RX, sizeof(rx_buf)); } void teardown() { delete serial_tx; serial_tx = NULL; delete serial_rx; serial_rx = NULL; } uint32_t cmpnbufc(uint8_t expect, uint8_t *actual, uint32_t offset, uint32_t end, const char *file, uint32_t line) { uint32_t i; for (i = offset; i < end; i++){ if (expect != actual[i]) { break; } } if (i < end) { CHECK_EQUAL_LOCATION((int)expect, (int)actual[i], file, line); } CHECK_EQUAL_LOCATION(end, i, file, line); return i; } uint32_t cmpnbuf(uint8_t *expect, uint8_t *actual, uint32_t offset, uint32_t end, const char *file, uint32_t line) { uint32_t i; for (i = offset; i < end; i++){ if (expect[i] != actual[i]) { break; } } if (i < end) { CHECK_EQUAL_LOCATION((int)expect[i], (int)actual[i], file, line); } CHECK_EQUAL_LOCATION(end, i, file, line); return i; } }; TEST(Serial_Asynchronous, short_tx_0_rx) { int rc; rc = serial_tx->write(tx_buf, SHORT_XFR, tx_callback, -1); CHECK_EQUAL(0, rc); while (!tx_complete); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); // rx buffer unchanged cmpnbufc(TEST_BYTE_RX, rx_buf, 0, sizeof(rx_buf), __FILE__, __LINE__); } TEST(Serial_Asynchronous, short_tx_short_rx) { int rc; serial_rx->read(rx_buf, SHORT_XFR, rx_callback, -1); rc = serial_tx->write(tx_buf, SHORT_XFR, tx_callback, -1); CHECK_EQUAL(0, rc); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_COMPLETE, rx_event_flag); // Check that the receive buffer contains the fill byte. cmpnbuf(tx_buf, rx_buf, 0, SHORT_XFR, __FILE__, __LINE__); // Check that remaining portion of the receive buffer contains the rx test byte cmpnbufc(TEST_BYTE_RX, rx_buf, SHORT_XFR, sizeof(rx_buf), __FILE__, __LINE__); } TEST(Serial_Asynchronous, long_tx_long_rx) { int rc; serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1); rc = serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); CHECK_EQUAL(0, rc); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_COMPLETE, rx_event_flag); // Check that the receive buffer contains the fill byte. cmpnbuf(tx_buf, rx_buf, 0, LONG_XFR, __FILE__, __LINE__); // Check that remaining portion of the receive buffer contains the rx test byte cmpnbufc(TEST_BYTE_RX, rx_buf, LONG_XFR, sizeof(rx_buf), __FILE__, __LINE__); } TEST(Serial_Asynchronous, rx_parity_error) { int rc; // Set different parity for RX and TX serial_rx->format(8, SerialBase::Even, 1); serial_tx->format(8, SerialBase::Odd, 1); serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1); rc = serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); CHECK_EQUAL(0, rc); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_PARITY_ERROR, rx_event_flag); } TEST(Serial_Asynchronous, rx_framing_error) { int rc; serial_tx->baud(4800); serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1); rc = serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); CHECK_EQUAL(0, rc); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_FRAMING_ERROR, rx_event_flag); } TEST(Serial_Asynchronous, char_matching_success) { // match found serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1, (uint8_t)(TEST_BYTE_TX_BASE+5)); serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_CHARACTER_MATCH, rx_event_flag); cmpnbufc(TEST_BYTE_RX, rx_buf, 5, sizeof(rx_buf), __FILE__, __LINE__); } TEST(Serial_Asynchronous, char_matching_failed) { // no match found (specified match char is not in tx buffer) serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1, (uint8_t)(TEST_BYTE_TX_BASE + sizeof(tx_buf))); serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL(SERIAL_EVENT_RX_COMPLETE, rx_event_flag); cmpnbuf(tx_buf, rx_buf, 0, LONG_XFR, __FILE__, __LINE__); } TEST(Serial_Asynchronous, char_matching_with_complete) { serial_rx->read(rx_buf, LONG_XFR, rx_callback, -1, (uint8_t)(TEST_BYTE_TX_BASE + sizeof(tx_buf) - 1)); serial_tx->write(tx_buf, LONG_XFR, tx_callback, -1); while ((!tx_complete) || (!rx_complete)); CHECK_EQUAL(SERIAL_EVENT_TX_COMPLETE, tx_event_flag); CHECK_EQUAL((SERIAL_EVENT_RX_COMPLETE | SERIAL_EVENT_RX_CHARACTER_MATCH), rx_event_flag); cmpnbuf(tx_buf, rx_buf, 0, LONG_XFR, __FILE__, __LINE__); } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg 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 author 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. */ #ifdef __GNUC__ #include <cxxabi.h> #include <string> #include <cstring> #include <stdlib.h> std::string demangle(char const* name) { // in case this string comes char const* start = strchr(name, '('); if (start != 0) ++start; else start = name; char const* end = strchr(start, '+'); std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #endif #ifdef TORRENT_DEBUG #include <stdlib.h> #include <stdio.h> #include <signal.h> #if defined __linux__ && defined __GNUC__ #include <execinfo.h> #endif void assert_fail(char const* expr, int line, char const* file, char const* function) { fprintf(stderr, "assertion failed. Please file a bugreport at " "http://code.rasterbar.com/libtorrent/newticket\n" "Please include the following information:\n\n" "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "stack:\n", file, line, function, expr); #if defined __linux__ && defined __GNUC__ void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 0; i < size; ++i) { fprintf(stderr, "%d: %s\n", i, demangle(symbols[i]).c_str()); } free(symbols); #endif // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); } #else void assert_fail(char const* expr, int line, char const* file, char const* function) {} #endif <commit_msg>simplified assert.cpp, included stack-traces on Mac (assumes 10.5). Makes it easier to debug asio hangs since the backtraces can be used externally<commit_after>/* Copyright (c) 2007, Arvid Norberg 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 author 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. */ #ifdef TORRENT_DEBUG #ifdef __GNUC__ #include <cxxabi.h> #include <string> #include <cstring> #include <stdlib.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> // execinfo.h is available in the MacOS X 10.5 SDK. I // don't know of a define to distiguish between SDKs, so // for now, all Mac builds are assumed to be using 10.5 // for debug builds. If this fails for you, just remove // the __APPLE__ check #if (defined __linux__ || defined __APPLE__) #include <execinfo.h> void print_backtrace(char const* label) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); fprintf(stderr, "%s\n", label); for (int i = 1; i < size; ++i) { fprintf(stderr, "%d: %s\n", i, demangle(symbols[i]).c_str()); } free(symbols); } #else void print_backtrace(char const* label) {} #endif void assert_fail(char const* expr, int line, char const* file, char const* function) { fprintf(stderr, "assertion failed. Please file a bugreport at " "http://code.rasterbar.com/libtorrent/newticket\n" "Please include the following information:\n\n" "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n", file, line, function, expr); print_backtrace("stack:"); // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); } #else void assert_fail(char const* expr, int line, char const* file, char const* function) {} #endif <|endoftext|>
<commit_before>#include <mach/mach_port.h> #include <mach/mach_interface.h> #include <mach/mach_init.h> #include <IOKit/pwr_mgt/IOPMLib.h> #include <IOKit/IOMessage.h> #include <pthread.h> #include <uv.h> #include "pm.h" #include "constants.h" io_connect_t root_port; // a reference to the Root Power Domain IOService IONotificationPortRef notifyPortRef; // notification port allocated by IORegisterForSystemPower pthread_t lookupThread; pthread_mutex_t notify_mutex; pthread_cond_t notify_cv; char *notify_msg; bool isRunning = false; void NotifyCallBack(void * refCon, io_service_t service, natural_t messageType, void * messageArgument ) { // fprintf(stderr, "messageType %08lx, arg %08lx\n", // (long unsigned int)messageType, // (long unsigned int)messageArgument ); switch ( messageType ) { case kIOMessageCanSystemSleep: /* Idle sleep is about to kick in. This message will not be sent for forced sleep. Applications have a chance to prevent sleep by calling IOCancelPowerChange. Most applications should not prevent idle sleep. Power Management waits up to 30 seconds for you to either allow or deny idle sleep. If you don't acknowledge this power change by calling either IOAllowPowerChange or IOCancelPowerChange, the system will wait 30 seconds then go to sleep. */ //Uncomment to cancel idle sleep //IOCancelPowerChange( root_port, (long)messageArgument ); // we will allow idle sleep // fprintf(stderr, "kIOMessageCanSystemSleep\n"); IOAllowPowerChange( root_port, (long)messageArgument ); break; case kIOMessageSystemWillSleep: /* The system WILL go to sleep. If you do not call IOAllowPowerChange or IOCancelPowerChange to acknowledge this message, sleep will be delayed by 30 seconds. NOTE: If you call IOCancelPowerChange to deny sleep it returns kIOReturnSuccess, however the system WILL still go to sleep. */ // fprintf(stderr, "kIOMessageSystemWillSleep\n"); pthread_mutex_lock(&notify_mutex); notify_msg = (char*) SLEEP_NOTIFY; pthread_cond_signal(&notify_cv); pthread_mutex_unlock(&notify_mutex); IOAllowPowerChange( root_port, (long)messageArgument ); break; case kIOMessageSystemWillPowerOn: //System has started the wake up process... // fprintf(stderr, "kIOMessageSystemWillPowerOn\n"); // pthread_mutex_lock(&notify_mutex); // strcpy(notify_msg, "waking"); // pthread_cond_signal(&notify_cv); // pthread_mutex_unlock(&notify_mutex); break; case kIOMessageSystemHasPoweredOn: //System has finished waking up... // fprintf(stderr, "kIOMessageSystemHasPoweredOn\n"); pthread_mutex_lock(&notify_mutex); notify_msg = (char*) WAKE_NOTIFY; pthread_cond_signal(&notify_cv); pthread_mutex_unlock(&notify_mutex); break; default: break; } } void NotifyAsync(uv_work_t* req) { pthread_mutex_lock(&notify_mutex); pthread_cond_wait(&notify_cv, &notify_mutex); pthread_mutex_unlock(&notify_mutex); } void NotifyFinished(uv_work_t* req) { pthread_mutex_lock(&notify_mutex); if (isRunning) { Notify(notify_msg); } pthread_mutex_unlock(&notify_mutex); uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished); } void *RunLoop(void * arg) { // add the notification port to the application runloop CFRunLoopAddSource( CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes ); /* Start the run loop to receive sleep notifications. Don't call CFRunLoopRun if this code is running on the main thread of a Cocoa or Carbon application. Cocoa and Carbon manage the main thread's run loop for you as part of their event handling mechanisms. */ CFRunLoopRun(); // We should never get here fprintf(stderr, "Unexpectedly back from CFRunLoopRun()!\n"); return NULL; } void Start() { isRunning = true; } void Stop() { isRunning = false; pthread_mutex_lock(&notify_mutex); pthread_cond_signal(&notify_cv); pthread_mutex_unlock(&notify_mutex); } void InitPM() { // notifier object, used to deregister later io_object_t notifierObject; // this parameter is passed to the callback void* refCon = NULL; // register to receive system sleep notifications root_port = IORegisterForSystemPower( refCon, &notifyPortRef, NotifyCallBack, &notifierObject ); if ( root_port == 0 ) { fprintf(stderr, "IORegisterForSystemPower failed\n"); } pthread_mutex_init(&notify_mutex, NULL); pthread_cond_init(&notify_cv, NULL); int rc = pthread_create(&lookupThread, NULL, RunLoop, NULL); if (rc) { fprintf(stderr, "ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } uv_work_t* req = new uv_work_t(); uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished); Start(); }<commit_msg>fix stop<commit_after>#include <mach/mach_port.h> #include <mach/mach_interface.h> #include <mach/mach_init.h> #include <IOKit/pwr_mgt/IOPMLib.h> #include <IOKit/IOMessage.h> #include <pthread.h> #include <uv.h> #include "pm.h" #include "constants.h" io_connect_t root_port; // a reference to the Root Power Domain IOService IONotificationPortRef notifyPortRef; // notification port allocated by IORegisterForSystemPower pthread_t lookupThread; pthread_mutex_t notify_mutex; pthread_cond_t notify_cv; char *notify_msg; bool isRunning = false; void NotifyCallBack(void * refCon, io_service_t service, natural_t messageType, void * messageArgument ) { // fprintf(stderr, "messageType %08lx, arg %08lx\n", // (long unsigned int)messageType, // (long unsigned int)messageArgument ); switch ( messageType ) { case kIOMessageCanSystemSleep: /* Idle sleep is about to kick in. This message will not be sent for forced sleep. Applications have a chance to prevent sleep by calling IOCancelPowerChange. Most applications should not prevent idle sleep. Power Management waits up to 30 seconds for you to either allow or deny idle sleep. If you don't acknowledge this power change by calling either IOAllowPowerChange or IOCancelPowerChange, the system will wait 30 seconds then go to sleep. */ //Uncomment to cancel idle sleep //IOCancelPowerChange( root_port, (long)messageArgument ); // we will allow idle sleep // fprintf(stderr, "kIOMessageCanSystemSleep\n"); IOAllowPowerChange( root_port, (long)messageArgument ); break; case kIOMessageSystemWillSleep: /* The system WILL go to sleep. If you do not call IOAllowPowerChange or IOCancelPowerChange to acknowledge this message, sleep will be delayed by 30 seconds. NOTE: If you call IOCancelPowerChange to deny sleep it returns kIOReturnSuccess, however the system WILL still go to sleep. */ // fprintf(stderr, "kIOMessageSystemWillSleep\n"); pthread_mutex_lock(&notify_mutex); notify_msg = (char*) SLEEP_NOTIFY; pthread_cond_signal(&notify_cv); pthread_mutex_unlock(&notify_mutex); IOAllowPowerChange( root_port, (long)messageArgument ); break; case kIOMessageSystemWillPowerOn: //System has started the wake up process... // fprintf(stderr, "kIOMessageSystemWillPowerOn\n"); // pthread_mutex_lock(&notify_mutex); // strcpy(notify_msg, "waking"); // pthread_cond_signal(&notify_cv); // pthread_mutex_unlock(&notify_mutex); break; case kIOMessageSystemHasPoweredOn: //System has finished waking up... // fprintf(stderr, "kIOMessageSystemHasPoweredOn\n"); pthread_mutex_lock(&notify_mutex); notify_msg = (char*) WAKE_NOTIFY; pthread_cond_signal(&notify_cv); pthread_mutex_unlock(&notify_mutex); break; default: break; } } void NotifyAsync(uv_work_t* req) { pthread_mutex_lock(&notify_mutex); pthread_cond_wait(&notify_cv, &notify_mutex); pthread_mutex_unlock(&notify_mutex); } void NotifyFinished(uv_work_t* req) { if (isRunning) { pthread_mutex_lock(&notify_mutex); Notify(notify_msg); pthread_mutex_unlock(&notify_mutex); uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished); } } void *RunLoop(void * arg) { // add the notification port to the application runloop CFRunLoopAddSource( CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes ); /* Start the run loop to receive sleep notifications. Don't call CFRunLoopRun if this code is running on the main thread of a Cocoa or Carbon application. Cocoa and Carbon manage the main thread's run loop for you as part of their event handling mechanisms. */ CFRunLoopRun(); // We should never get here fprintf(stderr, "Unexpectedly back from CFRunLoopRun()!\n"); return NULL; } void Start() { isRunning = true; } void Stop() { isRunning = false; pthread_mutex_lock(&notify_mutex); pthread_cond_signal(&notify_cv); pthread_mutex_unlock(&notify_mutex); } void InitPM() { // notifier object, used to deregister later io_object_t notifierObject; // this parameter is passed to the callback void* refCon = NULL; // register to receive system sleep notifications root_port = IORegisterForSystemPower( refCon, &notifyPortRef, NotifyCallBack, &notifierObject ); if ( root_port == 0 ) { fprintf(stderr, "IORegisterForSystemPower failed\n"); } pthread_mutex_init(&notify_mutex, NULL); pthread_cond_init(&notify_cv, NULL); int rc = pthread_create(&lookupThread, NULL, RunLoop, NULL); if (rc) { fprintf(stderr, "ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } uv_work_t* req = new uv_work_t(); uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished); Start(); }<|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 1998 Preston Brown <pbrown@kde.org> Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "calprinter.h" #include "calprintdefaultplugins.h" #include "korganizer/corehelper.h" #include <kvbox.h> #include <kconfig.h> #include <kdebug.h> #include <kdeversion.h> #include <kstandardguiitem.h> #include <kcombobox.h> #include <kprintpreview.h> #include <QButtonGroup> #include <QLabel> #include <QLayout> #include <QGridLayout> #include <QGroupBox> #include <QPushButton> #include <QRadioButton> #include <QSplitter> #include <QStackedWidget> #include <QPrintDialog> #include <QPrinter> #ifndef KORG_NOPRINTER #include "calprinter.moc" CalPrinter::CalPrinter( QWidget *parent, Calendar *calendar, KOrg::CoreHelper *helper ) : QObject( parent ) { mParent = parent; mConfig = new KConfig( "korganizer_printing.rc", KConfig::OnlyLocal ); mCoreHelper = helper; init( calendar ); } CalPrinter::~CalPrinter() { mPrintPlugins.clear(); delete mConfig; } void CalPrinter::init( Calendar *calendar ) { mCalendar = calendar; mPrintPlugins.clear(); mPrintPlugins = mCoreHelper->loadPrintPlugins(); mPrintPlugins.prepend( new CalPrintTodos() ); mPrintPlugins.prepend( new CalPrintMonth() ); mPrintPlugins.prepend( new CalPrintWeek() ); mPrintPlugins.prepend( new CalPrintDay() ); mPrintPlugins.prepend( new CalPrintIncidence() ); KOrg::PrintPlugin::List::Iterator it = mPrintPlugins.begin(); for ( ; it != mPrintPlugins.end(); ++it ) { if ( *it ) { (*it)->setConfig( mConfig ); (*it)->setCalendar( mCalendar ); (*it)->setKOrgCoreHelper( mCoreHelper ); (*it)->doLoadConfig(); } } } void CalPrinter::setDateRange( const QDate &fd, const QDate &td ) { KOrg::PrintPlugin::List::Iterator it = mPrintPlugins.begin(); for ( ; it != mPrintPlugins.end(); ++it ) { (*it)->setDateRange( fd, td ); } } void CalPrinter::print( int type, const QDate &fd, const QDate &td, Incidence::List selectedIncidences, bool preview ) { KOrg::PrintPlugin::List::Iterator it = mPrintPlugins.begin(); for ( it = mPrintPlugins.begin(); it != mPrintPlugins.end(); ++it ) { (*it)->setSelectedIncidences( selectedIncidences ); } CalPrintDialog printDialog( mPrintPlugins, mParent ); KConfigGroup grp( mConfig, "" ); //orientation setting isn't in a group printDialog.setOrientation( CalPrinter::ePrintOrientation( grp.readEntry( "Orientation", 1 ) ) ); printDialog.setPreview( preview ); printDialog.setPrintType( type ); setDateRange( fd, td ); if ( printDialog.exec() == QDialog::Accepted ) { grp.writeEntry( "Orientation", (int)printDialog.orientation() ); // Save all changes in the dialog for ( it = mPrintPlugins.begin(); it != mPrintPlugins.end(); ++it ) { (*it)->doSaveConfig(); } doPrint( printDialog.selectedPlugin(), printDialog.orientation(), preview ); } for ( it = mPrintPlugins.begin(); it != mPrintPlugins.end(); ++it ) { (*it)->setSelectedIncidences( Incidence::List() ); } } void CalPrinter::doPrint( KOrg::PrintPlugin *selectedStyle, CalPrinter::ePrintOrientation dlgorientation, bool preview ) { if ( !selectedStyle ) { KMessageBox::error( mParent, i18n( "Unable to print, no valid print style was returned." ), i18n( "Printing error" ) ); return; } QPrinter printer; switch ( dlgorientation ) { case eOrientPlugin: printer.setOrientation( selectedStyle->defaultOrientation() ); break; case eOrientPortrait: printer.setOrientation( QPrinter::Portrait ); break; case eOrientLandscape: printer.setOrientation( QPrinter::Landscape ); break; case eOrientPrinter: default: break; } if ( preview ) { KPrintPreview printPreview( &printer ); selectedStyle->doPrint( &printer ); printPreview.exec(); } else { QPrintDialog printDialog( &printer, mParent ); if ( printDialog.exec() == QDialog::Accepted ) { selectedStyle->doPrint( &printer ); } } } void CalPrinter::updateConfig() { } CalPrintDialog::CalPrintDialog( KOrg::PrintPlugin::List plugins, QWidget *parent ) : KDialog( parent ) { setCaption( i18n( "Print" ) ); setButtons( Ok | Cancel ); setModal( true ); KVBox *page = new KVBox( this ); setMainWidget( page ); QSplitter *splitter = new QSplitter( page ); splitter->setOrientation( Qt::Horizontal ); QGroupBox *typeBox = new QGroupBox( i18n( "Print Style" ), splitter ); QBoxLayout *typeLayout = new QVBoxLayout( typeBox ); mTypeGroup = new QButtonGroup( typeBox ); QWidget *splitterRight = new QWidget( splitter ); QGridLayout *splitterRightLayout = new QGridLayout( splitterRight ); splitterRightLayout->setMargin( marginHint() ); splitterRightLayout->setSpacing( spacingHint() ); mConfigArea = new QStackedWidget( splitterRight ); splitterRightLayout->addMultiCellWidget( mConfigArea, 0, 0, 0, 1 ); QLabel *orientationLabel = new QLabel( i18n( "Page &orientation:" ), splitterRight ); splitterRightLayout->addWidget( orientationLabel, 1, 0 ); mOrientationSelection = new KComboBox( splitterRight ); mOrientationSelection->addItem( i18n( "Use Default Orientation of Selected Style" ) ); mOrientationSelection->addItem( i18n( "Use Printer Default" ) ); mOrientationSelection->addItem( i18n( "Portrait" ) ); mOrientationSelection->addItem( i18n( "Landscape" ) ); splitterRightLayout->addWidget( mOrientationSelection, 1, 1 ); // signals and slots connections connect( mTypeGroup, SIGNAL( buttonClicked( int ) ), SLOT( setPrintType( int ) ) ); orientationLabel->setBuddy( mOrientationSelection ); // First insert the config widgets into the widget stack. This possibly assigns // proper ids (when two plugins have the same sortID), so store them in a map // and use these new IDs to later sort the plugins for the type selection. for ( KOrg::PrintPlugin::List::Iterator it = plugins.begin(); it != plugins.end(); ++it ) { int newid = mConfigArea->insertWidget( (*it)->sortID(), (*it)->configWidget( mConfigArea ) ); mPluginIDs[newid] = (*it); } // Insert all plugins in sorted order; plugins with clashing IDs will be first QMap<int, KOrg::PrintPlugin*>::ConstIterator mapit; int firstButton = true; int id = 0; for ( mapit = mPluginIDs.begin(); mapit != mPluginIDs.end(); ++mapit ) { KOrg::PrintPlugin *p = mapit.value(); QRadioButton *radioButton = new QRadioButton( p->description() ); radioButton->setEnabled( p->enabled() ); if ( firstButton && p->enabled() ) { firstButton = false; radioButton->setChecked( true ); setPrintType( id ); } mTypeGroup->addButton( radioButton, mapit.key() ); typeLayout->addWidget( radioButton ); id++; } typeLayout->insertStretch( -1, 100 ); connect( this, SIGNAL(okClicked()), SLOT(slotOk()) ); setMinimumSize( minimumSizeHint() ); resize( minimumSizeHint() ); } CalPrintDialog::~CalPrintDialog() { } void CalPrintDialog::setPreview( bool preview ) { if ( preview ) { setButtonText( Ok, i18n( "&Preview" ) ); } else { setButtonText( Ok, KStandardGuiItem::print().text() ); } } void CalPrintDialog::setPrintType( int i ) { mConfigArea->setCurrentIndex( i ); mConfigArea->currentWidget()->raise(); } void CalPrintDialog::setOrientation( CalPrinter::ePrintOrientation orientation ) { mOrientation = orientation; mOrientationSelection->setCurrentIndex( mOrientation ); } KOrg::PrintPlugin *CalPrintDialog::selectedPlugin() { int id = mConfigArea->currentIndex(); if ( mPluginIDs.contains( id ) ) { return mPluginIDs[id]; } else { return 0; } } void CalPrintDialog::slotOk() { mOrientation = ( CalPrinter::ePrintOrientation )mOrientationSelection->currentIndex(); QMap<int, KOrg::PrintPlugin*>::Iterator it = mPluginIDs.begin(); for ( ; it != mPluginIDs.end(); ++it ) { if ( it.value() ) { it.value()->readSettingsWidget(); } } } #endif <commit_msg>deprecated-- also, don't allow the splitter to collapse children because then the print type button group disappears, and that isn't good.<commit_after>/* This file is part of KOrganizer. Copyright (c) 1998 Preston Brown <pbrown@kde.org> Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "calprinter.h" #include "calprintdefaultplugins.h" #include "korganizer/corehelper.h" #include <kvbox.h> #include <kconfig.h> #include <kdebug.h> #include <kdeversion.h> #include <kstandardguiitem.h> #include <kcombobox.h> #include <kprintpreview.h> #include <QButtonGroup> #include <QLabel> #include <QLayout> #include <QGridLayout> #include <QGroupBox> #include <QPushButton> #include <QRadioButton> #include <QSplitter> #include <QStackedWidget> #include <QPrintDialog> #include <QPrinter> #ifndef KORG_NOPRINTER #include "calprinter.moc" CalPrinter::CalPrinter( QWidget *parent, Calendar *calendar, KOrg::CoreHelper *helper ) : QObject( parent ) { mParent = parent; mConfig = new KConfig( "korganizer_printing.rc", KConfig::OnlyLocal ); mCoreHelper = helper; init( calendar ); } CalPrinter::~CalPrinter() { mPrintPlugins.clear(); delete mConfig; } void CalPrinter::init( Calendar *calendar ) { mCalendar = calendar; mPrintPlugins.clear(); mPrintPlugins = mCoreHelper->loadPrintPlugins(); mPrintPlugins.prepend( new CalPrintTodos() ); mPrintPlugins.prepend( new CalPrintMonth() ); mPrintPlugins.prepend( new CalPrintWeek() ); mPrintPlugins.prepend( new CalPrintDay() ); mPrintPlugins.prepend( new CalPrintIncidence() ); KOrg::PrintPlugin::List::Iterator it = mPrintPlugins.begin(); for ( ; it != mPrintPlugins.end(); ++it ) { if ( *it ) { (*it)->setConfig( mConfig ); (*it)->setCalendar( mCalendar ); (*it)->setKOrgCoreHelper( mCoreHelper ); (*it)->doLoadConfig(); } } } void CalPrinter::setDateRange( const QDate &fd, const QDate &td ) { KOrg::PrintPlugin::List::Iterator it = mPrintPlugins.begin(); for ( ; it != mPrintPlugins.end(); ++it ) { (*it)->setDateRange( fd, td ); } } void CalPrinter::print( int type, const QDate &fd, const QDate &td, Incidence::List selectedIncidences, bool preview ) { KOrg::PrintPlugin::List::Iterator it = mPrintPlugins.begin(); for ( it = mPrintPlugins.begin(); it != mPrintPlugins.end(); ++it ) { (*it)->setSelectedIncidences( selectedIncidences ); } CalPrintDialog printDialog( mPrintPlugins, mParent ); KConfigGroup grp( mConfig, "" ); //orientation setting isn't in a group printDialog.setOrientation( CalPrinter::ePrintOrientation( grp.readEntry( "Orientation", 1 ) ) ); printDialog.setPreview( preview ); printDialog.setPrintType( type ); setDateRange( fd, td ); if ( printDialog.exec() == QDialog::Accepted ) { grp.writeEntry( "Orientation", (int)printDialog.orientation() ); // Save all changes in the dialog for ( it = mPrintPlugins.begin(); it != mPrintPlugins.end(); ++it ) { (*it)->doSaveConfig(); } doPrint( printDialog.selectedPlugin(), printDialog.orientation(), preview ); } for ( it = mPrintPlugins.begin(); it != mPrintPlugins.end(); ++it ) { (*it)->setSelectedIncidences( Incidence::List() ); } } void CalPrinter::doPrint( KOrg::PrintPlugin *selectedStyle, CalPrinter::ePrintOrientation dlgorientation, bool preview ) { if ( !selectedStyle ) { KMessageBox::error( mParent, i18n( "Unable to print, no valid print style was returned." ), i18n( "Printing error" ) ); return; } QPrinter printer; switch ( dlgorientation ) { case eOrientPlugin: printer.setOrientation( selectedStyle->defaultOrientation() ); break; case eOrientPortrait: printer.setOrientation( QPrinter::Portrait ); break; case eOrientLandscape: printer.setOrientation( QPrinter::Landscape ); break; case eOrientPrinter: default: break; } if ( preview ) { KPrintPreview printPreview( &printer ); selectedStyle->doPrint( &printer ); printPreview.exec(); } else { QPrintDialog printDialog( &printer, mParent ); if ( printDialog.exec() == QDialog::Accepted ) { selectedStyle->doPrint( &printer ); } } } void CalPrinter::updateConfig() { } CalPrintDialog::CalPrintDialog( KOrg::PrintPlugin::List plugins, QWidget *parent ) : KDialog( parent ) { setCaption( i18n( "Print" ) ); setButtons( Ok | Cancel ); setModal( true ); KVBox *page = new KVBox( this ); setMainWidget( page ); QSplitter *splitter = new QSplitter( page ); splitter->setOrientation( Qt::Horizontal ); splitter->setChildrenCollapsible( false ); QGroupBox *typeBox = new QGroupBox( i18n( "Print Style" ), splitter ); QBoxLayout *typeLayout = new QVBoxLayout( typeBox ); mTypeGroup = new QButtonGroup( typeBox ); QWidget *splitterRight = new QWidget( splitter ); QGridLayout *splitterRightLayout = new QGridLayout( splitterRight ); splitterRightLayout->setMargin( marginHint() ); splitterRightLayout->setSpacing( spacingHint() ); mConfigArea = new QStackedWidget( splitterRight ); splitterRightLayout->addWidget( mConfigArea, 0, 0, 1, 2 ); QLabel *orientationLabel = new QLabel( i18n( "Page &orientation:" ), splitterRight ); splitterRightLayout->addWidget( orientationLabel, 1, 0 ); mOrientationSelection = new KComboBox( splitterRight ); mOrientationSelection->addItem( i18n( "Use Default Orientation of Selected Style" ) ); mOrientationSelection->addItem( i18n( "Use Printer Default" ) ); mOrientationSelection->addItem( i18n( "Portrait" ) ); mOrientationSelection->addItem( i18n( "Landscape" ) ); splitterRightLayout->addWidget( mOrientationSelection, 1, 1 ); // signals and slots connections connect( mTypeGroup, SIGNAL( buttonClicked( int ) ), SLOT( setPrintType( int ) ) ); orientationLabel->setBuddy( mOrientationSelection ); // First insert the config widgets into the widget stack. This possibly assigns // proper ids (when two plugins have the same sortID), so store them in a map // and use these new IDs to later sort the plugins for the type selection. for ( KOrg::PrintPlugin::List::Iterator it = plugins.begin(); it != plugins.end(); ++it ) { int newid = mConfigArea->insertWidget( (*it)->sortID(), (*it)->configWidget( mConfigArea ) ); mPluginIDs[newid] = (*it); } // Insert all plugins in sorted order; plugins with clashing IDs will be first QMap<int, KOrg::PrintPlugin*>::ConstIterator mapit; int firstButton = true; int id = 0; for ( mapit = mPluginIDs.begin(); mapit != mPluginIDs.end(); ++mapit ) { KOrg::PrintPlugin *p = mapit.value(); QRadioButton *radioButton = new QRadioButton( p->description() ); radioButton->setEnabled( p->enabled() ); if ( firstButton && p->enabled() ) { firstButton = false; radioButton->setChecked( true ); setPrintType( id ); } mTypeGroup->addButton( radioButton, mapit.key() ); typeLayout->addWidget( radioButton ); id++; } typeLayout->insertStretch( -1, 100 ); connect( this, SIGNAL(okClicked()), SLOT(slotOk()) ); setMinimumSize( minimumSizeHint() ); resize( minimumSizeHint() ); } CalPrintDialog::~CalPrintDialog() { } void CalPrintDialog::setPreview( bool preview ) { if ( preview ) { setButtonText( Ok, i18n( "&Preview" ) ); } else { setButtonText( Ok, KStandardGuiItem::print().text() ); } } void CalPrintDialog::setPrintType( int i ) { mConfigArea->setCurrentIndex( i ); mConfigArea->currentWidget()->raise(); } void CalPrintDialog::setOrientation( CalPrinter::ePrintOrientation orientation ) { mOrientation = orientation; mOrientationSelection->setCurrentIndex( mOrientation ); } KOrg::PrintPlugin *CalPrintDialog::selectedPlugin() { int id = mConfigArea->currentIndex(); if ( mPluginIDs.contains( id ) ) { return mPluginIDs[id]; } else { return 0; } } void CalPrintDialog::slotOk() { mOrientation = ( CalPrinter::ePrintOrientation )mOrientationSelection->currentIndex(); QMap<int, KOrg::PrintPlugin*>::Iterator it = mPluginIDs.begin(); for ( ; it != mPluginIDs.end(); ++it ) { if ( it.value() ) { it.value()->readSettingsWidget(); } } } #endif <|endoftext|>
<commit_before>// Copyright 2010-2013 Google // 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 <algorithm> #include <string> #include <vector> #include "base/integral_types.h" #include "base/concise_iterator.h" #include "base/int-type-indexed-vector.h" #include "base/int-type.h" #include "base/logging.h" #include "base/hash.h" #include "base/scoped_ptr.h" #include "base/stringprintf.h" #include "constraint_solver/constraint_solver.h" #include "constraint_solver/constraint_solveri.h" #include "util/string_array.h" namespace operations_research { // Diffn constraint, Non overlapping rectangles. namespace { DEFINE_INT_TYPE(Box, int); class Diffn : public Constraint { public: Diffn(Solver* const solver, const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<IntVar*>& x_size, const std::vector<IntVar*>& y_size) : Constraint(solver), x_(x_vars), y_(y_vars), dx_(x_size), dy_(y_size), size_(x_vars.size()) { CHECK_EQ(x_vars.size(), y_vars.size()); CHECK_EQ(x_vars.size(), x_size.size()); CHECK_EQ(x_vars.size(), y_size.size()); } virtual ~Diffn() {} virtual void Post() { Solver* const s = solver(); for (int i = 0; i < size_; ++i) { Demon* const demon = MakeConstraintDemon1(solver(), this, &Diffn::RangeBox, "RangeBox", i); x_[i]->WhenRange(demon); y_[i]->WhenRange(demon); dx_[i]->WhenRange(demon); dy_[i]->WhenRange(demon); } delayed_demon_ = MakeDelayedConstraintDemon0( solver(), this, &Diffn::PropagateAll, "PropagateAll"); if (AreAllBound(dx_) && AreAllBound(dy_) && IsArrayInRange(x_, 0LL, kint64max) && IsArrayInRange(y_, 0LL, kint64max)) { // We can add redundant cumulative constraints. // Cumulative on x variables.e const int64 min_x = MinVarArray(x_); const int64 max_x = MaxVarArray(x_); const int64 max_size_x = MaxVarArray(dx_); const int64 min_y = MinVarArray(y_); const int64 max_y = MaxVarArray(y_); const int64 max_size_y = MaxVarArray(dy_); vector<int64> size_x; FillValues(dx_, &size_x); vector<int64> size_y; FillValues(dy_, &size_y); AddCumulativeConstraint(x_, size_x, size_y, max_size_y + max_y - min_y); AddCumulativeConstraint(y_, size_y, size_x, max_size_x + max_x - min_x); } } virtual void InitialPropagate() { // All sizes should be > 0. for (int i = 0; i < size_; ++i) { dx_[i]->SetMin(1); dy_[i]->SetMin(1); } // Force propagation on all boxes. to_propagate_.clear(); for (int i = 0; i < size_; i++) { to_propagate_.insert(i); } PropagateAll(); } void RangeBox(int box) { to_propagate_.insert(box); EnqueueDelayedDemon(delayed_demon_); } void PropagateAll() { for (ConstIter<hash_set<int>> it(to_propagate_); !it.at_end(); ++it) { const int box = *it; FillNeighbors(box); CheckEnergy(box); PushOverlappingBoxes(box); } to_propagate_.clear(); } virtual string DebugString() const { return StringPrintf("Diffn(x = [%s], y = [%s], dx = [%s], dy = [%s]))", DebugStringVector(x_, ", ").c_str(), DebugStringVector(y_, ", ").c_str(), DebugStringVector(dx_, ", ").c_str(), DebugStringVector(dy_, ", ").c_str()); } virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kDisjunctive, this); visitor->VisitIntegerVariableArrayArgument( ModelVisitor::kPositionXArgument, x_); visitor->VisitIntegerVariableArrayArgument( ModelVisitor::kPositionYArgument, y_); visitor->VisitIntegerVariableArrayArgument( ModelVisitor::kSizeXArgument, dx_); visitor->VisitIntegerVariableArrayArgument( ModelVisitor::kSizeYArgument, dy_); visitor->EndVisitConstraint(ModelVisitor::kDisjunctive, this); } private: bool Overlap(int i, int j) { if (DisjointHorizontal(i, j) || DisjointVertical(i, j)) { return false; } return true; } bool DisjointHorizontal(int i, int j) { return (x_[i]->Min() >= x_[j]->Max() + dx_[j]->Max()) || (x_[j]->Min() >= x_[i]->Max() + dx_[i]->Max()); } bool DisjointVertical(int i, int j) { return (y_[i]->Min() >= y_[j]->Max() + dy_[j]->Max()) || (y_[j]->Min() >= y_[i]->Max() + dy_[i]->Max()); } // Fill neighbors_ with all boxes overlapping box. void FillNeighbors(int box) { neighbors_.clear(); for (int other = 0; other < size_; ++other) { if (other != box && Overlap(other, box)) { neighbors_.push_back(other); } } } // Check that the minimum area of a set of boxes is always contained in // the bounding box of these boxes. void CheckEnergy(int box) { int64 area_min_x = x_[box]->Min(); int64 area_max_x = x_[box]->Max() + dx_[box]->Max(); int64 area_min_y = y_[box]->Min(); int64 area_max_y = y_[box]->Max() + dy_[box]->Max(); int64 sum_of_areas = dx_[box]->Min() * dy_[box]->Min(); for (int i = 0; i < neighbors_.size(); ++i) { const int other = neighbors_[i]; // Update Bounding box. area_min_x = std::min(area_min_x, x_[other]->Min()); area_max_x = std::max(area_max_x, x_[other]->Max() + dx_[other]->Max()); area_min_y = std::min(area_min_y, y_[other]->Min()); area_max_y = std::max(area_max_y, y_[other]->Max() + dy_[other]->Max()); // Update sum of areas. sum_of_areas += dx_[other]->Min() * dy_[other]->Min(); const int64 bounding_area = (area_max_x - area_min_x) * (area_max_y - area_min_y); if (sum_of_areas > bounding_area) { solver()->Fail(); } } } // Push all boxes apart the mandatory part of a box. void PushOverlappingBoxes(int box) { // Mandatory part of box. const int64 start_max_box_x = x_[box]->Max(); const int64 end_min_box_x = x_[box]->Min() + dx_[box]->Min(); const int64 start_max_box_y = y_[box]->Max(); const int64 end_min_box_y = y_[box]->Min() + dy_[box]->Min(); // Mandatory part non empty? if (start_max_box_x < end_min_box_x && start_max_box_y < end_min_box_y) { // Try to push overlapping boxes. for (int i = 0; i < neighbors_.size(); ++i) { PushOneBox(box, neighbors_[i], start_max_box_x, end_min_box_x, start_max_box_y, end_min_box_y); } } } void PushOneDirection(int box, int other, int64 start_max_box, int64 end_min_box, int64 start_max_other, int64 end_min_other, const std::vector<IntVar*>& positions, const std::vector<IntVar*>& sizes) { if (end_min_other > start_max_box) { // Other is forced after box. positions[other]->SetMin(end_min_box); positions[box]->SetMax(start_max_other - sizes[box]->Min()); sizes[box]->SetMax(start_max_other - positions[box]->Min()); } else if (end_min_box > start_max_other) { // Box is forced after other. positions[box]->SetMin(end_min_other); positions[other]->SetMax(start_max_box - sizes[other]->Min()); sizes[other]->SetMax(start_max_box - positions[other]->Min()); } } void PushOneBox(int box, int other, int64 start_max_box_x, int64 end_min_box_x, int64 start_max_box_y, int64 end_min_box_y) { // Mandatory part of the other box. const int64 start_max_other_x = x_[other]->Max(); const int64 end_min_other_x = x_[other]->Min() + dx_[other]->Min(); const int64 start_max_other_y = y_[other]->Max(); const int64 end_min_other_y = y_[other]->Min() + dy_[other]->Min(); // Mandatory part of the other box is non empty. if (start_max_other_x < end_min_other_x && start_max_other_y < end_min_other_y) { const bool overlap_horizontal = start_max_other_x < end_min_box_x && start_max_box_x < end_min_other_x; const bool overlap_vertical = start_max_other_y < end_min_box_y && start_max_box_y < end_min_other_y; if (overlap_horizontal && overlap_vertical) { // Mandatory parts overlap. We fail early. solver()->Fail(); } else if (overlap_horizontal) { PushOneDirection(box, other, start_max_box_y, end_min_box_y, start_max_other_y, end_min_other_y, y_, dy_); } else if (overlap_vertical) { PushOneDirection(box, other, start_max_box_x, end_min_box_x, start_max_other_x, end_min_other_x, x_, dx_); } } } void AddCumulativeConstraint(const std::vector<IntVar*>& positions, const std::vector<int64>& sizes, const std::vector<int64>& demands, int64 capacity) { vector<IntervalVar*> intervals; solver()->MakeFixedDurationIntervalVarArray( positions, sizes, "interval", &intervals); solver()->AddConstraint(solver()->MakeCumulative( intervals, demands, capacity, "cumul")); } std::vector<IntVar*> x_; std::vector<IntVar*> y_; std::vector<IntVar*> dx_; std::vector<IntVar*> dy_; const int64 size_; Demon* delayed_demon_; hash_set<int> to_propagate_; std::vector<int> neighbors_; }; } // namespace Constraint* Solver::MakeNonOverlappingRectanglesConstraint( const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<IntVar*>& x_size, const std::vector<IntVar*>& y_size) { return RevAlloc(new Diffn(this, x_vars, y_vars, x_size, y_size)); } } // namespace operations_research <commit_msg>simpler implementation of diffn, actually propagates more<commit_after>// Copyright 2010-2013 Google // 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 <algorithm> #include <string> #include <vector> #include "base/integral_types.h" #include "base/concise_iterator.h" #include "base/int-type-indexed-vector.h" #include "base/int-type.h" #include "base/logging.h" #include "base/hash.h" #include "base/scoped_ptr.h" #include "base/stringprintf.h" #include "constraint_solver/constraint_solver.h" #include "constraint_solver/constraint_solveri.h" #include "util/string_array.h" namespace operations_research { // Diffn constraint, Non overlapping rectangles. namespace { DEFINE_INT_TYPE(Box, int); class Diffn : public Constraint { public: Diffn(Solver* const solver, const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<IntVar*>& x_size, const std::vector<IntVar*>& y_size) : Constraint(solver), x_(x_vars), y_(y_vars), dx_(x_size), dy_(y_size), size_(x_vars.size()) { CHECK_EQ(x_vars.size(), y_vars.size()); CHECK_EQ(x_vars.size(), x_size.size()); CHECK_EQ(x_vars.size(), y_size.size()); } virtual ~Diffn() {} virtual void Post() { Solver* const s = solver(); for (int i = 0; i < size_; ++i) { Demon* const demon = MakeConstraintDemon1(solver(), this, &Diffn::RangeBox, "RangeBox", i); x_[i]->WhenRange(demon); y_[i]->WhenRange(demon); dx_[i]->WhenRange(demon); dy_[i]->WhenRange(demon); } delayed_demon_ = MakeDelayedConstraintDemon0( solver(), this, &Diffn::PropagateAll, "PropagateAll"); if (AreAllBound(dx_) && AreAllBound(dy_) && IsArrayInRange(x_, 0LL, kint64max) && IsArrayInRange(y_, 0LL, kint64max)) { // We can add redundant cumulative constraints. // Cumulative on x variables.e const int64 min_x = MinVarArray(x_); const int64 max_x = MaxVarArray(x_); const int64 max_size_x = MaxVarArray(dx_); const int64 min_y = MinVarArray(y_); const int64 max_y = MaxVarArray(y_); const int64 max_size_y = MaxVarArray(dy_); vector<int64> size_x; FillValues(dx_, &size_x); vector<int64> size_y; FillValues(dy_, &size_y); AddCumulativeConstraint(x_, size_x, size_y, max_size_y + max_y - min_y); AddCumulativeConstraint(y_, size_y, size_x, max_size_x + max_x - min_x); } } virtual void InitialPropagate() { // All sizes should be > 0. for (int i = 0; i < size_; ++i) { dx_[i]->SetMin(1); dy_[i]->SetMin(1); } // Force propagation on all boxes. to_propagate_.clear(); for (int i = 0; i < size_; i++) { to_propagate_.insert(i); } PropagateAll(); } void RangeBox(int box) { to_propagate_.insert(box); EnqueueDelayedDemon(delayed_demon_); } void PropagateAll() { for (ConstIter<hash_set<int>> it(to_propagate_); !it.at_end(); ++it) { const int box = *it; FillNeighbors(box); CheckEnergy(box); PushOverlappingBoxes(box); } to_propagate_.clear(); } virtual string DebugString() const { return StringPrintf("Diffn(x = [%s], y = [%s], dx = [%s], dy = [%s]))", DebugStringVector(x_, ", ").c_str(), DebugStringVector(y_, ", ").c_str(), DebugStringVector(dx_, ", ").c_str(), DebugStringVector(dy_, ", ").c_str()); } virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kDisjunctive, this); visitor->VisitIntegerVariableArrayArgument( ModelVisitor::kPositionXArgument, x_); visitor->VisitIntegerVariableArrayArgument( ModelVisitor::kPositionYArgument, y_); visitor->VisitIntegerVariableArrayArgument( ModelVisitor::kSizeXArgument, dx_); visitor->VisitIntegerVariableArrayArgument( ModelVisitor::kSizeYArgument, dy_); visitor->EndVisitConstraint(ModelVisitor::kDisjunctive, this); } private: bool Overlap(int i, int j) { if (DisjointHorizontal(i, j) || DisjointVertical(i, j)) { return false; } return true; } bool DisjointHorizontal(int i, int j) { return (x_[i]->Min() >= x_[j]->Max() + dx_[j]->Max()) || (x_[j]->Min() >= x_[i]->Max() + dx_[i]->Max()); } bool DisjointVertical(int i, int j) { return (y_[i]->Min() >= y_[j]->Max() + dy_[j]->Max()) || (y_[j]->Min() >= y_[i]->Max() + dy_[i]->Max()); } // Fill neighbors_ with all boxes overlapping box. void FillNeighbors(int box) { neighbors_.clear(); for (int other = 0; other < size_; ++other) { if (other != box && Overlap(other, box)) { neighbors_.push_back(other); } } } // Check that the minimum area of a set of boxes is always contained in // the bounding box of these boxes. void CheckEnergy(int box) { int64 area_min_x = x_[box]->Min(); int64 area_max_x = x_[box]->Max() + dx_[box]->Max(); int64 area_min_y = y_[box]->Min(); int64 area_max_y = y_[box]->Max() + dy_[box]->Max(); int64 sum_of_areas = dx_[box]->Min() * dy_[box]->Min(); for (int i = 0; i < neighbors_.size(); ++i) { const int other = neighbors_[i]; // Update Bounding box. area_min_x = std::min(area_min_x, x_[other]->Min()); area_max_x = std::max(area_max_x, x_[other]->Max() + dx_[other]->Max()); area_min_y = std::min(area_min_y, y_[other]->Min()); area_max_y = std::max(area_max_y, y_[other]->Max() + dy_[other]->Max()); // Update sum of areas. sum_of_areas += dx_[other]->Min() * dy_[other]->Min(); const int64 bounding_area = (area_max_x - area_min_x) * (area_max_y - area_min_y); if (sum_of_areas > bounding_area) { solver()->Fail(); } } } // Push all boxes apart the mandatory part of a box. void PushOverlappingBoxes(int box) { for (int i = 0; i < neighbors_.size(); ++i) { PushOneBox(box, neighbors_[i]); } } void PushOneBox(int box, int other) { const int count = (x_[box]->Min() + dx_[box]->Min() <= x_[other]->Max()) + (x_[other]->Min() + dx_[other]->Min() <= x_[box]->Max()) + (y_[box]->Min() + dy_[box]->Min() <= y_[other]->Max()) + (y_[other]->Min() + dy_[other]->Min() <= y_[box]->Max()); if (count == 0) { solver()->Fail(); } if (count == 1) { // Only one direction to avoid overlap. if (x_[box]->Min() + dx_[box]->Min() <= x_[other]->Max()) { x_[other]->SetMin(x_[box]->Min() + dx_[box]->Min()); x_[box]->SetMax(x_[other]->Max() - dx_[box]->Min()); dx_[box]->SetMax(x_[other]->Max() - x_[box]->Min()); } else if (x_[other]->Min() + dx_[other]->Min() <= x_[box]->Max()) { x_[box]->SetMin(x_[other]->Min() + dx_[other]->Min()); x_[other]->SetMax(x_[box]->Max() - dx_[other]->Min()); dx_[other]->SetMax(x_[box]->Max() - x_[other]->Min()); } else if (y_[box]->Min() + dy_[box]->Min() <= y_[other]->Max()) { y_[other]->SetMin(y_[box]->Min() + dy_[box]->Min()); y_[box]->SetMax(y_[other]->Max() - dy_[box]->Min()); dy_[box]->SetMax(y_[other]->Max() - y_[box]->Min()); } else { DCHECK(y_[other]->Min() + dy_[other]->Min() <= y_[box]->Max()); y_[box]->SetMin(y_[other]->Min() + dy_[other]->Min()); y_[other]->SetMax(y_[box]->Max() - dy_[other]->Min()); dy_[other]->SetMax(y_[box]->Max() - y_[other]->Min()); } } } void AddCumulativeConstraint(const std::vector<IntVar*>& positions, const std::vector<int64>& sizes, const std::vector<int64>& demands, int64 capacity) { vector<IntervalVar*> intervals; solver()->MakeFixedDurationIntervalVarArray( positions, sizes, "interval", &intervals); solver()->AddConstraint(solver()->MakeCumulative( intervals, demands, capacity, "cumul")); } std::vector<IntVar*> x_; std::vector<IntVar*> y_; std::vector<IntVar*> dx_; std::vector<IntVar*> dy_; const int64 size_; Demon* delayed_demon_; hash_set<int> to_propagate_; std::vector<int> neighbors_; }; } // namespace Constraint* Solver::MakeNonOverlappingRectanglesConstraint( const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<IntVar*>& x_size, const std::vector<IntVar*>& y_size) { return RevAlloc(new Diffn(this, x_vars, y_vars, x_size, y_size)); } } // namespace operations_research <|endoftext|>
<commit_before>/* * Banjax is an ATS plugin that: * enforce regex bans * store logs in a mysql db * run SVM on the log result * send a ban request to swabber in case of banning. * * Copyright (c) 2013 eQualit.ie under GNU AGPL v3.0 or later * * Vmon: June 2013 Initial version */ #include <ts/ts.h> //NULL not defined in c++ #include <cstddef> #include <string> #include <vector> #include <list> #include <iostream> #include <iomanip> using namespace std; #include <re2/re2.h> #include <zmq.hpp> #include "util.h" #include "banjax_continuation.h" #include "regex_manager.h" #include "challenge_manager.h" #include "white_lister.h" #include "bot_sniffer.h" #include "banjax.h" #include "swabber_interface.h" #include "ats_event_handler.h" extern TSCont Banjax::global_contp; extern const string Banjax::CONFIG_FILENAME = "banjax.conf"; extern Banjax* ATSEventHandler::banjax; /** Read the config file and create filters whose name is mentioned in the config file. If you make a new filter you need to add it inside this function */ void Banjax::filter_factory(const string& banjax_dir, YAML::Node main_root) { BanjaxFilter* cur_filter; if (main_root["challenger"]["regex_banner"]) { cur_filter = new RegexManager(banjax_dir, main_root["challenger"]["regex_banner"], &ip_database, &swabber_interface); } else if (main_root["challenger"]["challenges"]){ cur_filter = new ChallengeManager(banjax_dir, main_root["challenger"], &ip_database, &swabber_interface); } else if (main_root["white_listed_ips"]){ cur_filter = new WhiteLister(banjax_dir, main_root["white_listed_ips"]); } else if (main_root["botbanger_port"]){ cur_filter = new BotSniffer(banjax_dir, main_root); } for(unsigned int i = BanjaxFilter::HTTP_START; i < BanjaxFilter::TOTAL_NO_OF_QUEUES; i++) { if (cur_filter->queued_tasks[i]) { TSDebug(BANJAX_PLUGIN_NAME, "active task %s %u", cur_filter->BANJAX_FILTER_NAME.c_str(), i); task_queues[i].push_back(FilterTask(cur_filter,cur_filter->queued_tasks[i])); } } if(cur_filter){ filters.push_back(cur_filter); } } Banjax::Banjax() :swabber_interface(&ip_database), all_filters_requested_part(0), all_filters_response_part(0) { //Everything is static in ATSEventHandle so it is more like a namespace //than a class (we never instatiate from it). so the only reason //we have to create this object is to set the static reference to banjax into //ATSEventHandler, it is somehow the acknowledgementt that only one banjax //object can exist ATSEventHandler::banjax = this; /* create an TSTextLogObject to log blacklisted requests to */ TSReturnCode error = TSTextLogObjectCreate(BANJAX_PLUGIN_NAME, TS_LOG_MODE_ADD_TIMESTAMP, &log); if (!log || error == TS_ERROR) { TSDebug(BANJAX_PLUGIN_NAME, "error while creating log"); } TSDebug(BANJAX_PLUGIN_NAME, "in the beginning"); global_contp = TSContCreate(ATSEventHandler::banjax_global_eventhandler, ip_database.db_mutex); BanjaxContinuation* cd = (BanjaxContinuation *) TSmalloc(sizeof(BanjaxContinuation)); cd = new(cd) BanjaxContinuation(NULL); //no transaction attached to this cont TSContDataSet(global_contp, cd); cd->contp = global_contp; TSHttpHookAdd(TS_HTTP_TXN_START_HOOK, global_contp); //creation of filters happen here read_configuration(); //now Get rid of inactives events for(unsigned int cur_queue = BanjaxFilter::HTTP_START; cur_queue < BanjaxFilter::TOTAL_NO_OF_QUEUES; cur_queue++, ATSEventHandler::banjax_active_queues[cur_queue] = task_queues[cur_queue].empty() ? false : true); //Ask each filter what part of http transaction they are interested in for(list<BanjaxFilter*>::iterator cur_filter = filters.begin(); cur_filter != filters.end(); cur_filter++) { all_filters_requested_part |= (*cur_filter)->requested_info(); all_filters_response_part |= (*cur_filter)->response_info(); } } void Banjax::read_configuration() { // Read the file. If there is an error, report it and exit. string sep = "/"; string banjax_dir = TSPluginDirGet() + sep + BANJAX_PLUGIN_NAME; string absolute_config_file = /*TSInstallDirGet() + sep + */ banjax_dir + sep+ CONFIG_FILENAME; TSDebug(BANJAX_PLUGIN_NAME, "Reading configuration from [%s]", absolute_config_file.c_str()); try { cfg = YAML::LoadFile(absolute_config_file); } catch(const libconfig::FileIOException &fioex) { TSDebug(BANJAX_PLUGIN_NAME, "I/O error while reading config file [%s].", absolute_config_file.c_str()); return; } catch(const libconfig::ParseException &pex) { TSDebug(BANJAX_PLUGIN_NAME, "Parse error while reading the config file"); return; } for(YAML::const_iterator it=cfg["include"].begin();it!=cfg["include"].end();++it ) { string inc_loc = banjax_dir + sep + (*it).as<std::string>(); YAML::Node sub_cfg = YAML::LoadFile(inc_loc); cfg["challenger"]["challenges"].push_back(sub_cfg["challenges"]); cfg["challenger"]["regex_banner"].push_back(sub_cfg["regex_banner"]); } filter_factory(banjax_dir, cfg); } /* Global pointer that keep track of banjax global object */ Banjax* p_banjax_plugin; void TSPluginInit(int argc, const char *argv[]) { (void) argc; (void)argv; TSPluginRegistrationInfo info; info.plugin_name = (char*) BANJAX_PLUGIN_NAME; info.vendor_name = (char*) "eQualit.ie"; info.support_email = (char*) "info@deflect.ca"; if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) { TSError("Plugin registration failed. \n"); } if (!check_ts_version()) { TSError("Plugin requires Traffic Server 3.0 or later\n"); return; } /* create the banjax object that control the whole procedure */ p_banjax_plugin = (Banjax*)TSmalloc(sizeof(Banjax)); p_banjax_plugin = new(p_banjax_plugin) Banjax; } <commit_msg>added logging<commit_after>/* * Banjax is an ATS plugin that: * enforce regex bans * store logs in a mysql db * run SVM on the log result * send a ban request to swabber in case of banning. * * Copyright (c) 2013 eQualit.ie under GNU AGPL v3.0 or later * * Vmon: June 2013 Initial version */ #include <ts/ts.h> //NULL not defined in c++ #include <cstddef> #include <string> #include <vector> #include <list> #include <iostream> #include <iomanip> using namespace std; #include <re2/re2.h> #include <zmq.hpp> #include "util.h" #include "banjax_continuation.h" #include "regex_manager.h" #include "challenge_manager.h" #include "white_lister.h" #include "bot_sniffer.h" #include "banjax.h" #include "swabber_interface.h" #include "ats_event_handler.h" extern TSCont Banjax::global_contp; extern const string Banjax::CONFIG_FILENAME = "banjax.conf"; extern Banjax* ATSEventHandler::banjax; /** Read the config file and create filters whose name is mentioned in the config file. If you make a new filter you need to add it inside this function */ void Banjax::filter_factory(const string& banjax_dir, YAML::Node main_root) { BanjaxFilter* cur_filter; if (main_root["challenger"]["regex_banner"]) { cur_filter = new RegexManager(banjax_dir, main_root["challenger"]["regex_banner"], &ip_database, &swabber_interface); } else if (main_root["challenger"]["challenges"]){ cur_filter = new ChallengeManager(banjax_dir, main_root["challenger"], &ip_database, &swabber_interface); } else if (main_root["white_listed_ips"]){ cur_filter = new WhiteLister(banjax_dir, main_root["white_listed_ips"]); } else if (main_root["botbanger_port"]){ cur_filter = new BotSniffer(banjax_dir, main_root); } for(unsigned int i = BanjaxFilter::HTTP_START; i < BanjaxFilter::TOTAL_NO_OF_QUEUES; i++) { if (cur_filter->queued_tasks[i]) { TSDebug(BANJAX_PLUGIN_NAME, "active task %s %u", cur_filter->BANJAX_FILTER_NAME.c_str(), i); task_queues[i].push_back(FilterTask(cur_filter,cur_filter->queued_tasks[i])); } } if(cur_filter){ filters.push_back(cur_filter); } } Banjax::Banjax() :swabber_interface(&ip_database), all_filters_requested_part(0), all_filters_response_part(0) { //Everything is static in ATSEventHandle so it is more like a namespace //than a class (we never instatiate from it). so the only reason //we have to create this object is to set the static reference to banjax into //ATSEventHandler, it is somehow the acknowledgementt that only one banjax //object can exist ATSEventHandler::banjax = this; /* create an TSTextLogObject to log blacklisted requests to */ TSReturnCode error = TSTextLogObjectCreate(BANJAX_PLUGIN_NAME, TS_LOG_MODE_ADD_TIMESTAMP, &log); if (!log || error == TS_ERROR) { TSDebug(BANJAX_PLUGIN_NAME, "error while creating log"); } TSDebug(BANJAX_PLUGIN_NAME, "in the beginning"); global_contp = TSContCreate(ATSEventHandler::banjax_global_eventhandler, ip_database.db_mutex); BanjaxContinuation* cd = (BanjaxContinuation *) TSmalloc(sizeof(BanjaxContinuation)); cd = new(cd) BanjaxContinuation(NULL); //no transaction attached to this cont TSContDataSet(global_contp, cd); cd->contp = global_contp; TSHttpHookAdd(TS_HTTP_TXN_START_HOOK, global_contp); //creation of filters happen here read_configuration(); //now Get rid of inactives events for(unsigned int cur_queue = BanjaxFilter::HTTP_START; cur_queue < BanjaxFilter::TOTAL_NO_OF_QUEUES; cur_queue++, ATSEventHandler::banjax_active_queues[cur_queue] = task_queues[cur_queue].empty() ? false : true); //Ask each filter what part of http transaction they are interested in for(list<BanjaxFilter*>::iterator cur_filter = filters.begin(); cur_filter != filters.end(); cur_filter++) { all_filters_requested_part |= (*cur_filter)->requested_info(); all_filters_response_part |= (*cur_filter)->response_info(); } } void Banjax::read_configuration() { // Read the file. If there is an error, report it and exit. string sep = "/"; string banjax_dir = TSPluginDirGet() + sep + BANJAX_PLUGIN_NAME; string absolute_config_file = /*TSInstallDirGet() + sep + */ banjax_dir + sep+ CONFIG_FILENAME; TSDebug(BANJAX_PLUGIN_NAME, "Reading configuration from [%s]", absolute_config_file.c_str()); try { cfg = YAML::LoadFile(absolute_config_file); } catch(YAML::ParserException& e) { TSDebug(BANJAX_PLUGIN_NAME, "I/O error while reading config file [%s]: [%s].", absolute_config_file.c_str(), e.what()); return; } TSDebug(BANJAX_PLUGIN_NAME, "Finished loading main conf"); for(YAML::const_iterator it=cfg["include"].begin();it!=cfg["include"].end();++it ) { string inc_loc = banjax_dir + sep + (*it).as<std::string>(); TSDebug(BANJAX_PLUGIN_NAME, "Reading configuration from [%s]", inc_loc.c_str()); YAML::Node sub_cfg = YAML::LoadFile(inc_loc); cfg["challenger"]["challenges"].push_back(sub_cfg["challenges"]); cfg["challenger"]["regex_banner"].push_back(sub_cfg["regex_banner"]); TSDebug(BANJAX_PLUGIN_NAME, "Finished reading from [%s]", inc_loc.c_str()); } TSDebug(BANJAX_PLUGIN_NAME, "Finished loading include confs"); filter_factory(banjax_dir, cfg); } /* Global pointer that keep track of banjax global object */ Banjax* p_banjax_plugin; void TSPluginInit(int argc, const char *argv[]) { (void) argc; (void)argv; TSPluginRegistrationInfo info; info.plugin_name = (char*) BANJAX_PLUGIN_NAME; info.vendor_name = (char*) "eQualit.ie"; info.support_email = (char*) "info@deflect.ca"; if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) { TSError("Plugin registration failed. \n"); } if (!check_ts_version()) { TSError("Plugin requires Traffic Server 3.0 or later\n"); return; } /* create the banjax object that control the whole procedure */ p_banjax_plugin = (Banjax*)TSmalloc(sizeof(Banjax)); p_banjax_plugin = new(p_banjax_plugin) Banjax; } <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2009 See the AUTHORS file for details. * * This program 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. */ #include "User.h" class CNickServ : public CModule { public: MODCONSTRUCTOR(CNickServ) { } virtual ~CNickServ() { } virtual bool OnLoad(const CString& sArgs, CString& sMessage) { if (sArgs.empty()) m_sPass = GetNV("Password"); else m_sPass = sArgs; return true; } virtual void OnModCommand(const CString& sCommand) { CString sCmdName = sCommand.Token(0).AsLower(); if (sCmdName == "set") { CString sPass = sCommand.Token(1, true); m_sPass = sPass; SetNV("Password", m_sPass); PutModule("Password set"); } else if (xCmdName == "clear") { m_sPass = ""; DelNV("Password"); } else { PutModule("Commands: set <password>, clear"); } } void HandleMessage(CNick& Nick, const CString& sMessage) { if (!m_sPass.empty() && Nick.GetNick().Equals("NickServ") && (sMessage.find("msg") != CString::npos || sMessage.find("authenticate") != CString::npos) && sMessage.AsUpper().find("IDENTIFY") != CString::npos && sMessage.find("help") == CString::npos) { PutIRC("PRIVMSG NickServ :IDENTIFY " + m_sPass); } } virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage) { HandleMessage(Nick, sMessage); return CONTINUE; } virtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage) { HandleMessage(Nick, sMessage); return CONTINUE; } private: CString m_sPass; }; MODULEDEFS(CNickServ, "Auths you with NickServ") <commit_msg>I suck (I broke the build!)<commit_after>/* * Copyright (C) 2004-2009 See the AUTHORS file for details. * * This program 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. */ #include "User.h" class CNickServ : public CModule { public: MODCONSTRUCTOR(CNickServ) { } virtual ~CNickServ() { } virtual bool OnLoad(const CString& sArgs, CString& sMessage) { if (sArgs.empty()) m_sPass = GetNV("Password"); else m_sPass = sArgs; return true; } virtual void OnModCommand(const CString& sCommand) { CString sCmdName = sCommand.Token(0).AsLower(); if (sCmdName == "set") { CString sPass = sCommand.Token(1, true); m_sPass = sPass; SetNV("Password", m_sPass); PutModule("Password set"); } else if (sCmdName == "clear") { m_sPass = ""; DelNV("Password"); } else { PutModule("Commands: set <password>, clear"); } } void HandleMessage(CNick& Nick, const CString& sMessage) { if (!m_sPass.empty() && Nick.GetNick().Equals("NickServ") && (sMessage.find("msg") != CString::npos || sMessage.find("authenticate") != CString::npos) && sMessage.AsUpper().find("IDENTIFY") != CString::npos && sMessage.find("help") == CString::npos) { PutIRC("PRIVMSG NickServ :IDENTIFY " + m_sPass); } } virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage) { HandleMessage(Nick, sMessage); return CONTINUE; } virtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage) { HandleMessage(Nick, sMessage); return CONTINUE; } private: CString m_sPass; }; MODULEDEFS(CNickServ, "Auths you with NickServ") <|endoftext|>
<commit_before>// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "hash.h" #include "uint256.h" #include <assert.h> #include <stdint.h> #include <string.h> #include <vector> #include <string> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> /** All alphanumeric characters except for "0", "I", "O", and "l" */ static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch) { // Skip leading spaces. while (*psz && isspace(*psz)) psz++; // Skip and count leading '1's. int zeroes = 0; while (*psz == '1') { zeroes++; psz++; } // Allocate enough space in big-endian base256 representation. std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up. // Process the characters. while (*psz && !isspace(*psz)) { // Decode base58 character const char* ch = strchr(pszBase58, *psz); if (ch == NULL) return false; // Apply "b256 = b256 * 58 + ch". int carry = ch - pszBase58; for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) { carry += 58 * (*it); *it = carry % 256; carry /= 256; } assert(carry == 0); psz++; } // Skip trailing spaces. while (isspace(*psz)) psz++; if (*psz != 0) return false; // Skip leading zeroes in b256. std::vector<unsigned char>::iterator it = b256.begin(); while (it != b256.end() && *it == 0) it++; // Copy result into output vector. vch.reserve(zeroes + (b256.end() - it)); vch.assign(zeroes, 0x00); while (it != b256.end()) vch.push_back(*(it++)); return true; } std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { // Skip & count leading zeroes. int zeroes = 0; int length = 0; while (pbegin != pend && *pbegin == 0) { pbegin++; zeroes++; } // Allocate enough space in big-endian base58 representation. int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up. std::vector<unsigned char> b58(size); // Process the bytes. while (pbegin != pend) { int carry = *pbegin; int i = 0; // Apply "b58 = b58 * 256 + ch". for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) { carry += 256 * (*it); *it = carry % 58; carry /= 58; } assert(carry == 0); length = i; pbegin++; } // Skip leading zeroes in base58 result. std::vector<unsigned char>::iterator it = b58.begin() + (size - length); while (it != b58.end() && *it == 0) it++; // Translate the result into a string. std::string str; str.reserve(zeroes + (b58.end() - it)); str.assign(zeroes, '1'); while (it != b58.end()) str += pszBase58[*(it++)]; return str; } std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet) || (vchRet.size() < 4)) { vchRet.clear(); return false; } // re-calculate the checksum, insure it matches the included 4-byte checksum uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size() - 4); return true; } bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } CBase58Data::CBase58Data() { vchVersion.clear(); vchData.clear(); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize) { vchVersion = vchVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend) { SetData(vchVersionIn, (void*)pbegin, pend - pbegin); } bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes) { std::vector<unsigned char> vchTemp; bool rc58 = DecodeBase58Check(psz, vchTemp); if ((!rc58) || (vchTemp.size() < nVersionBytes)) { vchData.clear(); vchVersion.clear(); return false; } vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes); vchData.resize(vchTemp.size() - nVersionBytes); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size()); memory_cleanse(&vchTemp[0], vchTemp.size()); return true; } bool CBase58Data::SetString(const std::string& str) { return SetString(str.c_str()); } std::string CBase58Data::ToString() const { // if(vchData.To == "0x202020") // return "FUND_CONTRIBUTION"; std::vector<unsigned char> vch = vchVersion; vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CBase58Data::CompareTo(const CBase58Data& b58) const { if (vchVersion < b58.vchVersion) return -1; if (vchVersion > b58.vchVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } namespace { class CNavCoinAddressVisitor : public boost::static_visitor<bool> { private: CNavCoinAddress* addr; public: CNavCoinAddressVisitor(CNavCoinAddress* addrIn) : addr(addrIn) {} bool operator()(const CKeyID& id) const { return addr->Set(id); } bool operator()(const CScriptID& id) const { return addr->Set(id); } bool operator()(const CNoDestination& no) const { return false; } }; } // anon namespace bool CNavCoinAddress::Set(const CKeyID& id) { SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20); return true; } bool CNavCoinAddress::Set(const CScriptID& id) { SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20); return true; } bool CNavCoinAddress::Set(const CTxDestination& dest) { return boost::apply_visitor(CNavCoinAddressVisitor(this), dest); } bool CNavCoinAddress::IsValid() const { return IsValid(Params()); } bool CNavCoinAddress::IsValid(const CChainParams& params) const { bool fCorrectSize = vchData.size() == 20; bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) || vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS); return fCorrectSize && fKnownVersion; } CTxDestination CNavCoinAddress::Get() const { if (!IsValid()) return CNoDestination(); uint160 id; memcpy(&id, &vchData[0], 20); if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return CKeyID(id); else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) return CScriptID(id); else return CNoDestination(); } bool CNavCoinAddress::GetIndexKey(uint160& hashBytes, int& type) const { if (!IsValid()) { return false; } else if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) { memcpy(&hashBytes, &vchData[0], 20); type = 1; return true; } else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) { memcpy(&hashBytes, &vchData[0], 20); type = 2; return true; } return false; } bool CNavCoinAddress::GetKeyID(CKeyID& keyID) const { if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return false; uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } bool CNavCoinAddress::IsScript() const { return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); } void CNavCoinSecret::SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); } CKey CNavCoinSecret::GetKey() { CKey ret; assert(vchData.size() >= 32); ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1); return ret; } bool CNavCoinSecret::IsValid() const { bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1); bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY); return fExpectedFormat && fCorrectVersion; } bool CNavCoinSecret::SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool CNavCoinSecret::SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } <commit_msg>remove comment<commit_after>// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "hash.h" #include "uint256.h" #include <assert.h> #include <stdint.h> #include <string.h> #include <vector> #include <string> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> /** All alphanumeric characters except for "0", "I", "O", and "l" */ static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch) { // Skip leading spaces. while (*psz && isspace(*psz)) psz++; // Skip and count leading '1's. int zeroes = 0; while (*psz == '1') { zeroes++; psz++; } // Allocate enough space in big-endian base256 representation. std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up. // Process the characters. while (*psz && !isspace(*psz)) { // Decode base58 character const char* ch = strchr(pszBase58, *psz); if (ch == NULL) return false; // Apply "b256 = b256 * 58 + ch". int carry = ch - pszBase58; for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) { carry += 58 * (*it); *it = carry % 256; carry /= 256; } assert(carry == 0); psz++; } // Skip trailing spaces. while (isspace(*psz)) psz++; if (*psz != 0) return false; // Skip leading zeroes in b256. std::vector<unsigned char>::iterator it = b256.begin(); while (it != b256.end() && *it == 0) it++; // Copy result into output vector. vch.reserve(zeroes + (b256.end() - it)); vch.assign(zeroes, 0x00); while (it != b256.end()) vch.push_back(*(it++)); return true; } std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { // Skip & count leading zeroes. int zeroes = 0; int length = 0; while (pbegin != pend && *pbegin == 0) { pbegin++; zeroes++; } // Allocate enough space in big-endian base58 representation. int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up. std::vector<unsigned char> b58(size); // Process the bytes. while (pbegin != pend) { int carry = *pbegin; int i = 0; // Apply "b58 = b58 * 256 + ch". for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) { carry += 256 * (*it); *it = carry % 58; carry /= 58; } assert(carry == 0); length = i; pbegin++; } // Skip leading zeroes in base58 result. std::vector<unsigned char>::iterator it = b58.begin() + (size - length); while (it != b58.end() && *it == 0) it++; // Translate the result into a string. std::string str; str.reserve(zeroes + (b58.end() - it)); str.assign(zeroes, '1'); while (it != b58.end()) str += pszBase58[*(it++)]; return str; } std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet) || (vchRet.size() < 4)) { vchRet.clear(); return false; } // re-calculate the checksum, insure it matches the included 4-byte checksum uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size() - 4); return true; } bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } CBase58Data::CBase58Data() { vchVersion.clear(); vchData.clear(); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize) { vchVersion = vchVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend) { SetData(vchVersionIn, (void*)pbegin, pend - pbegin); } bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes) { std::vector<unsigned char> vchTemp; bool rc58 = DecodeBase58Check(psz, vchTemp); if ((!rc58) || (vchTemp.size() < nVersionBytes)) { vchData.clear(); vchVersion.clear(); return false; } vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes); vchData.resize(vchTemp.size() - nVersionBytes); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size()); memory_cleanse(&vchTemp[0], vchTemp.size()); return true; } bool CBase58Data::SetString(const std::string& str) { return SetString(str.c_str()); } std::string CBase58Data::ToString() const { std::vector<unsigned char> vch = vchVersion; vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CBase58Data::CompareTo(const CBase58Data& b58) const { if (vchVersion < b58.vchVersion) return -1; if (vchVersion > b58.vchVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } namespace { class CNavCoinAddressVisitor : public boost::static_visitor<bool> { private: CNavCoinAddress* addr; public: CNavCoinAddressVisitor(CNavCoinAddress* addrIn) : addr(addrIn) {} bool operator()(const CKeyID& id) const { return addr->Set(id); } bool operator()(const CScriptID& id) const { return addr->Set(id); } bool operator()(const CNoDestination& no) const { return false; } }; } // anon namespace bool CNavCoinAddress::Set(const CKeyID& id) { SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20); return true; } bool CNavCoinAddress::Set(const CScriptID& id) { SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20); return true; } bool CNavCoinAddress::Set(const CTxDestination& dest) { return boost::apply_visitor(CNavCoinAddressVisitor(this), dest); } bool CNavCoinAddress::IsValid() const { return IsValid(Params()); } bool CNavCoinAddress::IsValid(const CChainParams& params) const { bool fCorrectSize = vchData.size() == 20; bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) || vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS); return fCorrectSize && fKnownVersion; } CTxDestination CNavCoinAddress::Get() const { if (!IsValid()) return CNoDestination(); uint160 id; memcpy(&id, &vchData[0], 20); if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return CKeyID(id); else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) return CScriptID(id); else return CNoDestination(); } bool CNavCoinAddress::GetIndexKey(uint160& hashBytes, int& type) const { if (!IsValid()) { return false; } else if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) { memcpy(&hashBytes, &vchData[0], 20); type = 1; return true; } else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) { memcpy(&hashBytes, &vchData[0], 20); type = 2; return true; } return false; } bool CNavCoinAddress::GetKeyID(CKeyID& keyID) const { if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return false; uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } bool CNavCoinAddress::IsScript() const { return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); } void CNavCoinSecret::SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); } CKey CNavCoinSecret::GetKey() { CKey ret; assert(vchData.size() >= 32); ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1); return ret; } bool CNavCoinSecret::IsValid() const { bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1); bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY); return fExpectedFormat && fCorrectVersion; } bool CNavCoinSecret::SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool CNavCoinSecret::SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } <|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 <activemq/connector/openwire/commands/ActiveMQDestination.h> #include <activemq/exceptions/NullPointerException.h> #include <activemq/util/URISupport.h> using namespace std; using namespace activemq; using namespace activemq::util; using namespace activemq::exceptions; using namespace activemq::connector; using namespace activemq::connector::openwire; using namespace activemq::connector::openwire::commands; //////////////////////////////////////////////////////////////////////////////// const std::string ActiveMQDestination::ADVISORY_PREFIX = "ActiveMQ.Advisory."; const std::string ActiveMQDestination::CONSUMER_ADVISORY_PREFIX = ActiveMQDestination::ADVISORY_PREFIX + "Consumers."; const std::string ActiveMQDestination::PRODUCER_ADVISORY_PREFIX = ActiveMQDestination::ADVISORY_PREFIX + "Producers."; const std::string ActiveMQDestination::CONNECTION_ADVISORY_PREFIX = ActiveMQDestination::ADVISORY_PREFIX + "Connections."; const std::string ActiveMQDestination::DEFAULT_ORDERED_TARGET = "coordinator"; const std::string ActiveMQDestination::TEMP_PREFIX = "{TD{"; const std::string ActiveMQDestination::TEMP_POSTFIX = "}TD}"; const std::string ActiveMQDestination::COMPOSITE_SEPARATOR = ","; const std::string ActiveMQDestination::DestinationFilter::ANY_CHILD = ">"; const std::string ActiveMQDestination::DestinationFilter::ANY_DESCENDENT = "*"; //////////////////////////////////////////////////////////////////////////////// ActiveMQDestination::ActiveMQDestination() { this->physicalName = ""; this->orderedTarget = DEFAULT_ORDERED_TARGET; this->exclusive = false; this->ordered = false; this->advisory = false; } //////////////////////////////////////////////////////////////////////////////// ActiveMQDestination::ActiveMQDestination( const std::string& physicalName ) { this->setPhysicalName( physicalName ); this->orderedTarget = DEFAULT_ORDERED_TARGET; this->exclusive = false; this->ordered = false; this->advisory = false; } //////////////////////////////////////////////////////////////////////////////// void ActiveMQDestination::setPhysicalName( const std::string& physicalName ) { this->physicalName = physicalName; size_t pos = physicalName.find_first_of('?'); if( pos != string::npos ) { std::string optstring = physicalName.substr( pos + 1 ); this->physicalName = physicalName.substr( 0, pos ); URISupport::parseQuery( optstring, &options ); } this->advisory = physicalName.find_first_of( ADVISORY_PREFIX ) == 0; } //////////////////////////////////////////////////////////////////////////////// void ActiveMQDestination::copyDataStructure( const DataStructure* src ) { // Copy the data of the base class or classes BaseDataStructure::copyDataStructure( src ); const ActiveMQDestination* srcPtr = dynamic_cast<const ActiveMQDestination*>( src ); if( srcPtr == NULL || src == NULL ) { throw exceptions::NullPointerException( __FILE__, __LINE__, "BrokerId::copyDataStructure - src is NULL or invalid" ); } this->setPhysicalName( srcPtr->getPhysicalName() ); this->setAdvisory( srcPtr->isAdvisory() ); this->setOrdered( srcPtr->isOrdered() ); this->setExclusive( srcPtr->isExclusive() ); this->setOrderedTarget( srcPtr->getOrderedTarget() ); } //////////////////////////////////////////////////////////////////////////////// std::string ActiveMQDestination::toString() const { std::ostringstream stream; stream << "Begin Class = ActiveMQDestination" << std::endl; stream << " Value of exclusive = " << std::boolalpha << exclusive << std::endl; stream << " Value of ordered = " << std::boolalpha << ordered << std::endl; stream << " Value of advisory = " << std::boolalpha << advisory << std::endl; stream << " Value of orderedTarget = " << orderedTarget << std::endl; stream << " Value of physicalName = " << physicalName << std::endl; stream << " Value of options = " << this->options.toString() << std::endl; stream << BaseDataStructure::toString(); stream << "End Class = ActiveMQDestination" << std::endl; return stream.str(); } //////////////////////////////////////////////////////////////////////////////// unsigned char ActiveMQDestination::getDataStructureType() const { return ActiveMQDestination::ID_ACTIVEMQDESTINATION; } //////////////////////////////////////////////////////////////////////////////// std::string ActiveMQDestination::getClientId( const ActiveMQDestination* destination ) { std::string answer = ""; if( destination != NULL && destination->isTemporary() ) { std::string name = destination->getPhysicalName(); size_t start = name.find( TEMP_PREFIX ); if( start != std::string::npos ) { start += TEMP_PREFIX.length(); size_t stop = name.rfind( TEMP_POSTFIX ); if( stop > start && stop < name.length() ) { answer = name.substr( start, stop-start ); } } } return answer; } <commit_msg>https://issues.apache.org/activemq/browse/AMQCPP-112<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 <activemq/connector/openwire/commands/ActiveMQDestination.h> #include <activemq/exceptions/NullPointerException.h> #include <activemq/util/URISupport.h> using namespace std; using namespace activemq; using namespace activemq::util; using namespace activemq::exceptions; using namespace activemq::connector; using namespace activemq::connector::openwire; using namespace activemq::connector::openwire::commands; //////////////////////////////////////////////////////////////////////////////// const std::string ActiveMQDestination::ADVISORY_PREFIX = "ActiveMQ.Advisory."; const std::string ActiveMQDestination::CONSUMER_ADVISORY_PREFIX = ActiveMQDestination::ADVISORY_PREFIX + "Consumers."; const std::string ActiveMQDestination::PRODUCER_ADVISORY_PREFIX = ActiveMQDestination::ADVISORY_PREFIX + "Producers."; const std::string ActiveMQDestination::CONNECTION_ADVISORY_PREFIX = ActiveMQDestination::ADVISORY_PREFIX + "Connections."; const std::string ActiveMQDestination::DEFAULT_ORDERED_TARGET = "coordinator"; const std::string ActiveMQDestination::TEMP_PREFIX = "{TD{"; const std::string ActiveMQDestination::TEMP_POSTFIX = "}TD}"; const std::string ActiveMQDestination::COMPOSITE_SEPARATOR = ","; const std::string ActiveMQDestination::DestinationFilter::ANY_CHILD = ">"; const std::string ActiveMQDestination::DestinationFilter::ANY_DESCENDENT = "*"; //////////////////////////////////////////////////////////////////////////////// ActiveMQDestination::ActiveMQDestination() { this->physicalName = ""; this->orderedTarget = DEFAULT_ORDERED_TARGET; this->exclusive = false; this->ordered = false; this->advisory = false; } //////////////////////////////////////////////////////////////////////////////// ActiveMQDestination::ActiveMQDestination( const std::string& physicalName ) { this->setPhysicalName( physicalName ); this->orderedTarget = DEFAULT_ORDERED_TARGET; this->exclusive = false; this->ordered = false; this->advisory = false; } //////////////////////////////////////////////////////////////////////////////// void ActiveMQDestination::setPhysicalName( const std::string& physicalName ) { this->physicalName = physicalName; size_t pos = physicalName.find_first_of('?'); if( pos != string::npos ) { std::string optstring = physicalName.substr( pos + 1 ); this->physicalName = physicalName.substr( 0, pos ); URISupport::parseQuery( optstring, &options ); } this->advisory = physicalName.find_first_of( ADVISORY_PREFIX ) == 0; } //////////////////////////////////////////////////////////////////////////////// void ActiveMQDestination::copyDataStructure( const DataStructure* src ) { // Copy the data of the base class or classes BaseDataStructure::copyDataStructure( src ); const ActiveMQDestination* srcPtr = dynamic_cast<const ActiveMQDestination*>( src ); if( srcPtr == NULL || src == NULL ) { throw exceptions::NullPointerException( __FILE__, __LINE__, "BrokerId::copyDataStructure - src is NULL or invalid" ); } this->setPhysicalName( srcPtr->getPhysicalName() ); this->setAdvisory( srcPtr->isAdvisory() ); this->setOrdered( srcPtr->isOrdered() ); this->setExclusive( srcPtr->isExclusive() ); this->setOrderedTarget( srcPtr->getOrderedTarget() ); this->options.copy( &srcPtr->getOptions() ); } //////////////////////////////////////////////////////////////////////////////// std::string ActiveMQDestination::toString() const { std::ostringstream stream; stream << "Begin Class = ActiveMQDestination" << std::endl; stream << " Value of exclusive = " << std::boolalpha << exclusive << std::endl; stream << " Value of ordered = " << std::boolalpha << ordered << std::endl; stream << " Value of advisory = " << std::boolalpha << advisory << std::endl; stream << " Value of orderedTarget = " << orderedTarget << std::endl; stream << " Value of physicalName = " << physicalName << std::endl; stream << " Value of options = " << this->options.toString() << std::endl; stream << BaseDataStructure::toString(); stream << "End Class = ActiveMQDestination" << std::endl; return stream.str(); } //////////////////////////////////////////////////////////////////////////////// unsigned char ActiveMQDestination::getDataStructureType() const { return ActiveMQDestination::ID_ACTIVEMQDESTINATION; } //////////////////////////////////////////////////////////////////////////////// std::string ActiveMQDestination::getClientId( const ActiveMQDestination* destination ) { std::string answer = ""; if( destination != NULL && destination->isTemporary() ) { std::string name = destination->getPhysicalName(); size_t start = name.find( TEMP_PREFIX ); if( start != std::string::npos ) { start += TEMP_PREFIX.length(); size_t stop = name.rfind( TEMP_POSTFIX ); if( stop > start && stop < name.length() ) { answer = name.substr( start, stop-start ); } } } return answer; } <|endoftext|>
<commit_before>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "AnythingUtils.h" //--- standard modules used ---------------------------------------------------- #include "StringStream.h" #include "Renderer.h" #include "Dbg.h" //-- StoreCopier --------------------------------------------------------------- void StoreCopier::Operate(Context &c, Anything &dest, const Anything &config, char delim, char indexdelim) { StartTrace(StoreCopier.Operate); ROAnything ROconfig(config); Operate(c, dest, ROconfig, delim, indexdelim); } void StoreCopier::Operate(Context &c, Anything &dest, const ROAnything &config, char delim, char indexdelim) { StartTrace(StoreCopier.Operate); TraceAny(config, "Config"); Trace("delim [" << delim << "], indexdelim [" << indexdelim << "]"); long sz = config.GetSize(); for (long i = 0; i < sz; i++) { String sourceLookupName = config.SlotName(i); String destSlot; Renderer::RenderOnString(destSlot, c, config[i]); if ( sourceLookupName && destSlot ) { dest[destSlot] = c.Lookup(sourceLookupName, delim, indexdelim).DeepClone(); } } } //-- StoreFinder --------------------------------------------------------------- void StoreFinder::Operate(Context &c, Anything &dest, const Anything &config) { StartTrace(StoreFinder.Operate); ROAnything ROconfig(config); Operate(c, dest, ROconfig); } void StoreFinder::Operate(Context &context, Anything &dest, const ROAnything &config) { StartTrace(StoreFinder.Operate); TraceAny(config, "Config"); String store = config["Store"].AsString(""); dest = FindStore(context, store); String destSlotname; Renderer::RenderOnString(destSlotname, context, config["Slot"]); Trace("Destination slotname [" << destSlotname << "]"); Anything anyConfig; anyConfig["Slot"] = destSlotname; if (config.IsDefined("Delim")) { anyConfig["Delim"] = config["Delim"].AsCharPtr(".")[0L]; } if (config.IsDefined("IndexDelim")) { anyConfig["IndexDelim"] = config["IndexDelim"].AsCharPtr(":")[0L]; } SlotFinder::Operate(dest, dest, anyConfig); } Anything &StoreFinder::FindStore(Context &c, String &storeName) { StartTrace(StoreFinder.FindStore); if ( storeName == "Role" ) { return c.GetRoleStoreGlobal(); } if ( storeName == "Session" ) { return c.GetSessionStore(); } if ( storeName == "Request" ) { return c.GetRequest(); } return c.GetTmpStore(); } //-- StorePutter --------------------------------------------------------------- void StorePutter::Operate(Anything &source, Context &c, const Anything &config) { StartTrace(StorePutter.Operate); ROAnything ROconfig(config); Operate(source, c, ROconfig); } void StorePutter::Operate(Anything &source, Context &c, const ROAnything &config) { StartTrace(StorePutter.Operate); TraceAny(config, "Config"); Anything clonedConfig = config.DeepClone(); String destSlotname; Renderer::RenderOnString(destSlotname, c, config["Slot"]); clonedConfig["Slot"] = destSlotname; if (config.IsDefined("Delim")) { clonedConfig["Delim"] = config["Delim"].AsCharPtr(".")[0L]; } if (config.IsDefined("IndexDelim")) { clonedConfig["IndexDelim"] = config["IndexDelim"].AsCharPtr(":")[0L]; } String store = config["Store"].AsString(""); SlotPutter::Operate(source, StoreFinder::FindStore(c, store), clonedConfig); } <commit_msg>changed SlotPutter method used to the one using simple params instead of an anything<commit_after>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "AnythingUtils.h" //--- standard modules used ---------------------------------------------------- #include "StringStream.h" #include "Renderer.h" #include "Dbg.h" //-- StoreCopier --------------------------------------------------------------- void StoreCopier::Operate(Context &c, Anything &dest, const Anything &config, char delim, char indexdelim) { StartTrace(StoreCopier.Operate); ROAnything ROconfig(config); Operate(c, dest, ROconfig, delim, indexdelim); } void StoreCopier::Operate(Context &c, Anything &dest, const ROAnything &config, char delim, char indexdelim) { StartTrace(StoreCopier.Operate); TraceAny(config, "Config"); Trace("delim [" << delim << "], indexdelim [" << indexdelim << "]"); long sz = config.GetSize(); for (long i = 0; i < sz; i++) { String sourceLookupName = config.SlotName(i); String destSlot; Renderer::RenderOnString(destSlot, c, config[i]); if ( sourceLookupName && destSlot ) { dest[destSlot] = c.Lookup(sourceLookupName, delim, indexdelim).DeepClone(); } } } //-- StoreFinder --------------------------------------------------------------- void StoreFinder::Operate(Context &c, Anything &dest, const Anything &config) { StartTrace(StoreFinder.Operate); ROAnything ROconfig(config); Operate(c, dest, ROconfig); } void StoreFinder::Operate(Context &context, Anything &dest, const ROAnything &config) { StartTrace(StoreFinder.Operate); TraceAny(config, "Config"); String store = config["Store"].AsString(""); dest = FindStore(context, store); String destSlotname; Renderer::RenderOnString(destSlotname, context, config["Slot"]); Trace("Destination slotname [" << destSlotname << "]"); Anything anyConfig; anyConfig["Slot"] = destSlotname; if (config.IsDefined("Delim")) { anyConfig["Delim"] = config["Delim"].AsCharPtr(".")[0L]; } if (config.IsDefined("IndexDelim")) { anyConfig["IndexDelim"] = config["IndexDelim"].AsCharPtr(":")[0L]; } SlotFinder::Operate(dest, dest, anyConfig); } Anything &StoreFinder::FindStore(Context &c, String &storeName) { StartTrace(StoreFinder.FindStore); if ( storeName == "Role" ) { return c.GetRoleStoreGlobal(); } if ( storeName == "Session" ) { return c.GetSessionStore(); } if ( storeName == "Request" ) { return c.GetRequest(); } return c.GetTmpStore(); } //-- StorePutter --------------------------------------------------------------- void StorePutter::Operate(Anything &source, Context &c, const Anything &config) { StartTrace(StorePutter.Operate); ROAnything ROconfig(config); Operate(source, c, ROconfig); } void StorePutter::Operate(Anything &source, Context &c, const ROAnything &config) { StartTrace(StorePutter.Operate); TraceAny(config, "Config"); String strStoreName = config["Store"].AsString(""); SlotPutter::Operate(source, StoreFinder::FindStore(c, strStoreName), Renderer::RenderToString(c, config["Slot"]), config["Append"].AsBool(false), config["Delim"].AsCharPtr(".")[0L], config["IndexDelim"].AsCharPtr(":")[0L]); } <|endoftext|>
<commit_before>/** * Clever programming language * Copyright (c) 2011 Clever 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 OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include <cstdlib> #include "compiler/value.h" #include "compiler/symboltable.h" #include "modules/std/os/os.h" #include "types/nativetypes.h" namespace clever { namespace packages { namespace std { namespace os { /** * system(string command) * Calls a command and returns the exit code. */ static CLEVER_FUNCTION(system) { retval->setInteger(::system(args->at(0)->getString().c_str())); } } // namespace io /** * Initializes Standard module */ void OSModule::init() throw() { using namespace os; addFunction(new Function("system", &CLEVER_FUNC_NAME(system), CLEVER_INT)) ->addArg("command", CLEVER_STR); } }}} // clever::packages::std <commit_msg>Removed <iostream> from os.cc includes (unnecessary).<commit_after>/** * Clever programming language * Copyright (c) 2011 Clever 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 OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdlib> #include "compiler/value.h" #include "compiler/symboltable.h" #include "modules/std/os/os.h" #include "types/nativetypes.h" namespace clever { namespace packages { namespace std { namespace os { /** * system(string command) * Calls a command and returns the exit code. */ static CLEVER_FUNCTION(system) { retval->setInteger(::system(args->at(0)->getString().c_str())); } } // namespace io /** * Initializes Standard module */ void OSModule::init() throw() { using namespace os; addFunction(new Function("system", &CLEVER_FUNC_NAME(system), CLEVER_INT)) ->addArg("command", CLEVER_STR); } }}} // clever::packages::std <|endoftext|>
<commit_before>#ifndef SRC_CORE_DETAIL_CONNECTION_HPP_ #define SRC_CORE_DETAIL_CONNECTION_HPP_ #include <type_traits> #include "core/function_traits.hpp" #include "core/traits.hpp" namespace fc { namespace detail { enum void_flag { payload_void, payload_not_void, invalid, }; template<class source,class sink, class... P> constexpr auto void_check(int) -> decltype(std::declval<sink>()(), std::declval<source>()(std::declval<P>()...), void_flag()) { return payload_void; } template<class source,class sink, class... P> constexpr auto void_check(int) -> decltype(std::declval<sink>()(std::declval<source>()(std::declval<P>()...)), void_flag()) { return payload_not_void; } template<void_flag vflag, class source_t, class sink_t, class... param> struct invoke_helper { }; template<class source_t, class sink_t> struct invoke_helper<payload_void, source_t, sink_t> { template<class... param> decltype(auto) operator()(source_t& source, sink_t& sink, param&&... p) { source(p...); return sink(); } }; template<class source_t, class sink_t> struct invoke_helper<payload_not_void, source_t, sink_t> { template<class... param> decltype(auto) operator()(source_t& source, sink_t& sink, param&&... p) { return sink(source(p...)); } }; } //namespace detail /** * \brief defines basic connection object, which is connectable. * \tparam source_t the source node of the connection, data flows from here to the sink. * \tparam sink_t is the sink node of the connection, data goes here. * \tparam param_void is true if the parameter of operator() of source_t is void * \result_void param_void is true if the result of operator() of sink_t is void * \payload_void param_void is true if the result of operator() of source_t is void * the return value of source_t needs to be convertible to the parameter of sink_t. */ template< class source_t, class sink_t > struct connection { source_t source; sink_t sink; /** * \brief call operator, calls source and then sink with the result of source * * redundant return type specification is necessary at the moment, * as it causes missing operator() in source and sink to appear in function declaration * and thus be a substitution failure. */ template<class S = source_t, class T = sink_t, class... param> auto operator()(param&&... p) -> decltype(detail::invoke_helper< detail::void_check<S, T, param...>(0), S,T >() (source,sink,p...)) { constexpr auto test = detail::void_check<S, T, param...>(0); return detail::invoke_helper< test, S,T >() (source,sink,p...); } }; /// internals of flexcore, everything here can change any time. namespace detail { template<class source_t, class sink_t, class Enable = void> struct connect_impl { auto operator()(source_t&& source, sink_t&& sink) { return connection<source_t, sink_t> {std::forward<source_t>(source), std::forward<sink_t>(sink)}; } }; } // namespace detail template <typename T> using rm_ref_t = std::remove_reference_t<T>; /** * \brief Connect takes two connectables and returns a connection. * * \param source is the source of the data flowing through the connection. * \param sink is the target of the data flowing through the connection. * \returns connection object which has its type determined by the source_t and sink_t. * * If source_t and sink_t fulfill connectable, the result is connectable. * If one of source_t and sink_t fulfills receive_connectable and the other * fulfills send_connectable, the result is not non_connectable. * If either source_t or sink_t fulfill send_connectable, the result is send_connectable. * If either source_t or sink_t fulfill receive_connectable, the result is receive_connectable. */ template < class source_t, class sink_t > auto connect (source_t&& source, sink_t&& sink) { return detail::connect_impl<source_t, sink_t>()( std::forward<source_t>(source), std::forward<sink_t>(sink)); } /** * \brief Operator >> takes two connectables and returns a connection. * * This operator is syntactic sugar for Connect. */ template<class source_t, class sink_t, class enable = std::enable_if_t< (is_connectable<source_t>::value || is_active<rm_ref_t<source_t>>{}) && (is_connectable<sink_t>::value || is_active<rm_ref_t<sink_t>>{})>> auto operator >>(source_t&& source, sink_t&& sink) { return connect(std::forward<source_t>(source), std::forward<sink_t>(sink)); } //todo: does not belong here template <class source_t, class sink_t> struct is_passive_sink<connection<source_t, sink_t>> : is_passive_sink<rm_ref_t<sink_t>> {}; template <class source_t, class sink_t> struct result_of<connection<source_t, sink_t>> : result_of<rm_ref_t<sink_t>> {}; } //namespace fc #endif /* SRC_CORE_CONNECTION_HPP_ */ <commit_msg>connection: add extra checks in operator>> related to active connectables.<commit_after>#ifndef SRC_CORE_DETAIL_CONNECTION_HPP_ #define SRC_CORE_DETAIL_CONNECTION_HPP_ #include <type_traits> #include "core/function_traits.hpp" #include "core/traits.hpp" namespace fc { namespace detail { enum void_flag { payload_void, payload_not_void, invalid, }; template<class source,class sink, class... P> constexpr auto void_check(int) -> decltype(std::declval<sink>()(), std::declval<source>()(std::declval<P>()...), void_flag()) { return payload_void; } template<class source,class sink, class... P> constexpr auto void_check(int) -> decltype(std::declval<sink>()(std::declval<source>()(std::declval<P>()...)), void_flag()) { return payload_not_void; } template<void_flag vflag, class source_t, class sink_t, class... param> struct invoke_helper { }; template<class source_t, class sink_t> struct invoke_helper<payload_void, source_t, sink_t> { template<class... param> decltype(auto) operator()(source_t& source, sink_t& sink, param&&... p) { source(p...); return sink(); } }; template<class source_t, class sink_t> struct invoke_helper<payload_not_void, source_t, sink_t> { template<class... param> decltype(auto) operator()(source_t& source, sink_t& sink, param&&... p) { return sink(source(p...)); } }; } //namespace detail /** * \brief defines basic connection object, which is connectable. * \tparam source_t the source node of the connection, data flows from here to the sink. * \tparam sink_t is the sink node of the connection, data goes here. * \tparam param_void is true if the parameter of operator() of source_t is void * \result_void param_void is true if the result of operator() of sink_t is void * \payload_void param_void is true if the result of operator() of source_t is void * the return value of source_t needs to be convertible to the parameter of sink_t. */ template< class source_t, class sink_t > struct connection { source_t source; sink_t sink; /** * \brief call operator, calls source and then sink with the result of source * * redundant return type specification is necessary at the moment, * as it causes missing operator() in source and sink to appear in function declaration * and thus be a substitution failure. */ template<class S = source_t, class T = sink_t, class... param> auto operator()(param&&... p) -> decltype(detail::invoke_helper< detail::void_check<S, T, param...>(0), S,T >() (source,sink,p...)) { constexpr auto test = detail::void_check<S, T, param...>(0); return detail::invoke_helper< test, S,T >() (source,sink,p...); } }; /// internals of flexcore, everything here can change any time. namespace detail { template<class source_t, class sink_t, class Enable = void> struct connect_impl { auto operator()(source_t&& source, sink_t&& sink) { return connection<source_t, sink_t> {std::forward<source_t>(source), std::forward<sink_t>(sink)}; } }; } // namespace detail template <typename T> using rm_ref_t = std::remove_reference_t<T>; /** * \brief Connect takes two connectables and returns a connection. * * \param source is the source of the data flowing through the connection. * \param sink is the target of the data flowing through the connection. * \returns connection object which has its type determined by the source_t and sink_t. * * If source_t and sink_t fulfill connectable, the result is connectable. * If one of source_t and sink_t fulfills receive_connectable and the other * fulfills send_connectable, the result is not non_connectable. * If either source_t or sink_t fulfill send_connectable, the result is send_connectable. * If either source_t or sink_t fulfill receive_connectable, the result is receive_connectable. */ template < class source_t, class sink_t > auto connect (source_t&& source, sink_t&& sink) { return detail::connect_impl<source_t, sink_t>()( std::forward<source_t>(source), std::forward<sink_t>(sink)); } /** * \brief Operator >> takes two connectables and returns a connection. * * This operator is syntactic sugar for Connect. */ template<class source_t, class sink_t, class enable = std::enable_if_t< (is_connectable<source_t>::value || is_active_source<rm_ref_t<source_t>>{}) && (is_connectable<sink_t>::value || is_active_sink<rm_ref_t<sink_t>>{})>> auto operator >>(source_t&& source, sink_t&& sink) { static_assert(!(is_active<rm_ref_t<source_t>>{} && is_active<rm_ref_t<sink_t>>{}), "event_source can not be connected to state_sink."); return connect(std::forward<source_t>(source), std::forward<sink_t>(sink)); } //todo: does not belong here template <class source_t, class sink_t> struct is_passive_sink<connection<source_t, sink_t>> : is_passive_sink<rm_ref_t<sink_t>> {}; template <class source_t, class sink_t> struct result_of<connection<source_t, sink_t>> : result_of<rm_ref_t<sink_t>> {}; } //namespace fc #endif /* SRC_CORE_CONNECTION_HPP_ */ <|endoftext|>
<commit_before>/* * FilePathTests.cpp * * Copyright (C) 2009-20 by RStudio, PBC * * 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. * */ #define RSTUDIO_NO_TESTTHAT_ALIASES #include <tests/TestThat.hpp> #include <shared_core/Error.hpp> #include <shared_core/FilePath.hpp> namespace rstudio { namespace core { namespace tests { namespace { #ifdef _WIN32 // helper for creating a path with the system drive // prefixed for Windows. we try to use the current // drive if at all possible; if we cannot retrieve // that for some reason then we just fall back to // the default system drive (normally C:) std::string getDrivePrefix() { char buffer[MAX_PATH]; DWORD n = GetCurrentDirectory(MAX_PATH, buffer); if (n < 2) return ::getenv("SYSTEMDRIVE"); if (buffer[1] != ':') return ::getenv("SYSTEMDRIVE"); return std::string(buffer, 2); } FilePath createPath(const std::string& path = "/") { static const std::string prefix = getDrivePrefix(); return FilePath(prefix + path); } #else FilePath createPath(const std::string& path) { return FilePath(path); } #endif /* _WIN32 */ } // end anonymous namespace TEST_CASE("file paths") { SECTION("relative path construction") { FilePath rootPath = createPath(); FilePath pPath = createPath("/path/to"); FilePath aPath = createPath("/path/to/a"); FilePath bPath = createPath("/path/to/b"); CHECK(aPath.isWithin(pPath)); CHECK(bPath.isWithin(pPath)); CHECK(!aPath.isWithin(bPath)); CHECK(aPath.getRelativePath(pPath) == "a"); } SECTION("path containment pathology") { // isWithin should not be fooled by directory traversal; the first path is not inside the // second even though it appears to be lexically FilePath aPath = createPath("/path/to/a/../b"); FilePath bPath = createPath("/path/to/a"); CHECK(!aPath.isWithin(bPath)); // isWithin should not be fooled by substrings FilePath cPath = createPath("/path/to/foo"); FilePath dPath = createPath("/path/to/foobar"); CHECK(!dPath.isWithin(cPath)); } SECTION("child path completion") { // simple path completion should do what's expected FilePath aPath = createPath("/path/to/a"); FilePath bPath = createPath("/path/to/a/b"); CHECK(aPath.completeChildPath("b") == bPath); // trying to complete to a path outside should fail and return the original path FilePath cPath = createPath("/path/to/foo"); CHECK(cPath.completeChildPath("../bar") == cPath); CHECK(cPath.completeChildPath("/path/to/quux") == cPath); // trailing slashes are okay FilePath dPath = createPath("/path/to/"); FilePath ePath = createPath("/path/to/e"); CHECK(dPath.completeChildPath("e") == ePath); } SECTION("general path completion") { // simple path completion should do what's expected FilePath aPath = createPath("/path/to/a"); FilePath bPath = createPath("/path/to/a/b"); CHECK(aPath.completePath("b") == bPath); // absolute paths are allowed FilePath cPath = createPath("/path/to/c"); FilePath dPath = createPath("/path/to/d"); CHECK(cPath.completePath("/path/to/d") == dPath); // directory traversal is allowed FilePath ePath = createPath("/path/to/e"); FilePath fPath = createPath("/path/to/f"); CHECK(ePath.completePath("../f").getLexicallyNormalPath() == fPath.getAbsolutePath()); } #ifdef _WIN32 SECTION("relative paths for UNC shares") { // NOTE: need to be robust against mixed separators as these can // leak in depending on the API used to request the file path. // // https://github.com/rstudio/rstudio/issues/6587 FilePath pPath(R"(//LOCALHOST/c$/p)"); FilePath aPath(R"(\\LOCALHOST\c$\p\a)"); CHECK(aPath.getRelativePath(pPath) == "a"); } #endif /* _WIN32 */ } } // end namespace tests } // end namespace core } // end namespace rstudio <commit_msg>fix build<commit_after>/* * FilePathTests.cpp * * Copyright (C) 2009-20 by RStudio, PBC * * 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. * */ #define RSTUDIO_NO_TESTTHAT_ALIASES #include <tests/TestThat.hpp> #include <shared_core/Error.hpp> #include <shared_core/FilePath.hpp> namespace rstudio { namespace core { namespace tests { namespace { #ifdef _WIN32 // helper for creating a path with the system drive // prefixed for Windows. we try to use the current // drive if at all possible; if we cannot retrieve // that for some reason then we just fall back to // the default system drive (normally C:) std::string getDrivePrefix() { char buffer[MAX_PATH]; DWORD n = GetCurrentDirectory(MAX_PATH, buffer); if (n < 2) return ::getenv("SYSTEMDRIVE"); if (buffer[1] != ':') return ::getenv("SYSTEMDRIVE"); return std::string(buffer, 2); } FilePath createPath(const std::string& path = "/") { static const std::string prefix = getDrivePrefix(); return FilePath(prefix + path); } #else FilePath createPath(const std::string& path = "/") { return FilePath(path); } #endif /* _WIN32 */ } // end anonymous namespace TEST_CASE("file paths") { SECTION("relative path construction") { FilePath rootPath = createPath(); FilePath pPath = createPath("/path/to"); FilePath aPath = createPath("/path/to/a"); FilePath bPath = createPath("/path/to/b"); CHECK(aPath.isWithin(pPath)); CHECK(bPath.isWithin(pPath)); CHECK(!aPath.isWithin(bPath)); CHECK(aPath.getRelativePath(pPath) == "a"); } SECTION("path containment pathology") { // isWithin should not be fooled by directory traversal; the first path is not inside the // second even though it appears to be lexically FilePath aPath = createPath("/path/to/a/../b"); FilePath bPath = createPath("/path/to/a"); CHECK(!aPath.isWithin(bPath)); // isWithin should not be fooled by substrings FilePath cPath = createPath("/path/to/foo"); FilePath dPath = createPath("/path/to/foobar"); CHECK(!dPath.isWithin(cPath)); } SECTION("child path completion") { // simple path completion should do what's expected FilePath aPath = createPath("/path/to/a"); FilePath bPath = createPath("/path/to/a/b"); CHECK(aPath.completeChildPath("b") == bPath); // trying to complete to a path outside should fail and return the original path FilePath cPath = createPath("/path/to/foo"); CHECK(cPath.completeChildPath("../bar") == cPath); CHECK(cPath.completeChildPath("/path/to/quux") == cPath); // trailing slashes are okay FilePath dPath = createPath("/path/to/"); FilePath ePath = createPath("/path/to/e"); CHECK(dPath.completeChildPath("e") == ePath); } SECTION("general path completion") { // simple path completion should do what's expected FilePath aPath = createPath("/path/to/a"); FilePath bPath = createPath("/path/to/a/b"); CHECK(aPath.completePath("b") == bPath); // absolute paths are allowed FilePath cPath = createPath("/path/to/c"); FilePath dPath = createPath("/path/to/d"); CHECK(cPath.completePath("/path/to/d") == dPath); // directory traversal is allowed FilePath ePath = createPath("/path/to/e"); FilePath fPath = createPath("/path/to/f"); CHECK(ePath.completePath("../f").getLexicallyNormalPath() == fPath.getAbsolutePath()); } #ifdef _WIN32 SECTION("relative paths for UNC shares") { // NOTE: need to be robust against mixed separators as these can // leak in depending on the API used to request the file path. // // https://github.com/rstudio/rstudio/issues/6587 FilePath pPath(R"(//LOCALHOST/c$/p)"); FilePath aPath(R"(\\LOCALHOST\c$\p\a)"); CHECK(aPath.getRelativePath(pPath) == "a"); } #endif /* _WIN32 */ } } // end namespace tests } // end namespace core } // end namespace rstudio <|endoftext|>
<commit_before>#include "applications.h" #include <QDir> const int Applications::NameRole = Qt::UserRole + 1; const int Applications::IconRole = Qt::UserRole + 2; const int Applications::ExecRole = Qt::UserRole + 3; const int Applications::TerminalRole = Qt::UserRole + 4; Applications::Applications(QObject *parent) : QAbstractListModel(parent) { connect(&m_parserThreadWatcher, SIGNAL(finished()), this, SLOT(parseFinished())); m_parserRunning = true; m_parserThread = QtConcurrent::run(this, &Applications::parseApplications); m_parserThreadWatcher.setFuture(m_parserThread); } Applications::~Applications() { if (m_parserThread.isRunning()) m_parserThread.cancel(); qDeleteAll(this->m_internalData); } void Applications::parseApplications() { this->m_files.append(this->readFolder(QDir::homePath() + APPLICATIONS_LOCAL_PATH)); this->m_files.append(this->readFolder(APPLICATIONS_PATH)); foreach(QString file, this->m_files) { DesktopFile* app = new DesktopFile(file); if (!app->noDisplay()) { m_internalData.append(app); } } this->m_files.clear(); } QStringList Applications::readFolder(QString folder) { QDir dir(folder); QFileInfoList file_list = dir.entryInfoList( QStringList(APPLICATIONS_FILES), QDir::Files | QDir::Readable); QStringList files; foreach(QFileInfo file, file_list) { if (this->m_files.filter(file.fileName()).count() == 0) { files.append(file.absoluteFilePath()); } } return files; } void Applications::add(DesktopFile *item) { beginInsertRows(QModelIndex(), m_data.size(), m_data.size()); m_data.append(item); endInsertRows(); emit countChanged(m_data.size()); } void Applications::sort() { std::sort(this->m_data.begin(), this->m_data.end(), [](const DesktopFile* left, const DesktopFile* right) -> bool { return QString::compare(left->name(),right->name(), Qt::CaseInsensitive) < 0; }); } DesktopFile* Applications::get(int index) const { return m_data.at(index); } void Applications::filter(QString search) { if (m_parserRunning) return; beginRemoveRows(QModelIndex(), 0, m_data.size()); m_data.clear(); endRemoveRows(); foreach(DesktopFile* file, m_internalData) { if(file->name().contains(search,Qt::CaseInsensitive) || file->comment().contains(search, Qt::CaseInsensitive) || file->exec().contains(search, Qt::CaseInsensitive)) { this->add(file); } } this->sort(); } int Applications::rowCount(const QModelIndex &) const { return m_data.count(); } QVariant Applications::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() > (m_data.size()-1) ) return QVariant(); DesktopFile* obj = m_data.at(index.row()); switch(role) { case Qt::DisplayRole: case NameRole: return QVariant::fromValue(obj->name()); break; case IconRole: return QVariant::fromValue(obj->icon()); case ExecRole: return QVariant::fromValue(obj->exec()); case TerminalRole: return QVariant::fromValue(obj->terminal()); default: return QVariant(); } } QHash<int, QByteArray> Applications::roleNames() const { QHash<int, QByteArray> roles = QAbstractListModel::roleNames(); roles.insert(NameRole, QByteArray("name")); roles.insert(IconRole, QByteArray("icon")); roles.insert(ExecRole, QByteArray("exec")); roles.insert(TerminalRole, QByteArray("terminal")); return roles; } void Applications::parseFinished() { m_parserRunning = false; this->filter(""); emit ready(); } <commit_msg>Hide termianl apps<commit_after>#include "applications.h" #include <QDir> const int Applications::NameRole = Qt::UserRole + 1; const int Applications::IconRole = Qt::UserRole + 2; const int Applications::ExecRole = Qt::UserRole + 3; const int Applications::TerminalRole = Qt::UserRole + 4; Applications::Applications(QObject *parent) : QAbstractListModel(parent) { connect(&m_parserThreadWatcher, SIGNAL(finished()), this, SLOT(parseFinished())); m_parserRunning = true; m_parserThread = QtConcurrent::run(this, &Applications::parseApplications); m_parserThreadWatcher.setFuture(m_parserThread); } Applications::~Applications() { if (m_parserThread.isRunning()) m_parserThread.cancel(); qDeleteAll(this->m_internalData); } void Applications::parseApplications() { this->m_files.append(this->readFolder(QDir::homePath() + APPLICATIONS_LOCAL_PATH)); this->m_files.append(this->readFolder(APPLICATIONS_PATH)); foreach(QString file, this->m_files) { DesktopFile* app = new DesktopFile(file); if (!app->noDisplay() && !app->terminal()) { m_internalData.append(app); } } this->m_files.clear(); } QStringList Applications::readFolder(QString folder) { QDir dir(folder); QFileInfoList file_list = dir.entryInfoList( QStringList(APPLICATIONS_FILES), QDir::Files | QDir::Readable); QStringList files; foreach(QFileInfo file, file_list) { if (this->m_files.filter(file.fileName()).count() == 0) { files.append(file.absoluteFilePath()); } } return files; } void Applications::add(DesktopFile *item) { beginInsertRows(QModelIndex(), m_data.size(), m_data.size()); m_data.append(item); endInsertRows(); emit countChanged(m_data.size()); } void Applications::sort() { std::sort(this->m_data.begin(), this->m_data.end(), [](const DesktopFile* left, const DesktopFile* right) -> bool { return QString::compare(left->name(),right->name(), Qt::CaseInsensitive) < 0; }); } DesktopFile* Applications::get(int index) const { return m_data.at(index); } void Applications::filter(QString search) { if (m_parserRunning) return; beginRemoveRows(QModelIndex(), 0, m_data.size()); m_data.clear(); endRemoveRows(); foreach(DesktopFile* file, m_internalData) { if(file->name().contains(search,Qt::CaseInsensitive) || file->comment().contains(search, Qt::CaseInsensitive) || file->exec().contains(search, Qt::CaseInsensitive)) { this->add(file); } } this->sort(); } int Applications::rowCount(const QModelIndex &) const { return m_data.count(); } QVariant Applications::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() > (m_data.size()-1) ) return QVariant(); DesktopFile* obj = m_data.at(index.row()); switch(role) { case Qt::DisplayRole: case NameRole: return QVariant::fromValue(obj->name()); break; case IconRole: return QVariant::fromValue(obj->icon()); case ExecRole: return QVariant::fromValue(obj->exec()); case TerminalRole: return QVariant::fromValue(obj->terminal()); default: return QVariant(); } } QHash<int, QByteArray> Applications::roleNames() const { QHash<int, QByteArray> roles = QAbstractListModel::roleNames(); roles.insert(NameRole, QByteArray("name")); roles.insert(IconRole, QByteArray("icon")); roles.insert(ExecRole, QByteArray("exec")); roles.insert(TerminalRole, QByteArray("terminal")); return roles; } void Applications::parseFinished() { m_parserRunning = false; this->filter(""); emit ready(); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2014 Vadim Macagon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //------------------------------------------------------------------------------- #include "KlawrRuntimePluginPrivatePCH.h" #include "KlawrScriptContext.h" namespace Klawr { FScriptContext::FScriptContext() { ScriptObjectInfo.InstanceID = 0; } FScriptContext::~FScriptContext() { DestroyScriptObject(); } bool FScriptContext::Initialize(const FString& Code, UObject* Owner) { // TODO: // [editor-only] save the code out to a file // [editor-only][advanced] generate a C# class for each blueprint class in the inheritance hierarchy // [editor-only] update the .csproj // [editor-only] rebuild the .csproj // [editor-only] copy the assembly to a directory in the search path // [editor-only] reload the engine app domain // create an instance of the managed class //return IClrHost::Get()->CreateScriptObject(TEXT("Klawr.UnrealEngine.TestActor"), Owner, ScriptObjectInfo); return false; } void FScriptContext::DestroyScriptObject() { if (ScriptObjectInfo.InstanceID != 0) { //IClrHost::Get()->DestroyScriptObject(ScriptObjectInfo.InstanceID); ScriptObjectInfo.InstanceID = 0; } } void FScriptContext::BeginPlay() { if (ScriptObjectInfo.BeginPlay) { ScriptObjectInfo.BeginPlay(); } } void FScriptContext::Tick(float DeltaTime) { if (ScriptObjectInfo.Tick) { ScriptObjectInfo.Tick(DeltaTime); } } void FScriptContext::Destroy() { // clean up anything created in BeginPlay/Tick if (ScriptObjectInfo.Destroy) { ScriptObjectInfo.Destroy(); } // the managed object will not be accessed from here on, so get rid of it now DestroyScriptObject(); } bool FScriptContext::CanTick() { return ScriptObjectInfo.Tick != nullptr; } bool FScriptContext::CallFunction(const FString& FunctionName) { // TODO: return false; } void FScriptContext::InvokeScriptFunction(FFrame& Stack, RESULT_DECL) { P_FINISH; CallFunction(Stack.CurrentNativeFunction->GetName()); } } // namespace Klawr <commit_msg>Renaming to KlawrScriptContext<commit_after>//------------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2014 Vadim Macagon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //------------------------------------------------------------------------------- #include "KlawrRuntimePluginPrivatePCH.h" #include "KlawrScriptContext.h" namespace Klawr { FKlawrScriptContext::FKlawrScriptContext() { ScriptObjectInfo.InstanceID = 0; } FKlawrScriptContext::~FKlawrScriptContext() { DestroyScriptObject(); } bool FKlawrScriptContext::Initialize(const FString& Code, UObject* Owner) { // TODO: // [editor-only] save the code out to a file // [editor-only][advanced] generate a C# class for each blueprint class in the inheritance hierarchy // [editor-only] update the .csproj // [editor-only] rebuild the .csproj // [editor-only] copy the assembly to a directory in the search path // [editor-only] reload the engine app domain // create an instance of the managed class //return IClrHost::Get()->CreateScriptObject(TEXT("Klawr.UnrealEngine.TestActor"), Owner, ScriptObjectInfo); return false; } void FKlawrScriptContext::DestroyScriptObject() { if (ScriptObjectInfo.InstanceID != 0) { //IClrHost::Get()->DestroyScriptObject(ScriptObjectInfo.InstanceID); ScriptObjectInfo.InstanceID = 0; } } void FKlawrScriptContext::BeginPlay() { if (ScriptObjectInfo.BeginPlay) { ScriptObjectInfo.BeginPlay(); } } void FKlawrScriptContext::Tick(float DeltaTime) { if (ScriptObjectInfo.Tick) { ScriptObjectInfo.Tick(DeltaTime); } } void FKlawrScriptContext::Destroy() { // clean up anything created in BeginPlay/Tick if (ScriptObjectInfo.Destroy) { ScriptObjectInfo.Destroy(); } // the managed object will not be accessed from here on, so get rid of it now DestroyScriptObject(); } bool FKlawrScriptContext::CanTick() { return ScriptObjectInfo.Tick != nullptr; } bool FKlawrScriptContext::CallFunction(const FString& FunctionName) { // TODO: return false; } void FKlawrScriptContext::InvokeScriptFunction(FFrame& Stack, RESULT_DECL) { P_FINISH; CallFunction(Stack.CurrentNativeFunction->GetName()); } } // namespace Klawr <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2011-2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <vector> #include <string> #include <fnordmetric/cli/cli.h> #include <fnordmetric/cli/flagparser.h> #include <fnordmetric/ev/eventloop.h> #include <fnordmetric/ev/acceptor.h> #include <fnordmetric/http/httpserver.h> #include <fnordmetric/util/exceptionhandler.h> #include <fnordmetric/util/inputstream.h> #include <fnordmetric/util/outputstream.h> #include <fnordmetric/util/runtimeexception.h> #include <fnordmetric/web/webinterface.h> #include <fnordmetric/web/queryendpoint.h> namespace fnordmetric { namespace cli { FlagParser CLI::getDefaultFlagParser() { FlagParser flag_parser; // Execute queries from the commandline: flag_parser.defineFlag( "format", FlagParser::T_STRING, false, "f", "table", "The output format { svg, csv, table }", "<format>"); flag_parser.defineFlag( "output", FlagParser::T_STRING, false, "o", NULL, "Write output to a file", "<format>"); // Start a user interface: flag_parser.defineFlag( "repl", FlagParser::T_SWITCH, false, NULL, NULL, "Start an interactive readline shell", NULL); flag_parser.defineFlag( "web", FlagParser::T_INTEGER, false, NULL, NULL, "Start a web interface on this port", "<port>"); flag_parser.defineFlag( "cgi", FlagParser::T_SWITCH, false, NULL, NULL, "Run as CGI script"); flag_parser.defineFlag( "verbose", FlagParser::T_SWITCH, false, NULL, NULL, "Be verbose"); flag_parser.defineFlag( "help", FlagParser::T_SWITCH, false, "h", NULL, "You are reading it..."); return flag_parser; } int CLI::executeSafely( const std::vector<std::string>& argv, std::shared_ptr<util::OutputStream> error_stream) { bool verbose = true; auto flag_parser = getDefaultFlagParser(); try { flag_parser.parseArgv(argv); verbose = flag_parser.isSet("verbose"); execute(flag_parser, error_stream); } catch (util::RuntimeException e) { if (e.getTypeName() == "UsageError") { flag_parser.printUsage(error_stream.get()); return 1; } error_stream->printf("fatal error: %s\n", e.getMessage().c_str()); if (verbose) { e.debugPrint(); } return 1; } return 0; } void CLI::execute( const std::vector<std::string>& argv, std::shared_ptr<util::OutputStream> error_stream) { /* parse flags */ auto flag_parser = getDefaultFlagParser(); flag_parser.parseArgv(argv); bool verbose = flag_parser.isSet("verbose"); const auto& args = flag_parser.getArgv(); execute(flag_parser, error_stream); } void CLI::execute( const FlagParser& flag_parser, std::shared_ptr<util::OutputStream> error_stream) { const auto& args = flag_parser.getArgv(); bool verbose = flag_parser.isSet("verbose"); /* web / cgi mode */ if (flag_parser.isSet("web")) { fnordmetric::util::ThreadPool thread_pool( 32, std::unique_ptr<util::ExceptionHandler>( new util::CatchAndPrintExceptionHandler(error_stream))); fnordmetric::ev::EventLoop ev_loop; fnordmetric::ev::Acceptor acceptor(&ev_loop); fnordmetric::http::ThreadedHTTPServer http(&thread_pool); http.addHandler(fnordmetric::web::WebInterface::getHandler()); http.addHandler(fnordmetric::web::QueryEndpoint::getHandler()); acceptor.listen(flag_parser.getInt("web"), &http); ev_loop.loop(); } /* open input stream */ std::unique_ptr<util::InputStream> input; if (args.size() == 1) { if (args[0] == "-") { if (verbose) { error_stream->printf("[INFO] input from stdin %s\n"); } input = std::move(util::InputStream::getStdin()); } else { if (verbose) { error_stream->printf("[INFO] input file: %s\n", args[0].c_str()); } input = std::move(util::FileInputStream::openFile(args[0])); } } else { RAISE(UsageError); } /* open output stream */ std::unique_ptr<util::OutputStream> output; if (flag_parser.isSet("output")) { auto output_file = flag_parser.getString("output"); if (verbose) { error_stream->printf("[INFO] output file: %s\n", output_file.c_str()); } output = std::move(util::FileOutputStream::openFile(output_file)); } else { if (verbose) { error_stream->printf("[INFO] output to stdout\n"); } output = std::move(util::OutputStream::getStdout()); } /* execute query */ query::QueryService query_service; query_service.executeQuery( input.get(), getOutputFormat(flag_parser), output.get()); } const query::QueryService::kFormat CLI::getOutputFormat( const FlagParser& flags) { return query::QueryService::FORMAT_TABLE; } } } <commit_msg>implement output format<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2011-2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <vector> #include <string> #include <fnordmetric/cli/cli.h> #include <fnordmetric/cli/flagparser.h> #include <fnordmetric/ev/eventloop.h> #include <fnordmetric/ev/acceptor.h> #include <fnordmetric/http/httpserver.h> #include <fnordmetric/util/exceptionhandler.h> #include <fnordmetric/util/inputstream.h> #include <fnordmetric/util/outputstream.h> #include <fnordmetric/util/runtimeexception.h> #include <fnordmetric/web/webinterface.h> #include <fnordmetric/web/queryendpoint.h> namespace fnordmetric { namespace cli { FlagParser CLI::getDefaultFlagParser() { FlagParser flag_parser; // Execute queries from the commandline: flag_parser.defineFlag( "format", FlagParser::T_STRING, false, "f", "table", "The output format { svg, csv, table }", "<format>"); flag_parser.defineFlag( "output", FlagParser::T_STRING, false, "o", NULL, "Write output to a file", "<format>"); // Start a user interface: flag_parser.defineFlag( "repl", FlagParser::T_SWITCH, false, NULL, NULL, "Start an interactive readline shell", NULL); flag_parser.defineFlag( "web", FlagParser::T_INTEGER, false, NULL, NULL, "Start a web interface on this port", "<port>"); flag_parser.defineFlag( "cgi", FlagParser::T_SWITCH, false, NULL, NULL, "Run as CGI script"); flag_parser.defineFlag( "verbose", FlagParser::T_SWITCH, false, NULL, NULL, "Be verbose"); flag_parser.defineFlag( "help", FlagParser::T_SWITCH, false, "h", NULL, "You are reading it..."); return flag_parser; } int CLI::executeSafely( const std::vector<std::string>& argv, std::shared_ptr<util::OutputStream> error_stream) { bool verbose = true; auto flag_parser = getDefaultFlagParser(); try { flag_parser.parseArgv(argv); verbose = flag_parser.isSet("verbose"); execute(flag_parser, error_stream); } catch (util::RuntimeException e) { if (e.getTypeName() == "UsageError") { flag_parser.printUsage(error_stream.get()); return 1; } error_stream->printf("fatal error: %s\n", e.getMessage().c_str()); if (verbose) { e.debugPrint(); } return 1; } return 0; } void CLI::execute( const std::vector<std::string>& argv, std::shared_ptr<util::OutputStream> error_stream) { /* parse flags */ auto flag_parser = getDefaultFlagParser(); flag_parser.parseArgv(argv); bool verbose = flag_parser.isSet("verbose"); const auto& args = flag_parser.getArgv(); execute(flag_parser, error_stream); } void CLI::execute( const FlagParser& flag_parser, std::shared_ptr<util::OutputStream> error_stream) { const auto& args = flag_parser.getArgv(); bool verbose = flag_parser.isSet("verbose"); /* web / cgi mode */ if (flag_parser.isSet("web")) { fnordmetric::util::ThreadPool thread_pool( 32, std::unique_ptr<util::ExceptionHandler>( new util::CatchAndPrintExceptionHandler(error_stream))); fnordmetric::ev::EventLoop ev_loop; fnordmetric::ev::Acceptor acceptor(&ev_loop); fnordmetric::http::ThreadedHTTPServer http(&thread_pool); http.addHandler(fnordmetric::web::WebInterface::getHandler()); http.addHandler(fnordmetric::web::QueryEndpoint::getHandler()); acceptor.listen(flag_parser.getInt("web"), &http); ev_loop.loop(); } /* open input stream */ std::unique_ptr<util::InputStream> input; if (args.size() == 1) { if (args[0] == "-") { if (verbose) { error_stream->printf("[INFO] input from stdin %s\n"); } input = std::move(util::InputStream::getStdin()); } else { if (verbose) { error_stream->printf("[INFO] input file: %s\n", args[0].c_str()); } input = std::move(util::FileInputStream::openFile(args[0])); } } else { RAISE(UsageError); } /* open output stream */ std::unique_ptr<util::OutputStream> output; if (flag_parser.isSet("output")) { auto output_file = flag_parser.getString("output"); if (verbose) { error_stream->printf("[INFO] output file: %s\n", output_file.c_str()); } output = std::move(util::FileOutputStream::openFile(output_file)); } else { if (verbose) { error_stream->printf("[INFO] output to stdout\n"); } output = std::move(util::OutputStream::getStdout()); } /* execute query */ query::QueryService query_service; query_service.executeQuery( input.get(), getOutputFormat(flag_parser), output.get()); } const query::QueryService::kFormat CLI::getOutputFormat( const FlagParser& flags) { if (!flags.isSet("format")) { return query::QueryService::FORMAT_TABLE; } auto format_str = flags.getString("format"); if (format_str == "csv") { return query::QueryService::FORMAT_CSV; } if (format_str == "json") { return query::QueryService::FORMAT_JSON; } if (format_str == "svg") { return query::QueryService::FORMAT_SVG; } if (format_str == "table") { return query::QueryService::FORMAT_TABLE; } RAISE( util::RuntimeException, "invalid format: '%s', allowed formats are " "'svg', 'csv', 'json' and 'table'", format_str.c_str()); } } } <|endoftext|>
<commit_before>/* OpenHoW * Copyright (C) 2017-2020 Mark Sowden <markelswo@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <PL/platform_filesystem.h> #include "engine.h" #include "mod_support.h" #include "script/script_config.h" using namespace openhow; /* Mod Management * * Launching games and other state management * of the game as a whole is dealt with here. */ modsMap_t modsList; modDirectory_t* currentModification = nullptr; /** * Pull a list of registered mods which can be displayed * for user selection. * @return Pointer to modification list. */ const modsMap_t* Mod_GetRegisteredMods() { return &modsList; } static modDirectory_t* Mod_GetManifest( const std::string& name ) { auto campaign = modsList.find( name ); if ( campaign != modsList.end() ) { return &campaign->second; } LogWarn( "Failed to find mod \"%s\"!\n" ); return nullptr; } static modDirectory_t Mod_LoadManifest( const char* path ) { LogInfo( "Loading manifest \"%s\"...\n", path ); modDirectory_t slot; try { ScriptConfig config( path ); slot.name = config.GetStringProperty( "name" ); slot.version = config.GetStringProperty( "version", "Unknown", true ); slot.author = config.GetStringProperty( "author", "Unknown", true ); slot.isVisible = config.GetBooleanProperty( "isVisible", false, true ); char filename[64]; snprintf( filename, sizeof( filename ), "%s", plGetFileName( path ) ); slot.fileName = path; slot.internalName = std::string( filename, strlen( filename ) - 4 ); slot.directory = slot.internalName + "/"; slot.dependencies = config.GetArrayStrings( "dependencies" ); } catch ( const std::exception& e ) { Error( "Failed to read mod config, \"%s\"!\n%s\n", path, e.what() ); } return slot; } /** * Load in the mod manifest and store it into a buffer. * @param path Path to the manifest file. */ void Mod_RegisterMod( const char* path ) { modDirectory_t mod = Mod_LoadManifest( path ); modsList.emplace( mod.internalName, mod ); } /** * Registers all of the mods provided under the mods directory. */ void Mod_RegisterMods() { plScanDirectory( "mods", "mod", Mod_RegisterMod, false ); } /** * Returns a pointer to the mod that's currently active. * @return Pointer to the current mod. */ const modDirectory_t* Mod_GetCurrentMod() { return currentModification; } /** * Unmounts the specified modification. */ static void Mod_Unmount( modDirectory_t* mod ) { // If a modification is already mounted, unmount it if ( mod != nullptr ) { for ( const auto& i : mod->mountList ) { plClearMountedLocation( i ); } mod->mountList.clear(); } Engine::Resource()->ClearAll(); } void Mod_SetMod( const char* name ) { // Attempt to fetch the manifest, if it doesn't exist then attempt to load it modDirectory_t* mod = Mod_GetManifest( name ); if ( mod == nullptr ) { LogInfo( "Mod manifest, \"%s\", wasn't cached on launch... attempting to load!\n", name ); char path[PL_SYSTEM_MAX_PATH]; snprintf( path, sizeof( path ), "mods/%s.mod", name ); if ( plFileExists( path ) ) { Mod_RegisterMod( path ); mod = Mod_GetManifest( name ); } if ( mod == nullptr ) { LogWarn( "Mod \"%s\" doesn't exist!\n", name ); return; } } if ( currentModification == mod ) { LogInfo( "Mod is already mounted\n" ); return; } // Generate a list of directories to mount based on the dependencies std::list<std::string> dirList; for ( const auto& i : mod->dependencies ) { modDirectory_t* dependency = Mod_GetManifest( i ); if ( dependency == nullptr ) { LogWarn( "Failed to fetch dependency for mod, \"%s\"!\n", i.c_str() ); return; } dirList.push_back( dependency->directory ); } dirList.push_back( mod->directory ); // Now attempt to mount everything for ( const auto& i : dirList ) { char mountPath[PL_SYSTEM_MAX_PATH]; snprintf( mountPath, sizeof( mountPath ), "mods/%s", i.c_str() ); PLFileSystemMount* mount = plMountLocation( mountPath ); if ( mount == nullptr ) { Mod_Unmount( mod ); LogWarn( "Failed to mount location, \"%s\" (%s)!\n", i.c_str(), plGetError() ); return; } } if ( currentModification != nullptr ) { Mod_Unmount( currentModification ); } currentModification = mod; LogInfo( "Mod has been set to \"%s\" successfully!\n", mod->name.c_str() ); } <commit_msg>recursively fetch dependencies for mods<commit_after>/* OpenHoW * Copyright (C) 2017-2020 Mark Sowden <markelswo@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <PL/platform_filesystem.h> #include "engine.h" #include "mod_support.h" #include "script/script_config.h" using namespace openhow; /* Mod Management * * Launching games and other state management * of the game as a whole is dealt with here. */ modsMap_t modsList; modDirectory_t* currentModification = nullptr; /** * Pull a list of registered mods which can be displayed * for user selection. * @return Pointer to modification list. */ const modsMap_t* Mod_GetRegisteredMods() { return &modsList; } static modDirectory_t* Mod_GetManifest( const std::string& name ) { auto campaign = modsList.find( name ); if ( campaign != modsList.end() ) { return &campaign->second; } LogWarn( "Failed to find mod \"%s\"!\n" ); return nullptr; } static modDirectory_t Mod_LoadManifest( const char* path ) { LogInfo( "Loading manifest \"%s\"...\n", path ); modDirectory_t slot; try { ScriptConfig config( path ); slot.name = config.GetStringProperty( "name" ); slot.version = config.GetStringProperty( "version", "Unknown", true ); slot.author = config.GetStringProperty( "author", "Unknown", true ); slot.isVisible = config.GetBooleanProperty( "isVisible", false, true ); char filename[64]; snprintf( filename, sizeof( filename ), "%s", plGetFileName( path ) ); slot.fileName = path; slot.internalName = std::string( filename, strlen( filename ) - 4 ); slot.directory = slot.internalName + "/"; slot.dependencies = config.GetArrayStrings( "dependencies" ); } catch ( const std::exception& e ) { Error( "Failed to read mod config, \"%s\"!\n%s\n", path, e.what() ); } return slot; } /** * Load in the mod manifest and store it into a buffer. * @param path Path to the manifest file. */ void Mod_RegisterMod( const char* path ) { modDirectory_t mod = Mod_LoadManifest( path ); modsList.emplace( mod.internalName, mod ); } /** * Registers all of the mods provided under the mods directory. */ void Mod_RegisterMods() { plScanDirectory( "mods", "mod", Mod_RegisterMod, false ); } /** * Returns a pointer to the mod that's currently active. * @return Pointer to the current mod. */ const modDirectory_t* Mod_GetCurrentMod() { return currentModification; } /** * Unmounts the specified modification. */ static void Mod_Unmount( modDirectory_t* mod ) { // If a modification is already mounted, unmount it if ( mod != nullptr ) { for ( const auto& i : mod->mountList ) { plClearMountedLocation( i ); } mod->mountList.clear(); } Engine::Resource()->ClearAll(); } void Mod_FetchDependencies( modDirectory_t* mod, std::set<std::string>& dirSet ) { const auto& dir = dirSet.find( mod->directory ); if ( dir != dirSet.end() ) { LogInfo( "%s is already mounted, skipping\n", mod->directory ); return; } for ( const auto& i : mod->dependencies ) { modDirectory_t* dependency = Mod_GetManifest( i ); if ( dependency == nullptr ) { LogWarn( "Failed to fetch dependency for mod, \"%s\"!\n", i.c_str() ); return; } if ( !dependency->dependencies.empty() ) { Mod_FetchDependencies( dependency, dirSet ); } dirSet.emplace( dependency->directory ); } } void Mod_SetMod( const char* name ) { // Attempt to fetch the manifest, if it doesn't exist then attempt to load it modDirectory_t* mod = Mod_GetManifest( name ); if ( mod == nullptr ) { LogInfo( "Mod manifest, \"%s\", wasn't cached on launch... attempting to load!\n", name ); char path[PL_SYSTEM_MAX_PATH]; snprintf( path, sizeof( path ), "mods/%s.mod", name ); if ( plFileExists( path ) ) { Mod_RegisterMod( path ); mod = Mod_GetManifest( name ); } if ( mod == nullptr ) { LogWarn( "Mod \"%s\" doesn't exist!\n", name ); return; } } if ( currentModification == mod ) { LogInfo( "Mod is already mounted\n" ); return; } // Generate a list of directories to mount based on the dependencies std::set<std::string> dirSet; Mod_FetchDependencies( mod, dirSet ); dirSet.emplace( mod->directory ); // Now attempt to mount everything for ( const auto& i : dirSet ) { char mountPath[PL_SYSTEM_MAX_PATH]; snprintf( mountPath, sizeof( mountPath ), "mods/%s", i.c_str() ); PLFileSystemMount* mount = plMountLocation( mountPath ); if ( mount == nullptr ) { Mod_Unmount( mod ); LogWarn( "Failed to mount location, \"%s\" (%s)!\n", i.c_str(), plGetError() ); return; } } if ( currentModification != nullptr ) { Mod_Unmount( currentModification ); } currentModification = mod; LogInfo( "Mod has been set to \"%s\" successfully!\n", mod->name.c_str() ); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Dennis Hedback * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef DESCARTIFY_COMMON_HPP #define DESCARTIFY_COMMON_HPP #include <set> #include <string> #ifdef USE_LL #include <list> #else #include <vector> #endif //USE_LL #ifdef USE_LL typedef std::list<std::string> Tuple; #else typedef std::vector<std::string> Tuple; #endif // USE_LL typedef std::set<Tuple> Product; typedef std::set<std::string> Set; #ifdef USE_LL typedef std::list<Set> Generator; #else typedef std::vector<Set> Generator; #endif // USE_LL struct Options { }; void cartesian_product(Generator &, Product &, bool); #endif // DESCARTIFY_COMMON_HPP <commit_msg>Did a wee bit refactoring<commit_after>/* * Copyright (c) 2012, Dennis Hedback * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef DESCARTIFY_COMMON_HPP #define DESCARTIFY_COMMON_HPP #include <set> #include <string> #ifdef USE_LL #include <list> #else #include <vector> #endif //USE_LL typedef std::set<std::string> Set; #ifdef USE_LL typedef std::list<std::string> Tuple; typedef std::list<Set> Generator; #else typedef std::vector<std::string> Tuple; typedef std::vector<Set> Generator; #endif // USE_LL typedef std::set<Tuple> Product; struct Options { }; void cartesian_product(Generator &, Product &, bool); #endif // DESCARTIFY_COMMON_HPP <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <fnord-base/uri.h> #include <fnordmetric/environment.h> #include <fnordmetric/adminui.h> namespace fnordmetric { AdminUI::AdminUI( std::string path_prefix /* = "/admin" */) : path_prefix_(path_prefix), webui_bundle_("FnordMetric"), webui_mount_(&webui_bundle_, path_prefix) { webui_bundle_.addComponent("fnord/3rdparty/codemirror.js"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css"); webui_bundle_.addComponent("fnord/3rdparty/reset.css"); webui_bundle_.addComponent("fnord/components/fn-table.css"); webui_bundle_.addComponent("fnord/components/fn-button.css"); webui_bundle_.addComponent("fnord/components/fn-modal.css"); webui_bundle_.addComponent("fnord/components/fn-tabbar.css"); webui_bundle_.addComponent("fnord/components/fn-message.css"); webui_bundle_.addComponent("fnord/components/fn-tooltip.css"); webui_bundle_.addComponent("fnord/components/fn-dropdown.css"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/fnord.js"); webui_bundle_.addComponent("fnord/date_util.js"); webui_bundle_.addComponent("fnord/components/fn-appbar.html"); webui_bundle_.addComponent("fnord/components/fn-button.html"); webui_bundle_.addComponent("fnord/components/fn-button-group.html"); webui_bundle_.addComponent("fnord/components/fn-icon.html"); webui_bundle_.addComponent("fnord/components/fn-input.html"); webui_bundle_.addComponent("fnord/components/fn-loader.html"); webui_bundle_.addComponent("fnord/components/fn-menu.html"); webui_bundle_.addComponent("fnord/components/fn-search.html"); webui_bundle_.addComponent("fnord/components/fn-table.html"); webui_bundle_.addComponent("fnord/components/fn-splitpane.html"); webui_bundle_.addComponent("fnord/components/fn-codeeditor.html"); webui_bundle_.addComponent("fnord/components/fn-dropdown.html"); webui_bundle_.addComponent("fnord/components/fn-datepicker.html"); webui_bundle_.addComponent("fnord/components/fn-timeinput.html"); webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html"); webui_bundle_.addComponent("fnord/components/fn-tabbar.html"); webui_bundle_.addComponent("fnord/components/fn-modal.html"); webui_bundle_.addComponent("fnord/components/fn-pager.html"); webui_bundle_.addComponent("fnord/components/fn-tooltip.html"); webui_bundle_.addComponent("fnord/components/fn-flexbox.html"); webui_bundle_.addComponent("fnord/components/fn-checkbox.html"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.html"); webui_bundle_.addComponent("fnord/components/fn-calendar.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-list.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-preview.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-search.html"); webui_bundle_.addComponent("fnord-metricdb/metric-control.html"); webui_bundle_.addComponent("fnord-metricdb/fn-metric-explorer.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html"); //webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-midnightblue.css"); //webui_bundle_.addComponent("fnord/themes/midnight-blue.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-cockpit.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js"); webui_bundle_.addComponent( "fnordmetric/fnordmetric-embed-query-popup.html"); } void AdminUI::handleHTTPRequest( http::HTTPRequest* request, http::HTTPResponse* response) { fnord::URI uri(request->uri()); auto path = uri.path(); if (path == "/") { response->setStatus(http::kStatusFound); response->addHeader("Content-Type", "text/html; charset=utf-8"); response->addHeader("Location", path_prefix_); return; } if (path == "/fontawesome.woff") { request->setURI( StringUtil::format( "$0/__components__/fnord/3rdparty/fontawesome.woff", path_prefix_)); } webui_mount_.handleHTTPRequest(request, response); } } <commit_msg>included search<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <fnord-base/uri.h> #include <fnordmetric/environment.h> #include <fnordmetric/adminui.h> namespace fnordmetric { AdminUI::AdminUI( std::string path_prefix /* = "/admin" */) : path_prefix_(path_prefix), webui_bundle_("FnordMetric"), webui_mount_(&webui_bundle_, path_prefix) { webui_bundle_.addComponent("fnord/3rdparty/codemirror.js"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css"); webui_bundle_.addComponent("fnord/3rdparty/reset.css"); webui_bundle_.addComponent("fnord/components/fn-table.css"); webui_bundle_.addComponent("fnord/components/fn-button.css"); webui_bundle_.addComponent("fnord/components/fn-modal.css"); webui_bundle_.addComponent("fnord/components/fn-tabbar.css"); webui_bundle_.addComponent("fnord/components/fn-message.css"); webui_bundle_.addComponent("fnord/components/fn-tooltip.css"); webui_bundle_.addComponent("fnord/components/fn-dropdown.css"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/components/fn-input.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/fnord.js"); webui_bundle_.addComponent("fnord/date_util.js"); webui_bundle_.addComponent("fnord/components/fn-appbar.html"); webui_bundle_.addComponent("fnord/components/fn-button.html"); webui_bundle_.addComponent("fnord/components/fn-button-group.html"); webui_bundle_.addComponent("fnord/components/fn-icon.html"); webui_bundle_.addComponent("fnord/components/fn-input.html"); webui_bundle_.addComponent("fnord/components/fn-loader.html"); webui_bundle_.addComponent("fnord/components/fn-menu.html"); webui_bundle_.addComponent("fnord/components/fn-search.html"); webui_bundle_.addComponent("fnord/components/fn-table.html"); webui_bundle_.addComponent("fnord/components/fn-splitpane.html"); webui_bundle_.addComponent("fnord/components/fn-codeeditor.html"); webui_bundle_.addComponent("fnord/components/fn-dropdown.html"); webui_bundle_.addComponent("fnord/components/fn-datepicker.html"); webui_bundle_.addComponent("fnord/components/fn-timeinput.html"); webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html"); webui_bundle_.addComponent("fnord/components/fn-tabbar.html"); webui_bundle_.addComponent("fnord/components/fn-modal.html"); webui_bundle_.addComponent("fnord/components/fn-pager.html"); webui_bundle_.addComponent("fnord/components/fn-tooltip.html"); webui_bundle_.addComponent("fnord/components/fn-flexbox.html"); webui_bundle_.addComponent("fnord/components/fn-checkbox.html"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.html"); webui_bundle_.addComponent("fnord/components/fn-calendar.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-list.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-preview.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-search.html"); webui_bundle_.addComponent("fnord-metricdb/metric-control.html"); webui_bundle_.addComponent("fnord-metricdb/fn-metric-explorer.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html"); //webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-midnightblue.css"); //webui_bundle_.addComponent("fnord/themes/midnight-blue.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-cockpit.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js"); webui_bundle_.addComponent( "fnordmetric/fnordmetric-embed-query-popup.html"); } void AdminUI::handleHTTPRequest( http::HTTPRequest* request, http::HTTPResponse* response) { fnord::URI uri(request->uri()); auto path = uri.path(); if (path == "/") { response->setStatus(http::kStatusFound); response->addHeader("Content-Type", "text/html; charset=utf-8"); response->addHeader("Location", path_prefix_); return; } if (path == "/fontawesome.woff") { request->setURI( StringUtil::format( "$0/__components__/fnord/3rdparty/fontawesome.woff", path_prefix_)); } webui_mount_.handleHTTPRequest(request, response); } } <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <fnord-base/uri.h> #include <fnordmetric/environment.h> #include <fnordmetric/adminui.h> namespace fnordmetric { AdminUI::AdminUI( std::string path_prefix /* = "/admin" */) : path_prefix_(path_prefix), webui_bundle_("FnordMetric"), webui_mount_(&webui_bundle_, path_prefix) { webui_bundle_.addComponent("fnord/3rdparty/codemirror.js"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css"); webui_bundle_.addComponent("fnord/3rdparty/reset.css"); webui_bundle_.addComponent("fnord/components/fn-table.css"); webui_bundle_.addComponent("fnord/components/fn-button.css"); webui_bundle_.addComponent("fnord/components/fn-modal.css"); webui_bundle_.addComponent("fnord/components/fn-tabbar.css"); webui_bundle_.addComponent("fnord/components/fn-message.css"); webui_bundle_.addComponent("fnord/components/fn-tooltip.css"); webui_bundle_.addComponent("fnord/components/fn-dropdown.css"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/components/fn-input.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/fnord.js"); webui_bundle_.addComponent("fnord/date_util.js"); webui_bundle_.addComponent("fnord/components/fn-appbar.html"); webui_bundle_.addComponent("fnord/components/fn-button.html"); webui_bundle_.addComponent("fnord/components/fn-button-group.html"); webui_bundle_.addComponent("fnord/components/fn-icon.html"); webui_bundle_.addComponent("fnord/components/fn-input.html"); webui_bundle_.addComponent("fnord/components/fn-loader.html"); webui_bundle_.addComponent("fnord/components/fn-menu.html"); webui_bundle_.addComponent("fnord/components/fn-search.html"); webui_bundle_.addComponent("fnord/components/fn-table.html"); webui_bundle_.addComponent("fnord/components/fn-splitpane.html"); webui_bundle_.addComponent("fnord/components/fn-codeeditor.html"); webui_bundle_.addComponent("fnord/components/fn-dropdown.html"); webui_bundle_.addComponent("fnord/components/fn-datepicker.html"); webui_bundle_.addComponent("fnord/components/fn-timeinput.html"); webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html"); webui_bundle_.addComponent("fnord/components/fn-tabbar.html"); webui_bundle_.addComponent("fnord/components/fn-modal.html"); webui_bundle_.addComponent("fnord/components/fn-pager.html"); webui_bundle_.addComponent("fnord/components/fn-tooltip.html"); webui_bundle_.addComponent("fnord/components/fn-flexbox.html"); webui_bundle_.addComponent("fnord/components/fn-checkbox.html"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.html"); webui_bundle_.addComponent("fnord/components/fn-calendar.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-list.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-preview.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-search.html"); webui_bundle_.addComponent("fnord-metricdb/metric-control.html"); webui_bundle_.addComponent("fnord-metricdb/fn-metric-explorer.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html"); //webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-midnightblue.css"); //webui_bundle_.addComponent("fnord/themes/midnight-blue.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-cockpit.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js"); webui_bundle_.addComponent( "fnordmetric/fnordmetric-embed-query-popup.html"); } void AdminUI::handleHTTPRequest( http::HTTPRequest* request, http::HTTPResponse* response) { fnord::URI uri(request->uri()); auto path = uri.path(); if (path == "/") { response->setStatus(http::kStatusFound); response->addHeader("Content-Type", "text/html; charset=utf-8"); response->addHeader("Location", path_prefix_); return; } if (path == "/fontawesome.woff") { request->setURI( StringUtil::format( "$0/__components__/fnord/3rdparty/fontawesome.woff", path_prefix_)); } webui_mount_.handleHTTPRequest(request, response); } } <commit_msg>render search view in metric-explorer-list<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <fnord-base/uri.h> #include <fnordmetric/environment.h> #include <fnordmetric/adminui.h> namespace fnordmetric { AdminUI::AdminUI( std::string path_prefix /* = "/admin" */) : path_prefix_(path_prefix), webui_bundle_("FnordMetric"), webui_mount_(&webui_bundle_, path_prefix) { webui_bundle_.addComponent("fnord/3rdparty/codemirror.js"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css"); webui_bundle_.addComponent("fnord/3rdparty/reset.css"); webui_bundle_.addComponent("fnord/components/fn-table.css"); webui_bundle_.addComponent("fnord/components/fn-button.css"); webui_bundle_.addComponent("fnord/components/fn-modal.css"); webui_bundle_.addComponent("fnord/components/fn-tabbar.css"); webui_bundle_.addComponent("fnord/components/fn-message.css"); webui_bundle_.addComponent("fnord/components/fn-tooltip.css"); webui_bundle_.addComponent("fnord/components/fn-dropdown.css"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/components/fn-input.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/fnord.js"); webui_bundle_.addComponent("fnord/date_util.js"); webui_bundle_.addComponent("fnord/components/fn-appbar.html"); webui_bundle_.addComponent("fnord/components/fn-button.html"); webui_bundle_.addComponent("fnord/components/fn-button-group.html"); webui_bundle_.addComponent("fnord/components/fn-icon.html"); webui_bundle_.addComponent("fnord/components/fn-input.html"); webui_bundle_.addComponent("fnord/components/fn-loader.html"); webui_bundle_.addComponent("fnord/components/fn-menu.html"); webui_bundle_.addComponent("fnord/components/fn-search.html"); webui_bundle_.addComponent("fnord/components/fn-table.html"); webui_bundle_.addComponent("fnord/components/fn-splitpane.html"); webui_bundle_.addComponent("fnord/components/fn-codeeditor.html"); webui_bundle_.addComponent("fnord/components/fn-dropdown.html"); webui_bundle_.addComponent("fnord/components/fn-datepicker.html"); webui_bundle_.addComponent("fnord/components/fn-timeinput.html"); webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html"); webui_bundle_.addComponent("fnord/components/fn-tabbar.html"); webui_bundle_.addComponent("fnord/components/fn-modal.html"); webui_bundle_.addComponent("fnord/components/fn-pager.html"); webui_bundle_.addComponent("fnord/components/fn-tooltip.html"); webui_bundle_.addComponent("fnord/components/fn-flexbox.html"); webui_bundle_.addComponent("fnord/components/fn-checkbox.html"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.html"); webui_bundle_.addComponent("fnord/components/fn-calendar.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-list.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-preview.html"); webui_bundle_.addComponent("fnord-metricdb/metric-control.html"); webui_bundle_.addComponent("fnord-metricdb/fn-metric-explorer.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html"); //webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-midnightblue.css"); //webui_bundle_.addComponent("fnord/themes/midnight-blue.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-cockpit.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js"); webui_bundle_.addComponent( "fnordmetric/fnordmetric-embed-query-popup.html"); } void AdminUI::handleHTTPRequest( http::HTTPRequest* request, http::HTTPResponse* response) { fnord::URI uri(request->uri()); auto path = uri.path(); if (path == "/") { response->setStatus(http::kStatusFound); response->addHeader("Content-Type", "text/html; charset=utf-8"); response->addHeader("Location", path_prefix_); return; } if (path == "/fontawesome.woff") { request->setURI( StringUtil::format( "$0/__components__/fnord/3rdparty/fontawesome.woff", path_prefix_)); } webui_mount_.handleHTTPRequest(request, response); } } <|endoftext|>
<commit_before>/* Efficient left and right language model state for sentence fragments. * Intended usage: * Store ChartState with every chart entry. * To do a rule application: * 1. Make a ChartState object for your new entry. * 2. Construct RuleScore. * 3. Going from left to right, call Terminal or NonTerminal. * For terminals, just pass the vocab id. * For non-terminals, pass that non-terminal's ChartState. * If your decoder expects scores inclusive of subtree scores (i.e. you * label entries with the highest-scoring path), pass the non-terminal's * score as prob. * If your decoder expects relative scores and will walk the chart later, * pass prob = 0.0. * In other words, the only effect of prob is that it gets added to the * returned log probability. * 4. Call Finish. It returns the log probability. * * There's a couple more details: * Do not pass <s> to Terminal as it is formally not a word in the sentence, * only context. Instead, call BeginSentence. If called, it should be the * first call after RuleScore is constructed (since <s> is always the * leftmost). * * If the leftmost RHS is a non-terminal, it's faster to call BeginNonTerminal. * * Hashing and sorting comparison operators are provided. All state objects * are POD. If you intend to use memcmp on raw state objects, you must call * ZeroRemaining first, as the value of array entries beyond length is * otherwise undefined. * * Usage is of course not limited to chart decoding. Anything that generates * sentence fragments missing left context could benefit. For example, a * phrase-based decoder could pre-score phrases, storing ChartState with each * phrase, even if hypotheses are generated left-to-right. */ #ifndef LM_LEFT__ #define LM_LEFT__ #include "lm/max_order.hh" #include "lm/model.hh" #include "lm/return.hh" #include "util/murmur_hash.hh" #include <algorithm> namespace lm { namespace ngram { struct Left { bool operator==(const Left &other) const { return (length == other.length) && pointers[length - 1] == other.pointers[length - 1]; } int Compare(const Left &other) const { if (length != other.length) return length < other.length ? -1 : 1; if (pointers[length - 1] > other.pointers[length - 1]) return 1; if (pointers[length - 1] < other.pointers[length - 1]) return -1; return 0; } bool operator<(const Left &other) const { if (length != other.length) return length < other.length; return pointers[length - 1] < other.pointers[length - 1]; } void ZeroRemaining() { for (uint64_t * i = pointers + length; i < pointers + kMaxOrder - 1; ++i) *i = 0; } unsigned char length; uint64_t pointers[kMaxOrder - 1]; }; inline size_t hash_value(const Left &left) { return util::MurmurHashNative(&left.length, 1, left.pointers[left.length - 1]); } struct ChartState { bool operator==(const ChartState &other) { return (left == other.left) && (right == other.right) && (full == other.full); } int Compare(const ChartState &other) const { int lres = left.Compare(other.left); if (lres) return lres; int rres = right.Compare(other.right); if (rres) return rres; return (int)full - (int)other.full; } bool operator<(const ChartState &other) const { return Compare(other) == -1; } void ZeroRemaining() { left.ZeroRemaining(); right.ZeroRemaining(); } Left left; bool full; State right; }; inline size_t hash_value(const ChartState &state) { size_t hashes[2]; hashes[0] = hash_value(state.left); hashes[1] = hash_value(state.right); return util::MurmurHashNative(hashes, sizeof(size_t), state.full); } template <class M> class RuleScore { public: explicit RuleScore(const M &model, ChartState &out) : model_(model), out_(out), left_done_(false), prob_(0.0) { out.left.length = 0; out.right.length = 0; } void BeginSentence() { out_.right = model_.BeginSentenceState(); // out_.left is empty. left_done_ = true; } void Terminal(WordIndex word) { State copy(out_.right); FullScoreReturn ret(model_.FullScore(copy, word, out_.right)); prob_ += ret.prob; if (left_done_) return; if (ret.independent_left) { left_done_ = true; return; } out_.left.pointers[out_.left.length++] = ret.extend_left; if (out_.right.length != copy.length + 1) left_done_ = true; } // Faster version of NonTerminal for the case where the rule begins with a non-terminal. void BeginNonTerminal(const ChartState &in, float prob) { prob_ = prob; out_ = in; left_done_ = in.full; } void NonTerminal(const ChartState &in, float prob) { prob_ += prob; if (!in.left.length) { if (in.full) { for (const float *i = out_.right.backoff; i < out_.right.backoff + out_.right.length; ++i) prob_ += *i; left_done_ = true; out_.right = in.right; } return; } if (!out_.right.length) { out_.right = in.right; if (left_done_) return; if (out_.left.length) { left_done_ = true; } else { out_.left = in.left; left_done_ = in.full; } return; } float backoffs[kMaxOrder - 1], backoffs2[kMaxOrder - 1]; float *back = backoffs, *back2 = backoffs2; unsigned char next_use; // First word ProcessRet(model_.ExtendLeft(out_.right.words, out_.right.words + out_.right.length, out_.right.backoff, in.left.pointers[0], 1, back, next_use)); if (!next_use) { left_done_ = true; out_.right = in.right; return; } // Words after the first, so extending a bigram to begin with unsigned char extend_length = 2; for (const uint64_t *i = in.left.pointers + 1; i < in.left.pointers + in.left.length; ++i, ++extend_length) { ProcessRet(model_.ExtendLeft(out_.right.words, out_.right.words + next_use, back, *i, extend_length, back2, next_use)); if (!next_use) { left_done_ = true; out_.right = in.right; return; } std::swap(back, back2); } if (in.full) { for (const float *i = back; i != back + next_use; ++i) prob_ += *i; left_done_ = true; out_.right = in.right; return; } // Right state was minimized, so it's already independent of the new words to the left. if (in.right.length < in.left.length) { out_.right = in.right; return; } // Shift exisiting words down. for (WordIndex *i = out_.right.words + next_use - 1; i >= out_.right.words; --i) { *(i + in.right.length) = *i; } // Add words from in.right. std::copy(in.right.words, in.right.words + in.right.length, out_.right.words); // Assemble backoff composed on the existing state's backoff followed by the new state's backoff. std::copy(in.right.backoff, in.right.backoff + in.right.length, out_.right.backoff); std::copy(back, back + next_use, out_.right.backoff + in.right.length); out_.right.length = in.right.length + next_use; } float Finish() { // A N-1-gram might extend left and right but we should still set full to true because it's an N-1-gram. out_.full = left_done_ || (out_.left.length == model_.Order() - 1); return prob_; } private: void ProcessRet(const FullScoreReturn &ret) { prob_ += ret.prob; if (left_done_) return; if (ret.independent_left) { left_done_ = true; return; } out_.left.pointers[out_.left.length++] = ret.extend_left; } const M &model_; ChartState &out_; bool left_done_; float prob_; }; } // namespace ngram } // namespace lm #endif // LM_LEFT__ <commit_msg>Corner case left state was not being fully minimized<commit_after>/* Efficient left and right language model state for sentence fragments. * Intended usage: * Store ChartState with every chart entry. * To do a rule application: * 1. Make a ChartState object for your new entry. * 2. Construct RuleScore. * 3. Going from left to right, call Terminal or NonTerminal. * For terminals, just pass the vocab id. * For non-terminals, pass that non-terminal's ChartState. * If your decoder expects scores inclusive of subtree scores (i.e. you * label entries with the highest-scoring path), pass the non-terminal's * score as prob. * If your decoder expects relative scores and will walk the chart later, * pass prob = 0.0. * In other words, the only effect of prob is that it gets added to the * returned log probability. * 4. Call Finish. It returns the log probability. * * There's a couple more details: * Do not pass <s> to Terminal as it is formally not a word in the sentence, * only context. Instead, call BeginSentence. If called, it should be the * first call after RuleScore is constructed (since <s> is always the * leftmost). * * If the leftmost RHS is a non-terminal, it's faster to call BeginNonTerminal. * * Hashing and sorting comparison operators are provided. All state objects * are POD. If you intend to use memcmp on raw state objects, you must call * ZeroRemaining first, as the value of array entries beyond length is * otherwise undefined. * * Usage is of course not limited to chart decoding. Anything that generates * sentence fragments missing left context could benefit. For example, a * phrase-based decoder could pre-score phrases, storing ChartState with each * phrase, even if hypotheses are generated left-to-right. */ #ifndef LM_LEFT__ #define LM_LEFT__ #include "lm/max_order.hh" #include "lm/model.hh" #include "lm/return.hh" #include "util/murmur_hash.hh" #include <algorithm> namespace lm { namespace ngram { struct Left { bool operator==(const Left &other) const { return (length == other.length) && pointers[length - 1] == other.pointers[length - 1]; } int Compare(const Left &other) const { if (length != other.length) return length < other.length ? -1 : 1; if (pointers[length - 1] > other.pointers[length - 1]) return 1; if (pointers[length - 1] < other.pointers[length - 1]) return -1; return 0; } bool operator<(const Left &other) const { if (length != other.length) return length < other.length; return pointers[length - 1] < other.pointers[length - 1]; } void ZeroRemaining() { for (uint64_t * i = pointers + length; i < pointers + kMaxOrder - 1; ++i) *i = 0; } unsigned char length; uint64_t pointers[kMaxOrder - 1]; }; inline size_t hash_value(const Left &left) { return util::MurmurHashNative(&left.length, 1, left.pointers[left.length - 1]); } struct ChartState { bool operator==(const ChartState &other) { return (left == other.left) && (right == other.right) && (full == other.full); } int Compare(const ChartState &other) const { int lres = left.Compare(other.left); if (lres) return lres; int rres = right.Compare(other.right); if (rres) return rres; return (int)full - (int)other.full; } bool operator<(const ChartState &other) const { return Compare(other) == -1; } void ZeroRemaining() { left.ZeroRemaining(); right.ZeroRemaining(); } Left left; bool full; State right; }; inline size_t hash_value(const ChartState &state) { size_t hashes[2]; hashes[0] = hash_value(state.left); hashes[1] = hash_value(state.right); return util::MurmurHashNative(hashes, sizeof(size_t), state.full); } template <class M> class RuleScore { public: explicit RuleScore(const M &model, ChartState &out) : model_(model), out_(out), left_done_(false), prob_(0.0) { out.left.length = 0; out.right.length = 0; } void BeginSentence() { out_.right = model_.BeginSentenceState(); // out_.left is empty. left_done_ = true; } void Terminal(WordIndex word) { State copy(out_.right); FullScoreReturn ret(model_.FullScore(copy, word, out_.right)); prob_ += ret.prob; if (left_done_) return; if (ret.independent_left) { left_done_ = true; return; } out_.left.pointers[out_.left.length++] = ret.extend_left; if (out_.right.length != copy.length + 1) left_done_ = true; } // Faster version of NonTerminal for the case where the rule begins with a non-terminal. void BeginNonTerminal(const ChartState &in, float prob) { prob_ = prob; out_ = in; left_done_ = in.full; } void NonTerminal(const ChartState &in, float prob) { prob_ += prob; if (!in.left.length) { if (in.full) { for (const float *i = out_.right.backoff; i < out_.right.backoff + out_.right.length; ++i) prob_ += *i; left_done_ = true; out_.right = in.right; } return; } if (!out_.right.length) { out_.right = in.right; if (left_done_) return; if (out_.left.length) { left_done_ = true; } else { out_.left = in.left; left_done_ = in.full; } return; } float backoffs[kMaxOrder - 1], backoffs2[kMaxOrder - 1]; float *back = backoffs, *back2 = backoffs2; unsigned char next_use = out_.right.length; // First word if (ExtendLeft(in, next_use, 1, out_.right.backoff, back)) return; // Words after the first, so extending a bigram to begin with for (unsigned char extend_length = 2; extend_length <= in.left.length; ++extend_length) { if (ExtendLeft(in, next_use, extend_length, back, back2)) return; std::swap(back, back2); } if (in.full) { for (const float *i = back; i != back + next_use; ++i) prob_ += *i; left_done_ = true; out_.right = in.right; return; } // Right state was minimized, so it's already independent of the new words to the left. if (in.right.length < in.left.length) { out_.right = in.right; return; } // Shift exisiting words down. for (WordIndex *i = out_.right.words + next_use - 1; i >= out_.right.words; --i) { *(i + in.right.length) = *i; } // Add words from in.right. std::copy(in.right.words, in.right.words + in.right.length, out_.right.words); // Assemble backoff composed on the existing state's backoff followed by the new state's backoff. std::copy(in.right.backoff, in.right.backoff + in.right.length, out_.right.backoff); std::copy(back, back + next_use, out_.right.backoff + in.right.length); out_.right.length = in.right.length + next_use; } float Finish() { // A N-1-gram might extend left and right but we should still set full to true because it's an N-1-gram. out_.full = left_done_ || (out_.left.length == model_.Order() - 1); return prob_; } private: bool ExtendLeft(const ChartState &in, unsigned char &next_use, unsigned char extend_length, const float *back_in, float *back_out) { ProcessRet(model_.ExtendLeft( out_.right.words, out_.right.words + next_use, // Words to extend into back_in, // Backoffs to use in.left.pointers[extend_length - 1], extend_length, // Words to be extended back_out, // Backoffs for the next score next_use)); // Length of n-gram to use in next scoring. if (next_use != out_.right.length) { left_done_ = true; if (!next_use) { out_.right = in.right; // Early exit. return true; } } // Continue scoring. return false; } void ProcessRet(const FullScoreReturn &ret) { prob_ += ret.prob; if (left_done_) return; if (ret.independent_left) { left_done_ = true; return; } out_.left.pointers[out_.left.length++] = ret.extend_left; } const M &model_; ChartState &out_; bool left_done_; float prob_; }; } // namespace ngram } // namespace lm #endif // LM_LEFT__ <|endoftext|>
<commit_before>#include "config.hpp" #include <sys/types.h> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <libconfig.h++> #ifdef _WIN32 #include <shlobj.h> #include <windows.h> #include <tchar.h> // Use explicitly wide char functions and compile for unicode. tstring home_directory() { tchar app_data_path[MAX_PATH]; auto result = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, app_data_path); return tstring(SUCCEEDED(result) ? app_data_path : L""); } tstring sx_config_path() { tchar environment_buffer[MAX_PATH]; return tstring(GetEnvironmentVariableW(L"SX_CFG", environment_buffer, MAX_PATH) == TRUE ? environment_buffer : L""); } #else #include <unistd.h> #include <pwd.h> // This is ANSI/MBCS if compiled on Windows but is always Unicode on Linux, // so we can safely return it as tstring when excluded from Windows. /* tstring home_directory() { const char* home_path = getenv("HOME"); return std::string(home_path == nullptr ? getpwuid(getuid())->pw_dir : home_path); } tstring sx_config_path() { const char* config_path = getenv("SX_CFG"); return std::string(config_path == nullptr ? "" : config_path); } */ using boost::filesystem::path; path home_directory() { const char* home_path = getenv("HOME"); if (!home_path) { passwd* pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; return path(homedir); } return path(home_path); } #endif template <typename T> void get_value(const libconfig::Setting& root, config_map_type& config_map, const std::string& key_name, const T& fallback_value) { T value; // libconfig is ANSI/MBCS on Windows - no Unicode support. // This reads ANSI/MBCS values from XML. If they are UTF-8 (and above the // ASCII band) the values will be misinterpreted upon use. config_map[key_name] = (root.lookupValue(key_name, value)) ? boost::lexical_cast<std::string>(value) : boost::lexical_cast<std::string>(fallback_value); } void set_config_path(libconfig::Config& configuration, const char* config_path) { // Ignore error if unable to read config file. try { // libconfig is ANSI/MBCS on Windows - no Unicode support. // This translates the path from Unicode to a "generic" path in // ANSI/MBCS, which can result in failures. configuration.readFile(config_path); } catch (const libconfig::FileIOException&) {} catch (const libconfig::ParseException&) {} } void load_config(config_map_type& config) { libconfig::Config configuration; #ifdef _WIN32 tstring environment_path = sx_config_path(); tpath config_path = environment_path.empty() ? tpath(home_directory()) / L".sx.cfg" : tpath(environment_path); set_config_path(configuration, config_path.generic_string().c_str()); #else path conf_path = home_directory() / ".sx.cfg"; // Check for env variable config to override default path. char* env_path = getenv("SX_CFG"); if (env_path) conf_path = env_path; set_config_path(configuration, conf_path.native().c_str()); #endif // Read off values. const libconfig::Setting& root = configuration.getRoot(); get_value<std::string>(root, config, "service", "tcp://37.139.11.99:9091"); get_value<std::string>(root, config, "client-certificate", ".sx.cert"); get_value<std::string>(root, config, "server-public-key", ""); } <commit_msg>fix conf loading for linux.<commit_after>#include "config.hpp" #include <sys/types.h> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <libconfig.h++> #ifdef _WIN32 #include <shlobj.h> #include <windows.h> #include <tchar.h> // Use explicitly wide char functions and compile for unicode. tstring home_directory() { tchar app_data_path[MAX_PATH]; auto result = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, app_data_path); return tstring(SUCCEEDED(result) ? app_data_path : L""); } tstring sx_config_path() { tchar environment_buffer[MAX_PATH]; return tstring(GetEnvironmentVariableW(L"SX_CFG", environment_buffer, MAX_PATH) == TRUE ? environment_buffer : L""); } #else #include <unistd.h> #include <pwd.h> // This is ANSI/MBCS if compiled on Windows but is always Unicode on Linux, // so we can safely return it as tstring when excluded from Windows. /* tstring home_directory() { const char* home_path = getenv("HOME"); return std::string(home_path == nullptr ? getpwuid(getuid())->pw_dir : home_path); } tstring sx_config_path() { const char* config_path = getenv("SX_CFG"); return std::string(config_path == nullptr ? "" : config_path); } */ using boost::filesystem::path; path home_directory() { const char* home_path = getenv("HOME"); if (!home_path) { passwd* pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; return path(homedir); } return path(home_path); } */ using boost::filesystem::path; path home_directory() { const char* home_path = getenv("HOME"); if (!home_path) { passwd* pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; return path(homedir); } return path(home_path); } #endif template <typename T> void get_value(const libconfig::Setting& root, config_map_type& config_map, const std::string& key_name, const T& fallback_value) { T value; // libconfig is ANSI/MBCS on Windows - no Unicode support. // This reads ANSI/MBCS values from XML. If they are UTF-8 (and above the // ASCII band) the values will be misinterpreted upon use. config_map[key_name] = (root.lookupValue(key_name, value)) ? boost::lexical_cast<std::string>(value) : boost::lexical_cast<std::string>(fallback_value); } void set_config_path(libconfig::Config& configuration, const char* config_path) { // Ignore error if unable to read config file. try { // libconfig is ANSI/MBCS on Windows - no Unicode support. // This translates the path from Unicode to a "generic" path in // ANSI/MBCS, which can result in failures. configuration.readFile(config_path); } catch (const libconfig::FileIOException&) {} catch (const libconfig::ParseException&) {} } void load_config(config_map_type& config) { libconfig::Config configuration; #ifdef _WIN32 tstring environment_path = sx_config_path(); tpath config_path = environment_path.empty() ? tpath(home_directory()) / L".sx.cfg" : tpath(environment_path); set_config_path(configuration, config_path.generic_string().c_str()); #else path conf_path = home_directory() / ".sx.cfg"; // Check for env variable config to override default path. char* env_path = getenv("SX_CFG"); if (env_path) conf_path = env_path; set_config_path(configuration, conf_path.native().c_str()); #endif // Read off values. const libconfig::Setting& root = configuration.getRoot(); get_value<std::string>(root, config, "service", "tcp://37.139.11.99:9091"); get_value<std::string>(root, config, "client-certificate", ".sx.cert"); get_value<std::string>(root, config, "server-public-key", ""); } <|endoftext|>
<commit_before>#include "input-manager.h" #include "configuration.h" #include "object/object.h" #include "util/joystick.h" #include "globals.h" #include <stdlib.h> #include <vector> using namespace std; InputManager * InputManager::manager = 0; InputManager::InputManager(){ manager = this; joystick = Joystick::create(); } InputManager::~InputManager(){ } vector<PaintownInput> InputManager::getInput(const Configuration & configuration, const int facing){ if (manager == 0){ Global::debug(0) << "*BUG* Input manager not set up" << endl; exit(0); } return manager->_getInput(configuration, facing); } static vector<PaintownInput> convertJoystick(JoystickInput input, const int facing){ vector<PaintownInput> all; if (input.up){ all.push_back(Up); } if (input.right){ if (facing == Object::FACING_RIGHT){ all.push_back(Forward); } else { all.push_back(Back); } } if (input.left){ if (facing == Object::FACING_RIGHT){ all.push_back(Back); } else { all.push_back(Forward); } } if (input.down){ all.push_back(Down); } if (input.button1){ all.push_back(Attack1); } if (input.button2){ all.push_back(Attack2); } if (input.button3){ all.push_back(Attack3); } if (input.button4){ all.push_back(Jump); } return all; } vector<PaintownInput> InputManager::_getInput(const Configuration & configuration, const int facing){ /* polling should probably go somewhere else */ keyboard.poll(); if (joystick != NULL){ joystick->poll(); } vector<int> all_keys; keyboard.readKeys( all_keys ); vector<PaintownInput> real_input = Input::convertKeyboard(configuration, facing, all_keys); if (joystick != NULL){ vector<PaintownInput> joystick_keys = convertJoystick(joystick->readAll(), facing); for (vector<PaintownInput>::iterator it = joystick_keys.begin(); it != joystick_keys.end(); it++){ Global::debug(2) << "Read joystick key " << *it << endl; } all_keys.insert(all_keys.begin(), joystick_keys.begin(), joystick_keys.end()); } return real_input; } <commit_msg>fix joystick input<commit_after>#include "input-manager.h" #include "configuration.h" #include "object/object.h" #include "util/joystick.h" #include "globals.h" #include <stdlib.h> #include <vector> using namespace std; InputManager * InputManager::manager = 0; InputManager::InputManager(){ manager = this; joystick = Joystick::create(); } InputManager::~InputManager(){ } vector<PaintownInput> InputManager::getInput(const Configuration & configuration, const int facing){ if (manager == 0){ Global::debug(0) << "*BUG* Input manager not set up" << endl; exit(0); } return manager->_getInput(configuration, facing); } static vector<PaintownInput> convertJoystick(JoystickInput input, const int facing){ vector<PaintownInput> all; if (input.up){ all.push_back(Up); } if (input.right){ if (facing == Object::FACING_RIGHT){ all.push_back(Forward); } else { all.push_back(Back); } } if (input.left){ if (facing == Object::FACING_RIGHT){ all.push_back(Back); } else { all.push_back(Forward); } } if (input.down){ all.push_back(Down); } if (input.button1){ all.push_back(Attack1); } if (input.button2){ all.push_back(Attack2); } if (input.button3){ all.push_back(Attack3); } if (input.button4){ all.push_back(Jump); } return all; } vector<PaintownInput> InputManager::_getInput(const Configuration & configuration, const int facing){ /* polling should probably go somewhere else */ keyboard.poll(); if (joystick != NULL){ joystick->poll(); } vector<int> all_keys; keyboard.readKeys( all_keys ); vector<PaintownInput> real_input = Input::convertKeyboard(configuration, facing, all_keys); if (joystick != NULL){ vector<PaintownInput> joystick_keys = convertJoystick(joystick->readAll(), facing); real_input.insert(real_input.begin(), joystick_keys.begin(), joystick_keys.end()); } return real_input; } <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // 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 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 // // Current versions can be found at www.libavg.de // #include "GLTexture.h" #include "../base/Exception.h" #include "../base/StringHelper.h" #include "../base/MathHelper.h" #include "../base/ObjectCounter.h" #include "GLContext.h" #include "TextureMover.h" #ifndef AVG_ENABLE_EGL #include "PBO.h" #endif #include "FBO.h" #include <string.h> #include <iostream> namespace avg { using namespace std; // We assign our own texture ids and never reuse them instead of using glGenTextures. // That works very well, except that other components (e.g. Ogre3d) with shared gl // contexts don't know anything about our ids and thus use the same ones. // Somewhat hackish solution: Assign ids starting with a very high id, so the id ranges // don't overlap. unsigned GLTexture::s_LastTexID = 10000000; GLTexture::GLTexture(const IntPoint& size, PixelFormat pf, bool bMipmap, int potBorderColor, unsigned wrapSMode, unsigned wrapTMode, bool bForcePOT) : m_Size(size), m_pf(pf), m_bMipmap(bMipmap), m_bDeleteTex(true), m_bIsDirty(true) { m_pGLContext = GLContext::getCurrent(); ObjectCounter::get()->incRef(&typeid(*this)); m_bUsePOT = m_pGLContext->usePOTTextures() || bForcePOT; if (m_pGLContext->isGLES() && bMipmap) { m_bUsePOT = true; } if (m_bUsePOT) { m_GLSize.x = nextpow2(m_Size.x); m_GLSize.y = nextpow2(m_Size.y); } else { m_GLSize = m_Size; } int maxTexSize = m_pGLContext->getMaxTexSize(); if (m_Size.x > maxTexSize || m_Size.y > maxTexSize) { throw Exception(AVG_ERR_VIDEO_GENERAL, "Texture too large (" + toString(m_Size) + "). Maximum supported by graphics card is " + toString(maxTexSize)); } if (getGLType(m_pf) == GL_FLOAT && !isFloatFormatSupported()) { throw Exception(AVG_ERR_UNSUPPORTED, "Float textures not supported by OpenGL configuration."); } s_LastTexID++; m_TexID = s_LastTexID; m_pGLContext->bindTexture(GL_TEXTURE0, m_TexID); if (bMipmap) { glproc::GenerateMipmap(GL_TEXTURE_2D); GLContext::checkError("GLTexture::generateMipmap()"); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } else { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode); glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, m_GLSize.y, 0, getGLFormat(m_pf), getGLType(m_pf), 0); GLContext::checkError("GLTexture: glTexImage2D()"); if (m_bUsePOT) { // Make sure the texture is transparent and black before loading stuff // into it to avoid garbage at the borders. // In the case of UV textures, we set the border color to 128... int TexMemNeeded = m_GLSize.x*m_GLSize.y*getBytesPerPixel(m_pf); char * pPixels = new char[TexMemNeeded]; memset(pPixels, potBorderColor, TexMemNeeded); glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, m_GLSize.y, 0, getGLFormat(m_pf), getGLType(m_pf), pPixels); GLContext::checkError("PBOTexture::createTexture: glTexImage2D()"); delete[] pPixels; } // dump(wrapSMode, wrapTMode); } GLTexture::GLTexture(unsigned glTexID, const IntPoint& size, PixelFormat pf, bool bMipmap, bool bDeleteTex) : m_Size(size), m_GLSize(size), m_pf(pf), m_bMipmap(bMipmap), m_bDeleteTex(bDeleteTex), m_bUsePOT(false), m_TexID(glTexID), m_bIsDirty(true) { m_pGLContext = GLContext::getCurrent(); ObjectCounter::get()->incRef(&typeid(*this)); } GLTexture::~GLTexture() { if (m_bDeleteTex) { glDeleteTextures(1, &m_TexID); GLContext::checkError("GLTexture: DeleteTextures()"); } ObjectCounter::get()->decRef(&typeid(*this)); } void GLTexture::activate(int textureUnit) { m_pGLContext->bindTexture(textureUnit, m_TexID); } void GLTexture::generateMipmaps() { if (m_bMipmap) { activate(); glproc::GenerateMipmap(GL_TEXTURE_2D); GLContext::checkError("GLTexture::generateMipmap()"); } } void GLTexture::setWrapMode(unsigned wrapSMode, unsigned wrapTMode) { activate(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode); } void GLTexture::enableStreaming() { m_pMover = TextureMover::create(m_Size, m_pf, GL_STREAM_DRAW); } BitmapPtr GLTexture::lockStreamingBmp() { AVG_ASSERT(m_pMover); return m_pMover->lock(); } void GLTexture::unlockStreamingBmp(bool bUpdated) { AVG_ASSERT(m_pMover); m_pMover->unlock(); if (bUpdated) { m_pMover->moveToTexture(*this); m_bIsDirty = true; } } void GLTexture::moveBmpToTexture(BitmapPtr pBmp) { TextureMoverPtr pMover = TextureMover::create(m_Size, m_pf, GL_DYNAMIC_DRAW); pMover->moveBmpToTexture(pBmp, *this); m_bIsDirty = true; } BitmapPtr GLTexture::moveTextureToBmp(int mipmapLevel) { TextureMoverPtr pMover = TextureMover::create(m_GLSize, m_pf, GL_DYNAMIC_READ); return pMover->moveTextureToBmp(*this, mipmapLevel); } const IntPoint& GLTexture::getSize() const { return m_Size; } const IntPoint& GLTexture::getGLSize() const { return m_GLSize; } PixelFormat GLTexture::getPF() const { return m_pf; } unsigned GLTexture::getID() const { return m_TexID; } IntPoint GLTexture::getMipmapSize(int level) const { IntPoint size = m_Size; for (int i=0; i<level; ++i) { size.x = max(1, size.x >> 1); size.y = max(1, size.y >> 1); } return size; } bool GLTexture::isFloatFormatSupported() { return queryOGLExtension("GL_ARB_texture_float"); } int GLTexture::getGLFormat(PixelFormat pf) { switch (pf) { case I8: case I32F: return GL_LUMINANCE; case A8: return GL_ALPHA; case R8G8B8A8: case R8G8B8X8: return GL_RGBA; case B8G8R8A8: case B8G8R8X8: AVG_ASSERT(!GLContext::getMain()->isGLES()); return GL_BGRA; #ifndef AVG_ENABLE_EGL case R32G32B32A32F: return GL_BGRA; #endif case R8G8B8: case B5G6R5: return GL_RGB; default: AVG_ASSERT(false); return 0; } } int GLTexture::getGLType(PixelFormat pf) { switch (pf) { case I8: case A8: return GL_UNSIGNED_BYTE; case R8G8B8A8: case R8G8B8X8: case B8G8R8A8: case B8G8R8X8: #ifdef __APPLE__ return GL_UNSIGNED_INT_8_8_8_8_REV; #else return GL_UNSIGNED_BYTE; #endif case R32G32B32A32F: case I32F: return GL_FLOAT; case R8G8B8: return GL_UNSIGNED_BYTE; case B5G6R5: return GL_UNSIGNED_SHORT_5_6_5; default: AVG_ASSERT(false); return 0; } } int GLTexture::getGLInternalFormat() const { switch (m_pf) { case I8: return GL_LUMINANCE; case A8: return GL_ALPHA; case R8G8B8A8: case R8G8B8X8: return GL_RGBA; case B8G8R8A8: case B8G8R8X8: AVG_ASSERT(!GLContext::getMain()->isGLES()); return GL_RGBA; #ifndef AVG_ENABLE_EGL case R32G32B32A32F: return GL_RGBA32F_ARB; case I32F: return GL_LUMINANCE32F_ARB; #endif case R8G8B8: case B5G6R5: return GL_RGB; default: AVG_ASSERT(false); return 0; } } void GLTexture::setDirty() { m_bIsDirty = true; } bool GLTexture::isDirty() const { return m_bIsDirty; } void GLTexture::resetDirty() { m_bIsDirty = false; } const string wrapModeToStr(unsigned wrapMode) { string sWrapMode; switch (wrapMode) { case GL_CLAMP_TO_EDGE: sWrapMode = "CLAMP_TO_EDGE"; break; #ifndef AVG_ENABLE_EGL case GL_CLAMP: sWrapMode = "CLAMP"; break; case GL_CLAMP_TO_BORDER: sWrapMode = "CLAMP_TO_BORDER"; break; #endif case GL_REPEAT: sWrapMode = "REPEAT"; break; case GL_MIRRORED_REPEAT: sWrapMode = "MIRRORED_REPEAT"; break; default: sWrapMode = "unknown"; } return sWrapMode; } void GLTexture::dump(unsigned wrapSMode, unsigned wrapTMode) const { cerr << "GLTexture" << endl; cerr << "m_Size: " << m_Size << endl; cerr << "m_GLSize: " << m_GLSize << endl; cerr << "m_pf: " << m_pf << endl; cerr << "m_bMipmap: " << m_bMipmap << endl; if (wrapSMode != (unsigned)-1) { cerr << "Wrap modes: " << \ wrapModeToStr(wrapSMode) << ", " << wrapModeToStr(wrapTMode) << endl; } } } <commit_msg>Better generateMipmap error reporting.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // 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 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 // // Current versions can be found at www.libavg.de // #include "GLTexture.h" #include "../base/Exception.h" #include "../base/StringHelper.h" #include "../base/MathHelper.h" #include "../base/ObjectCounter.h" #include "GLContext.h" #include "TextureMover.h" #ifndef AVG_ENABLE_EGL #include "PBO.h" #endif #include "FBO.h" #include <string.h> #include <iostream> namespace avg { using namespace std; // We assign our own texture ids and never reuse them instead of using glGenTextures. // That works very well, except that other components (e.g. Ogre3d) with shared gl // contexts don't know anything about our ids and thus use the same ones. // Somewhat hackish solution: Assign ids starting with a very high id, so the id ranges // don't overlap. unsigned GLTexture::s_LastTexID = 10000000; GLTexture::GLTexture(const IntPoint& size, PixelFormat pf, bool bMipmap, int potBorderColor, unsigned wrapSMode, unsigned wrapTMode, bool bForcePOT) : m_Size(size), m_pf(pf), m_bMipmap(bMipmap), m_bDeleteTex(true), m_bIsDirty(true) { m_pGLContext = GLContext::getCurrent(); ObjectCounter::get()->incRef(&typeid(*this)); m_bUsePOT = m_pGLContext->usePOTTextures() || bForcePOT; if (m_pGLContext->isGLES() && bMipmap) { m_bUsePOT = true; } if (m_bUsePOT) { m_GLSize.x = nextpow2(m_Size.x); m_GLSize.y = nextpow2(m_Size.y); } else { m_GLSize = m_Size; } int maxTexSize = m_pGLContext->getMaxTexSize(); if (m_Size.x > maxTexSize || m_Size.y > maxTexSize) { throw Exception(AVG_ERR_VIDEO_GENERAL, "Texture too large (" + toString(m_Size) + "). Maximum supported by graphics card is " + toString(maxTexSize)); } if (getGLType(m_pf) == GL_FLOAT && !isFloatFormatSupported()) { throw Exception(AVG_ERR_UNSUPPORTED, "Float textures not supported by OpenGL configuration."); } s_LastTexID++; m_TexID = s_LastTexID; m_pGLContext->bindTexture(GL_TEXTURE0, m_TexID); if (bMipmap) { glproc::GenerateMipmap(GL_TEXTURE_2D); GLContext::checkError("GLTexture::GLTexture generateMipmap()"); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } else { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode); glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, m_GLSize.y, 0, getGLFormat(m_pf), getGLType(m_pf), 0); GLContext::checkError("GLTexture::GLTexture glTexImage2D()"); if (m_bUsePOT) { // Make sure the texture is transparent and black before loading stuff // into it to avoid garbage at the borders. // In the case of UV textures, we set the border color to 128... int TexMemNeeded = m_GLSize.x*m_GLSize.y*getBytesPerPixel(m_pf); char * pPixels = new char[TexMemNeeded]; memset(pPixels, potBorderColor, TexMemNeeded); glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, m_GLSize.y, 0, getGLFormat(m_pf), getGLType(m_pf), pPixels); GLContext::checkError("PBOTexture::createTexture: glTexImage2D()"); delete[] pPixels; } // dump(wrapSMode, wrapTMode); } GLTexture::GLTexture(unsigned glTexID, const IntPoint& size, PixelFormat pf, bool bMipmap, bool bDeleteTex) : m_Size(size), m_GLSize(size), m_pf(pf), m_bMipmap(bMipmap), m_bDeleteTex(bDeleteTex), m_bUsePOT(false), m_TexID(glTexID), m_bIsDirty(true) { m_pGLContext = GLContext::getCurrent(); ObjectCounter::get()->incRef(&typeid(*this)); } GLTexture::~GLTexture() { if (m_bDeleteTex) { glDeleteTextures(1, &m_TexID); GLContext::checkError("GLTexture: DeleteTextures()"); } ObjectCounter::get()->decRef(&typeid(*this)); } void GLTexture::activate(int textureUnit) { m_pGLContext->bindTexture(textureUnit, m_TexID); } void GLTexture::generateMipmaps() { if (m_bMipmap) { activate(); glproc::GenerateMipmap(GL_TEXTURE_2D); GLContext::checkError("GLTexture::generateMipmap()"); } } void GLTexture::setWrapMode(unsigned wrapSMode, unsigned wrapTMode) { activate(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode); } void GLTexture::enableStreaming() { m_pMover = TextureMover::create(m_Size, m_pf, GL_STREAM_DRAW); } BitmapPtr GLTexture::lockStreamingBmp() { AVG_ASSERT(m_pMover); return m_pMover->lock(); } void GLTexture::unlockStreamingBmp(bool bUpdated) { AVG_ASSERT(m_pMover); m_pMover->unlock(); if (bUpdated) { m_pMover->moveToTexture(*this); m_bIsDirty = true; } } void GLTexture::moveBmpToTexture(BitmapPtr pBmp) { TextureMoverPtr pMover = TextureMover::create(m_Size, m_pf, GL_DYNAMIC_DRAW); pMover->moveBmpToTexture(pBmp, *this); m_bIsDirty = true; } BitmapPtr GLTexture::moveTextureToBmp(int mipmapLevel) { TextureMoverPtr pMover = TextureMover::create(m_GLSize, m_pf, GL_DYNAMIC_READ); return pMover->moveTextureToBmp(*this, mipmapLevel); } const IntPoint& GLTexture::getSize() const { return m_Size; } const IntPoint& GLTexture::getGLSize() const { return m_GLSize; } PixelFormat GLTexture::getPF() const { return m_pf; } unsigned GLTexture::getID() const { return m_TexID; } IntPoint GLTexture::getMipmapSize(int level) const { IntPoint size = m_Size; for (int i=0; i<level; ++i) { size.x = max(1, size.x >> 1); size.y = max(1, size.y >> 1); } return size; } bool GLTexture::isFloatFormatSupported() { return queryOGLExtension("GL_ARB_texture_float"); } int GLTexture::getGLFormat(PixelFormat pf) { switch (pf) { case I8: case I32F: return GL_LUMINANCE; case A8: return GL_ALPHA; case R8G8B8A8: case R8G8B8X8: return GL_RGBA; case B8G8R8A8: case B8G8R8X8: AVG_ASSERT(!GLContext::getMain()->isGLES()); return GL_BGRA; #ifndef AVG_ENABLE_EGL case R32G32B32A32F: return GL_BGRA; #endif case R8G8B8: case B5G6R5: return GL_RGB; default: AVG_ASSERT(false); return 0; } } int GLTexture::getGLType(PixelFormat pf) { switch (pf) { case I8: case A8: return GL_UNSIGNED_BYTE; case R8G8B8A8: case R8G8B8X8: case B8G8R8A8: case B8G8R8X8: #ifdef __APPLE__ return GL_UNSIGNED_INT_8_8_8_8_REV; #else return GL_UNSIGNED_BYTE; #endif case R32G32B32A32F: case I32F: return GL_FLOAT; case R8G8B8: return GL_UNSIGNED_BYTE; case B5G6R5: return GL_UNSIGNED_SHORT_5_6_5; default: AVG_ASSERT(false); return 0; } } int GLTexture::getGLInternalFormat() const { switch (m_pf) { case I8: return GL_LUMINANCE; case A8: return GL_ALPHA; case R8G8B8A8: case R8G8B8X8: return GL_RGBA; case B8G8R8A8: case B8G8R8X8: AVG_ASSERT(!GLContext::getMain()->isGLES()); return GL_RGBA; #ifndef AVG_ENABLE_EGL case R32G32B32A32F: return GL_RGBA32F_ARB; case I32F: return GL_LUMINANCE32F_ARB; #endif case R8G8B8: case B5G6R5: return GL_RGB; default: AVG_ASSERT(false); return 0; } } void GLTexture::setDirty() { m_bIsDirty = true; } bool GLTexture::isDirty() const { return m_bIsDirty; } void GLTexture::resetDirty() { m_bIsDirty = false; } const string wrapModeToStr(unsigned wrapMode) { string sWrapMode; switch (wrapMode) { case GL_CLAMP_TO_EDGE: sWrapMode = "CLAMP_TO_EDGE"; break; #ifndef AVG_ENABLE_EGL case GL_CLAMP: sWrapMode = "CLAMP"; break; case GL_CLAMP_TO_BORDER: sWrapMode = "CLAMP_TO_BORDER"; break; #endif case GL_REPEAT: sWrapMode = "REPEAT"; break; case GL_MIRRORED_REPEAT: sWrapMode = "MIRRORED_REPEAT"; break; default: sWrapMode = "unknown"; } return sWrapMode; } void GLTexture::dump(unsigned wrapSMode, unsigned wrapTMode) const { cerr << "GLTexture" << endl; cerr << "m_Size: " << m_Size << endl; cerr << "m_GLSize: " << m_GLSize << endl; cerr << "m_pf: " << m_pf << endl; cerr << "m_bMipmap: " << m_bMipmap << endl; if (wrapSMode != (unsigned)-1) { cerr << "Wrap modes: " << \ wrapModeToStr(wrapSMode) << ", " << wrapModeToStr(wrapTMode) << endl; } } } <|endoftext|>
<commit_before>// Copyright (c) 2013, 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 file in the root of the Project. #include <nix/util/util.hpp> #include <nix/hdf5/DataArrayHDF5.hpp> #include <nix/hdf5/DataSet.hpp> #include <nix/hdf5/DimensionHDF5.hpp> using namespace std; namespace nix { namespace hdf5 { DataArrayHDF5::DataArrayHDF5(const DataArrayHDF5 &data_array) : EntityWithSourcesHDF5(data_array.file(), data_array.block(), data_array.group(), data_array.id(), data_array.type(), data_array.name()), dimension_group(data_array.dimension_group) { } DataArrayHDF5::DataArrayHDF5(const File &file, const Block &block, const Group &group, const string &id, const string &type, const string &name) : DataArrayHDF5(file, block, group, id, type, name, util::getTime()) { } DataArrayHDF5::DataArrayHDF5(const File &file, const Block &block, const Group &group, const string &id, const string &type, const string &name, time_t time) : EntityWithSourcesHDF5(file, block, group, id, type, name, time) { dimension_group = this->group().openGroup("dimensions", true); } //-------------------------------------------------- // Element getters and setters //-------------------------------------------------- boost::optional<std::string> DataArrayHDF5::label() const { boost::optional<std::string> ret; string value; group().getAttr("label", value); ret = value; return ret; } void DataArrayHDF5::label(const string &label) { if(label.empty()) { throw EmptyString("label"); } else { group().setAttr("label", label); forceUpdatedAt(); } } void DataArrayHDF5::label(const none_t t) { if(group().hasAttr("label")) { group().removeAttr("label"); } forceUpdatedAt(); } boost::optional<std::string> DataArrayHDF5::unit() const { boost::optional<std::string> ret; string value; group().getAttr("unit", value); ret = value; return ret; } void DataArrayHDF5::unit(const string &unit) { if(unit.empty()) { throw EmptyString("unit"); } else { group().setAttr("unit", unit); forceUpdatedAt(); } } void DataArrayHDF5::unit(const none_t t) { if(group().hasAttr("unit")) { group().removeAttr("unit"); } forceUpdatedAt(); } // TODO use defaults boost::optional<double> DataArrayHDF5::expansionOrigin() const { boost::optional<double> ret; double expansion_origin; group().getAttr("expansion_origin", expansion_origin); ret = expansion_origin; return ret; } void DataArrayHDF5::expansionOrigin(double expansion_origin) { group().setAttr("expansion_origin", expansion_origin); forceUpdatedAt(); } void DataArrayHDF5::expansionOrigin(const none_t t) { if(group().hasAttr("expansionOrigin")) { group().removeAttr("expansionOrigin"); } forceUpdatedAt(); } // TODO use defaults vector<double> DataArrayHDF5::polynomCoefficients()const{ vector<double> polynom_coefficients; if (group().hasData("polynom_coefficients")) { DataSet ds = group().openData("polynom_coefficients"); ds.read(polynom_coefficients, true); } return polynom_coefficients; } void DataArrayHDF5::polynomCoefficients(vector<double> &coefficients) { DataSet ds; if (group().hasData("polynom_coefficients")) { ds = group().openData("polynom_coefficients"); ds.setExtent({coefficients.size()}); } else { ds = DataSet::create(group().h5Group(), "polynom_coefficients", coefficients); } ds.write(coefficients); forceUpdatedAt(); } void DataArrayHDF5::polynomCoefficients(const none_t t) { if(group().hasAttr("polynom_coefficients")) { group().removeAttr("polynom_coefficients"); } forceUpdatedAt(); } //-------------------------------------------------- // Methods concerning dimensions //-------------------------------------------------- size_t DataArrayHDF5::dimensionCount() const { return dimension_group.objectCount(); } Dimension DataArrayHDF5::getDimension(size_t id) const { string str_id = util::numToStr(id); if (dimension_group.hasGroup(str_id)) { Group dim_group = dimension_group.openGroup(str_id, false); string dim_type_name; dim_group.getAttr("dimension_type", dim_type_name); DimensionType dim_type = dimensionTypeFromStr(dim_type_name); Dimension dim; if (dim_type == DimensionType::Set ) { auto tmp = make_shared<SetDimensionHDF5>(dim_group, id); dim = SetDimension(tmp); } else if (dim_type == DimensionType::Range) { std::vector<double> ticks; dim_group.getData("ticks", ticks); auto tmp = make_shared<RangeDimensionHDF5>(dim_group, id, ticks); dim = RangeDimension(tmp); } else if (dim_type == DimensionType::Sample) { double samplingInterval; dim_group.getAttr("sampling_interval", samplingInterval); auto tmp = make_shared<SampledDimensionHDF5>(dim_group, id, samplingInterval); dim = SampledDimension(tmp); } else { throw runtime_error("Invalid dimension type"); } return dim; } else { return Dimension(); } } template<DimensionType dtype, typename T> Dimension DataArrayHDF5::_createDimension(size_t id, T var) { size_t dim_count = dimensionCount(); if (id > (dim_count + 1) || id <= 0) { // dim_count+1 since index starts at 1 runtime_error("Invalid dimension id: has to be 0 < id <= #(dimensions)+1"); } string str_id = util::numToStr(id); if (dimension_group.hasGroup(str_id)) { dimension_group.removeGroup(str_id); } Group dim_group = dimension_group.openGroup(str_id, true); Dimension dim; if (dtype == DimensionType::Range || dtype == DimensionType::Sample) { typedef typename std::conditional<dtype == DimensionType::Range, RangeDimensionHDF5, SampledDimensionHDF5>::type dimTypeHDF5; typedef typename std::conditional<dtype == DimensionType::Range, RangeDimension, SampledDimension>::type dimType; auto tmp = make_shared<dimTypeHDF5>(dim_group, id, var); dim = dimType(tmp); } else { throw runtime_error("Invalid dimension type"); } return dim; } template<> Dimension DataArrayHDF5::_createDimension<DimensionType::Set, none_t>(size_t id, none_t var) { size_t dim_count = dimensionCount(); if (id > (dim_count + 1) || id <= 0) { // dim_count+1 since index starts at 1 runtime_error("Invalid dimension id: has to be 0 < id <= #(dimensions)+1"); } string str_id = util::numToStr(id); if (dimension_group.hasGroup(str_id)) { dimension_group.removeGroup(str_id); } Group dim_group = dimension_group.openGroup(str_id, true); Dimension dim; // no dim-type check needed since method only called if type=DimensionType::Set auto tmp = make_shared<SetDimensionHDF5>(dim_group, id); dim = SetDimension(tmp); return dim; } Dimension DataArrayHDF5::createSetDimension(size_t id) { return _createDimension<DimensionType::Set>(id); } Dimension DataArrayHDF5::createRangeDimension(size_t id, std::vector<double> ticks) { return _createDimension<DimensionType::Range>(id, ticks); } Dimension DataArrayHDF5::createSampledDimension(size_t id, double samplingInterval) { return _createDimension<DimensionType::Sample>(id, samplingInterval); } bool DataArrayHDF5::deleteDimension(size_t id) { bool deleted = false; size_t dim_count = dimensionCount(); string str_id = util::numToStr(id); if (dimension_group.hasGroup(str_id)) { dimension_group.removeGroup(str_id); deleted = true; } if (deleted && id < dim_count) { for (size_t old_id = id + 1; old_id <= dim_count; old_id++) { string str_old_id = util::numToStr(old_id); string str_new_id = util::numToStr(old_id - 1); dimension_group.renameGroup(str_old_id, str_new_id); } } return deleted; } //-------------------------------------------------- // Other methods and functions //-------------------------------------------------- void DataArrayHDF5::swap(DataArrayHDF5 &other) { using std::swap; EntityWithSourcesHDF5::swap(other); swap(dimension_group, other.dimension_group); } DataArrayHDF5& DataArrayHDF5::operator=(const DataArrayHDF5 &other) { if (*this != other) { DataArrayHDF5 tmp(other); swap(tmp); } return *this; } DataArrayHDF5::~DataArrayHDF5() {} void DataArrayHDF5::createData(DataType dtype, const NDSize &size) { if (group().hasData("data")) { throw new std::runtime_error("DataArray alread exists"); //TODO: FIXME, better exception } DataSet::create(group().h5Group(), "data", dtype, size); DataSet ds = group().openData("data"); } bool DataArrayHDF5::hasData() const { return group().hasData("data"); } void DataArrayHDF5::write(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) { DataSet ds; if (!group().hasData("data")) { ds = DataSet::create(group().h5Group(), "data", dtype, count); } else { ds = group().openData("data"); } if (offset.size()) { Selection fileSel = ds.createSelection(); fileSel.select(count, offset); Selection memSel(DataSpace::create(count, false)); ds.write(dtype, data, fileSel, memSel); } else { ds.write(dtype, count, data); } } void DataArrayHDF5::read(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const { if (!group().hasData("data")) { return; } DataSet ds = group().openData("data"); if (offset.size()) { Selection fileSel = ds.createSelection(); fileSel.select(count, offset); Selection memSel(DataSpace::create(count, false)); ds.read(dtype, data, fileSel, memSel); } else { ds.read(dtype, count, data); } } NDSize DataArrayHDF5::dataExtent(void) const { if (!group().hasData("data")) { return NDSize{}; } DataSet ds = group().openData("data"); return ds.size(); } void DataArrayHDF5::dataExtent(const NDSize &extent) { if (!group().hasData("data")) { throw runtime_error("Data field not found in DataArray!"); } DataSet ds = group().openData("data"); ds.setExtent(extent); } DataType DataArrayHDF5::dataType(void) const { if (!group().hasData("data")) { //we could also throw an exception but I think returning //Nothing here is better (ck) - agreed (bm) return DataType::Nothing; } DataSet ds = group().openData("data"); return ds.dataType(); } } // namespace hdf5 } // namespace nix <commit_msg>[h5] DataArray: fix label getter to correctly return none<commit_after>// Copyright (c) 2013, 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 file in the root of the Project. #include <nix/util/util.hpp> #include <nix/hdf5/DataArrayHDF5.hpp> #include <nix/hdf5/DataSet.hpp> #include <nix/hdf5/DimensionHDF5.hpp> using namespace std; namespace nix { namespace hdf5 { DataArrayHDF5::DataArrayHDF5(const DataArrayHDF5 &data_array) : EntityWithSourcesHDF5(data_array.file(), data_array.block(), data_array.group(), data_array.id(), data_array.type(), data_array.name()), dimension_group(data_array.dimension_group) { } DataArrayHDF5::DataArrayHDF5(const File &file, const Block &block, const Group &group, const string &id, const string &type, const string &name) : DataArrayHDF5(file, block, group, id, type, name, util::getTime()) { } DataArrayHDF5::DataArrayHDF5(const File &file, const Block &block, const Group &group, const string &id, const string &type, const string &name, time_t time) : EntityWithSourcesHDF5(file, block, group, id, type, name, time) { dimension_group = this->group().openGroup("dimensions", true); } //-------------------------------------------------- // Element getters and setters //-------------------------------------------------- boost::optional<std::string> DataArrayHDF5::label() const { boost::optional<std::string> ret; string value; bool have_attr = group().getAttr("label", value); if (have_attr) { ret = value; } return ret; } void DataArrayHDF5::label(const string &label) { if(label.empty()) { throw EmptyString("label"); } else { group().setAttr("label", label); forceUpdatedAt(); } } void DataArrayHDF5::label(const none_t t) { if(group().hasAttr("label")) { group().removeAttr("label"); } forceUpdatedAt(); } boost::optional<std::string> DataArrayHDF5::unit() const { boost::optional<std::string> ret; string value; group().getAttr("unit", value); ret = value; return ret; } void DataArrayHDF5::unit(const string &unit) { if(unit.empty()) { throw EmptyString("unit"); } else { group().setAttr("unit", unit); forceUpdatedAt(); } } void DataArrayHDF5::unit(const none_t t) { if(group().hasAttr("unit")) { group().removeAttr("unit"); } forceUpdatedAt(); } // TODO use defaults boost::optional<double> DataArrayHDF5::expansionOrigin() const { boost::optional<double> ret; double expansion_origin; group().getAttr("expansion_origin", expansion_origin); ret = expansion_origin; return ret; } void DataArrayHDF5::expansionOrigin(double expansion_origin) { group().setAttr("expansion_origin", expansion_origin); forceUpdatedAt(); } void DataArrayHDF5::expansionOrigin(const none_t t) { if(group().hasAttr("expansionOrigin")) { group().removeAttr("expansionOrigin"); } forceUpdatedAt(); } // TODO use defaults vector<double> DataArrayHDF5::polynomCoefficients()const{ vector<double> polynom_coefficients; if (group().hasData("polynom_coefficients")) { DataSet ds = group().openData("polynom_coefficients"); ds.read(polynom_coefficients, true); } return polynom_coefficients; } void DataArrayHDF5::polynomCoefficients(vector<double> &coefficients) { DataSet ds; if (group().hasData("polynom_coefficients")) { ds = group().openData("polynom_coefficients"); ds.setExtent({coefficients.size()}); } else { ds = DataSet::create(group().h5Group(), "polynom_coefficients", coefficients); } ds.write(coefficients); forceUpdatedAt(); } void DataArrayHDF5::polynomCoefficients(const none_t t) { if(group().hasAttr("polynom_coefficients")) { group().removeAttr("polynom_coefficients"); } forceUpdatedAt(); } //-------------------------------------------------- // Methods concerning dimensions //-------------------------------------------------- size_t DataArrayHDF5::dimensionCount() const { return dimension_group.objectCount(); } Dimension DataArrayHDF5::getDimension(size_t id) const { string str_id = util::numToStr(id); if (dimension_group.hasGroup(str_id)) { Group dim_group = dimension_group.openGroup(str_id, false); string dim_type_name; dim_group.getAttr("dimension_type", dim_type_name); DimensionType dim_type = dimensionTypeFromStr(dim_type_name); Dimension dim; if (dim_type == DimensionType::Set ) { auto tmp = make_shared<SetDimensionHDF5>(dim_group, id); dim = SetDimension(tmp); } else if (dim_type == DimensionType::Range) { std::vector<double> ticks; dim_group.getData("ticks", ticks); auto tmp = make_shared<RangeDimensionHDF5>(dim_group, id, ticks); dim = RangeDimension(tmp); } else if (dim_type == DimensionType::Sample) { double samplingInterval; dim_group.getAttr("sampling_interval", samplingInterval); auto tmp = make_shared<SampledDimensionHDF5>(dim_group, id, samplingInterval); dim = SampledDimension(tmp); } else { throw runtime_error("Invalid dimension type"); } return dim; } else { return Dimension(); } } template<DimensionType dtype, typename T> Dimension DataArrayHDF5::_createDimension(size_t id, T var) { size_t dim_count = dimensionCount(); if (id > (dim_count + 1) || id <= 0) { // dim_count+1 since index starts at 1 runtime_error("Invalid dimension id: has to be 0 < id <= #(dimensions)+1"); } string str_id = util::numToStr(id); if (dimension_group.hasGroup(str_id)) { dimension_group.removeGroup(str_id); } Group dim_group = dimension_group.openGroup(str_id, true); Dimension dim; if (dtype == DimensionType::Range || dtype == DimensionType::Sample) { typedef typename std::conditional<dtype == DimensionType::Range, RangeDimensionHDF5, SampledDimensionHDF5>::type dimTypeHDF5; typedef typename std::conditional<dtype == DimensionType::Range, RangeDimension, SampledDimension>::type dimType; auto tmp = make_shared<dimTypeHDF5>(dim_group, id, var); dim = dimType(tmp); } else { throw runtime_error("Invalid dimension type"); } return dim; } template<> Dimension DataArrayHDF5::_createDimension<DimensionType::Set, none_t>(size_t id, none_t var) { size_t dim_count = dimensionCount(); if (id > (dim_count + 1) || id <= 0) { // dim_count+1 since index starts at 1 runtime_error("Invalid dimension id: has to be 0 < id <= #(dimensions)+1"); } string str_id = util::numToStr(id); if (dimension_group.hasGroup(str_id)) { dimension_group.removeGroup(str_id); } Group dim_group = dimension_group.openGroup(str_id, true); Dimension dim; // no dim-type check needed since method only called if type=DimensionType::Set auto tmp = make_shared<SetDimensionHDF5>(dim_group, id); dim = SetDimension(tmp); return dim; } Dimension DataArrayHDF5::createSetDimension(size_t id) { return _createDimension<DimensionType::Set>(id); } Dimension DataArrayHDF5::createRangeDimension(size_t id, std::vector<double> ticks) { return _createDimension<DimensionType::Range>(id, ticks); } Dimension DataArrayHDF5::createSampledDimension(size_t id, double samplingInterval) { return _createDimension<DimensionType::Sample>(id, samplingInterval); } bool DataArrayHDF5::deleteDimension(size_t id) { bool deleted = false; size_t dim_count = dimensionCount(); string str_id = util::numToStr(id); if (dimension_group.hasGroup(str_id)) { dimension_group.removeGroup(str_id); deleted = true; } if (deleted && id < dim_count) { for (size_t old_id = id + 1; old_id <= dim_count; old_id++) { string str_old_id = util::numToStr(old_id); string str_new_id = util::numToStr(old_id - 1); dimension_group.renameGroup(str_old_id, str_new_id); } } return deleted; } //-------------------------------------------------- // Other methods and functions //-------------------------------------------------- void DataArrayHDF5::swap(DataArrayHDF5 &other) { using std::swap; EntityWithSourcesHDF5::swap(other); swap(dimension_group, other.dimension_group); } DataArrayHDF5& DataArrayHDF5::operator=(const DataArrayHDF5 &other) { if (*this != other) { DataArrayHDF5 tmp(other); swap(tmp); } return *this; } DataArrayHDF5::~DataArrayHDF5() {} void DataArrayHDF5::createData(DataType dtype, const NDSize &size) { if (group().hasData("data")) { throw new std::runtime_error("DataArray alread exists"); //TODO: FIXME, better exception } DataSet::create(group().h5Group(), "data", dtype, size); DataSet ds = group().openData("data"); } bool DataArrayHDF5::hasData() const { return group().hasData("data"); } void DataArrayHDF5::write(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) { DataSet ds; if (!group().hasData("data")) { ds = DataSet::create(group().h5Group(), "data", dtype, count); } else { ds = group().openData("data"); } if (offset.size()) { Selection fileSel = ds.createSelection(); fileSel.select(count, offset); Selection memSel(DataSpace::create(count, false)); ds.write(dtype, data, fileSel, memSel); } else { ds.write(dtype, count, data); } } void DataArrayHDF5::read(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const { if (!group().hasData("data")) { return; } DataSet ds = group().openData("data"); if (offset.size()) { Selection fileSel = ds.createSelection(); fileSel.select(count, offset); Selection memSel(DataSpace::create(count, false)); ds.read(dtype, data, fileSel, memSel); } else { ds.read(dtype, count, data); } } NDSize DataArrayHDF5::dataExtent(void) const { if (!group().hasData("data")) { return NDSize{}; } DataSet ds = group().openData("data"); return ds.size(); } void DataArrayHDF5::dataExtent(const NDSize &extent) { if (!group().hasData("data")) { throw runtime_error("Data field not found in DataArray!"); } DataSet ds = group().openData("data"); ds.setExtent(extent); } DataType DataArrayHDF5::dataType(void) const { if (!group().hasData("data")) { //we could also throw an exception but I think returning //Nothing here is better (ck) - agreed (bm) return DataType::Nothing; } DataSet ds = group().openData("data"); return ds.dataType(); } } // namespace hdf5 } // namespace nix <|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file rao_blackwell_coordinate_particle_filter.hpp * \date 05/25/2014 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com) */ #ifndef FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP #define FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP #include <vector> #include <limits> #include <string> #include <algorithm> #include <cmath> #include <memory> #include <Eigen/Core> #include <fl/util/math.hpp> #include <fl/util/traits.hpp> #include <fl/util/profiling.hpp> #include <fl/util/assertions.hpp> #include <fl/util/discrete_distribution.hpp> #include <fl/distribution/sum_of_deltas.hpp> #include <fl/distribution/standard_gaussian.hpp> #include <fl/distribution/interface/standard_gaussian_mapping.hpp> #include <fl/model/process/process_model_interface.hpp> #include <ff/models/observation_models/interfaces/rao_blackwell_observation_model.hpp> namespace fl { // Forward declarations template < typename ProcessModel, typename ObservationModel > class RaoBlackwellCoordinateParticleFilter; /** * RaoBlackwellCoordinateParticleFilter Traits */ template < typename ProcessModel, typename ObservationModel > struct Traits< RaoBlackwellCoordinateParticleFilter<ProcessModel, ObservationModel> > { typedef RaoBlackwellCoordinateParticleFilter< ProcessModel, ObservationModel > Filter; /* * Required concept (interface) types * * - Ptr * - State * - Input * - Observation * - StateDistribution */ typedef std::shared_ptr<Filter> Ptr; typedef typename Traits<ProcessModel>::State State; typedef typename Traits<ProcessModel>::Input Input; typedef typename Traits<ProcessModel>::Noise Noise; typedef typename ObservationModel::Observation Observation; //!< \todo traits missing /** * Represents the underlying distribution of the estimated state. */ typedef SumOfDeltas<State> StateDistribution; /** \cond INTERNAL */ typedef typename StateDistribution::Scalar Scalar; /** \endcond */ }; /** * * * \todo MISSING DOC. MISSING UTESTS */ template<typename ProcessModel, typename ObservationModel> class RaoBlackwellCoordinateParticleFilter { protected: /** \cond INTERNAL */ typedef RaoBlackwellCoordinateParticleFilter< ProcessModel, ObservationModel > This; /** \endcond */ public: /* public concept interface types */ typedef typename Traits<This>::Scalar Scalar; typedef typename Traits<This>::State State; typedef typename Traits<This>::Input Input; typedef typename Traits<This>::Noise Noise; typedef typename Traits<This>::Observation Observation; typedef typename Traits<This>::StateDistribution StateDistribution; public: /** * Creates a RaoBlackwellCoordinateParticleFilter * * \param process_model Process model instance * \param observation_model Obsrv model instance * \param sampling_blocks * \param max_kl_divergence */ RaoBlackwellCoordinateParticleFilter( const std::shared_ptr<ProcessModel> process_model, const std::shared_ptr<ObservationModel> observation_model, const std::vector<std::vector<size_t>>& sampling_blocks, const Scalar& max_kl_divergence = 0) : observation_model_(observation_model), process_model_(process_model), max_kl_divergence_(max_kl_divergence) { static_assert_base( ProcessModel, ProcessModelInterface<State, Noise, Input>); static_assert_base( ProcessModel, StandardGaussianMapping<State, Noise>); static_assert_base( ObservationModel, RaoBlackwellObservationModel<State, Observation>); SamplingBlocks(sampling_blocks); } /** * \brief Overridable default constructor */ virtual ~RaoBlackwellCoordinateParticleFilter() { } public: /** * \param observation * \param delta_time * \param input */ void Filter(const Observation& observation, const Scalar& delta_time, const Input& input) { observation_model_->SetObservation(observation, delta_time); loglikes_ = std::vector<Scalar>(samples_.size(), 0); noises_ = std::vector<Noise>(samples_.size(), Noise::Zero(process_model_->noise_dimension())); next_samples_ = samples_; for(size_t block_index = 0; block_index < sampling_blocks_.size(); block_index++) { for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++) { for(size_t i = 0; i < sampling_blocks_[block_index].size(); i++) noises_[particle_index](sampling_blocks_[block_index][i]) = unit_gaussian_.sample(); next_samples_[particle_index] = process_model_->predict_state(delta_time, samples_[particle_index], noises_[particle_index], input); } bool update_occlusions = (block_index == sampling_blocks_.size()-1); std::vector<Scalar> new_loglikes = observation_model_->Loglikes(next_samples_, indices_, update_occlusions); std::vector<Scalar> delta_loglikes(new_loglikes.size()); for(size_t i = 0; i < delta_loglikes.size(); i++) delta_loglikes[i] = new_loglikes[i] - loglikes_[i]; loglikes_ = new_loglikes; UpdateWeights(delta_loglikes); } samples_ = next_samples_; state_distribution_.SetDeltas(samples_); // not sure whether this is the right place } /** * \param sample_count */ void Resample(const size_t& sample_count) { std::vector<State> samples(sample_count); std::vector<size_t> indices(sample_count); std::vector<Noise> noises(sample_count); std::vector<State> next_samples(sample_count); std::vector<Scalar> loglikes(sample_count); hf::DiscreteDistribution sampler(log_weights_); for(size_t i = 0; i < sample_count; i++) { size_t index = sampler.sample(); samples[i] = samples_[index]; indices[i] = indices_[index]; noises[i] = noises_[index]; next_samples[i] = next_samples_[index]; loglikes[i] = loglikes_[index]; } samples_ = samples; indices_ = indices; noises_ = noises; next_samples_ = next_samples; loglikes_ = loglikes; log_weights_ = std::vector<Scalar>(samples_.size(), 0.); state_distribution_.SetDeltas(samples_); // not sure whether this is the right place } private: // O(6n + nlog(n)) might be reducible to O(4n) void UpdateWeights(std::vector<Scalar> log_weight_diffs) { for(size_t i = 0; i < log_weight_diffs.size(); i++) log_weights_[i] += log_weight_diffs[i]; std::vector<Scalar> weights = log_weights_; // descendant sorting std::sort(weights.begin(), weights.end(), std::greater<Scalar>()); for(int i = weights.size() - 1; i >= 0; i--) weights[i] -= weights[0]; std::for_each(weights.begin(), weights.end(), [](Scalar& w){ w = std::exp(w); }); weights = fl::normalize(weights, Scalar(1)); // compute KL divergence to uniform distribution KL(p|u) Scalar kl_divergence = std::log(Scalar(weights.size())); for(size_t i = 0; i < weights.size(); i++) { Scalar information = - std::log(weights[i]) * weights[i]; if(!std::isfinite(information)) information = 0; // the limit for weight -> 0 is equal to 0 kl_divergence -= information; } if(kl_divergence > max_kl_divergence_) Resample(samples_.size()); } public: // set void Samples(const std::vector<State >& samples) { samples_ = samples; indices_ = std::vector<size_t>(samples_.size(), 0); observation_model_->Reset(); log_weights_ = std::vector<Scalar>(samples_.size(), 0); } void SamplingBlocks(const std::vector<std::vector<size_t>>& sampling_blocks) { sampling_blocks_ = sampling_blocks; // make sure sizes are consistent size_t dimension = 0; for(size_t i = 0; i < sampling_blocks_.size(); i++) for(size_t j = 0; j < sampling_blocks_[i].size(); j++) dimension++; if(dimension != process_model_->standard_variate_dimension()) { std::cout << "the dimension of the sampling blocks is " << dimension << " while the dimension of the noise is " << process_model_->standard_variate_dimension() << std::endl; exit(-1); } } // get const std::vector<State>& Samples() const { return samples_; } StateDistribution& state_distribution() { return state_distribution_; } private: // internal state TODO: THIS COULD BE MADE MORE COMPACT!! StateDistribution state_distribution_; std::vector<State > samples_; std::vector<size_t> indices_; std::vector<Scalar> log_weights_; std::vector<Noise> noises_; std::vector<State> next_samples_; std::vector<Scalar> loglikes_; std::shared_ptr<ObservationModel> observation_model_; std::shared_ptr<ProcessModel> process_model_; // parameters std::vector<std::vector<size_t>> sampling_blocks_; Scalar max_kl_divergence_; // distribution for sampling //Gaussian<Eigen::Matrix<Scalar,1,1>> unit_gaussian_; StandardGaussian<Scalar> unit_gaussian_; }; } #endif <commit_msg>removed Gaussian<Eigen::Matrix<Scalar,1,1>> comment<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file rao_blackwell_coordinate_particle_filter.hpp * \date 05/25/2014 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com) */ #ifndef FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP #define FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP #include <vector> #include <limits> #include <string> #include <algorithm> #include <cmath> #include <memory> #include <Eigen/Core> #include <fl/util/math.hpp> #include <fl/util/traits.hpp> #include <fl/util/profiling.hpp> #include <fl/util/assertions.hpp> #include <fl/util/discrete_distribution.hpp> #include <fl/distribution/sum_of_deltas.hpp> #include <fl/distribution/standard_gaussian.hpp> #include <fl/distribution/interface/standard_gaussian_mapping.hpp> #include <fl/model/process/process_model_interface.hpp> #include <ff/models/observation_models/interfaces/rao_blackwell_observation_model.hpp> namespace fl { // Forward declarations template < typename ProcessModel, typename ObservationModel > class RaoBlackwellCoordinateParticleFilter; /** * RaoBlackwellCoordinateParticleFilter Traits */ template < typename ProcessModel, typename ObservationModel > struct Traits< RaoBlackwellCoordinateParticleFilter<ProcessModel, ObservationModel> > { typedef RaoBlackwellCoordinateParticleFilter< ProcessModel, ObservationModel > Filter; /* * Required concept (interface) types * * - Ptr * - State * - Input * - Observation * - StateDistribution */ typedef std::shared_ptr<Filter> Ptr; typedef typename Traits<ProcessModel>::State State; typedef typename Traits<ProcessModel>::Input Input; typedef typename Traits<ProcessModel>::Noise Noise; typedef typename ObservationModel::Observation Observation; //!< \todo traits missing /** * Represents the underlying distribution of the estimated state. */ typedef SumOfDeltas<State> StateDistribution; /** \cond INTERNAL */ typedef typename StateDistribution::Scalar Scalar; /** \endcond */ }; /** * * * \todo MISSING DOC. MISSING UTESTS */ template<typename ProcessModel, typename ObservationModel> class RaoBlackwellCoordinateParticleFilter { protected: /** \cond INTERNAL */ typedef RaoBlackwellCoordinateParticleFilter< ProcessModel, ObservationModel > This; /** \endcond */ public: /* public concept interface types */ typedef typename Traits<This>::Scalar Scalar; typedef typename Traits<This>::State State; typedef typename Traits<This>::Input Input; typedef typename Traits<This>::Noise Noise; typedef typename Traits<This>::Observation Observation; typedef typename Traits<This>::StateDistribution StateDistribution; public: /** * Creates a RaoBlackwellCoordinateParticleFilter * * \param process_model Process model instance * \param observation_model Obsrv model instance * \param sampling_blocks * \param max_kl_divergence */ RaoBlackwellCoordinateParticleFilter( const std::shared_ptr<ProcessModel> process_model, const std::shared_ptr<ObservationModel> observation_model, const std::vector<std::vector<size_t>>& sampling_blocks, const Scalar& max_kl_divergence = 0) : observation_model_(observation_model), process_model_(process_model), max_kl_divergence_(max_kl_divergence) { static_assert_base( ProcessModel, ProcessModelInterface<State, Noise, Input>); static_assert_base( ProcessModel, StandardGaussianMapping<State, Noise>); static_assert_base( ObservationModel, RaoBlackwellObservationModel<State, Observation>); SamplingBlocks(sampling_blocks); } /** * \brief Overridable default constructor */ virtual ~RaoBlackwellCoordinateParticleFilter() { } public: /** * \param observation * \param delta_time * \param input */ void Filter(const Observation& observation, const Scalar& delta_time, const Input& input) { observation_model_->SetObservation(observation, delta_time); loglikes_ = std::vector<Scalar>(samples_.size(), 0); noises_ = std::vector<Noise>(samples_.size(), Noise::Zero(process_model_->noise_dimension())); next_samples_ = samples_; for(size_t block_index = 0; block_index < sampling_blocks_.size(); block_index++) { for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++) { for(size_t i = 0; i < sampling_blocks_[block_index].size(); i++) noises_[particle_index](sampling_blocks_[block_index][i]) = unit_gaussian_.sample(); next_samples_[particle_index] = process_model_->predict_state(delta_time, samples_[particle_index], noises_[particle_index], input); } bool update_occlusions = (block_index == sampling_blocks_.size()-1); std::vector<Scalar> new_loglikes = observation_model_->Loglikes(next_samples_, indices_, update_occlusions); std::vector<Scalar> delta_loglikes(new_loglikes.size()); for(size_t i = 0; i < delta_loglikes.size(); i++) delta_loglikes[i] = new_loglikes[i] - loglikes_[i]; loglikes_ = new_loglikes; UpdateWeights(delta_loglikes); } samples_ = next_samples_; state_distribution_.SetDeltas(samples_); // not sure whether this is the right place } /** * \param sample_count */ void Resample(const size_t& sample_count) { std::vector<State> samples(sample_count); std::vector<size_t> indices(sample_count); std::vector<Noise> noises(sample_count); std::vector<State> next_samples(sample_count); std::vector<Scalar> loglikes(sample_count); hf::DiscreteDistribution sampler(log_weights_); for(size_t i = 0; i < sample_count; i++) { size_t index = sampler.sample(); samples[i] = samples_[index]; indices[i] = indices_[index]; noises[i] = noises_[index]; next_samples[i] = next_samples_[index]; loglikes[i] = loglikes_[index]; } samples_ = samples; indices_ = indices; noises_ = noises; next_samples_ = next_samples; loglikes_ = loglikes; log_weights_ = std::vector<Scalar>(samples_.size(), 0.); state_distribution_.SetDeltas(samples_); // not sure whether this is the right place } private: // O(6n + nlog(n)) might be reducible to O(4n) void UpdateWeights(std::vector<Scalar> log_weight_diffs) { for(size_t i = 0; i < log_weight_diffs.size(); i++) log_weights_[i] += log_weight_diffs[i]; std::vector<Scalar> weights = log_weights_; // descendant sorting std::sort(weights.begin(), weights.end(), std::greater<Scalar>()); for(int i = weights.size() - 1; i >= 0; i--) weights[i] -= weights[0]; std::for_each(weights.begin(), weights.end(), [](Scalar& w){ w = std::exp(w); }); weights = fl::normalize(weights, Scalar(1)); // compute KL divergence to uniform distribution KL(p|u) Scalar kl_divergence = std::log(Scalar(weights.size())); for(size_t i = 0; i < weights.size(); i++) { Scalar information = - std::log(weights[i]) * weights[i]; if(!std::isfinite(information)) information = 0; // the limit for weight -> 0 is equal to 0 kl_divergence -= information; } if(kl_divergence > max_kl_divergence_) Resample(samples_.size()); } public: // set void Samples(const std::vector<State >& samples) { samples_ = samples; indices_ = std::vector<size_t>(samples_.size(), 0); observation_model_->Reset(); log_weights_ = std::vector<Scalar>(samples_.size(), 0); } void SamplingBlocks(const std::vector<std::vector<size_t>>& sampling_blocks) { sampling_blocks_ = sampling_blocks; // make sure sizes are consistent size_t dimension = 0; for(size_t i = 0; i < sampling_blocks_.size(); i++) for(size_t j = 0; j < sampling_blocks_[i].size(); j++) dimension++; if(dimension != process_model_->standard_variate_dimension()) { std::cout << "the dimension of the sampling blocks is " << dimension << " while the dimension of the noise is " << process_model_->standard_variate_dimension() << std::endl; exit(-1); } } // get const std::vector<State>& Samples() const { return samples_; } StateDistribution& state_distribution() { return state_distribution_; } private: // internal state TODO: THIS COULD BE MADE MORE COMPACT!! StateDistribution state_distribution_; std::vector<State > samples_; std::vector<size_t> indices_; std::vector<Scalar> log_weights_; std::vector<Noise> noises_; std::vector<State> next_samples_; std::vector<Scalar> loglikes_; std::shared_ptr<ObservationModel> observation_model_; std::shared_ptr<ProcessModel> process_model_; // parameters std::vector<std::vector<size_t>> sampling_blocks_; Scalar max_kl_divergence_; // distribution for sampling StandardGaussian<Scalar> unit_gaussian_; }; } #endif <|endoftext|>
<commit_before>#include <node.h> #include <node_buffer.h> #include "dbstore.h" using namespace v8; DbStore::DbStore() : _db(0), _env(0), _txn(0) {}; DbStore::~DbStore() { fprintf(stderr, "~DbStore %p\n", this); close(); }; void DbStore::Init(Handle<Object> target) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("DbStore")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype tpl->PrototypeTemplate()->Set(String::NewSymbol("open"), FunctionTemplate::New(Open)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("close"), FunctionTemplate::New(Close)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("_put"), FunctionTemplate::New(Put)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("_get"), FunctionTemplate::New(Get)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("del"), FunctionTemplate::New(Del)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("sync"), FunctionTemplate::New(Sync)->GetFunction()); Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction()); target->Set(String::NewSymbol("DbStore"), constructor); } int DbStore::open(char const *fname, char const *db, DBTYPE type, u_int32_t flags, int mode) { int ret = db_create(&_db, NULL, 0); if (ret) return ret; fprintf(stderr, "%p: open %p\n", this, _db); return _db->open(_db, NULL, fname, db, type, flags, mode); } int DbStore::close() { int ret = 0; if (_db && _db->pgsize) { fprintf(stderr, "%p: close %p\n", this, _db); ret = _db->close(_db, 0); _db = NULL; } return ret; } static void dbt_set(DBT *dbt, void *data, u_int32_t size, u_int32_t flags = DB_DBT_USERMEM) { memset(dbt, 0, sizeof(*dbt)); dbt->data = data; dbt->size = size; dbt->flags = flags; } int DbStore::put(DBT *key, DBT *data, u_int32_t flags) { return _db->put(_db, 0, key, data, flags); } int DbStore::get(DBT *key, DBT *data, u_int32_t flags) { return _db->get(_db, 0, key, data, flags); } int DbStore::del(DBT *key, u_int32_t flags) { return _db->del(_db, 0, key, flags); } int DbStore::sync(u_int32_t flags) { return 0; } Handle<Value> DbStore::New(const Arguments& args) { HandleScope scope; DbStore* obj = new DbStore(); obj->Wrap(args.This()); return args.This(); } struct WorkBaton { uv_work_t *req; DbStore *store; char *str_arg; Persistent<Function> callback; Persistent<Object> data; char const *call; DBT retbuf; int ret; WorkBaton(uv_work_t *_r, DbStore *_s); ~WorkBaton(); }; WorkBaton::WorkBaton(uv_work_t *_r, DbStore *_s) : req(_r), store(_s), str_arg(0) { //fprintf(stderr, "new WorkBaton %p\n", this); } WorkBaton::~WorkBaton() { //fprintf(stderr, "~WorkBaton %p\n", this); delete req; if (str_arg) free(str_arg); callback.Dispose(); data.Dispose(); // Ignore retbuf since it will be freed by Buffer } static void After(WorkBaton *baton, Handle<Value> *argv, int argc) { if (baton->ret) { fprintf(stderr, "%s %s error %d\n", baton->call, baton->str_arg, baton->ret); argv[0] = node::UVException(0, baton->call, db_strerror(baton->ret)); } else { argv[0] = Local<Value>::New(Null()); } // surround in a try/catch for safety TryCatch try_catch; // execute the callback function //fprintf(stderr, "%p.%s Calling cb\n", baton->store, call); baton->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) node::FatalException(try_catch); delete baton; } void OpenWork(uv_work_t *req) { WorkBaton *baton = (WorkBaton *) req->data; DbStore *store = baton->store; baton->call = "open"; baton->ret = store->open(baton->str_arg, NULL, DB_BTREE, DB_CREATE|DB_THREAD, 0); } void OpenAfter(uv_work_t *req) { HandleScope scope; // fetch our data structure WorkBaton *baton = (WorkBaton *)req->data; // create an arguments array for the callback Handle<Value> argv[1]; After(baton, argv, 1); } Handle<Value> DbStore::Open(const Arguments& args) { HandleScope scope; DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); if (! args[0]->IsString()) { ThrowException(Exception::TypeError(String::New("First argument must be String"))); return scope.Close(Undefined()); } if (! args[1]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Second argument must be callback function"))); return scope.Close(Undefined()); } // create an async work token uv_work_t *req = new uv_work_t; // assign our data structure that will be passed around WorkBaton *baton = new WorkBaton(req, obj); req->data = baton; String::Utf8Value fname(args[0]); baton->str_arg = strdup(*fname); baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); uv_queue_work(uv_default_loop(), req, OpenWork, OpenAfter); return args.This(); } static void CloseWork(uv_work_t *req) { WorkBaton *baton = (WorkBaton *) req->data; DbStore *store = baton->store; baton->call = "close"; baton->ret = store->close(); } static void CloseAfter(uv_work_t *req) { HandleScope scope; // fetch our data structure WorkBaton *baton = (WorkBaton *)req->data; // create an arguments array for the callback Handle<Value> argv[1]; After(baton, argv, 1); } Handle<Value> DbStore::Close(const Arguments& args) { HandleScope scope; DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); if (! args[0]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Argument must be callback function"))); return scope.Close(Undefined()); } // create an async work token uv_work_t *req = new uv_work_t; // assign our data structure that will be passed around WorkBaton *baton = new WorkBaton(req, obj); req->data = baton; baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[0])); uv_queue_work(uv_default_loop(), req, CloseWork, CloseAfter); return args.This(); } static void PutWork(uv_work_t *req) { WorkBaton *baton = (WorkBaton *) req->data; DbStore *store = baton->store; DBT key_dbt; dbt_set(&key_dbt, baton->str_arg, strlen(baton->str_arg)); DBT data_dbt; dbt_set(&data_dbt, node::Buffer::Data(baton->data), node::Buffer::Length(baton->data)); baton->call = "put"; baton->ret = store->put(&key_dbt, &data_dbt, 0); //fprintf(stderr, "put %s\n", baton->str_arg); } static void PutAfter(uv_work_t *req) { HandleScope scope; // fetch our data structure WorkBaton *baton = (WorkBaton *)req->data; // create an arguments array for the callback Handle<Value> argv[1]; After(baton, argv, 1); } Handle<Value> DbStore::Put(const Arguments& args) { HandleScope scope; DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); if (! args.Length() > 0 && ! args[0]->IsString()) { ThrowException(Exception::TypeError(String::New("First argument must be a string"))); return scope.Close(Undefined()); } String::Utf8Value key(args[0]); if (! args.Length() > 1 && ! node::Buffer::HasInstance(args[1])) { ThrowException(Exception::TypeError(String::New("Second argument must be a Buffer"))); return scope.Close(Undefined()); } Persistent<Object> data = Persistent<Object>::New(Local<Object>::Cast(args[1])); if (! args.Length() > 2 && ! args[2]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Argument must be callback function"))); return scope.Close(Undefined()); } // create an async work token uv_work_t *req = new uv_work_t; // assign our data structure that will be passed around WorkBaton *baton = new WorkBaton(req, obj); req->data = baton; baton->str_arg = strdup(*key); baton->data = data; baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[2])); uv_queue_work(uv_default_loop(), req, PutWork, PutAfter); return args.This(); } static void GetWork(uv_work_t *req) { WorkBaton *baton = (WorkBaton *) req->data; DbStore *store = baton->store; DBT key_dbt; dbt_set(&key_dbt, baton->str_arg, strlen(baton->str_arg)); DBT *retbuf = &baton->retbuf; dbt_set(retbuf, 0, 0, DB_DBT_MALLOC); baton->call = "get"; baton->ret = store->get(&key_dbt, retbuf, 0); //fprintf(stderr, "get %s => %p[%d]\n", baton->str_arg, key_dbt.data, key_dbt.size); } static void free_buf(char *data, void *hint) { //fprintf(stderr, "Free %p\n", data); free(data); } static void GetAfter(uv_work_t *req) { HandleScope scope; // fetch our data structure WorkBaton *baton = (WorkBaton *)req->data; // create an arguments array for the callback Handle<Value> argv[2]; DBT *retbuf = &baton->retbuf; node::Buffer *buf = node::Buffer::New((char*)retbuf->data, retbuf->size, free_buf, NULL); argv[1] = buf->handle_; After(baton, argv, 2); } Handle<Value> DbStore::Get(const Arguments& args) { HandleScope scope; DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); if (! args.Length() > 0 && ! args[0]->IsString()) { ThrowException(Exception::TypeError(String::New("First argument must be a string"))); return scope.Close(Undefined()); } String::Utf8Value key(args[0]); if (! args.Length() > 1 && ! args[1]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Argument must be callback function"))); return scope.Close(Undefined()); } // create an async work token uv_work_t *req = new uv_work_t; // assign our data structure that will be passed around WorkBaton *baton = new WorkBaton(req, obj); req->data = baton; baton->str_arg = strdup(*key); baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); uv_queue_work(uv_default_loop(), req, GetWork, GetAfter); return args.This(); } static void DelWork(uv_work_t *req) { WorkBaton *baton = (WorkBaton *) req->data; DbStore *store = baton->store; DBT key_dbt; dbt_set(&key_dbt, baton->str_arg, strlen(baton->str_arg)); //fprintf(stderr, "del %s\n", baton->str_arg); baton->call = "del"; baton->ret = store->del(&key_dbt, 0); } Handle<Value> DbStore::Del(const Arguments& args) { HandleScope scope; DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); if (! args.Length() > 0 && ! args[0]->IsString()) { ThrowException(Exception::TypeError(String::New("First argument must be a string"))); return scope.Close(Undefined()); } String::Utf8Value key(args[0]); if (! args.Length() > 1 && ! args[1]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Argument must be callback function"))); return scope.Close(Undefined()); } // create an async work token uv_work_t *req = new uv_work_t; // assign our data structure that will be passed around WorkBaton *baton = new WorkBaton(req, obj); req->data = baton; baton->str_arg = strdup(*key); baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); uv_queue_work(uv_default_loop(), req, DelWork, PutAfter); // Yes, use the same. return args.This(); } Handle<Value> DbStore::Sync(const Arguments& args) { HandleScope scope; //DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); return scope.Close(Number::New(0)); } <commit_msg>Remove extraneous debug output<commit_after>#include <node.h> #include <node_buffer.h> #include "dbstore.h" using namespace v8; DbStore::DbStore() : _db(0), _env(0), _txn(0) {}; DbStore::~DbStore() { fprintf(stderr, "~DbStore %p\n", this); close(); }; void DbStore::Init(Handle<Object> target) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("DbStore")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype tpl->PrototypeTemplate()->Set(String::NewSymbol("open"), FunctionTemplate::New(Open)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("close"), FunctionTemplate::New(Close)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("_put"), FunctionTemplate::New(Put)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("_get"), FunctionTemplate::New(Get)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("del"), FunctionTemplate::New(Del)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("sync"), FunctionTemplate::New(Sync)->GetFunction()); Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction()); target->Set(String::NewSymbol("DbStore"), constructor); } int DbStore::open(char const *fname, char const *db, DBTYPE type, u_int32_t flags, int mode) { int ret = db_create(&_db, NULL, 0); if (ret) return ret; //fprintf(stderr, "%p: open %p\n", this, _db); return _db->open(_db, NULL, fname, db, type, flags, mode); } int DbStore::close() { int ret = 0; if (_db && _db->pgsize) { //fprintf(stderr, "%p: close %p\n", this, _db); ret = _db->close(_db, 0); _db = NULL; } return ret; } static void dbt_set(DBT *dbt, void *data, u_int32_t size, u_int32_t flags = DB_DBT_USERMEM) { memset(dbt, 0, sizeof(*dbt)); dbt->data = data; dbt->size = size; dbt->flags = flags; } int DbStore::put(DBT *key, DBT *data, u_int32_t flags) { return _db->put(_db, 0, key, data, flags); } int DbStore::get(DBT *key, DBT *data, u_int32_t flags) { return _db->get(_db, 0, key, data, flags); } int DbStore::del(DBT *key, u_int32_t flags) { return _db->del(_db, 0, key, flags); } int DbStore::sync(u_int32_t flags) { return 0; } Handle<Value> DbStore::New(const Arguments& args) { HandleScope scope; DbStore* obj = new DbStore(); obj->Wrap(args.This()); return args.This(); } struct WorkBaton { uv_work_t *req; DbStore *store; char *str_arg; Persistent<Function> callback; Persistent<Object> data; char const *call; DBT retbuf; int ret; WorkBaton(uv_work_t *_r, DbStore *_s); ~WorkBaton(); }; WorkBaton::WorkBaton(uv_work_t *_r, DbStore *_s) : req(_r), store(_s), str_arg(0) { //fprintf(stderr, "new WorkBaton %p\n", this); } WorkBaton::~WorkBaton() { //fprintf(stderr, "~WorkBaton %p\n", this); delete req; if (str_arg) free(str_arg); callback.Dispose(); data.Dispose(); // Ignore retbuf since it will be freed by Buffer } static void After(WorkBaton *baton, Handle<Value> *argv, int argc) { if (baton->ret) { //fprintf(stderr, "%s %s error %d\n", baton->call, baton->str_arg, baton->ret); argv[0] = node::UVException(0, baton->call, db_strerror(baton->ret)); } else { argv[0] = Local<Value>::New(Null()); } // surround in a try/catch for safety TryCatch try_catch; // execute the callback function //fprintf(stderr, "%p.%s Calling cb\n", baton->store, call); baton->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) node::FatalException(try_catch); delete baton; } void OpenWork(uv_work_t *req) { WorkBaton *baton = (WorkBaton *) req->data; DbStore *store = baton->store; baton->call = "open"; baton->ret = store->open(baton->str_arg, NULL, DB_BTREE, DB_CREATE|DB_THREAD, 0); } void OpenAfter(uv_work_t *req) { HandleScope scope; // fetch our data structure WorkBaton *baton = (WorkBaton *)req->data; // create an arguments array for the callback Handle<Value> argv[1]; After(baton, argv, 1); } Handle<Value> DbStore::Open(const Arguments& args) { HandleScope scope; DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); if (! args[0]->IsString()) { ThrowException(Exception::TypeError(String::New("First argument must be String"))); return scope.Close(Undefined()); } if (! args[1]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Second argument must be callback function"))); return scope.Close(Undefined()); } // create an async work token uv_work_t *req = new uv_work_t; // assign our data structure that will be passed around WorkBaton *baton = new WorkBaton(req, obj); req->data = baton; String::Utf8Value fname(args[0]); baton->str_arg = strdup(*fname); baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); uv_queue_work(uv_default_loop(), req, OpenWork, OpenAfter); return args.This(); } static void CloseWork(uv_work_t *req) { WorkBaton *baton = (WorkBaton *) req->data; DbStore *store = baton->store; baton->call = "close"; baton->ret = store->close(); } static void CloseAfter(uv_work_t *req) { HandleScope scope; // fetch our data structure WorkBaton *baton = (WorkBaton *)req->data; // create an arguments array for the callback Handle<Value> argv[1]; After(baton, argv, 1); } Handle<Value> DbStore::Close(const Arguments& args) { HandleScope scope; DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); if (! args[0]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Argument must be callback function"))); return scope.Close(Undefined()); } // create an async work token uv_work_t *req = new uv_work_t; // assign our data structure that will be passed around WorkBaton *baton = new WorkBaton(req, obj); req->data = baton; baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[0])); uv_queue_work(uv_default_loop(), req, CloseWork, CloseAfter); return args.This(); } static void PutWork(uv_work_t *req) { WorkBaton *baton = (WorkBaton *) req->data; DbStore *store = baton->store; DBT key_dbt; dbt_set(&key_dbt, baton->str_arg, strlen(baton->str_arg)); DBT data_dbt; dbt_set(&data_dbt, node::Buffer::Data(baton->data), node::Buffer::Length(baton->data)); baton->call = "put"; baton->ret = store->put(&key_dbt, &data_dbt, 0); //fprintf(stderr, "put %s\n", baton->str_arg); } static void PutAfter(uv_work_t *req) { HandleScope scope; // fetch our data structure WorkBaton *baton = (WorkBaton *)req->data; // create an arguments array for the callback Handle<Value> argv[1]; After(baton, argv, 1); } Handle<Value> DbStore::Put(const Arguments& args) { HandleScope scope; DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); if (! args.Length() > 0 && ! args[0]->IsString()) { ThrowException(Exception::TypeError(String::New("First argument must be a string"))); return scope.Close(Undefined()); } String::Utf8Value key(args[0]); if (! args.Length() > 1 && ! node::Buffer::HasInstance(args[1])) { ThrowException(Exception::TypeError(String::New("Second argument must be a Buffer"))); return scope.Close(Undefined()); } Persistent<Object> data = Persistent<Object>::New(Local<Object>::Cast(args[1])); if (! args.Length() > 2 && ! args[2]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Argument must be callback function"))); return scope.Close(Undefined()); } // create an async work token uv_work_t *req = new uv_work_t; // assign our data structure that will be passed around WorkBaton *baton = new WorkBaton(req, obj); req->data = baton; baton->str_arg = strdup(*key); baton->data = data; baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[2])); uv_queue_work(uv_default_loop(), req, PutWork, PutAfter); return args.This(); } static void GetWork(uv_work_t *req) { WorkBaton *baton = (WorkBaton *) req->data; DbStore *store = baton->store; DBT key_dbt; dbt_set(&key_dbt, baton->str_arg, strlen(baton->str_arg)); DBT *retbuf = &baton->retbuf; dbt_set(retbuf, 0, 0, DB_DBT_MALLOC); baton->call = "get"; baton->ret = store->get(&key_dbt, retbuf, 0); //fprintf(stderr, "get %s => %p[%d]\n", baton->str_arg, key_dbt.data, key_dbt.size); } static void free_buf(char *data, void *hint) { //fprintf(stderr, "Free %p\n", data); free(data); } static void GetAfter(uv_work_t *req) { HandleScope scope; // fetch our data structure WorkBaton *baton = (WorkBaton *)req->data; // create an arguments array for the callback Handle<Value> argv[2]; DBT *retbuf = &baton->retbuf; node::Buffer *buf = node::Buffer::New((char*)retbuf->data, retbuf->size, free_buf, NULL); argv[1] = buf->handle_; After(baton, argv, 2); } Handle<Value> DbStore::Get(const Arguments& args) { HandleScope scope; DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); if (! args.Length() > 0 && ! args[0]->IsString()) { ThrowException(Exception::TypeError(String::New("First argument must be a string"))); return scope.Close(Undefined()); } String::Utf8Value key(args[0]); if (! args.Length() > 1 && ! args[1]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Argument must be callback function"))); return scope.Close(Undefined()); } // create an async work token uv_work_t *req = new uv_work_t; // assign our data structure that will be passed around WorkBaton *baton = new WorkBaton(req, obj); req->data = baton; baton->str_arg = strdup(*key); baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); uv_queue_work(uv_default_loop(), req, GetWork, GetAfter); return args.This(); } static void DelWork(uv_work_t *req) { WorkBaton *baton = (WorkBaton *) req->data; DbStore *store = baton->store; DBT key_dbt; dbt_set(&key_dbt, baton->str_arg, strlen(baton->str_arg)); //fprintf(stderr, "del %s\n", baton->str_arg); baton->call = "del"; baton->ret = store->del(&key_dbt, 0); } Handle<Value> DbStore::Del(const Arguments& args) { HandleScope scope; DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); if (! args.Length() > 0 && ! args[0]->IsString()) { ThrowException(Exception::TypeError(String::New("First argument must be a string"))); return scope.Close(Undefined()); } String::Utf8Value key(args[0]); if (! args.Length() > 1 && ! args[1]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Argument must be callback function"))); return scope.Close(Undefined()); } // create an async work token uv_work_t *req = new uv_work_t; // assign our data structure that will be passed around WorkBaton *baton = new WorkBaton(req, obj); req->data = baton; baton->str_arg = strdup(*key); baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); uv_queue_work(uv_default_loop(), req, DelWork, PutAfter); // Yes, use the same. return args.This(); } Handle<Value> DbStore::Sync(const Arguments& args) { HandleScope scope; //DbStore* obj = ObjectWrap::Unwrap<DbStore>(args.This()); return scope.Close(Number::New(0)); } <|endoftext|>
<commit_before>// // ulib - a collection of useful classes // Copyright (C) 2006,2007,2008,2012,2013,2016,2017 Michael Fink // /// \file Timer.hpp Timer class // #pragma once #pragma warning(push) #pragma warning(disable: 28159) // Consider using 'GetTickCount64' instead of 'GetTickCount'. Reason: GetTickCount overflows roughly every 49 days. Code that does not take that into account can loop indefinitely. GetTickCount64 operates on 64 bit values and does not have that problem /// \brief Timer class /// \details Has a precision of about 15 ms. class Timer { public: /// ctor Timer() :m_isStarted(false), m_tickStart(0), m_totalElapsed(0) { } /// starts timer; timer must be stopped or reset void Start() { ATLASSERT(m_isStarted == false); m_tickStart = GetTickCount(); m_isStarted = true; } /// stops timer; timer must be started void Stop() { ATLASSERT(m_isStarted == true); DWORD tickEnd = GetTickCount(); m_totalElapsed += (tickEnd - m_tickStart); m_isStarted = false; } /// resets timer; timer must be stopped void Reset() { ATLASSERT(m_isStarted == false); // must be stopped when calling Reset() m_totalElapsed = 0; } /// restarts timer by resetting and starting again void Restart() { // can either be stopped or started when restarting if (m_isStarted) Stop(); Reset(); Start(); } /// returns elapsed time since Start() was called, in seconds double Elapsed() const { if (!m_isStarted) return 0.0; // no time elapsed, since timer isn't started DWORD tickNow = GetTickCount(); return 0.001 * (tickNow - m_tickStart); } /// returns total elapsed time in seconds double TotalElapsed() const { DWORD tickNow = GetTickCount(); return 0.001 * (m_totalElapsed + (m_isStarted ? (tickNow - m_tickStart) : 0)); } /// returns if timer is running bool IsStarted() const { return m_isStarted; } private: /// indicates if timer is started bool m_isStarted; /// tick count of start DWORD m_tickStart; /// number of ticks already elapsed DWORD m_totalElapsed; }; #pragma warning(pop) <commit_msg>added comment about TraceOutputStopwatch<commit_after>// // ulib - a collection of useful classes // Copyright (C) 2006,2007,2008,2012,2013,2016,2017 Michael Fink // /// \file Timer.hpp Timer class // #pragma once #pragma warning(push) #pragma warning(disable: 28159) // Consider using 'GetTickCount64' instead of 'GetTickCount'. Reason: GetTickCount overflows roughly every 49 days. Code that does not take that into account can loop indefinitely. GetTickCount64 operates on 64 bit values and does not have that problem /// \brief Timer class /// \details Has a precision of about 15 ms. Has identical interface as class /// HighResolutionTimer. Can be used in TraceOutputStopwatch. class Timer { public: /// ctor Timer() :m_isStarted(false), m_tickStart(0), m_totalElapsed(0) { } /// starts timer; timer must be stopped or reset void Start() { ATLASSERT(m_isStarted == false); m_tickStart = GetTickCount(); m_isStarted = true; } /// stops timer; timer must be started void Stop() { ATLASSERT(m_isStarted == true); DWORD tickEnd = GetTickCount(); m_totalElapsed += (tickEnd - m_tickStart); m_isStarted = false; } /// resets timer; timer must be stopped void Reset() { ATLASSERT(m_isStarted == false); // must be stopped when calling Reset() m_totalElapsed = 0; } /// restarts timer by resetting and starting again void Restart() { // can either be stopped or started when restarting if (m_isStarted) Stop(); Reset(); Start(); } /// returns elapsed time since Start() was called, in seconds double Elapsed() const { if (!m_isStarted) return 0.0; // no time elapsed, since timer isn't started DWORD tickNow = GetTickCount(); return 0.001 * (tickNow - m_tickStart); } /// returns total elapsed time in seconds double TotalElapsed() const { DWORD tickNow = GetTickCount(); return 0.001 * (m_totalElapsed + (m_isStarted ? (tickNow - m_tickStart) : 0)); } /// returns if timer is running bool IsStarted() const { return m_isStarted; } private: /// indicates if timer is started bool m_isStarted; /// tick count of start DWORD m_tickStart; /// number of ticks already elapsed DWORD m_totalElapsed; }; #pragma warning(pop) <|endoftext|>
<commit_before>// vi:cin:et:sw=4 ts=4 // // drafter.cc // // Created by Jiri Kratochvil on 2015-02-11 // Copyright (c) 2015 Apiary Inc. All rights reserved. // // // #include <string> #include <iostream> #include <sstream> #include <fstream> #include <tr1/memory> #include <tr1/shared_ptr.h> #include "snowcrash.h" #include "SectionParserData.h" // snowcrash::BlueprintParserOptions #include "sos.h" #include "sosJSON.h" #include "sosYAML.h" #include "SerializeAST.h" #include "SerializeSourcemap.h" #include "reporting.h" #include "config.h" namespace sc = snowcrash; template<typename T> struct dummy_deleter { void operator()(T* obj) const { // do nothing } }; template<typename T> struct std_io_selector; template<> struct std_io_selector<std::ostream>{ std::ostream* operator()() { return &std::cout; } }; template<> struct std_io_selector<std::istream>{ std::istream* operator()() { return &std::cin; } }; template <typename Stream> struct to_fstream; template<> struct to_fstream<std::istream>{ typedef std::ifstream stream_type; }; template<> struct to_fstream<std::ostream>{ typedef std::ofstream stream_type; }; template<typename T> struct file_io_selector; template<> struct file_io_selector<std::ofstream>{ std::ofstream* operator()(const char* name) { return new std::ofstream(name); } }; template<> struct file_io_selector<std::ifstream>{ std::ifstream* operator()(const char* name) { return new std::ifstream(name); } }; template<typename T> std::tr1::shared_ptr<T> CreateStreamFromName(const std::string& file) { if(file.empty()) { return std::tr1::shared_ptr<T>( std_io_selector<T>()(), dummy_deleter<T>() ); } typedef typename to_fstream<T>::stream_type stream_type; std::tr1::shared_ptr<stream_type>stream( file_io_selector<stream_type>()(file.c_str()) ); if (!stream->is_open()) { std::cerr << "fatal: unable to open file '" << file << "'\n"; exit(EXIT_FAILURE); } return stream; } void Serialization(const std::string& out, const sos::Object& object, sos::Serialize* serializer) { std::tr1::shared_ptr<std::ostream> stream = CreateStreamFromName<std::ostream>(out); serializer->process(object, *stream); *stream << std::endl; } sos::Serialize* CreateSerializer(const std::string& format) { if(format == "json") { return new sos::SerializeJSON; } else if(format == "yaml") { return new sos::SerializeYAML; } std::cerr << "fatal: unknow serialization format: '" << format << "'\n"; exit(EXIT_FAILURE); } int main(int argc, const char *argv[]) { Config config; ParseCommadLineOptions(argc, argv, config); sc::BlueprintParserOptions options = 0; // Or snowcrash::RequireBlueprintNameOption if(!config.sourceMap.empty()) { options |= snowcrash::ExportSourcemapOption; } std::stringstream inputStream; std::tr1::shared_ptr<std::istream> in = CreateStreamFromName<std::istream>(config.input); inputStream << in->rdbuf(); sc::ParseResult<sc::Blueprint> blueprint; sc::parse(inputStream.str(), options, blueprint); if (!config.validate) { sos::Serialize* serializer = CreateSerializer(config.format); Serialization(config.output, snowcrash::WrapBlueprint(blueprint.node), serializer ); Serialization(config.sourceMap, snowcrash::WrapBlueprintSourcemap(blueprint.sourceMap), serializer ); delete serializer; } PrintReport(blueprint.report, inputStream.str(), config.lineNumbers); return blueprint.report.error.code; } <commit_msg>* refactoring CreateStreamFromName()<commit_after>// vi:cin:et:sw=4 ts=4 // // drafter.cc // // Created by Jiri Kratochvil on 2015-02-11 // Copyright (c) 2015 Apiary Inc. All rights reserved. // // // #include <string> #include <iostream> #include <sstream> #include <fstream> #include <tr1/memory> #include <tr1/shared_ptr.h> #include "snowcrash.h" #include "SectionParserData.h" // snowcrash::BlueprintParserOptions #include "sos.h" #include "sosJSON.h" #include "sosYAML.h" #include "SerializeAST.h" #include "SerializeSourcemap.h" #include "reporting.h" #include "config.h" namespace sc = snowcrash; template<typename T> struct dummy_deleter { void operator()(T* obj) const { // do nothing } }; template<typename T> struct std_io; template<> struct std_io<std::istream> { static std::istream* io() { return &std::cin; } }; template<> struct std_io<std::ostream> { static std::ostream* io() { return &std::cout; } }; template<typename T> struct std_io_selector { typedef T stream_type; typedef std::tr1::shared_ptr<stream_type> return_type; return_type operator()() { return return_type(std_io<T>::io(), dummy_deleter<stream_type>()); } }; template <typename Stream> struct to_fstream; template<> struct to_fstream<std::istream>{ typedef std::ifstream stream_type; }; template<> struct to_fstream<std::ostream>{ typedef std::ofstream stream_type; }; template<typename T> struct file_io_selector{ typedef typename to_fstream<T>::stream_type stream_type; typedef std::tr1::shared_ptr<stream_type> return_type; return_type operator()(const char* name) const { return return_type(new stream_type(name)); } }; template<typename T> std::tr1::shared_ptr<T> CreateStreamFromName(const std::string& file) { if(file.empty()) { return std_io_selector<T>()(); } typedef typename file_io_selector<T>::return_type return_type; return_type stream = file_io_selector<T>()(file.c_str()); if (!stream->is_open()) { std::cerr << "fatal: unable to open file '" << file << "'\n"; exit(EXIT_FAILURE); } return stream; } void Serialization(const std::string& out, const sos::Object& object, sos::Serialize* serializer) { std::tr1::shared_ptr<std::ostream> stream = CreateStreamFromName<std::ostream>(out); serializer->process(object, *stream); *stream << std::endl; } sos::Serialize* CreateSerializer(const std::string& format) { if(format == "json") { return new sos::SerializeJSON; } else if(format == "yaml") { return new sos::SerializeYAML; } std::cerr << "fatal: unknow serialization format: '" << format << "'\n"; exit(EXIT_FAILURE); } int main(int argc, const char *argv[]) { Config config; ParseCommadLineOptions(argc, argv, config); sc::BlueprintParserOptions options = 0; // Or snowcrash::RequireBlueprintNameOption if(!config.sourceMap.empty()) { options |= snowcrash::ExportSourcemapOption; } std::stringstream inputStream; std::tr1::shared_ptr<std::istream> in = CreateStreamFromName<std::istream>(config.input); inputStream << in->rdbuf(); sc::ParseResult<sc::Blueprint> blueprint; sc::parse(inputStream.str(), options, blueprint); if (!config.validate) { sos::Serialize* serializer = CreateSerializer(config.format); Serialization(config.output, snowcrash::WrapBlueprint(blueprint.node), serializer ); Serialization(config.sourceMap, snowcrash::WrapBlueprintSourcemap(blueprint.sourceMap), serializer ); delete serializer; } PrintReport(blueprint.report, inputStream.str(), config.lineNumbers); return blueprint.report.error.code; } <|endoftext|>
<commit_before>#include "driver.hpp" #include "scanner.hpp" #include "parser.hpp" #include "ast.hpp" #include "codegen.hpp" #include <sstream> #include <vector> #include <cstdlib> #include <getopt.h> #include <fstream> #include <functional> #include <boost/filesystem.hpp> using namespace std; using boost::filesystem::path; lisplike_driver::lisplike_driver() : trace_scanning(false) , trace_parsing(false) { } lisplike_driver::~lisplike_driver() { } bool lisplike_driver::parse_stream(istream& in, const string& sname, std::ostream& out) { streamname = sname; lisplike_scanner scanner(&in); scanner.set_debug(trace_scanning); lexer = &scanner; yy::lisplike_parser parser(*this); parser.set_debug_level(trace_parsing); return parser.parse() == 0; } bool lisplike_driver::parse_string(const string& line, const string& sname, std::ostream& out) { istringstream iss(line); return parse_stream(iss, sname); } bool lisplike_driver::parse_file(const string& filename, std::ostream& out) { ifstream in(filename); if(!in.good()) return false; return parse_stream(in, filename); } void lisplike_driver::error (const yy::location& l, const string& m) { cerr << l << ": " << m << endl; } void lisplike_driver::error (const string& m) { cerr << m << endl; } static vector<string> filenames; static path outdir = "."; bool verbose = false; static bool outfile = true; static bool genheader = true; static bool genmain = true; static void print_usage(int argc, char **argv) { cout << "usage: " << argv[0] << " [opts] [input1 [input2 input3 ...]]" << endl; cout << "opts:" << endl << "-p --trace-parsing traces the Bison parse of the input" << endl << "-s --trace-scanning traces the Lexx scan of the input" << endl << "-o --no-outfile don't generate an output file" << endl << "-h --no-header don't generate a header file" << endl << "-m --no-main don't generate a main file" << endl << "-d --dir [outdir] directory to save output file to" << endl << "-v --verbose verbose output" << endl << "-? --help shows this help message" << endl; } static void parse_args(int argc, char **argv, lisplike_driver &driver) { while(1) { int optindex; static struct option long_options[] = { { "trace-parsing", no_argument, 0, 'p' }, { "trace-scanning", no_argument, 0, 's' }, { "outfile", no_argument, 0, 'o' }, { "gen-header", no_argument, 0, 'h' }, { "gen-main", no_argument, 0, 'm' }, { "dir", required_argument, 0, 'd' }, { "verbose", no_argument, 0, 'v' }, { "help", required_argument, 0, '?' }, { nullptr, 0, 0, 0 }, }; int c = getopt_long(argc, argv, "sphogmd:v", long_options, &optindex); if(c == -1) break; switch(c) { case 's': driver.trace_scanning = true; break; case 'p': driver.trace_parsing = true; break; case 'o': outfile = false; break; case 'h': genheader = false; break; case 'm': genmain = false; break; case 'd': outdir = path(optarg); break; case 'v': verbose = true; break; case '?': print_usage(argc, argv); exit(0); break; default: break; } } while(optind < argc) filenames.push_back(argv[optind++]); for(; optind < argc; optind++) cerr << "ignoring input file: " << argv[optind] << endl; } static int do_codegen(function<string(const ll_children&)> codegen_fn, const ll_children& ast, cstref filename) { path outpath = outdir / (path(filename).filename()); ofstream out_stream(outpath.string()); if(!out_stream.good()) { cerr << "could not open " << outpath << endl; return 1; } VCERR << "generating " << outpath.string() << endl; out_stream << codegen_fn(ast); return 0; } int main(int argc, char **argv) { int mainresult = 0; lisplike_driver driver; parse_args(argc, argv, driver); if(!filenames.empty()) { ll_children ast; if(!create_directory_tree(outdir)) { cerr << "could not create directory tree " << outdir << endl; return 1; } for(auto filename : filenames) { if(!driver.parse_file(filename)) { cerr << "error in " << filename << endl; return 1; } else { ast.insert(ast.end(), driver.ast.begin(), driver.ast.end()); if(outfile) mainresult |= do_codegen(gen_cpp, driver.ast, filename + ".cpp"); if(genheader) mainresult |= do_codegen(gen_header, driver.ast, filename + ".hpp"); } } if(genmain) mainresult |= do_codegen(gen_main, ast, "main.cpp"); if(mainresult == 0) cerr << "OK" << endl; } else { string line; while(getline(cin, line)) { bool result = driver.parse_string(line, "stdin"); if(result) cout << "OK" << endl; } } return mainresult; } <commit_msg>Changed code generation filenames to not include the original file extension<commit_after>#include "driver.hpp" #include "scanner.hpp" #include "parser.hpp" #include "ast.hpp" #include "codegen.hpp" #include <sstream> #include <vector> #include <cstdlib> #include <getopt.h> #include <fstream> #include <functional> #include <boost/filesystem.hpp> using namespace std; using boost::filesystem::path; lisplike_driver::lisplike_driver() : trace_scanning(false) , trace_parsing(false) { } lisplike_driver::~lisplike_driver() { } bool lisplike_driver::parse_stream(istream& in, const string& sname, std::ostream& out) { streamname = sname; lisplike_scanner scanner(&in); scanner.set_debug(trace_scanning); lexer = &scanner; yy::lisplike_parser parser(*this); parser.set_debug_level(trace_parsing); return parser.parse() == 0; } bool lisplike_driver::parse_string(const string& line, const string& sname, std::ostream& out) { istringstream iss(line); return parse_stream(iss, sname); } bool lisplike_driver::parse_file(const string& filename, std::ostream& out) { ifstream in(filename); if(!in.good()) return false; return parse_stream(in, filename); } void lisplike_driver::error (const yy::location& l, const string& m) { cerr << l << ": " << m << endl; } void lisplike_driver::error (const string& m) { cerr << m << endl; } static vector<string> filenames; static path outdir = "."; bool verbose = false; static bool outfile = true; static bool genheader = true; static bool genmain = true; static void print_usage(int argc, char **argv) { cout << "usage: " << argv[0] << " [opts] [input1 [input2 input3 ...]]" << endl; cout << "opts:" << endl << "-p --trace-parsing traces the Bison parse of the input" << endl << "-s --trace-scanning traces the Lexx scan of the input" << endl << "-o --no-outfile don't generate an output file" << endl << "-h --no-header don't generate a header file" << endl << "-m --no-main don't generate a main file" << endl << "-d --dir [outdir] directory to save output file to" << endl << "-v --verbose verbose output" << endl << "-? --help shows this help message" << endl; } static void parse_args(int argc, char **argv, lisplike_driver &driver) { while(1) { int optindex; static struct option long_options[] = { { "trace-parsing", no_argument, 0, 'p' }, { "trace-scanning", no_argument, 0, 's' }, { "outfile", no_argument, 0, 'o' }, { "gen-header", no_argument, 0, 'h' }, { "gen-main", no_argument, 0, 'm' }, { "dir", required_argument, 0, 'd' }, { "verbose", no_argument, 0, 'v' }, { "help", required_argument, 0, '?' }, { nullptr, 0, 0, 0 }, }; int c = getopt_long(argc, argv, "sphogmd:v", long_options, &optindex); if(c == -1) break; switch(c) { case 's': driver.trace_scanning = true; break; case 'p': driver.trace_parsing = true; break; case 'o': outfile = false; break; case 'h': genheader = false; break; case 'm': genmain = false; break; case 'd': outdir = path(optarg); break; case 'v': verbose = true; break; case '?': print_usage(argc, argv); exit(0); break; default: break; } } while(optind < argc) filenames.push_back(argv[optind++]); for(; optind < argc; optind++) cerr << "ignoring input file: " << argv[optind] << endl; } static int do_codegen(function<string(const ll_children&)> codegen_fn, const ll_children& ast, const path& filename) { path outpath = outdir / (path(filename).filename()); ofstream out_stream(outpath.string()); if(!out_stream.good()) { cerr << "could not open " << outpath << endl; return 1; } VCERR << "generating " << outpath.string() << endl; out_stream << codegen_fn(ast); return 0; } int main(int argc, char **argv) { int mainresult = 0; lisplike_driver driver; parse_args(argc, argv, driver); if(!filenames.empty()) { ll_children ast; if(!create_directory_tree(outdir)) { cerr << "could not create directory tree " << outdir << endl; return 1; } for(path filename : filenames) { if(!driver.parse_file(filename.string())) { cerr << "error in " << filename << endl; return 1; } else { ast.insert(ast.end(), driver.ast.begin(), driver.ast.end()); if(outfile) mainresult |= do_codegen(gen_cpp, driver.ast, filename.replace_extension(".cpp")); if(genheader) mainresult |= do_codegen(gen_header, driver.ast, filename.replace_extension(".hpp")); } } if(genmain) mainresult |= do_codegen(gen_main, ast, path("main.cpp")); if(mainresult == 0) cerr << "OK" << endl; } else { string line; while(getline(cin, line)) { bool result = driver.parse_string(line, "stdin"); if(result) cout << "OK" << endl; } } return mainresult; } <|endoftext|>
<commit_before>/* * Convert an input and an output pipe to a duplex socket. * * This code is used in the test cases to convert stdin/stdout to a * single socket. * * author: Max Kellermann <mk@cm4all.com> */ #include "duplex.hxx" #include "system/fd-util.h" #include "system/fd_util.h" #include "event/event2.h" #include "buffered_io.hxx" #include "pool.hxx" #include "fb_pool.hxx" #include "SliceFifoBuffer.hxx" #include <inline/compiler.h> #include <daemon/log.h> #include <sys/socket.h> #include <assert.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <limits.h> struct duplex { int read_fd; int write_fd; int sock_fd; bool sock_eof; SliceFifoBuffer from_read, to_write; struct event2 read_event, write_event, sock_event; }; static void duplex_close(struct duplex *duplex) { if (duplex->read_fd >= 0) { event2_set(&duplex->read_event, 0); if (duplex->read_fd > 2) close(duplex->read_fd); duplex->read_fd = -1; } if (duplex->write_fd >= 0) { event2_set(&duplex->write_event, 0); if (duplex->write_fd > 2) close(duplex->write_fd); duplex->write_fd = -1; } if (duplex->sock_fd >= 0) { event2_set(&duplex->sock_event, 0); event2_commit(&duplex->sock_event); close(duplex->sock_fd); duplex->sock_fd = -1; } duplex->from_read.Free(fb_pool_get()); duplex->to_write.Free(fb_pool_get()); } static bool duplex_check_close(struct duplex *duplex) { if (duplex->read_fd < 0 && duplex->sock_eof && duplex->from_read.IsEmpty() && duplex->to_write.IsEmpty()) { duplex_close(duplex); return true; } else return false; } static void read_event_callback(int fd, short event gcc_unused, void *ctx) { struct duplex *duplex = (struct duplex *)ctx; assert((event & EV_READ) != 0); event2_reset(&duplex->read_event); ssize_t nbytes = read_to_buffer(fd, duplex->from_read, INT_MAX); if (nbytes == -1) { daemon_log(1, "failed to read: %s\n", strerror(errno)); duplex_close(duplex); return; } if (nbytes == 0) { close(fd); duplex->read_fd = -1; if (duplex_check_close(duplex)) return; } if (nbytes > 0) event2_or(&duplex->sock_event, EV_WRITE); if (duplex->read_fd >= 0 && !duplex->from_read.IsFull()) event2_or(&duplex->read_event, EV_READ); } static void write_event_callback(int fd, short event gcc_unused, void *ctx) { struct duplex *duplex = (struct duplex *)ctx; assert((event & EV_WRITE) != 0); event2_reset(&duplex->write_event); ssize_t nbytes = write_from_buffer(fd, duplex->to_write); if (nbytes == -1) { duplex_close(duplex); return; } if (nbytes > 0 && !duplex->sock_eof) event2_or(&duplex->sock_event, EV_READ); if (!duplex->to_write.IsEmpty()) event2_or(&duplex->write_event, EV_WRITE); } static void sock_event_callback(int fd, short event, void *ctx) { struct duplex *duplex = (struct duplex *)ctx; event2_lock(&duplex->sock_event); event2_occurred_persist(&duplex->sock_event, event); if ((event & EV_READ) != 0) { ssize_t nbytes = recv_to_buffer(fd, duplex->to_write, INT_MAX); if (nbytes == -1) { daemon_log(1, "failed to read: %s\n", strerror(errno)); duplex_close(duplex); return; } if (nbytes == 0) { duplex->sock_eof = true; if (duplex_check_close(duplex)) return; } if (likely(nbytes > 0)) event2_or(&duplex->write_event, EV_WRITE); if (!duplex->to_write.IsFull()) event2_or(&duplex->sock_event, EV_READ); } if ((event & EV_WRITE) != 0) { ssize_t nbytes = send_from_buffer(fd, duplex->from_read); if (nbytes == -1) { duplex_close(duplex); return; } if (nbytes > 0 && duplex->read_fd >= 0) event2_or(&duplex->read_event, EV_READ); if (!duplex->from_read.IsEmpty()) event2_or(&duplex->sock_event, EV_WRITE); } event2_unlock(&duplex->sock_event); } int duplex_new(struct pool *pool, int read_fd, int write_fd) { assert(pool != nullptr); assert(read_fd >= 0); assert(write_fd >= 0); int fds[2]; if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fds) < 0) return -1; if (fd_set_nonblock(fds[1], 1) < 0) { int save_errno = errno; close(fds[0]); close(fds[1]); errno = save_errno; return -1; } auto duplex = NewFromPool<struct duplex>(*pool); duplex->read_fd = read_fd; duplex->write_fd = write_fd; duplex->sock_fd = fds[0]; duplex->sock_eof = false; duplex->from_read.Allocate(fb_pool_get()); duplex->to_write.Allocate(fb_pool_get()); event2_init(&duplex->read_event, read_fd, read_event_callback, duplex, nullptr); event2_set(&duplex->read_event, EV_READ); event2_init(&duplex->write_event, write_fd, write_event_callback, duplex, nullptr); event2_init(&duplex->sock_event, duplex->sock_fd, sock_event_callback, duplex, nullptr); event2_persist(&duplex->sock_event); event2_set(&duplex->sock_event, EV_READ); return fds[1]; } <commit_msg>duplex: upper case struct name<commit_after>/* * Convert an input and an output pipe to a duplex socket. * * This code is used in the test cases to convert stdin/stdout to a * single socket. * * author: Max Kellermann <mk@cm4all.com> */ #include "duplex.hxx" #include "system/fd-util.h" #include "system/fd_util.h" #include "event/event2.h" #include "buffered_io.hxx" #include "pool.hxx" #include "fb_pool.hxx" #include "SliceFifoBuffer.hxx" #include <inline/compiler.h> #include <daemon/log.h> #include <sys/socket.h> #include <assert.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <limits.h> struct Duplex { int read_fd; int write_fd; int sock_fd; bool sock_eof; SliceFifoBuffer from_read, to_write; struct event2 read_event, write_event, sock_event; }; static void duplex_close(Duplex *duplex) { if (duplex->read_fd >= 0) { event2_set(&duplex->read_event, 0); if (duplex->read_fd > 2) close(duplex->read_fd); duplex->read_fd = -1; } if (duplex->write_fd >= 0) { event2_set(&duplex->write_event, 0); if (duplex->write_fd > 2) close(duplex->write_fd); duplex->write_fd = -1; } if (duplex->sock_fd >= 0) { event2_set(&duplex->sock_event, 0); event2_commit(&duplex->sock_event); close(duplex->sock_fd); duplex->sock_fd = -1; } duplex->from_read.Free(fb_pool_get()); duplex->to_write.Free(fb_pool_get()); } static bool duplex_check_close(Duplex *duplex) { if (duplex->read_fd < 0 && duplex->sock_eof && duplex->from_read.IsEmpty() && duplex->to_write.IsEmpty()) { duplex_close(duplex); return true; } else return false; } static void read_event_callback(int fd, short event gcc_unused, void *ctx) { Duplex *duplex = (Duplex *)ctx; assert((event & EV_READ) != 0); event2_reset(&duplex->read_event); ssize_t nbytes = read_to_buffer(fd, duplex->from_read, INT_MAX); if (nbytes == -1) { daemon_log(1, "failed to read: %s\n", strerror(errno)); duplex_close(duplex); return; } if (nbytes == 0) { close(fd); duplex->read_fd = -1; if (duplex_check_close(duplex)) return; } if (nbytes > 0) event2_or(&duplex->sock_event, EV_WRITE); if (duplex->read_fd >= 0 && !duplex->from_read.IsFull()) event2_or(&duplex->read_event, EV_READ); } static void write_event_callback(int fd, short event gcc_unused, void *ctx) { Duplex *duplex = (Duplex *)ctx; assert((event & EV_WRITE) != 0); event2_reset(&duplex->write_event); ssize_t nbytes = write_from_buffer(fd, duplex->to_write); if (nbytes == -1) { duplex_close(duplex); return; } if (nbytes > 0 && !duplex->sock_eof) event2_or(&duplex->sock_event, EV_READ); if (!duplex->to_write.IsEmpty()) event2_or(&duplex->write_event, EV_WRITE); } static void sock_event_callback(int fd, short event, void *ctx) { Duplex *duplex = (Duplex *)ctx; event2_lock(&duplex->sock_event); event2_occurred_persist(&duplex->sock_event, event); if ((event & EV_READ) != 0) { ssize_t nbytes = recv_to_buffer(fd, duplex->to_write, INT_MAX); if (nbytes == -1) { daemon_log(1, "failed to read: %s\n", strerror(errno)); duplex_close(duplex); return; } if (nbytes == 0) { duplex->sock_eof = true; if (duplex_check_close(duplex)) return; } if (likely(nbytes > 0)) event2_or(&duplex->write_event, EV_WRITE); if (!duplex->to_write.IsFull()) event2_or(&duplex->sock_event, EV_READ); } if ((event & EV_WRITE) != 0) { ssize_t nbytes = send_from_buffer(fd, duplex->from_read); if (nbytes == -1) { duplex_close(duplex); return; } if (nbytes > 0 && duplex->read_fd >= 0) event2_or(&duplex->read_event, EV_READ); if (!duplex->from_read.IsEmpty()) event2_or(&duplex->sock_event, EV_WRITE); } event2_unlock(&duplex->sock_event); } int duplex_new(struct pool *pool, int read_fd, int write_fd) { assert(pool != nullptr); assert(read_fd >= 0); assert(write_fd >= 0); int fds[2]; if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fds) < 0) return -1; if (fd_set_nonblock(fds[1], 1) < 0) { int save_errno = errno; close(fds[0]); close(fds[1]); errno = save_errno; return -1; } auto duplex = NewFromPool<Duplex>(*pool); duplex->read_fd = read_fd; duplex->write_fd = write_fd; duplex->sock_fd = fds[0]; duplex->sock_eof = false; duplex->from_read.Allocate(fb_pool_get()); duplex->to_write.Allocate(fb_pool_get()); event2_init(&duplex->read_event, read_fd, read_event_callback, duplex, nullptr); event2_set(&duplex->read_event, EV_READ); event2_init(&duplex->write_event, write_fd, write_event_callback, duplex, nullptr); event2_init(&duplex->sock_event, duplex->sock_fd, sock_event_callback, duplex, nullptr); event2_persist(&duplex->sock_event); event2_set(&duplex->sock_event, EV_READ); return fds[1]; } <|endoftext|>
<commit_before>#include "fast++.hpp" #include <vif/core/main.hpp> const char* fastpp_version = "1.2"; const constexpr uint_t grid_id::z; const constexpr uint_t grid_id::av; const constexpr uint_t grid_id::age; const constexpr uint_t grid_id::metal; const constexpr uint_t grid_id::custom; const constexpr uint_t prop_id::scale; const constexpr uint_t prop_id::spec_scale; const constexpr uint_t prop_id::mass; const constexpr uint_t prop_id::sfr; const constexpr uint_t prop_id::ssfr; const constexpr uint_t prop_id::ldust; const constexpr uint_t prop_id::lion; const constexpr uint_t prop_id::mform; const constexpr uint_t prop_id::custom; const constexpr uint_t log_style::none; const constexpr uint_t log_style::decimal; const constexpr uint_t log_style::abmag; int vif_main(int argc, char* argv[]) { std::string param_file = (argc >= 2 ? argv[1] : "fast.param"); // Read input data options_t opts; input_state_t input; if (!read_input(opts, input, param_file)) { return 1; } // Initialize the grid output_state_t output; gridder_t gridder(opts, input, output); if (!gridder.check_options()) { return 1; } if (!opts.make_seds.empty()) { // Write SEDs if asked, then terminate gridder.write_seds(); return 0; } if (gridder.read_from_cache && opts.parallel == parallel_choice::generators && opts.n_thread > 0) { if (opts.verbose) { note("using cache, switched parallel execution from 'generators' to 'models'"); } opts.parallel = parallel_choice::models; } // Initizalize the fitter fitter_t fitter(opts, input, gridder, output); // Build/read the grid and fit galaxies if (!gridder.build_and_send(fitter)) { return 1; } // Compile results fitter.find_best_fits(); // Write output to disk write_output(opts, input, gridder, fitter, output); return 0; } <commit_msg>Increased version number<commit_after>#include "fast++.hpp" #include <vif/core/main.hpp> const char* fastpp_version = "1.3-git"; const constexpr uint_t grid_id::z; const constexpr uint_t grid_id::av; const constexpr uint_t grid_id::age; const constexpr uint_t grid_id::metal; const constexpr uint_t grid_id::custom; const constexpr uint_t prop_id::scale; const constexpr uint_t prop_id::spec_scale; const constexpr uint_t prop_id::mass; const constexpr uint_t prop_id::sfr; const constexpr uint_t prop_id::ssfr; const constexpr uint_t prop_id::ldust; const constexpr uint_t prop_id::lion; const constexpr uint_t prop_id::mform; const constexpr uint_t prop_id::custom; const constexpr uint_t log_style::none; const constexpr uint_t log_style::decimal; const constexpr uint_t log_style::abmag; int vif_main(int argc, char* argv[]) { std::string param_file = (argc >= 2 ? argv[1] : "fast.param"); // Read input data options_t opts; input_state_t input; if (!read_input(opts, input, param_file)) { return 1; } // Initialize the grid output_state_t output; gridder_t gridder(opts, input, output); if (!gridder.check_options()) { return 1; } if (!opts.make_seds.empty()) { // Write SEDs if asked, then terminate gridder.write_seds(); return 0; } if (gridder.read_from_cache && opts.parallel == parallel_choice::generators && opts.n_thread > 0) { if (opts.verbose) { note("using cache, switched parallel execution from 'generators' to 'models'"); } opts.parallel = parallel_choice::models; } // Initizalize the fitter fitter_t fitter(opts, input, gridder, output); // Build/read the grid and fit galaxies if (!gridder.build_and_send(fitter)) { return 1; } // Compile results fitter.find_best_fits(); // Write output to disk write_output(opts, input, gridder, fitter, output); return 0; } <|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 "mitkPASpectralUnmixingFilterBase.h" // Includes for AddEnmemberMatrix #include "mitkPAPropertyCalculator.h" #include <eigen3/Eigen/Dense> // ImageAccessor #include <mitkImageReadAccessor.h> #include <mitkImageWriteAccessor.h> mitk::pa::SpectralUnmixingFilterBase::SpectralUnmixingFilterBase() { this->SetNumberOfIndexedOutputs(4);// find solution for (unsigned int i = 0; i<GetNumberOfIndexedOutputs(); i++) { this->SetNthOutput(i, mitk::Image::New()); } m_PropertyCalculatorEigen = mitk::pa::PropertyCalculator::New(); } mitk::pa::SpectralUnmixingFilterBase::~SpectralUnmixingFilterBase() { } void mitk::pa::SpectralUnmixingFilterBase::AddWavelength(int wavelength) { m_Wavelength.push_back(wavelength); } void mitk::pa::SpectralUnmixingFilterBase::AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType chromophore) { m_Chromophore.push_back(chromophore); } void mitk::pa::SpectralUnmixingFilterBase::GenerateData() { MITK_INFO << "GENERATING DATA.."; // Get input image mitk::Image::Pointer input = GetInput(0); unsigned int xDim = input->GetDimensions()[0]; unsigned int yDim = input->GetDimensions()[1]; unsigned int zDim = input->GetDimensions()[2]; unsigned int size = xDim * yDim * zDim; MITK_INFO << "x dimension: " << xDim; MITK_INFO << "y dimension: " << yDim; MITK_INFO << "z dimension: " << zDim; InitializeOutputs(); auto EndmemberMatrix = CalculateEndmemberMatrix(m_Chromophore, m_Wavelength); //Eigen Endmember Matrix // Copy input image into array mitk::ImageReadAccessor readAccess(input); const float* inputDataArray = ((const float*)readAccess.GetData()); CheckPreConditions(size, zDim, inputDataArray); /* READ OUT INPUTARRAY MITK_INFO << "Info Array:"; int numberOfPixels= 6; for (int i=0; i< numberOfPixels; ++i) MITK_INFO << inputDataArray[i];/**/ // test to see pixel values @ txt file ofstream myfile; myfile.open("PASpectralUnmixingPixelValues.txt"); //loop over every pixel @ x,y plane for (unsigned int x = 0; x < xDim; x++) { for (unsigned int y = 0; y < yDim; y++) { Eigen::VectorXf inputVector(zDim); for (unsigned int z = 0; z < zDim; z++) { // Get pixel value of pixel x,y @ wavelength z unsigned int pixelNumber = (xDim*yDim*z) + x * yDim + y; auto pixel = inputDataArray[pixelNumber]; //MITK_INFO << "Pixel_values: " << pixel; // dummy values for pixel for testing purposes //float pixel = rand(); //write all wavelength absorbtion values for one(!) pixel to a vector inputVector[z] = pixel; } Eigen::VectorXf resultVector = SpectralUnmixingAlgorithm(EndmemberMatrix, inputVector); //Eigen::VectorXf resultVector = SpectralUnmixingAlgorithm(m_Chromophore, inputVector); // write output for (int outputIdx = 0; outputIdx < GetNumberOfIndexedOutputs(); ++outputIdx) { auto output = GetOutput(outputIdx); mitk::ImageWriteAccessor writeOutput(output); float* writeBuffer = (float *)writeOutput.GetData(); writeBuffer[x*yDim + y] = resultVector[outputIdx]; } myfile << "Input Pixel(x,y): " << x << "," << y << "\n" << inputVector << "\n"; myfile << "Result: " << "\n HbO2: " << resultVector[0] << "\n Hb: " << resultVector[1] << "\n Mel: " << resultVector[2] << "Result vector size" << resultVector.size() << "\n"; } } MITK_INFO << "GENERATING DATA...[DONE]"; myfile.close(); } void mitk::pa::SpectralUnmixingFilterBase::CheckPreConditions(unsigned int size, unsigned int NumberOfInputImages, const float* inputDataArray) { // Checking if number of Inputs == added wavelengths if (m_Wavelength.size() != NumberOfInputImages) mitkThrow() << "CHECK INPUTS! WAVELENGTHERROR"; // Checking if number of wavelengths >= number of chromophores if (m_Chromophore.size() > m_Wavelength.size()) mitkThrow() << "PRESS 'IGNORE' AND ADD MORE WAVELENGTHS!"; // Checking if pixel type is float int maxPixel = size; for (int i = 0; i < maxPixel; ++i) { if (typeid(inputDataArray[i]).name() != typeid(float).name()) { mitkThrow() << "PIXELTYPE ERROR! FLOAT 32 REQUIRED"; } else continue; } MITK_INFO << "CHECK PRECONDITIONS ...[DONE]"; } void mitk::pa::SpectralUnmixingFilterBase::InitializeOutputs() { unsigned int numberOfInputs = GetNumberOfIndexedInputs(); unsigned int numberOfOutputs = GetNumberOfIndexedOutputs(); //MITK_INFO << "Inputs: " << numberOfInputs << " Outputs: " << numberOfOutputs; // Set dimensions (2) and pixel type (float) for output mitk::PixelType pixelType = mitk::MakeScalarPixelType<float>(); const int NUMBER_OF_SPATIAL_DIMENSIONS = 2; auto* dimensions = new unsigned int[NUMBER_OF_SPATIAL_DIMENSIONS]; for(unsigned int dimIdx=0; dimIdx<NUMBER_OF_SPATIAL_DIMENSIONS; dimIdx++) { dimensions[dimIdx] = GetInput()->GetDimensions()[dimIdx]; } // Initialize numberOfOutput pictures with pixel type and dimensions for (unsigned int outputIdx = 0; outputIdx < numberOfOutputs; outputIdx++) { GetOutput(outputIdx)->Initialize(pixelType, NUMBER_OF_SPATIAL_DIMENSIONS, dimensions); } } //Matrix with #chromophores colums and #wavelengths rows //so Matrix Element (i,j) contains the Absorbtion of chromophore j @ wavelength i Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> mitk::pa::SpectralUnmixingFilterBase::CalculateEndmemberMatrix( std::vector<mitk::pa::PropertyCalculator::ChromophoreType> m_Chromophore, std::vector<int> m_Wavelength) { unsigned int numberOfChromophores = m_Chromophore.size(); //columns unsigned int numberOfWavelengths = m_Wavelength.size(); //rows Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> EndmemberMatrixEigen(numberOfWavelengths, numberOfChromophores); for (unsigned int j = 0; j < numberOfChromophores; ++j) { if (m_Chromophore[j] == mitk::pa::PropertyCalculator::ChromophoreType::OXYGENATED) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) EndmemberMatrixEigen(i, j) = propertyElement(m_Chromophore[j], m_Wavelength[i]); } else if (m_Chromophore[j] == mitk::pa::PropertyCalculator::ChromophoreType::DEOXYGENATED) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) EndmemberMatrixEigen(i, j) = propertyElement(m_Chromophore[j], m_Wavelength[i]); } else if (m_Chromophore[j] == mitk::pa::PropertyCalculator::ChromophoreType::MELANIN) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) { EndmemberMatrixEigen(i, j) = propertyElement(m_Chromophore[j], m_Wavelength[i]); MITK_INFO << "MELANIN " << EndmemberMatrixEigen(i, j); } } else if (m_Chromophore[j] == mitk::pa::PropertyCalculator::ChromophoreType::ONEENDMEMBER) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) EndmemberMatrixEigen(i, j) = 1; } else mitkThrow() << "404 CHROMOPHORE NOT FOUND!"; } MITK_INFO << "GENERATING ENMEMBERMATRIX [DONE]!"; MITK_INFO << "endmember matrix: " << EndmemberMatrixEigen; return EndmemberMatrixEigen; } float mitk::pa::SpectralUnmixingFilterBase::propertyElement(mitk::pa::PropertyCalculator::ChromophoreType Chromophore, int Wavelength) { float value = m_PropertyCalculatorEigen->GetAbsorptionForWavelength(Chromophore, Wavelength); if (value == 0) mitkThrow() << "WAVELENGTH " << Wavelength << "nm NOT SUPPORTED!"; return value; } <commit_msg>add chrono.<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 "mitkPASpectralUnmixingFilterBase.h" // Includes for AddEnmemberMatrix #include "mitkPAPropertyCalculator.h" #include <eigen3/Eigen/Dense> // ImageAccessor #include <mitkImageReadAccessor.h> #include <mitkImageWriteAccessor.h> #include <chrono> mitk::pa::SpectralUnmixingFilterBase::SpectralUnmixingFilterBase() { this->SetNumberOfIndexedOutputs(4);// find solution for (unsigned int i = 0; i<GetNumberOfIndexedOutputs(); i++) { this->SetNthOutput(i, mitk::Image::New()); } m_PropertyCalculatorEigen = mitk::pa::PropertyCalculator::New(); } mitk::pa::SpectralUnmixingFilterBase::~SpectralUnmixingFilterBase() { } void mitk::pa::SpectralUnmixingFilterBase::AddWavelength(int wavelength) { m_Wavelength.push_back(wavelength); } void mitk::pa::SpectralUnmixingFilterBase::AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType chromophore) { m_Chromophore.push_back(chromophore); } void mitk::pa::SpectralUnmixingFilterBase::GenerateData() { MITK_INFO << "GENERATING DATA.."; // Get input image mitk::Image::Pointer input = GetInput(0); unsigned int xDim = input->GetDimensions()[0]; unsigned int yDim = input->GetDimensions()[1]; unsigned int zDim = input->GetDimensions()[2]; unsigned int size = xDim * yDim * zDim; MITK_INFO << "x dimension: " << xDim; MITK_INFO << "y dimension: " << yDim; MITK_INFO << "z dimension: " << zDim; InitializeOutputs(); auto EndmemberMatrix = CalculateEndmemberMatrix(m_Chromophore, m_Wavelength); //Eigen Endmember Matrix // Copy input image into array mitk::ImageReadAccessor readAccess(input); const float* inputDataArray = ((const float*)readAccess.GetData()); CheckPreConditions(size, zDim, inputDataArray); /* READ OUT INPUTARRAY MITK_INFO << "Info Array:"; int numberOfPixels= 6; for (int i=0; i< numberOfPixels; ++i) MITK_INFO << inputDataArray[i];/**/ // test to see pixel values @ txt file ofstream myfile; myfile.open("PASpectralUnmixingPixelValues.txt"); std::chrono::steady_clock::time_point _start(std::chrono::steady_clock::now()); //loop over every pixel @ x,y plane for (unsigned int x = 0; x < xDim; x++) { for (unsigned int y = 0; y < yDim; y++) { Eigen::VectorXf inputVector(zDim); for (unsigned int z = 0; z < zDim; z++) { // Get pixel value of pixel x,y @ wavelength z unsigned int pixelNumber = (xDim*yDim*z) + x * yDim + y; auto pixel = inputDataArray[pixelNumber]; //MITK_INFO << "Pixel_values: " << pixel; // dummy values for pixel for testing purposes //float pixel = rand(); //write all wavelength absorbtion values for one(!) pixel to a vector inputVector[z] = pixel; } Eigen::VectorXf resultVector = SpectralUnmixingAlgorithm(EndmemberMatrix, inputVector); //Eigen::VectorXf resultVector = SpectralUnmixingAlgorithm(m_Chromophore, inputVector); // write output for (int outputIdx = 0; outputIdx < GetNumberOfIndexedOutputs(); ++outputIdx) { auto output = GetOutput(outputIdx); mitk::ImageWriteAccessor writeOutput(output); float* writeBuffer = (float *)writeOutput.GetData(); writeBuffer[x*yDim + y] = resultVector[outputIdx]; } myfile << "Input Pixel(x,y): " << x << "," << y << "\n" << inputVector << "\n"; myfile << "Result: " << "\n HbO2: " << resultVector[0] << "\n Hb: " << resultVector[1] << "\n Mel: " << resultVector[2] << "Result vector size" << resultVector.size() << "\n"; } } std::chrono::steady_clock::time_point _end(std::chrono::steady_clock::now()); MITK_INFO << "GENERATING DATA...[DONE]"; myfile.close(); MITK_INFO << "Chrono: " << std::chrono::duration_cast<std::chrono::duration<double>>( _end - _start).count() << "s"; } void mitk::pa::SpectralUnmixingFilterBase::CheckPreConditions(unsigned int size, unsigned int NumberOfInputImages, const float* inputDataArray) { // Checking if number of Inputs == added wavelengths if (m_Wavelength.size() != NumberOfInputImages) mitkThrow() << "CHECK INPUTS! WAVELENGTHERROR"; // Checking if number of wavelengths >= number of chromophores if (m_Chromophore.size() > m_Wavelength.size()) mitkThrow() << "PRESS 'IGNORE' AND ADD MORE WAVELENGTHS!"; // Checking if pixel type is float int maxPixel = size; for (int i = 0; i < maxPixel; ++i) { if (typeid(inputDataArray[i]).name() != typeid(float).name()) { mitkThrow() << "PIXELTYPE ERROR! FLOAT 32 REQUIRED"; } else continue; } MITK_INFO << "CHECK PRECONDITIONS ...[DONE]"; } void mitk::pa::SpectralUnmixingFilterBase::InitializeOutputs() { unsigned int numberOfInputs = GetNumberOfIndexedInputs(); unsigned int numberOfOutputs = GetNumberOfIndexedOutputs(); //MITK_INFO << "Inputs: " << numberOfInputs << " Outputs: " << numberOfOutputs; // Set dimensions (2) and pixel type (float) for output mitk::PixelType pixelType = mitk::MakeScalarPixelType<float>(); const int NUMBER_OF_SPATIAL_DIMENSIONS = 2; auto* dimensions = new unsigned int[NUMBER_OF_SPATIAL_DIMENSIONS]; for(unsigned int dimIdx=0; dimIdx<NUMBER_OF_SPATIAL_DIMENSIONS; dimIdx++) { dimensions[dimIdx] = GetInput()->GetDimensions()[dimIdx]; } // Initialize numberOfOutput pictures with pixel type and dimensions for (unsigned int outputIdx = 0; outputIdx < numberOfOutputs; outputIdx++) { GetOutput(outputIdx)->Initialize(pixelType, NUMBER_OF_SPATIAL_DIMENSIONS, dimensions); } } //Matrix with #chromophores colums and #wavelengths rows //so Matrix Element (i,j) contains the Absorbtion of chromophore j @ wavelength i Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> mitk::pa::SpectralUnmixingFilterBase::CalculateEndmemberMatrix( std::vector<mitk::pa::PropertyCalculator::ChromophoreType> m_Chromophore, std::vector<int> m_Wavelength) { unsigned int numberOfChromophores = m_Chromophore.size(); //columns unsigned int numberOfWavelengths = m_Wavelength.size(); //rows Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> EndmemberMatrixEigen(numberOfWavelengths, numberOfChromophores); for (unsigned int j = 0; j < numberOfChromophores; ++j) { if (m_Chromophore[j] == mitk::pa::PropertyCalculator::ChromophoreType::OXYGENATED) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) EndmemberMatrixEigen(i, j) = propertyElement(m_Chromophore[j], m_Wavelength[i]); } else if (m_Chromophore[j] == mitk::pa::PropertyCalculator::ChromophoreType::DEOXYGENATED) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) EndmemberMatrixEigen(i, j) = propertyElement(m_Chromophore[j], m_Wavelength[i]); } else if (m_Chromophore[j] == mitk::pa::PropertyCalculator::ChromophoreType::MELANIN) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) { EndmemberMatrixEigen(i, j) = propertyElement(m_Chromophore[j], m_Wavelength[i]); MITK_INFO << "MELANIN " << EndmemberMatrixEigen(i, j); } } else if (m_Chromophore[j] == mitk::pa::PropertyCalculator::ChromophoreType::ONEENDMEMBER) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) EndmemberMatrixEigen(i, j) = 1; } else mitkThrow() << "404 CHROMOPHORE NOT FOUND!"; } MITK_INFO << "GENERATING ENMEMBERMATRIX [DONE]!"; MITK_INFO << "endmember matrix: " << EndmemberMatrixEigen; return EndmemberMatrixEigen; } float mitk::pa::SpectralUnmixingFilterBase::propertyElement(mitk::pa::PropertyCalculator::ChromophoreType Chromophore, int Wavelength) { float value = m_PropertyCalculatorEigen->GetAbsorptionForWavelength(Chromophore, Wavelength); if (value == 0) mitkThrow() << "WAVELENGTH " << Wavelength << "nm NOT SUPPORTED!"; return value; } <|endoftext|>
<commit_before>// Time: O(nlogn) // Space: O(n) // BST solution. class Solution { public: /** * @param buildings: A list of lists of integers * @return: Find the outline of those buildings */ vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) { unordered_map<int, vector<int>> start_point_to_heights; unordered_map<int, vector<int>> end_point_to_heights; set<int> points; for (int i = 0; i < buildings.size(); ++i) { start_point_to_heights[buildings[i][0]].emplace_back(buildings[i][2]); end_point_to_heights[buildings[i][1]].emplace_back(buildings[i][2]); points.emplace(buildings[i][0]); points.emplace(buildings[i][1]); } vector<vector<int>> res; map<int, int> height_to_count; int curr_start = -1; int curr_max = 0; // Enumerate each point in increasing order. for (auto it = points.begin(); it != points.end(); ++it) { vector<int> start_point_heights = start_point_to_heights[*it]; vector<int> end_point_heights = end_point_to_heights[*it]; for (int i = 0; i < start_point_heights.size(); ++i) { ++height_to_count[start_point_heights[i]]; } for (int i = 0; i < end_point_heights.size(); ++i) { --height_to_count[end_point_heights[i]]; if (height_to_count[end_point_heights[i]] == 0) { height_to_count.erase(end_point_heights[i]); } } if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { if (curr_max > 0) { res.emplace_back(move(vector<int>{curr_start, *it, curr_max})); } curr_start = *it; curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; } } return res; } }; // Time: O(nlogn) // Space: O(n) // Divide and conquer solution. class Solution2 { public: enum {start, end, height}; /** * @param buildings: A list of lists of integers * @return: Find the outline of those buildings */ vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) { return ComputeSkylineInInterval(buildings, 0, buildings.size()); } // Divide and Conquer. vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings, int left_endpoint, int right_endpoint) { if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it. return {buildings.cbegin() + left_endpoint, buildings.cbegin() + right_endpoint}; } int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2); auto left_skyline = move(ComputeSkylineInInterval(buildings, left_endpoint, mid)); auto right_skyline = move(ComputeSkylineInInterval(buildings, mid, right_endpoint)); return MergeSkylines(left_skyline, right_skyline); } // Merge Sort vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) { int i = 0, j = 0; vector<vector<int>> merged; while (i < left_skyline.size() && j < right_skyline.size()) { if (left_skyline[i][end] < right_skyline[j][start]) { merged.emplace_back(move(left_skyline[i++])); } else if (right_skyline[j][end] < left_skyline[i][start]) { merged.emplace_back(move(right_skyline[j++])); } else if (left_skyline[i][start] <= right_skyline[j][start]) { MergeIntersectSkylines(merged, left_skyline[i], i, right_skyline[j], j); } else { // left_skyline[i][start] > right_skyline[j][start]. MergeIntersectSkylines(merged, right_skyline[j], j, left_skyline[i], i); } } // Insert the remaining skylines. merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end()); merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end()); return merged; } // a[start] <= b[start] void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx, vector<int>& b, int& b_idx) { if (a[end] <= b[end]) { if (a[height] > b[height]) { // |aaa| if (b[end] != a[end]) { // |abb|b b[start] = a[end]; merged.emplace_back(move(a)), ++a_idx; } else { // aaa ++b_idx; // abb } } else if (a[height] == b[height]) { // abb b[start] = a[start], ++a_idx; // abb } else { // a[height] < b[height]. if (a[start] != b[start]) { // bb merged.emplace_back(move(vector<int>{a[start], b[start], a[height]})); // |a|bb } ++a_idx; } } else { // a[end] > b[end]. if (a[height] >= b[height]) { // aaaa ++b_idx; // abba } else { // |bb| // |a||bb|a if (a[start] != b[start]) { merged.emplace_back(move(vector<int>{a[start], b[start], a[height]})); } a[start] = b[end]; merged.emplace_back(move(b)), ++b_idx; } } } }; <commit_msg>Update building-outline.cpp<commit_after>// Time: O(nlogn) // Space: O(n) // BST solution. class Solution { public: /** * @param buildings: A list of lists of integers * @return: Find the outline of those buildings */ vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) { unordered_map<int, vector<int>> start_point_to_heights; unordered_map<int, vector<int>> end_point_to_heights; set<int> points; for (int i = 0; i < buildings.size(); ++i) { start_point_to_heights[buildings[i][0]].emplace_back(buildings[i][2]); end_point_to_heights[buildings[i][1]].emplace_back(buildings[i][2]); points.emplace(buildings[i][0]); points.emplace(buildings[i][1]); } vector<vector<int>> res; map<int, int> height_to_count; int curr_start = -1; int curr_max = 0; // Enumerate each point in increasing order. for (auto it = points.begin(); it != points.end(); ++it) { vector<int> start_point_heights = start_point_to_heights[*it]; vector<int> end_point_heights = end_point_to_heights[*it]; for (int i = 0; i < start_point_heights.size(); ++i) { ++height_to_count[start_point_heights[i]]; } for (int i = 0; i < end_point_heights.size(); ++i) { --height_to_count[end_point_heights[i]]; if (height_to_count[end_point_heights[i]] == 0) { height_to_count.erase(end_point_heights[i]); } } if (height_to_count.empty() || curr_max != height_to_count.rbegin()->first) { if (curr_max > 0) { res.emplace_back(move(vector<int>{curr_start, *it, curr_max})); } curr_start = *it; curr_max = height_to_count.empty() ? 0 : height_to_count.rbegin()->first; } } return res; } }; // Time: O(nlogn) // Space: O(n) // Divide and conquer solution. class Solution2 { public: enum {start, end, height}; /** * @param buildings: A list of lists of integers * @return: Find the outline of those buildings */ vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) { return ComputeSkylineInInterval(buildings, 0, buildings.size()); } // Divide and Conquer. vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings, int left_endpoint, int right_endpoint) { if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it. return {buildings.cbegin() + left_endpoint, buildings.cbegin() + right_endpoint}; } int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2); auto left_skyline = move(ComputeSkylineInInterval(buildings, left_endpoint, mid)); auto right_skyline = move(ComputeSkylineInInterval(buildings, mid, right_endpoint)); return MergeSkylines(left_skyline, right_skyline); } // Merge Sort vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) { int i = 0, j = 0; vector<vector<int>> merged; while (i < left_skyline.size() && j < right_skyline.size()) { if (left_skyline[i][end] < right_skyline[j][start]) { merged.emplace_back(move(left_skyline[i++])); } else if (right_skyline[j][end] < left_skyline[i][start]) { merged.emplace_back(move(right_skyline[j++])); } else if (left_skyline[i][start] <= right_skyline[j][start]) { MergeIntersectSkylines(merged, left_skyline[i], i, right_skyline[j], j); } else { // left_skyline[i][start] > right_skyline[j][start]. MergeIntersectSkylines(merged, right_skyline[j], j, left_skyline[i], i); } } // Insert the remaining skylines. merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end()); merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end()); return merged; } // a[start] <= b[start] void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx, vector<int>& b, int& b_idx) { if (a[end] <= b[end]) { if (a[height] > b[height]) { // |aaa| if (b[end] != a[end]) { // |abb|b b[start] = a[end]; merged.emplace_back(move(a)), ++a_idx; } else { // aaa ++b_idx; // abb } } else if (a[height] == b[height]) { // abb b[start] = a[start], ++a_idx; // abb } else { // a[height] < b[height]. if (a[start] != b[start]) { // bb merged.emplace_back(move(vector<int>{a[start], b[start], a[height]})); // |a|bb } ++a_idx; } } else { // a[end] > b[end]. if (a[height] >= b[height]) { // aaaa ++b_idx; // abba } else { // |bb| // |a||bb|a if (a[start] != b[start]) { merged.emplace_back(move(vector<int>{a[start], b[start], a[height]})); } a[start] = b[end]; merged.emplace_back(move(b)), ++b_idx; } } } }; <|endoftext|>
<commit_before>// Time: O(|V| + |E|) // Space: O(|V| + |E|) class Solution { public: struct node { int parent; vector<int>neighbors; }; bool validTree(int n, vector<pair<int, int>>& edges) { if (edges.size() != n - 1) { return false; } else if (n == 1) { return true; } unordered_map<int, node> nodes; for (const auto& edge : edges) { nodes[edge.first].neighbors.emplace_back(edge.second); nodes[edge.second].neighbors.emplace_back(edge.first); } if (nodes.size() != n) { return false; } for (int i = 0; i < n; ++i) { nodes[i].parent = -1; } unordered_set<int> visited; queue<int> q; q.emplace(0); while (!q.empty()) { const int i = q.front(); q.pop(); visited.emplace(i); for (const auto& n : nodes[i].neighbors) { if (n != nodes[i].parent) { if (visited.find(n) != visited.end()) { return false; } else { visited.emplace(n); nodes[n].parent = i; q.emplace(n); } } } } return true; } }; <commit_msg>Update graph-valid-tree.cpp<commit_after> // Time: O(|V| + |E|) // Space: O(|V| + |E|) class Solution { public: struct node { int parent = -1; vector<int>neighbors; }; bool validTree(int n, vector<pair<int, int>>& edges) { if (edges.size() != n - 1) { return false; } else if (n == 1) { return true; } unordered_map<int, node> nodes; for (const auto& edge : edges) { nodes[edge.first].neighbors.emplace_back(edge.second); nodes[edge.second].neighbors.emplace_back(edge.first); } if (nodes.size() != n) { return false; } unordered_set<int> visited; queue<int> q; q.emplace(0); while (!q.empty()) { const int i = q.front(); q.pop(); visited.emplace(i); for (const auto& n : nodes[i].neighbors) { if (n != nodes[i].parent) { if (visited.find(n) != visited.end()) { return false; } else { visited.emplace(n); nodes[n].parent = i; q.emplace(n); } } } } return true; } }; <|endoftext|>
<commit_before>#include <rm.hpp> #include <kdb.hpp> #include <cmdline.hpp> #include <print.hpp> #include <iostream> using namespace std; using namespace kdb; RemoveCommand::RemoveCommand() {} int RemoveCommand::execute(Cmdline const& cl) { if (cl.arguments.size() != 1) throw invalid_argument("1 argument required"); KeySet conf; Key x(cl.arguments[0], KEY_END); if (!x) { throw invalid_argument(cl.arguments[0] + " is not a valid keyname"); } kdb.get(conf, x); if (!cl.recursive) { /* TODO crash? Key f = conf.lookup(x, KDB_O_POP); */ KeySet ks = conf.cut (x); // if (!f) if (ks.size() == 0) { cerr << "Did not find the key" << endl; return 1; } } else { // do recursive removing KeySet ks = conf.cut (x); if (ks.size() == 0) { cerr << "Did not find any key" << endl; return 1; } } Key n; kdb.set(conf, n); return 0; } RemoveCommand::~RemoveCommand() {} <commit_msg>fix removing of single items<commit_after>#include <rm.hpp> #include <kdb.hpp> #include <cmdline.hpp> #include <print.hpp> #include <iostream> using namespace std; using namespace kdb; RemoveCommand::RemoveCommand() {} int RemoveCommand::execute(Cmdline const& cl) { if (cl.arguments.size() != 1) throw invalid_argument("1 argument required"); KeySet conf; Key x(cl.arguments[0], KEY_END); if (!x) { throw invalid_argument(cl.arguments[0] + " is not a valid keyname"); } kdb.get(conf, x); if (!cl.recursive) { Key f = conf.lookup(x, KDB_O_POP); if (!f) { cerr << "Did not find the key" << endl; return 1; } } else { // do recursive removing KeySet ks = conf.cut (x); if (ks.size() == 0) { cerr << "Did not find any key" << endl; return 1; } } Key n; kdb.set(conf, n); return 0; } RemoveCommand::~RemoveCommand() {} <|endoftext|>
<commit_before>void k_print_line(const char* string); void k_print(const char* string); extern "C" void __attribute__ ((section ("main_section"))) kernel_main(){ k_print("thor> "); return; } typedef unsigned int uint8_t __attribute__((__mode__(__QI__))); typedef unsigned int uint16_t __attribute__ ((__mode__ (__HI__))); enum vga_color { BLACK = 0, BLUE = 1, GREEN = 2, CYAN = 3, RED = 4, MAGENTA = 5, BROWN = 6, LIGHT_GREY = 7, DARK_GREY = 8, LIGHT_BLUE = 9, LIGHT_GREEN = 10, LIGHT_CYAN = 11, LIGHT_RED = 12, LIGHT_MAGENTA = 13, LIGHT_BROWN = 14, WHITE = 15, }; long current_line = 0; long current_column = 0; uint8_t make_color(vga_color fg, vga_color bg){ return fg | bg << 4; } uint16_t make_vga_entry(char c, uint8_t color){ uint16_t c16 = c; uint16_t color16 = color; return c16 | color16 << 8; } void k_print_line(const char* string){ k_print(string); current_column = 0; ++current_line; } void k_print(const char* string){ uint16_t* vga_buffer = (uint16_t*) 0x0B8000; for(int i = 0; string[i] != 0; ++i){ vga_buffer[current_line * 80 + current_column] = make_vga_entry(string[i], make_color(WHITE, BLACK)); ++current_column; } return; } <commit_msg>Clean<commit_after>void k_print_line(const char* string); void k_print(const char* string); extern "C" void __attribute__ ((section ("main_section"))) kernel_main(){ k_print("thor> "); //TODO Register keyword handler return; } typedef unsigned int uint8_t __attribute__((__mode__(__QI__))); typedef unsigned int uint16_t __attribute__ ((__mode__ (__HI__))); enum vga_color { BLACK = 0, BLUE = 1, GREEN = 2, CYAN = 3, RED = 4, MAGENTA = 5, BROWN = 6, LIGHT_GREY = 7, DARK_GREY = 8, LIGHT_BLUE = 9, LIGHT_GREEN = 10, LIGHT_CYAN = 11, LIGHT_RED = 12, LIGHT_MAGENTA = 13, LIGHT_BROWN = 14, WHITE = 15, }; long current_line = 0; long current_column = 0; uint8_t make_color(vga_color fg, vga_color bg){ return fg | bg << 4; } uint16_t make_vga_entry(char c, uint8_t color){ uint16_t c16 = c; uint16_t color16 = color; return c16 | color16 << 8; } void k_print_line(const char* string){ k_print(string); current_column = 0; ++current_line; } void k_print(const char* string){ uint16_t* vga_buffer = (uint16_t*) 0x0B8000; for(int i = 0; string[i] != 0; ++i){ vga_buffer[current_line * 80 + current_column] = make_vga_entry(string[i], make_color(WHITE, BLACK)); ++current_column; } return; } <|endoftext|>
<commit_before>#include <jni.h> #include <string> static ln::Application* g_app = nullptr; extern "C" ::ln::Application* LuminoCreateApplicationInstance(); extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeInitialize( JNIEnv *env, jobject /* this */, jint width, jint height) { ln::GlobalLogger::addLogcatAdapter(); g_app = ::LuminoCreateApplicationInstance(); ln::detail::ApplicationHelper::initialize(g_app); } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeUpdateFrame( JNIEnv *env, jobject /* this */) { ln::detail::ApplicationHelper::processTick(g_app); } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeFinalize( JNIEnv *env, jobject /* this */) { ln::detail::ApplicationHelper::finalize(g_app); ln::RefObjectHelper::release(g_app); g_app = nullptr; } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeOnSurfaceChanged( JNIEnv *env, jobject /* this */, jint width, jint height) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeOnPause( JNIEnv *env, jobject /* this */) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeOnResume( JNIEnv *env, jobject /* this */) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeTouchesBegin( JNIEnv *env, jobject /* this */, jint id, jfloat x, jfloat y) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeTouchesEnd( JNIEnv *env, jobject /* this */, jint id, jfloat x, jfloat y) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeTouchesMove( JNIEnv *env, jobject /* this */, jintArray ids, jfloatArray xs, jfloatArray ys) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeTouchesCancel( JNIEnv *env, jobject /* this */, jintArray ids, jfloatArray xs, jfloatArray ys) { } extern "C" JNIEXPORT jboolean JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeKeyEvent( JNIEnv *env, jobject /* this */, jint keyCode, jboolean isPressed) { return JNI_FALSE; } <commit_msg>Update tools/LuminoCLI/Templates/NativeProject/Projects/LuminoApp.Android/app/src/main/cpp/native-lib.cpp<commit_after>#include <jni.h> #include <string> static ln::Application* g_app = nullptr; extern "C" ::ln::Application* LuminoCreateApplicationInstance(); extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeInitialize( JNIEnv *env, jobject /* this */, jint width, jint height) { ln::GlobalLogger::addLogcatAdapter(); g_app = ::LuminoCreateApplicationInstance(); ln::detail::ApplicationHelper::initialize(g_app); ln::detail::SwapChainHelper::setBackendBufferSize(ln::Engine::mainWindow()->swapChain(), width, height); } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeUpdateFrame( JNIEnv *env, jobject /* this */) { ln::detail::ApplicationHelper::processTick(g_app); } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeFinalize( JNIEnv *env, jobject /* this */) { ln::detail::ApplicationHelper::finalize(g_app); ln::RefObjectHelper::release(g_app); g_app = nullptr; } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeOnSurfaceChanged( JNIEnv *env, jobject /* this */, jint width, jint height) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeOnPause( JNIEnv *env, jobject /* this */) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeOnResume( JNIEnv *env, jobject /* this */) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeTouchesBegin( JNIEnv *env, jobject /* this */, jint id, jfloat x, jfloat y) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeTouchesEnd( JNIEnv *env, jobject /* this */, jint id, jfloat x, jfloat y) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeTouchesMove( JNIEnv *env, jobject /* this */, jintArray ids, jfloatArray xs, jfloatArray ys) { } extern "C" JNIEXPORT void JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeTouchesCancel( JNIEnv *env, jobject /* this */, jintArray ids, jfloatArray xs, jfloatArray ys) { } extern "C" JNIEXPORT jboolean JNICALL Java_org_lumino_lib_luminoapp_LuminoRenderer_nativeKeyEvent( JNIEnv *env, jobject /* this */, jint keyCode, jboolean isPressed) { return JNI_FALSE; } <|endoftext|>
<commit_before>#ifndef _macros_hpp_INCLUDED #define _macros_hpp_INCLUDED // Central file for keeping (most) macros. /*------------------------------------------------------------------------*/ // Profiling support. #define START(P,ARGS...) \ do { \ if (internal->profiles.P.level > internal->opts.profile) break; \ internal->start_profiling (&internal->profiles.P, ##ARGS); \ } while (0) #define STOP(P,ARGS...) \ do { \ if (internal->profiles.P.level > internal->opts.profile) break; \ internal->stop_profiling (&internal->profiles.P, ##ARGS); \ } while (0) #define SWITCH_AND_START(F,T,P) \ do { \ const double N = seconds (); \ const int L = internal->opts.profile; \ if (internal->profiles.F.level > L) STOP (F, N); \ if (internal->profiles.T.level > L) START (T, N); \ if (internal->profiles.P.level > L) START (P, N); \ } while (0) #define STOP_AND_SWITCH(P,F,T) \ do { \ const double N = seconds (); \ const int L = internal->opts.profile; \ if (internal->profiles.P.level > L) STOP (P, N); \ if (internal->profiles.F.level > L) STOP (F, N); \ if (internal->profiles.T.level > L) START (T, N); \ } while (0) /*------------------------------------------------------------------------*/ // Memory allocation with implicit memory usage updates. #define NEW(P,T,N) \ do { (P) = new T[N], internal->inc_bytes ((N) * sizeof (T)); } while (0) #define DEL(P,T,N) \ do { delete [] (P), internal->dec_bytes ((N) * sizeof (T)); } while (0) #define ENLARGE(P,T,O,N) \ do { \ T * TMP = (P); \ NEW (P, T, N); \ for (size_t I = 0; I < (O); I++) (P)[I] = (TMP)[I]; \ internal->dec_bytes ((O) * sizeof (T)); \ delete [] TMP; \ } while (0) #define VECTOR_BYTES(V) ((V).capacity () * sizeof ((V)[0])) /*------------------------------------------------------------------------*/ // Compact message code. #define MSG(ARGS...) Message::print (internal, 0, ##ARGS) #define VRB(ARGS...) Message::print (internal, 1, ##ARGS) #define SECTION(ARGS...) Message::section (internal, ##ARGS) /*------------------------------------------------------------------------*/ // Compact average update and initialization code for better logging. #define UPDATE_AVG(EMA_OR_AVG,Y) \ do { EMA_OR_AVG.update (internal, (Y), #EMA_OR_AVG); } while (0) #define INIT_EMA(E,V) \ E = EMA (V); \ LOG ("init " #E " EMA target alpha %g", (double) V) #endif <commit_msg>fixed<commit_after>#ifndef _macros_hpp_INCLUDED #define _macros_hpp_INCLUDED // Central file for keeping (most) macros. /*------------------------------------------------------------------------*/ // Profiling support. #define START(P,ARGS...) \ do { \ if (internal->profiles.P.level > internal->opts.profile) break; \ internal->start_profiling (&internal->profiles.P, ##ARGS); \ } while (0) #define STOP(P,ARGS...) \ do { \ if (internal->profiles.P.level > internal->opts.profile) break; \ internal->stop_profiling (&internal->profiles.P, ##ARGS); \ } while (0) #define SWITCH_AND_START(F,T,P) \ do { \ const double N = seconds (); \ const int L = internal->opts.profile; \ if (internal->profiles.F.level <= L) STOP (F, N); \ if (internal->profiles.T.level <= L) START (T, N); \ if (internal->profiles.P.level <= L) START (P, N); \ } while (0) #define STOP_AND_SWITCH(P,F,T) \ do { \ const double N = seconds (); \ const int L = internal->opts.profile; \ if (internal->profiles.P.level <= L) STOP (P, N); \ if (internal->profiles.F.level <= L) STOP (F, N); \ if (internal->profiles.T.level <= L) START (T, N); \ } while (0) /*------------------------------------------------------------------------*/ // Memory allocation with implicit memory usage updates. #define NEW(P,T,N) \ do { (P) = new T[N], internal->inc_bytes ((N) * sizeof (T)); } while (0) #define DEL(P,T,N) \ do { delete [] (P), internal->dec_bytes ((N) * sizeof (T)); } while (0) #define ENLARGE(P,T,O,N) \ do { \ T * TMP = (P); \ NEW (P, T, N); \ for (size_t I = 0; I < (O); I++) (P)[I] = (TMP)[I]; \ internal->dec_bytes ((O) * sizeof (T)); \ delete [] TMP; \ } while (0) #define VECTOR_BYTES(V) ((V).capacity () * sizeof ((V)[0])) /*------------------------------------------------------------------------*/ // Compact message code. #define MSG(ARGS...) Message::print (internal, 0, ##ARGS) #define VRB(ARGS...) Message::print (internal, 1, ##ARGS) #define SECTION(ARGS...) Message::section (internal, ##ARGS) /*------------------------------------------------------------------------*/ // Compact average update and initialization code for better logging. #define UPDATE_AVG(EMA_OR_AVG,Y) \ do { EMA_OR_AVG.update (internal, (Y), #EMA_OR_AVG); } while (0) #define INIT_EMA(E,V) \ E = EMA (V); \ LOG ("init " #E " EMA target alpha %g", (double) V) #endif <|endoftext|>
<commit_before>#include <iostream> #include <vw/Image/ImageMath.h> #include <vw/Image/UtilityViews.h> #include <vw/Plate/PlateFile.h> #include <vw/Image/MaskViews.h> #include <vw/Octave/Main.h> #include <mvp/Config.h> #include <mvp/MVPWorkspace.h> #include <mvp/MVPJob.h> #include <boost/program_options.hpp> using namespace vw; using namespace vw::cartography; using namespace vw::platefile; using namespace vw::octave; using namespace std; using namespace mvp; namespace po = boost::program_options; template <class BBoxT, class RealT, size_t DimN> void print_bbox_helper(math::BBoxBase<BBoxT, RealT, DimN> const& bbox) { cout << "BBox = " << bbox << endl; cout << "width, height = " << bbox.width() << ", " << bbox.height() << endl; } int main(int argc, char* argv[]) { #if MVP_ENABLE_OCTAVE_SUPPORT start_octave_interpreter(); #endif po::options_description cmd_opts("Command line options"); cmd_opts.add_options() ("help,h", "Print this message") ("silent", "Run without outputting status") ("config-file,f", po::value<string>()->default_value("mvp.conf"), "Specify a pipeline configuration file") ("print-workspace,p", "Print information about the workspace and exit") ("dump-job", "Dump a jobfile") ("col,c", po::value<int>(), "When dumping a jobfile, column of tile to dump") ("row,r", po::value<int>(), "When dumping a jobfile, row of tile to dump") ("level,l", po::value<int>(), "When dumping a jobfile or printing the workspace, level to operate at") ("job", po::value<string>(), "Render a jobfile") ; po::options_description render_opts("Render Options"); render_opts.add_options() ("col-start", po::value<int>(), "Col to start rendering at") ("col-end", po::value<int>(), "One past last col to render") ("row-start", po::value<int>(), "Row to start rendering at") ("row-end", po::value<int>(), "One past last row to render") ("render-level", po::value<int>(), "Level to render at") ; po::options_description mvp_opts; mvp_opts.add(MVPWorkspace::program_options()).add(render_opts); po::options_description all_opts; all_opts.add(cmd_opts).add(mvp_opts); po::variables_map vm; store(po::command_line_parser(argc, argv).options(all_opts).run(), vm); if (vm.count("help")) { cout << all_opts << endl; return 0; } ifstream ifs(vm["config-file"].as<string>().c_str()); if (ifs) { store(parse_config_file(ifs, mvp_opts), vm); } notify(vm); MVPWorkspace work(MVPWorkspace::construct_from_program_options(vm)); if (!vm.count("silent")) { cout << boolalpha << endl; cout << "-------------------------------------" << endl; cout << "Welcome to the Multiple View Pipeline" << endl; cout << "-------------------------------------" << endl; cout << endl; cout << "Number of images loaded = " << work.num_images() << endl; cout << " Equal resolution level = " << work.equal_resolution_level() << endl; cout << " Equal density level = " << work.equal_density_level() << endl; cout << endl; cout << "# Workspace lonlat BBox #" << endl; print_bbox_helper(work.lonlat_work_area()); cout << endl; cout << "# Workspace tile BBox (@ equal density level) #" << endl; print_bbox_helper(work.tile_work_area(work.equal_density_level())); if (vm.count("level")) { int print_level = vm["level"].as<int>(); cout << endl; cout << "# Workspace tile BBox (@ level " << print_level << ") #" << endl; print_bbox_helper(work.tile_work_area(print_level)); } cout << endl; } if (vm.count("print-workspace")) { return 0; } if (vm.count("dump-job")) { if (!vm.count("col") || !vm.count("row") || !vm.count("level")) { cerr << "Error: Must specify a col, row, and level to dump" << endl; return 1; } save_job_file(work.assemble_job(vm["col"].as<int>(), vm["row"].as<int>(), vm["level"].as<int>())); return 0; } int render_level = work.equal_density_level(); if (vm.count("render-level")) { render_level = vm["render-level"].as<int>(); } BBox2i tile_bbox(work.tile_work_area(render_level)); if (vm.count("col-start")) { VW_ASSERT(vm.count("col-end"), ArgumentErr() << "col-start specified, but col-end not"); tile_bbox.min()[0] = vm["col-start"].as<int>(); tile_bbox.max()[0] = vm["col-end"].as<int>(); } if (vm.count("row-start")) { VW_ASSERT(vm.count("row-end"), ArgumentErr() << "row-start specified, but col-end not"); tile_bbox.min()[1] = vm["row-start"].as<int>(); tile_bbox.max()[1] = vm["row-end"].as<int>(); } if (!vm.count("silent")) { cout << "-------------------------------------" << endl; cout << " Rendering Information" << endl; cout << "-------------------------------------" << endl; cout << endl; cout << "Render level = " << render_level << endl; cout << " Use octave = " << vm["use-octave"].as<bool>() << endl; cout << endl; cout << "# Render tile BBox #" << endl; print_bbox_helper(tile_bbox); cout << endl; cout << "-------------------------------------" << endl; cout << " Status" << endl; cout << "-------------------------------------" << endl; cout << endl; } if (vm.count("job")) { MVPTileResult result = mvpjob_process_tile(vm["job"].as<string>(), TerminalProgressCallback("mvp", "Processing job: ")); write_georeferenced_image(vm["job"].as<string>() + ".tif", result.alt, result.georef); } else { boost::shared_ptr<PlateFile> pf(new PlateFile(work.result_platefile(), work.plate_georef().map_proj(), "MVP Result Plate", work.plate_georef().tile_size(), "tif", VW_PIXEL_GRAYA, VW_CHANNEL_FLOAT32)); Transaction tid = pf->transaction_request("Post Heights", -1); int curr_tile = 0; int num_tiles = tile_bbox.width() * tile_bbox.height(); float32 plate_min_val = numeric_limits<float32>::max(), plate_max_val = numeric_limits<float32>::min(); for (int col = tile_bbox.min().x(); col < tile_bbox.max().x(); col++) { for (int row = tile_bbox.min().y(); row < tile_bbox.max().y(); row++) { boost::shared_ptr<ProgressCallback> progress; if (!vm.count("silent")) { ostringstream status; status << "Tile: " << ++curr_tile << "/" << num_tiles << " Location: [" << col << ", " << row << "] @" << render_level << " "; progress.reset(new TerminalProgressCallback("mvp", status.str())); } else { progress.reset(new ProgressCallback); } MVPTileResult result = mvpjob_process_tile(work.assemble_job(col, row, render_level), *progress); ImageView<PixelGrayA<float32> > rendered_tile = mask_to_alpha(pixel_cast<PixelMask<PixelGray<float32> > >(result.alt)); float32 tile_min_val, tile_max_val; try { min_max_channel_values(result.alt, tile_min_val, tile_max_val); } catch (ArgumentErr& e) { tile_min_val = numeric_limits<float32>::max(); tile_max_val = numeric_limits<float32>::min(); } plate_min_val = min(plate_min_val, tile_min_val); plate_max_val = max(plate_max_val, tile_max_val); pf->write_request(); pf->write_update(rendered_tile, col, row, render_level, tid); pf->sync(); pf->write_complete(); } } // This way that tile is easy to find... for (int level = 2; level < render_level; level++) { int divisor = render_level - level; for (int col = tile_bbox.min().x() >> divisor; col <= tile_bbox.max().x() >> divisor; col++) { for (int row = tile_bbox.min().y() >> divisor; row <= tile_bbox.max().y() >> divisor; row++) { ImageView<PixelGrayA<float32> > rendered_tile(constant_view(PixelGrayA<float32>(), work.plate_georef().tile_size(), work.plate_georef().tile_size())); pf->write_request(); pf->write_update(rendered_tile, col, row, level, tid); pf->sync(); pf->write_complete(); } } } if (!vm.count("silent")) { cout << "Plate (min, max): (" << plate_min_val << ", " << plate_max_val << ")" << endl; cout << endl; } } #if MVP_ENABLE_OCTAVE_SUPPORT do_octave_atexit(); #endif return 0; } <commit_msg>updated mvp.cc for new platefile api<commit_after>#include <iostream> #include <vw/Image/ImageMath.h> #include <vw/Image/UtilityViews.h> #include <vw/Plate/PlateFile.h> #include <vw/Image/MaskViews.h> #include <vw/Octave/Main.h> #include <mvp/Config.h> #include <mvp/MVPWorkspace.h> #include <mvp/MVPJob.h> #include <boost/program_options.hpp> using namespace vw; using namespace vw::cartography; using namespace vw::platefile; using namespace vw::octave; using namespace std; using namespace mvp; namespace po = boost::program_options; template <class BBoxT, class RealT, size_t DimN> void print_bbox_helper(math::BBoxBase<BBoxT, RealT, DimN> const& bbox) { cout << "BBox = " << bbox << endl; cout << "width, height = " << bbox.width() << ", " << bbox.height() << endl; } int main(int argc, char* argv[]) { #if MVP_ENABLE_OCTAVE_SUPPORT start_octave_interpreter(); #endif po::options_description cmd_opts("Command line options"); cmd_opts.add_options() ("help,h", "Print this message") ("silent", "Run without outputting status") ("config-file,f", po::value<string>()->default_value("mvp.conf"), "Specify a pipeline configuration file") ("print-workspace,p", "Print information about the workspace and exit") ("dump-job", "Dump a jobfile") ("col,c", po::value<int>(), "When dumping a jobfile, column of tile to dump") ("row,r", po::value<int>(), "When dumping a jobfile, row of tile to dump") ("level,l", po::value<int>(), "When dumping a jobfile or printing the workspace, level to operate at") ("job", po::value<string>(), "Render a jobfile") ; po::options_description render_opts("Render Options"); render_opts.add_options() ("col-start", po::value<int>(), "Col to start rendering at") ("col-end", po::value<int>(), "One past last col to render") ("row-start", po::value<int>(), "Row to start rendering at") ("row-end", po::value<int>(), "One past last row to render") ("render-level", po::value<int>(), "Level to render at") ; po::options_description mvp_opts; mvp_opts.add(MVPWorkspace::program_options()).add(render_opts); po::options_description all_opts; all_opts.add(cmd_opts).add(mvp_opts); po::variables_map vm; store(po::command_line_parser(argc, argv).options(all_opts).run(), vm); if (vm.count("help")) { cout << all_opts << endl; return 0; } ifstream ifs(vm["config-file"].as<string>().c_str()); if (ifs) { store(parse_config_file(ifs, mvp_opts), vm); } notify(vm); MVPWorkspace work(MVPWorkspace::construct_from_program_options(vm)); if (!vm.count("silent")) { cout << boolalpha << endl; cout << "-------------------------------------" << endl; cout << "Welcome to the Multiple View Pipeline" << endl; cout << "-------------------------------------" << endl; cout << endl; cout << "Number of images loaded = " << work.num_images() << endl; cout << " Equal resolution level = " << work.equal_resolution_level() << endl; cout << " Equal density level = " << work.equal_density_level() << endl; cout << endl; cout << "# Workspace lonlat BBox #" << endl; print_bbox_helper(work.lonlat_work_area()); cout << endl; cout << "# Workspace tile BBox (@ equal density level) #" << endl; print_bbox_helper(work.tile_work_area(work.equal_density_level())); if (vm.count("level")) { int print_level = vm["level"].as<int>(); cout << endl; cout << "# Workspace tile BBox (@ level " << print_level << ") #" << endl; print_bbox_helper(work.tile_work_area(print_level)); } cout << endl; } if (vm.count("print-workspace")) { return 0; } if (vm.count("dump-job")) { if (!vm.count("col") || !vm.count("row") || !vm.count("level")) { cerr << "Error: Must specify a col, row, and level to dump" << endl; return 1; } save_job_file(work.assemble_job(vm["col"].as<int>(), vm["row"].as<int>(), vm["level"].as<int>())); return 0; } int render_level = work.equal_density_level(); if (vm.count("render-level")) { render_level = vm["render-level"].as<int>(); } BBox2i tile_bbox(work.tile_work_area(render_level)); if (vm.count("col-start")) { VW_ASSERT(vm.count("col-end"), ArgumentErr() << "col-start specified, but col-end not"); tile_bbox.min()[0] = vm["col-start"].as<int>(); tile_bbox.max()[0] = vm["col-end"].as<int>(); } if (vm.count("row-start")) { VW_ASSERT(vm.count("row-end"), ArgumentErr() << "row-start specified, but col-end not"); tile_bbox.min()[1] = vm["row-start"].as<int>(); tile_bbox.max()[1] = vm["row-end"].as<int>(); } if (!vm.count("silent")) { cout << "-------------------------------------" << endl; cout << " Rendering Information" << endl; cout << "-------------------------------------" << endl; cout << endl; cout << "Render level = " << render_level << endl; cout << " Use octave = " << vm["use-octave"].as<bool>() << endl; cout << endl; cout << "# Render tile BBox #" << endl; print_bbox_helper(tile_bbox); cout << endl; cout << "-------------------------------------" << endl; cout << " Status" << endl; cout << "-------------------------------------" << endl; cout << endl; } if (vm.count("job")) { MVPTileResult result = mvpjob_process_tile(vm["job"].as<string>(), TerminalProgressCallback("mvp", "Processing job: ")); write_georeferenced_image(vm["job"].as<string>() + ".tif", result.alt, result.georef); } else { boost::shared_ptr<PlateFile> pf(new PlateFile(work.result_platefile(), work.plate_georef().map_proj(), "MVP Result Plate", work.plate_georef().tile_size(), "tif", VW_PIXEL_GRAYA, VW_CHANNEL_FLOAT32)); pf->transaction_begin("Post Heights", -1); pf->write_request(); int curr_tile = 0; int num_tiles = tile_bbox.width() * tile_bbox.height(); float32 plate_min_val = numeric_limits<float32>::max(), plate_max_val = numeric_limits<float32>::min(); for (int col = tile_bbox.min().x(); col < tile_bbox.max().x(); col++) { for (int row = tile_bbox.min().y(); row < tile_bbox.max().y(); row++) { boost::shared_ptr<ProgressCallback> progress; if (!vm.count("silent")) { ostringstream status; status << "Tile: " << ++curr_tile << "/" << num_tiles << " Location: [" << col << ", " << row << "] @" << render_level << " "; progress.reset(new TerminalProgressCallback("mvp", status.str())); } else { progress.reset(new ProgressCallback); } MVPTileResult result = mvpjob_process_tile(work.assemble_job(col, row, render_level), *progress); ImageView<PixelGrayA<float32> > rendered_tile = mask_to_alpha(pixel_cast<PixelMask<PixelGray<float32> > >(result.alt)); float32 tile_min_val, tile_max_val; try { min_max_channel_values(result.alt, tile_min_val, tile_max_val); } catch (ArgumentErr& e) { tile_min_val = numeric_limits<float32>::max(); tile_max_val = numeric_limits<float32>::min(); } plate_min_val = min(plate_min_val, tile_min_val); plate_max_val = max(plate_max_val, tile_max_val); pf->write_update(rendered_tile, col, row, render_level); pf->sync(); } } // This way that tile is easy to find... for (int level = 2; level < render_level; level++) { int divisor = render_level - level; for (int col = tile_bbox.min().x() >> divisor; col <= tile_bbox.max().x() >> divisor; col++) { for (int row = tile_bbox.min().y() >> divisor; row <= tile_bbox.max().y() >> divisor; row++) { ImageView<PixelGrayA<float32> > rendered_tile(constant_view(PixelGrayA<float32>(), work.plate_georef().tile_size(), work.plate_georef().tile_size())); pf->write_update(rendered_tile, col, row, level); } } } pf->sync(); pf->write_complete(); pf->transaction_end(true); if (!vm.count("silent")) { cout << "Plate (min, max): (" << plate_min_val << ", " << plate_max_val << ")" << endl; cout << endl; } } #if MVP_ENABLE_OCTAVE_SUPPORT do_octave_atexit(); #endif return 0; } <|endoftext|>
<commit_before>#include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/common/common.h> #include <pcl/common/transforms.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/console/parse.h> #include <pcl/console/print.h> #include <pcl/io/pcd_io.h> #include <iostream> #include <flann/flann.h> #include <flann/io/hdf5.h> #include <boost/filesystem.hpp> typedef std::pair<std::string, std::vector<float> > vfh_model; /** \brief Loads an n-D histogram file as a VFH signature * \param path the input file name * \param vfh the resultant VFH model */ bool loadHist (const boost::filesystem::path &path, vfh_model &vfh) { int vfh_idx; // Load the file as a PCD try { sensor_msgs::PointCloud2 cloud; int version; Eigen::Vector4f origin; Eigen::Quaternionf orientation; pcl::PCDReader r; unsigned int type; int idx; r.readHeader (path.string (), cloud, origin, orientation, version, type, idx); vfh_idx = pcl::getFieldIndex (cloud, "vfh"); if (vfh_idx == -1) return (false); if ((int)cloud.width * cloud.height != 1) return (false); } catch (pcl::InvalidConversionException e) { return (false); } // Treat the VFH signature as a single Point Cloud pcl::PointCloud <pcl::VFHSignature308> point; pcl::io::loadPCDFile (path.string (), point); vfh.second.resize (308); std::vector <sensor_msgs::PointField> fields; getFieldIndex (point, "vfh", fields); for (size_t i = 0; i < fields[vfh_idx].count; ++i) { vfh.second[i] = point.points[0].histogram[i]; } vfh.first = path.string (); return (true); } /** \brief Search for the closest k neighbors * \param index the tree * \param model the query model * \param k the number of neighbors to search for * \param indices the resultant neighbor indices * \param distances the resultant neighbor distances */ inline void nearestKSearch (flann::Index<flann::ChiSquareDistance<float> > &index, const vfh_model &model, int k, flann::Matrix<int> &indices, flann::Matrix<float> &distances) { // Query point flann::Matrix<float> p = flann::Matrix<float>(new float[model.second.size ()], 1, model.second.size ()); memcpy (&p.ptr ()[0], &model.second[0], p.cols * p.rows * sizeof (float)); indices = flann::Matrix<int>(new int[k], 1, k); distances = flann::Matrix<float>(new float[k], 1, k); index.knnSearch (p, indices, distances, k, flann::SearchParams (512)); delete[] p.ptr (); } /** \brief Load the list of file model names from an ASCII file * \param models the resultant list of model name * \param filename the input file name */ bool loadFileList (std::vector<vfh_model> &models, const std::string &filename) { ifstream fs; fs.open (filename.c_str ()); if (!fs.is_open () || fs.fail ()) return (false); std::string line; while (!fs.eof ()) { getline (fs, line); if (line.empty ()) continue; vfh_model m; m.first = line; models.push_back (m); } fs.close (); return (true); } int main (int argc, char** argv) { int k = 6; double thresh = DBL_MAX; // No threshold, disabled by default if (argc < 2) { pcl::console::print_error ("Need at least three parameters! Syntax is: %s <query_vfh_model.pcd> [options] {kdtree.idx} {training_data.h5} {training_data.list}\n", argv[0]); pcl::console::print_info (" where [options] are: -k = number of nearest neighbors to search for in the tree (default: "); pcl::console::print_value ("%d", k); pcl::console::print_info (")\n"); pcl::console::print_info (" -thresh = maximum distance threshold for a model to be considered VALID (default: "); pcl::console::print_value ("%f", thresh); pcl::console::print_info (")\n\n"); return (-1); } std::string extension (".pcd"); transform (extension.begin (), extension.end (), extension.begin (), (int(*)(int))tolower); // Load the test histogram std::vector<int> pcd_indices = pcl::console::parse_file_extension_argument (argc, argv, ".pcd"); vfh_model histogram; if (!loadHist (argv[pcd_indices.at (0)], histogram)) { pcl::console::print_error ("Cannot load test file %s\n", argv[pcd_indices.at (0)]); return (-1); } pcl::console::parse_argument (argc, argv, "-thresh", thresh); // Search for the k closest matches pcl::console::parse_argument (argc, argv, "-k", k); pcl::console::print_highlight ("Using "); pcl::console::print_value ("%d", k); pcl::console::print_info (" nearest neighbors.\n"); std::string kdtree_idx_file_name = "kdtree.idx"; std::string training_data_h5_file_name = "training_data.h5"; std::string training_data_list_file_name = "training_data.list"; std::vector<vfh_model> models; flann::Matrix<int> k_indices; flann::Matrix<float> k_distances; flann::Matrix<float> data; // Check if the data has already been saved to disk if (!boost::filesystem::exists ("training_data.h5") || !boost::filesystem::exists ("training_data.list")) { pcl::console::print_error ("Could not find training data models files %s and %s!\n", training_data_h5_file_name.c_str (), training_data_list_file_name.c_str ()); return (-1); } else { loadFileList (models, training_data_list_file_name); flann::load_from_file (data, training_data_h5_file_name, "training_data"); pcl::console::print_highlight ("Training data found. Loaded %d VFH models from %s/%s.\n", (int)data.rows, training_data_h5_file_name.c_str (), training_data_list_file_name.c_str ()); } // Check if the tree index has already been saved to disk if (!boost::filesystem::exists (kdtree_idx_file_name)) { pcl::console::print_error ("Could not find kd-tree index in file %s!", kdtree_idx_file_name.c_str ()); return (-1); } else { flann::Index<flann::ChiSquareDistance<float> > index (data, flann::SavedIndexParams ("kdtree.idx")); index.buildIndex (); nearestKSearch (index, histogram, k, k_indices, k_distances); } // Output the results on screen pcl::console::print_highlight ("The closest %d neighbors for %s are:\n", k, argv[pcd_indices[0]]); for (int i = 0; i < k; ++i) pcl::console::print_info (" %d - %s (%d) with a distance of: %f\n", i, models.at (k_indices[0][i]).first.c_str (), k_indices[0][i], k_distances[0][i]); // Load the results pcl::visualization::PCLVisualizer p (argc, argv, "VFH Cluster Classifier"); int y_s = (int)floor (sqrt ((double)k)); int x_s = y_s + (int)ceil ((k / (double)y_s) - y_s); double x_step = (double)(1 / (double)x_s); double y_step = (double)(1 / (double)y_s); pcl::console::print_highlight ("Preparing to load "); pcl::console::print_value ("%d", k); pcl::console::print_info (" files ("); pcl::console::print_value ("%d", x_s); pcl::console::print_info ("x"); pcl::console::print_value ("%d", y_s); pcl::console::print_info (" / "); pcl::console::print_value ("%f", x_step); pcl::console::print_info ("x"); pcl::console::print_value ("%f", y_step); pcl::console::print_info (")\n"); int viewport = 0, l = 0, m = 0; for (int i = 0; i < k; ++i) { std::string cloud_name = models.at (k_indices[0][i]).first; boost::replace_last (cloud_name, "_vfh", ""); p.createViewPort (l * x_step, m * y_step, (l + 1) * x_step, (m + 1) * y_step, viewport); l++; if (l >= x_s) { l = 0; m++; } sensor_msgs::PointCloud2 cloud; pcl::console::print_highlight (stderr, "Loading "); pcl::console::print_value (stderr, "%s ", cloud_name.c_str ()); if (pcl::io::loadPCDFile (cloud_name, cloud) == -1) break; // Convert from blob to PointCloud pcl::PointCloud<pcl::PointXYZ> cloud_xyz; pcl::fromROSMsg (cloud, cloud_xyz); if (cloud_xyz.points.size () == 0) break; pcl::console::print_info ("[done, "); pcl::console::print_value ("%d", (int)cloud_xyz.points.size ()); pcl::console::print_info (" points]\n"); pcl::console::print_info ("Available dimensions: "); pcl::console::print_value ("%s\n", pcl::getFieldsList (cloud).c_str ()); // Demean the cloud Eigen::Vector4f centroid; pcl::compute3DCentroid (cloud_xyz, centroid); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz_demean (new pcl::PointCloud<pcl::PointXYZ>); pcl::demeanPointCloud<pcl::PointXYZ> (cloud_xyz, centroid, *cloud_xyz_demean); // Add to renderer* p.addPointCloud (cloud_xyz_demean, cloud_name, viewport); // Check if the model found is within our inlier tolerance std::stringstream ss; ss << k_distances[0][i]; if (k_distances[0][i] > thresh) { p.addText (ss.str (), 20, 30, 1, 0, 0, ss.str (), viewport); // display the text with red // Create a red line pcl::PointXYZ min_p, max_p; pcl::getMinMax3D (*cloud_xyz_demean, min_p, max_p); std::stringstream line_name; line_name << "line_" << i; p.addLine (min_p, max_p, 1, 0, 0, line_name.str (), viewport); p.setShapeRenderingProperties (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 5, line_name.str (), viewport); } else p.addText (ss.str (), 20, 30, 0, 1, 0, ss.str (), viewport); // Increase the font size for the score* p.setShapeRenderingProperties (pcl::visualization::PCL_VISUALIZER_FONT_SIZE, 18, ss.str (), viewport); // Add the cluster name p.addText (cloud_name, 20, 10, cloud_name, viewport); } // Add coordianate systems to all viewports p.addCoordinateSystem (0.1, 0); p.spin (); return (0); } <commit_msg>second attenmpt to fix the build of vfh_recognition tutorial on mac os<commit_after>#include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/common/common.h> #include <pcl/common/transforms.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/console/parse.h> #include <pcl/console/print.h> #include <pcl/io/pcd_io.h> #include <iostream> #include <flann/flann.h> #include <flann/io/hdf5.h> #include <boost/filesystem.hpp> typedef std::pair<std::string, std::vector<float> > vfh_model; /** \brief Loads an n-D histogram file as a VFH signature * \param path the input file name * \param vfh the resultant VFH model */ bool loadHist (const boost::filesystem::path &path, vfh_model &vfh) { int vfh_idx; // Load the file as a PCD try { sensor_msgs::PointCloud2 cloud; int version; Eigen::Vector4f origin; Eigen::Quaternionf orientation; pcl::PCDReader r; int type; unsigned int idx; r.readHeader (path.string (), cloud, origin, orientation, version, type, idx); vfh_idx = pcl::getFieldIndex (cloud, "vfh"); if (vfh_idx == -1) return (false); if ((int)cloud.width * cloud.height != 1) return (false); } catch (pcl::InvalidConversionException e) { return (false); } // Treat the VFH signature as a single Point Cloud pcl::PointCloud <pcl::VFHSignature308> point; pcl::io::loadPCDFile (path.string (), point); vfh.second.resize (308); std::vector <sensor_msgs::PointField> fields; getFieldIndex (point, "vfh", fields); for (size_t i = 0; i < fields[vfh_idx].count; ++i) { vfh.second[i] = point.points[0].histogram[i]; } vfh.first = path.string (); return (true); } /** \brief Search for the closest k neighbors * \param index the tree * \param model the query model * \param k the number of neighbors to search for * \param indices the resultant neighbor indices * \param distances the resultant neighbor distances */ inline void nearestKSearch (flann::Index<flann::ChiSquareDistance<float> > &index, const vfh_model &model, int k, flann::Matrix<int> &indices, flann::Matrix<float> &distances) { // Query point flann::Matrix<float> p = flann::Matrix<float>(new float[model.second.size ()], 1, model.second.size ()); memcpy (&p.ptr ()[0], &model.second[0], p.cols * p.rows * sizeof (float)); indices = flann::Matrix<int>(new int[k], 1, k); distances = flann::Matrix<float>(new float[k], 1, k); index.knnSearch (p, indices, distances, k, flann::SearchParams (512)); delete[] p.ptr (); } /** \brief Load the list of file model names from an ASCII file * \param models the resultant list of model name * \param filename the input file name */ bool loadFileList (std::vector<vfh_model> &models, const std::string &filename) { ifstream fs; fs.open (filename.c_str ()); if (!fs.is_open () || fs.fail ()) return (false); std::string line; while (!fs.eof ()) { getline (fs, line); if (line.empty ()) continue; vfh_model m; m.first = line; models.push_back (m); } fs.close (); return (true); } int main (int argc, char** argv) { int k = 6; double thresh = DBL_MAX; // No threshold, disabled by default if (argc < 2) { pcl::console::print_error ("Need at least three parameters! Syntax is: %s <query_vfh_model.pcd> [options] {kdtree.idx} {training_data.h5} {training_data.list}\n", argv[0]); pcl::console::print_info (" where [options] are: -k = number of nearest neighbors to search for in the tree (default: "); pcl::console::print_value ("%d", k); pcl::console::print_info (")\n"); pcl::console::print_info (" -thresh = maximum distance threshold for a model to be considered VALID (default: "); pcl::console::print_value ("%f", thresh); pcl::console::print_info (")\n\n"); return (-1); } std::string extension (".pcd"); transform (extension.begin (), extension.end (), extension.begin (), (int(*)(int))tolower); // Load the test histogram std::vector<int> pcd_indices = pcl::console::parse_file_extension_argument (argc, argv, ".pcd"); vfh_model histogram; if (!loadHist (argv[pcd_indices.at (0)], histogram)) { pcl::console::print_error ("Cannot load test file %s\n", argv[pcd_indices.at (0)]); return (-1); } pcl::console::parse_argument (argc, argv, "-thresh", thresh); // Search for the k closest matches pcl::console::parse_argument (argc, argv, "-k", k); pcl::console::print_highlight ("Using "); pcl::console::print_value ("%d", k); pcl::console::print_info (" nearest neighbors.\n"); std::string kdtree_idx_file_name = "kdtree.idx"; std::string training_data_h5_file_name = "training_data.h5"; std::string training_data_list_file_name = "training_data.list"; std::vector<vfh_model> models; flann::Matrix<int> k_indices; flann::Matrix<float> k_distances; flann::Matrix<float> data; // Check if the data has already been saved to disk if (!boost::filesystem::exists ("training_data.h5") || !boost::filesystem::exists ("training_data.list")) { pcl::console::print_error ("Could not find training data models files %s and %s!\n", training_data_h5_file_name.c_str (), training_data_list_file_name.c_str ()); return (-1); } else { loadFileList (models, training_data_list_file_name); flann::load_from_file (data, training_data_h5_file_name, "training_data"); pcl::console::print_highlight ("Training data found. Loaded %d VFH models from %s/%s.\n", (int)data.rows, training_data_h5_file_name.c_str (), training_data_list_file_name.c_str ()); } // Check if the tree index has already been saved to disk if (!boost::filesystem::exists (kdtree_idx_file_name)) { pcl::console::print_error ("Could not find kd-tree index in file %s!", kdtree_idx_file_name.c_str ()); return (-1); } else { flann::Index<flann::ChiSquareDistance<float> > index (data, flann::SavedIndexParams ("kdtree.idx")); index.buildIndex (); nearestKSearch (index, histogram, k, k_indices, k_distances); } // Output the results on screen pcl::console::print_highlight ("The closest %d neighbors for %s are:\n", k, argv[pcd_indices[0]]); for (int i = 0; i < k; ++i) pcl::console::print_info (" %d - %s (%d) with a distance of: %f\n", i, models.at (k_indices[0][i]).first.c_str (), k_indices[0][i], k_distances[0][i]); // Load the results pcl::visualization::PCLVisualizer p (argc, argv, "VFH Cluster Classifier"); int y_s = (int)floor (sqrt ((double)k)); int x_s = y_s + (int)ceil ((k / (double)y_s) - y_s); double x_step = (double)(1 / (double)x_s); double y_step = (double)(1 / (double)y_s); pcl::console::print_highlight ("Preparing to load "); pcl::console::print_value ("%d", k); pcl::console::print_info (" files ("); pcl::console::print_value ("%d", x_s); pcl::console::print_info ("x"); pcl::console::print_value ("%d", y_s); pcl::console::print_info (" / "); pcl::console::print_value ("%f", x_step); pcl::console::print_info ("x"); pcl::console::print_value ("%f", y_step); pcl::console::print_info (")\n"); int viewport = 0, l = 0, m = 0; for (int i = 0; i < k; ++i) { std::string cloud_name = models.at (k_indices[0][i]).first; boost::replace_last (cloud_name, "_vfh", ""); p.createViewPort (l * x_step, m * y_step, (l + 1) * x_step, (m + 1) * y_step, viewport); l++; if (l >= x_s) { l = 0; m++; } sensor_msgs::PointCloud2 cloud; pcl::console::print_highlight (stderr, "Loading "); pcl::console::print_value (stderr, "%s ", cloud_name.c_str ()); if (pcl::io::loadPCDFile (cloud_name, cloud) == -1) break; // Convert from blob to PointCloud pcl::PointCloud<pcl::PointXYZ> cloud_xyz; pcl::fromROSMsg (cloud, cloud_xyz); if (cloud_xyz.points.size () == 0) break; pcl::console::print_info ("[done, "); pcl::console::print_value ("%d", (int)cloud_xyz.points.size ()); pcl::console::print_info (" points]\n"); pcl::console::print_info ("Available dimensions: "); pcl::console::print_value ("%s\n", pcl::getFieldsList (cloud).c_str ()); // Demean the cloud Eigen::Vector4f centroid; pcl::compute3DCentroid (cloud_xyz, centroid); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz_demean (new pcl::PointCloud<pcl::PointXYZ>); pcl::demeanPointCloud<pcl::PointXYZ> (cloud_xyz, centroid, *cloud_xyz_demean); // Add to renderer* p.addPointCloud (cloud_xyz_demean, cloud_name, viewport); // Check if the model found is within our inlier tolerance std::stringstream ss; ss << k_distances[0][i]; if (k_distances[0][i] > thresh) { p.addText (ss.str (), 20, 30, 1, 0, 0, ss.str (), viewport); // display the text with red // Create a red line pcl::PointXYZ min_p, max_p; pcl::getMinMax3D (*cloud_xyz_demean, min_p, max_p); std::stringstream line_name; line_name << "line_" << i; p.addLine (min_p, max_p, 1, 0, 0, line_name.str (), viewport); p.setShapeRenderingProperties (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 5, line_name.str (), viewport); } else p.addText (ss.str (), 20, 30, 0, 1, 0, ss.str (), viewport); // Increase the font size for the score* p.setShapeRenderingProperties (pcl::visualization::PCL_VISUALIZER_FONT_SIZE, 18, ss.str (), viewport); // Add the cluster name p.addText (cloud_name, 20, 10, cloud_name, viewport); } // Add coordianate systems to all viewports p.addCoordinateSystem (0.1, 0); p.spin (); return (0); } <|endoftext|>
<commit_before>Parcer::Parcer(std::string filename){ Tokens = LexicalAnaltysis(filename); }; /* 構文解析実行 @return 成功:true 失敗:false */ bool Parser::doParse(){ if(!Tokens){ fprintf(stderr, "error at lexer\n"); return false; } else{ return VisitTranslationUnit(); } }; TranslationUnitAST &Parser::getAST(){ if(TU){ return *TU; } else{ return *(new TranslationUnitAST()); } }; // TranslationUnit用構文解析メソッド bool Parser::visitTranslationUnit(){ TU = new TranslatonUnitAST(); // ExternalDecl while(true){ if(!visitExternalDeclaration(TU)){ SAFE_DELETE(TU); return false; } if(Tokens->getCurType == TOK_EOF){ break; } } return true; } // ExternalDeclaration用構文解析メソッド bool Parser::visitExternalDeclaration(TranslationUnitAST *tunit){ PrototypeAST *proto = visitFunctionDeclaration(); if(proto){ tunit->addPrototype(proto); return true; } FunctionAST *func_def = visitFunctionDefinition(); if(func_def){ tunit->addFunction(func_def); return true; } return false; } PrototypeAST *Parser::zisitFunctionDeclaration(){ int backup = Tokens->getCurIndex(); PrototypeAST *proto = visitPrototype(); if(!proto){ return NULL; } if(Tokens->getCurString() == ';'){ // 本来であればここで再定義されていないか確認 Tokens->getNextToken(); return proto; } else{ SAFE_DELETE(proto); Tokens->applyTokenIndex(backup); return NULL; } } FunctionAST *Parser::visitFunctionDefinition(){ int backup = Tokens->getCurIndex(); PrototypeAST *proto = visitPrototype(); if(!proto){ return NULL; } // 本来であればここで再定義されていないか確認 FunctionStmtAST *func_stmt = visitFunctionStatement(proto); } <commit_msg>変数宣言のチェック<commit_after>Parcer::Parcer(std::string filename){ Tokens = LexicalAnaltysis(filename); }; /* 構文解析実行 @return 成功:true 失敗:false */ bool Parser::doParse(){ if(!Tokens){ fprintf(stderr, "error at lexer\n"); return false; } else{ return VisitTranslationUnit(); } }; TranslationUnitAST &Parser::getAST(){ if(TU){ return *TU; } else{ return *(new TranslationUnitAST()); } }; // TranslationUnit用構文解析メソッド bool Parser::visitTranslationUnit(){ TU = new TranslatonUnitAST(); // ExternalDecl while(true){ if(!visitExternalDeclaration(TU)){ SAFE_DELETE(TU); return false; } if(Tokens->getCurType == TOK_EOF){ break; } } return true; } // ExternalDeclaration用構文解析メソッド bool Parser::visitExternalDeclaration(TranslationUnitAST *tunit){ PrototypeAST *proto = visitFunctionDeclaration(); if(proto){ tunit->addPrototype(proto); return true; } FunctionAST *func_def = visitFunctionDefinition(); if(func_def){ tunit->addFunction(func_def); return true; } return false; } PrototypeAST *Parser::zisitFunctionDeclaration(){ int backup = Tokens->getCurIndex(); PrototypeAST *proto = visitPrototype(); if(!proto){ return NULL; } if(Tokens->getCurString() == ";"){ // 本来であればここで再定義されていないか確認 Tokens->getNextToken(); return proto; } else{ SAFE_DELETE(proto); Tokens->applyTokenIndex(backup); return NULL; } } FunctionAST *Parser::visitFunctionDefinition(){ int backup = Tokens->getCurIndex(); PrototypeAST *proto = visitPrototype(); if(!proto){ return NULL; } // 本来であればここで再定義されていないか確認 FunctionStmtAST *func_stmt = visitFunctionStatement(proto); } PrototypeAST *Parser::visitPrototype(){ int backup = Tokens->getCurIndex(); bool is_first_param = true; std::vector<std::string> param_list; while(true){ if(!is_first_param && Tokens->getCurType() == TOK_SYMBOL && Tokens->getCurString() == ","){ Tokens->getNextToken(); } if(Tokens->getCurType() == TOK_INT){ Tokens->getNextToken(); } else{ break; } if(Tokens->getCurType() == TOK_IDENTIFIRE){ param_list.push_back(Tokens->getCurString()); Tokens->getNextToken(); } else{ Tokens->applyTokenIndex(buckup); return NULL; } } } <|endoftext|>
<commit_before>/* * Copyright 2014 David Moreno * * 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 <iostream> #include "parser.hpp" #include "tokenizer.hpp" #include "ast.hpp" #include "ast_all.hpp" #include "program.hpp" using namespace loglang; namespace loglang{ class Parser{ Tokenizer tokenizer; AST parse_stmt(); AST parse_expr(); AST parse_expr2(); AST parse_expr3(); AST parse_expr4(); AST parse_term(); AST parse_val(); void parse_arg_list(std::unique_ptr<ast::Function> &f); AST parse_block(); Token &assert_next(Token::type_t t); public: Parser(const std::string &sourcecode); AST parse(); }; AST parse_program(const std::string &sourcecode){ Parser parser(sourcecode); return parser.parse(); } } Parser::Parser(const std::string& sourcecode) : tokenizer(sourcecode) { } AST Parser::parse() { try{ AST ret=parse_stmt(); // std::cerr<<ret->to_string()<<std::endl; return std::move(ret); } catch(parsing_exception &excp){ std::cerr<<"Error parsing: "<<excp.what()<<std::endl; std::cerr<<tokenizer.position_to_string()<<std::endl; throw; } } Token &Parser::assert_next(Token::type_t expected) { Token &tok=tokenizer.next(); if (tok.type!=expected){ print_backtrace(); std::stringstream s; s<<tokenizer.position_to_string(); s<<"Got "<<std::to_string(tok)<<" expected token type "<<expected; throw unexpected_token_type(s.str()); } return tok; } AST Parser::parse_stmt() { Token &tok=tokenizer.next(); if (tok.type==Token::OPEN_CURLY){ return parse_block(); } tokenizer.rewind(); return parse_expr(); } AST Parser::parse_block() { AST retblock=std::make_unique<ast::Block>(); ast::Block *block=static_cast<ast::Block*>(&*retblock); Token &tok=tokenizer.next(); while (tok.type!=Token::CLOSE_CURLY){ tokenizer.rewind(); block->stmts.push_back( std::move(parse_stmt()) ); assert_next(Token::COLON); tok=tokenizer.next(); } return retblock; } AST Parser::parse_expr() { AST op1=parse_expr2(); auto &op=tokenizer.next(); if (op.type==Token::OP && op.token=="="){ AST op2=parse_expr(); ASTBase *op1p=&*op1; auto var=dynamic_cast<ast::Value_var*>(op1p); if (var==nullptr){ throw semantic_exception(tokenizer.position_to_string() + "; lvalue invalid. Only variables are allowed."); } return std::make_unique<ast::Equal>(std::move(var->var), std::move(op2)); } tokenizer.rewind(); return op1; } AST Parser::parse_expr2() // < > <= >= == in and or { AST op1=parse_expr3(); auto &op=tokenizer.next(); if (op.type==Token::OP){ if (op.token=="<"){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_lt>(std::move(op1), std::move(op2)); } if (op.token==">"){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_gt>(std::move(op1), std::move(op2)); } if (op.token=="<="){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_lte>(std::move(op1), std::move(op2)); } if (op.token==">="){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_gte>(std::move(op1), std::move(op2)); } if (op.token=="=="){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_eq>(std::move(op1), std::move(op2)); } if (op.token=="!="){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_neq>(std::move(op1), std::move(op2)); } if (op.token=="and"){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_and>(std::move(op1), std::move(op2)); } if (op.token=="or"){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_or>(std::move(op1), std::move(op2)); } if (op.token=="in"){ AST op2=parse_expr2(); throw parsing_exception("'in' not yet"); //return std::make_unique<ast::Expr_gt>(std::move(op1), std::move(op2)); } } tokenizer.rewind(); // Ops, not any of those return op1; } AST Parser::parse_expr3() // + - { AST op1=parse_expr4(); auto &op=tokenizer.next(); if (op.type==Token::OP){ if (op.token=="+"){ AST op2=parse_expr3(); return std::make_unique<ast::Expr_add>(std::move(op1), std::move(op2)); } if (op.token=="-"){ AST op2=parse_expr3(); return std::make_unique<ast::Expr_sub>(std::move(op1), std::move(op2)); } } tokenizer.rewind(); // Ops, not + nor - return op1; } AST Parser::parse_expr4() // * / { AST op1=parse_term(); auto &op=tokenizer.next(); if (op.type==Token::OP){ if (op.token=="*"){ AST op2=parse_expr4(); return std::make_unique<ast::Expr_mul>(std::move(op1), std::move(op2)); } if (op.token=="/"){ AST op2=parse_expr4(); return std::make_unique<ast::Expr_div>(std::move(op1), std::move(op2)); } } tokenizer.rewind(); // Ops, not / nor * return op1; } AST Parser::parse_term() { auto &tok=tokenizer.next(); if (tok.type==Token::IF){ throw parsing_exception("'if' not yet"); } if (tok.type==Token::EDGE_IF){ auto cmp=parse_expr(); assert_next(Token::THEN); auto if_true=parse_stmt(); assert_next(Token::ELSE); auto if_false=parse_stmt(); return std::make_unique<ast::Edge_if>(std::move(cmp), std::move(if_true), std::move(if_false)); } if (tok.type==Token::AT){ auto at=parse_expr(); assert_next(Token::DO); auto then=parse_stmt(); return std::make_unique<ast::At>(std::move(at), std::move(then)); } if (tok.type==Token::OPEN_PAREN){ auto expr=parse_expr(); assert_next(Token::CLOSE_PAREN); return expr; } if (tok.type==Token::OP && tok.token=="-"){ auto expr=parse_expr(); throw parsing_exception("unary op '-' not yet"); //return std::make_unique<ast::Neg>(std::move(expr)); } tokenizer.rewind(); return parse_val(); } AST Parser::parse_val() { Token tok=tokenizer.next(); if (tok.type==Token::NUMBER || tok.type==Token::STRING){ return std::make_unique<ast::Value_const>(tok); } if (tok.type==Token::VAR){ Token &next=tokenizer.next(); if (next.type==Token::OPEN_PAREN){ auto f=std::make_unique<ast::Function>(tok.token); parse_arg_list(f); assert_next(Token::CLOSE_PAREN); return std::move(f); } tokenizer.rewind(); if (tok.type==Token::VAR){ if (std::find(std::begin(tok.token), std::end(tok.token), '*')==std::end(tok.token) && std::find(std::begin(tok.token), std::end(tok.token), '?')==std::end(tok.token)) return std::make_unique<ast::Value_var>(tok); else return std::make_unique<ast::Value_glob>(tok); } } throw unexpected_token_type(tok); } void Parser::parse_arg_list(std::unique_ptr< ast::Function >& f) { while (true){ f->params.push_back( std::move(parse_expr()) ); Token &tok=tokenizer.next(); if (tok.type==Token::CLOSE_PAREN){ tokenizer.rewind(); return; } tokenizer.rewind(); assert_next(Token::COMMA); } } <commit_msg>Allow parse "*" as var name for all vars.<commit_after>/* * Copyright 2014 David Moreno * * 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 <iostream> #include "parser.hpp" #include "tokenizer.hpp" #include "ast.hpp" #include "ast_all.hpp" #include "program.hpp" using namespace loglang; namespace loglang{ class Parser{ Tokenizer tokenizer; AST parse_stmt(); AST parse_expr(); AST parse_expr2(); AST parse_expr3(); AST parse_expr4(); AST parse_term(); AST parse_val(); void parse_arg_list(std::unique_ptr<ast::Function> &f); AST parse_block(); Token &assert_next(Token::type_t t); public: Parser(const std::string &sourcecode); AST parse(); }; AST parse_program(const std::string &sourcecode){ Parser parser(sourcecode); return parser.parse(); } } Parser::Parser(const std::string& sourcecode) : tokenizer(sourcecode) { } AST Parser::parse() { try{ AST ret=parse_stmt(); // std::cerr<<ret->to_string()<<std::endl; return std::move(ret); } catch(parsing_exception &excp){ std::cerr<<"Error parsing: "<<excp.what()<<std::endl; std::cerr<<tokenizer.position_to_string()<<std::endl; throw; } } Token &Parser::assert_next(Token::type_t expected) { Token &tok=tokenizer.next(); if (tok.type!=expected){ print_backtrace(); std::stringstream s; s<<tokenizer.position_to_string(); s<<"Got "<<std::to_string(tok)<<" expected token type "<<expected; throw unexpected_token_type(s.str()); } return tok; } AST Parser::parse_stmt() { Token &tok=tokenizer.next(); if (tok.type==Token::OPEN_CURLY){ return parse_block(); } tokenizer.rewind(); return parse_expr(); } AST Parser::parse_block() { AST retblock=std::make_unique<ast::Block>(); ast::Block *block=static_cast<ast::Block*>(&*retblock); Token &tok=tokenizer.next(); while (tok.type!=Token::CLOSE_CURLY){ tokenizer.rewind(); block->stmts.push_back( std::move(parse_stmt()) ); assert_next(Token::COLON); tok=tokenizer.next(); } return retblock; } AST Parser::parse_expr() { AST op1=parse_expr2(); auto &op=tokenizer.next(); if (op.type==Token::OP && op.token=="="){ AST op2=parse_expr(); ASTBase *op1p=&*op1; auto var=dynamic_cast<ast::Value_var*>(op1p); if (var==nullptr){ throw semantic_exception(tokenizer.position_to_string() + "; lvalue invalid. Only variables are allowed."); } return std::make_unique<ast::Equal>(std::move(var->var), std::move(op2)); } tokenizer.rewind(); return op1; } AST Parser::parse_expr2() // < > <= >= == in and or { AST op1=parse_expr3(); auto &op=tokenizer.next(); if (op.type==Token::OP){ if (op.token=="<"){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_lt>(std::move(op1), std::move(op2)); } if (op.token==">"){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_gt>(std::move(op1), std::move(op2)); } if (op.token=="<="){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_lte>(std::move(op1), std::move(op2)); } if (op.token==">="){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_gte>(std::move(op1), std::move(op2)); } if (op.token=="=="){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_eq>(std::move(op1), std::move(op2)); } if (op.token=="!="){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_neq>(std::move(op1), std::move(op2)); } if (op.token=="and"){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_and>(std::move(op1), std::move(op2)); } if (op.token=="or"){ AST op2=parse_expr2(); return std::make_unique<ast::Expr_or>(std::move(op1), std::move(op2)); } if (op.token=="in"){ AST op2=parse_expr2(); throw parsing_exception("'in' not yet"); //return std::make_unique<ast::Expr_gt>(std::move(op1), std::move(op2)); } } tokenizer.rewind(); // Ops, not any of those return op1; } AST Parser::parse_expr3() // + - { AST op1=parse_expr4(); auto &op=tokenizer.next(); if (op.type==Token::OP){ if (op.token=="+"){ AST op2=parse_expr3(); return std::make_unique<ast::Expr_add>(std::move(op1), std::move(op2)); } if (op.token=="-"){ AST op2=parse_expr3(); return std::make_unique<ast::Expr_sub>(std::move(op1), std::move(op2)); } } tokenizer.rewind(); // Ops, not + nor - return op1; } AST Parser::parse_expr4() // * / { AST op1=parse_term(); auto &op=tokenizer.next(); if (op.type==Token::OP){ if (op.token=="*"){ AST op2=parse_expr4(); return std::make_unique<ast::Expr_mul>(std::move(op1), std::move(op2)); } if (op.token=="/"){ AST op2=parse_expr4(); return std::make_unique<ast::Expr_div>(std::move(op1), std::move(op2)); } } tokenizer.rewind(); // Ops, not / nor * return op1; } AST Parser::parse_term() { auto &tok=tokenizer.next(); if (tok.type==Token::IF){ throw parsing_exception("'if' not yet"); } if (tok.type==Token::EDGE_IF){ auto cmp=parse_expr(); assert_next(Token::THEN); auto if_true=parse_stmt(); assert_next(Token::ELSE); auto if_false=parse_stmt(); return std::make_unique<ast::Edge_if>(std::move(cmp), std::move(if_true), std::move(if_false)); } if (tok.type==Token::AT){ auto at=parse_expr(); assert_next(Token::DO); auto then=parse_stmt(); return std::make_unique<ast::At>(std::move(at), std::move(then)); } if (tok.type==Token::OPEN_PAREN){ auto expr=parse_expr(); assert_next(Token::CLOSE_PAREN); return expr; } if (tok.type==Token::OP && tok.token=="-"){ auto expr=parse_expr(); throw parsing_exception("unary op '-' not yet"); //return std::make_unique<ast::Neg>(std::move(expr)); } tokenizer.rewind(); return parse_val(); } AST Parser::parse_val() { Token tok=tokenizer.next(); if (tok.type==Token::NUMBER || tok.type==Token::STRING){ return std::make_unique<ast::Value_const>(tok); } if (tok.token=="*") // All vars glob tok.type=Token::VAR; if (tok.type==Token::VAR){ Token &next=tokenizer.next(); if (next.type==Token::OPEN_PAREN){ auto f=std::make_unique<ast::Function>(tok.token); parse_arg_list(f); assert_next(Token::CLOSE_PAREN); return std::move(f); } tokenizer.rewind(); if (tok.type==Token::VAR){ if (std::find(std::begin(tok.token), std::end(tok.token), '*')==std::end(tok.token) && std::find(std::begin(tok.token), std::end(tok.token), '?')==std::end(tok.token)) return std::make_unique<ast::Value_var>(tok); else return std::make_unique<ast::Value_glob>(tok); } } throw unexpected_token_type(tok); } void Parser::parse_arg_list(std::unique_ptr< ast::Function >& f) { while (true){ f->params.push_back( std::move(parse_expr()) ); Token &tok=tokenizer.next(); if (tok.type==Token::CLOSE_PAREN){ tokenizer.rewind(); return; } tokenizer.rewind(); assert_next(Token::COMMA); } } <|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) 2011 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/base/init.h> #include <shogun/features/SparseFeatures.h> #include <shogun/features/Subset.h> using namespace shogun; void print_message(FILE* target, const char* str) { fprintf(target, "%s", str); } const int32_t num_vectors=6; const int32_t dim_features=6; void check_transposed(CSparseFeatures<int32_t>* features) { CSparseFeatures<int32_t>* transposed=features->get_transposed(); CSparseFeatures<int32_t>* double_transposed=transposed->get_transposed(); for (index_t i=0; i<features->get_num_vectors(); ++i) { int32_t len; bool free_1, free_2; SGSparseVectorEntry<int32_t>* orig_vec= features->get_sparse_feature_vector(i, len, free_1); SGSparseVectorEntry<int32_t>* new_vec= double_transposed->get_sparse_feature_vector(i, len, free_2); for (index_t j=0; j<len; j++) ASSERT(orig_vec[j].entry==new_vec[j].entry); /* not necessary since feature matrix is in memory. for documentation */ features->free_sparse_feature_vector(orig_vec, i, free_1); double_transposed->free_sparse_feature_vector(new_vec, i, free_2); } SG_UNREF(transposed); SG_UNREF(double_transposed); } int main(int argc, char **argv) { init_shogun(&print_message, &print_message, &print_message); const int32_t num_subset_idx=CMath::random(1, num_vectors); /* create feature data matrix */ SGMatrix<int32_t> data(dim_features, num_vectors); /* fill matrix with random data */ for (index_t i=0; i<num_vectors*dim_features; ++i) data.matrix[i]=CMath::random(1, 9); /* create sparse features */ CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); /* print dense feature matrix */ CMath::display_matrix(data.matrix, data.num_rows, data.num_cols, "dense feature matrix"); /* create subset indices */ SGVector<index_t> subset_idx(CMath::randperm(num_subset_idx), num_subset_idx); /* print subset indices */ CMath::display_vector(subset_idx.vector, subset_idx.vlen, "subset indices"); /* apply subset to features */ SG_SPRINT("\n-------------------\n" "applying subset to features\n" "-------------------\n"); features->set_subset(new CSubset(subset_idx)); /* do some stuff do check and output */ ASSERT(features->get_num_vectors()==num_subset_idx); SG_SPRINT("features->get_num_vectors(): %d\n", features->get_num_vectors()); /* check get_Transposed method */ SG_SPRINT("checking transpose..."); check_transposed(features); SG_SPRINT("does work\n"); for (index_t i=0; i<features->get_num_vectors(); ++i) { int32_t len; bool free; SGSparseVectorEntry<int32_t>* vec=features->get_sparse_feature_vector(i, len, free); SG_SPRINT("sparse_vector[%d]=", i); for (index_t j=0; j<len; ++j) { SG_SPRINT("%d", vec[j].entry); if (j<len-1) SG_SPRINT(","); } SG_SPRINT("\n"); for (index_t j=0; j<len; ++j) ASSERT( vec[j].entry==data.matrix[features->subset_idx_conversion( i)*num_vectors+j]); /* not necessary since feature matrix is in memory. for documentation */ features->free_sparse_feature_vector(vec, i, free); } /* remove features subset */ SG_SPRINT("\n-------------------\n" "removing subset from features\n" "-------------------\n"); features->remove_subset(); /* do some stuff do check and output */ ASSERT(features->get_num_vectors()==num_vectors); SG_SPRINT("features->get_num_vectors(): %d\n", features->get_num_vectors()); /* check get_Transposed method */ SG_SPRINT("checking transpose..."); check_transposed(features); SG_SPRINT("does work\n"); for (index_t i=0; i<features->get_num_vectors(); ++i) { int32_t len; bool free; SGSparseVectorEntry<int32_t>* vec=features->get_sparse_feature_vector(i, len, free); SG_SPRINT("sparse_vector[%d]=", i); for (index_t j=0; j<len; ++j) { SG_SPRINT("%d", vec[j].entry); if (j<len-1) SG_SPRINT(","); } SG_SPRINT("\n"); for (index_t j=0; j<len; ++j) ASSERT(vec[j].entry==data.matrix[i*num_vectors+j]); /* not necessary since feature matrix is in memory. for documentation */ features->free_sparse_feature_vector(vec, i, free); } SG_UNREF(features); SG_FREE(data.matrix); SG_SPRINT("\nEND\n"); exit_shogun(); return 0; } <commit_msg>applied get_spare_vector() changes<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) 2011 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/base/init.h> #include <shogun/features/SparseFeatures.h> #include <shogun/features/Subset.h> using namespace shogun; void print_message(FILE* target, const char* str) { fprintf(target, "%s", str); } const int32_t num_vectors=6; const int32_t dim_features=6; void check_transposed(CSparseFeatures<int32_t>* features) { CSparseFeatures<int32_t>* transposed=features->get_transposed(); CSparseFeatures<int32_t>* double_transposed=transposed->get_transposed(); for (index_t i=0; i<features->get_num_vectors(); ++i) { SGSparseVector<int32_t> orig_vec=features->get_sparse_feature_vector(i); SGSparseVector<int32_t> new_vec= double_transposed->get_sparse_feature_vector(i); for (index_t j=0; j<dim_features; j++) ASSERT(orig_vec.features[j].entry==new_vec.features[j].entry); /* not necessary since feature matrix is in memory. for documentation */ features->free_sparse_feature_vector(orig_vec, i); double_transposed->free_sparse_feature_vector(new_vec, i); } SG_UNREF(transposed); SG_UNREF(double_transposed); } int main(int argc, char **argv) { init_shogun(&print_message, &print_message, &print_message); const int32_t num_subset_idx=CMath::random(1, num_vectors); /* create feature data matrix */ SGMatrix<int32_t> data(dim_features, num_vectors); /* fill matrix with random data */ for (index_t i=0; i<num_vectors*dim_features; ++i) data.matrix[i]=CMath::random(1, 9); /* create sparse features */ CSparseFeatures<int32_t>* features=new CSparseFeatures<int32_t>(data); /* print dense feature matrix */ CMath::display_matrix(data.matrix, data.num_rows, data.num_cols, "dense feature matrix"); /* create subset indices */ SGVector<index_t> subset_idx(CMath::randperm(num_subset_idx), num_subset_idx); /* print subset indices */ CMath::display_vector(subset_idx.vector, subset_idx.vlen, "subset indices"); /* apply subset to features */ SG_SPRINT("\n-------------------\n" "applying subset to features\n" "-------------------\n"); features->set_subset(new CSubset(subset_idx)); /* do some stuff do check and output */ ASSERT(features->get_num_vectors()==num_subset_idx); SG_SPRINT("features->get_num_vectors(): %d\n", features->get_num_vectors()); /* check get_Transposed method */ SG_SPRINT("checking transpose..."); check_transposed(features); SG_SPRINT("does work\n"); for (index_t i=0; i<features->get_num_vectors(); ++i) { SGSparseVector<int32_t> vec=features->get_sparse_feature_vector(i); SG_SPRINT("sparse_vector[%d]=", i); for (index_t j=0; j<vec.num_feat_entries; ++j) { SG_SPRINT("%d", vec.features[j].entry); if (j<vec.num_feat_entries-1) SG_SPRINT(","); } SG_SPRINT("\n"); for (index_t j=0; j<vec.num_feat_entries; ++j) { int32_t a=vec.features[j].entry; index_t ind=features->subset_idx_conversion(i)*num_vectors+j; int32_t b=data.matrix[ind]; ASSERT(a==b); } features->free_sparse_feature_vector(vec, i); } /* remove features subset */ SG_SPRINT("\n-------------------\n" "removing subset from features\n" "-------------------\n"); features->remove_subset(); /* do some stuff do check and output */ ASSERT(features->get_num_vectors()==num_vectors); SG_SPRINT("features->get_num_vectors(): %d\n", features->get_num_vectors()); /* check get_Transposed method */ SG_SPRINT("checking transpose..."); check_transposed(features); SG_SPRINT("does work\n"); for (index_t i=0; i<features->get_num_vectors(); ++i) { SGSparseVector<int32_t> vec=features->get_sparse_feature_vector(i); SG_SPRINT("sparse_vector[%d]=", i); for (index_t j=0; j<vec.num_feat_entries; ++j) { SG_SPRINT("%d", vec.features[j].entry); if (j<vec.num_feat_entries-1) SG_SPRINT(","); } SG_SPRINT("\n"); for (index_t j=0; j<vec.num_feat_entries; ++j) ASSERT(vec.features[j].entry==data.matrix[i*num_vectors+j]); features->free_sparse_feature_vector(vec, i); } SG_UNREF(features); SG_FREE(data.matrix); exit_shogun(); return 0; } <|endoftext|>
<commit_before>/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __elxRayCastResampleInterpolator_hxx #define __elxRayCastResampleInterpolator_hxx #include "elxRayCastResampleInterpolator.h" #include "itkImageFileWriter.h" namespace elastix { using namespace itk; /* * ***************** BeforeAll ***************** */ template <class TElastix> void RayCastResampleInterpolator<TElastix> ::InitializeRayCastInterpolator( void ) { this->m_CombinationTransform = CombinationTransformType::New(); this->m_CombinationTransform->SetUseComposition( true ); typedef typename elastix::OptimizerBase< TElastix>::ITKBaseType::ParametersType ParametersType; this->m_PreTransform = EulerTransformType::New(); unsigned int numberofparameters = this->m_PreTransform->GetNumberOfParameters(); TransformParametersType preParameters( numberofparameters ); preParameters.Fill( 0.0 ); for ( unsigned int i = 0; i < numberofparameters; i++ ) { bool ret = this->GetConfiguration()->ReadParameter( preParameters[ i ], "PreParameters", this->GetComponentLabel(), i, 0 ); if ( !ret ) { std::cerr << " Error, not enough PreParameters are given" << std::endl; } } typename EulerTransformType::InputPointType centerofrotation; centerofrotation.Fill( 0.0 ); for( unsigned int i = 0; i < this->m_Elastix->GetMovingImage()->GetImageDimension() ; i++ ) { this->GetConfiguration()->ReadParameter( centerofrotation[ i ], "CenterOfRotationPoint", this->GetComponentLabel(), i, 0 ); } this->m_PreTransform->SetParameters( preParameters ); this->m_PreTransform->SetCenter( centerofrotation ); this->m_CombinationTransform->SetInitialTransform( this->m_PreTransform ); this->m_CombinationTransform->SetCurrentTransform( this->m_Elastix->GetElxTransformBase()->GetAsITKBaseType() ); this->SetTransform( this->m_CombinationTransform ); this->SetInputImage( this->m_Elastix->GetMovingImage() ); PointType focalPoint; focalPoint.Fill( 0.0 ); for ( unsigned int i = 0; i < this->m_Elastix->GetFixedImage()->GetImageDimension(); i++ ) { bool ret = this->GetConfiguration()->ReadParameter( focalPoint[ i ], "FocalPoint", this->GetComponentLabel(), i, 0 ); if ( !ret ) { std::cerr << " Error, FocalPoint not assigned" << std::endl; } } this->SetFocalPoint( focalPoint ); this->m_Elastix->GetElxResamplerBase()->GetAsITKBaseType()->SetTransform( this->m_CombinationTransform ); double threshold = 0.; this->GetConfiguration()->ReadParameter( threshold, "Threshold", 0 ); this->SetThreshold( threshold ); } // end InitializeRayCastInterpolator() /* * ***************** BeforeAll ***************** */ template <class TElastix> int RayCastResampleInterpolator<TElastix> ::BeforeAll( void ) { // Check if 2D-3D if ( this->m_Elastix->GetFixedImage()->GetImageDimension() != 3 ) { itkExceptionMacro( << "The RayCastInterpolator expects the fixed image to be 3D." ); return 1; } if ( this->m_Elastix->GetMovingImage()->GetImageDimension() != 3 ) { itkExceptionMacro( << "The RayCastInterpolator expects the moving image to be 3D." ); return 1; } return 0; } // end BeforeAll() /* * ***************** BeforeRegistration ***************** */ template <class TElastix> void RayCastResampleInterpolator<TElastix> ::BeforeRegistration( void ) { this->InitializeRayCastInterpolator(); } // end BeforeRegistration() /* * ***************** ReadFromFile ***************** */ template <class TElastix> void RayCastResampleInterpolator<TElastix> ::ReadFromFile( void ) { /** Call ReadFromFile of the ResamplerBase. */ this->Superclass2::ReadFromFile(); this->InitializeRayCastInterpolator(); } // end ReadFromFile() /** * ******************* WriteToFile ****************************** */ template <class TElastix> void RayCastResampleInterpolator<TElastix> ::WriteToFile( void ) const { /** Call WriteToFile of the ResamplerBase. */ this->Superclass2::WriteToFile(); PointType focalpoint = this->GetFocalPoint(); xout["transpar"] << "(" << "FocalPoint "; for( unsigned int i = 0; i < this->m_Elastix->GetMovingImage()->GetImageDimension() ; i++ ) { xout["transpar"] << focalpoint[i] << " "; } xout["transpar"] << ")" << std::endl; typedef typename elastix::OptimizerBase<TElastix>::ITKBaseType::ParametersType ParametersType; TransformParametersType preParameters = this->m_PreTransform->GetParameters(); xout["transpar"] << "(" << "PreParameters "; unsigned int numberofparameters = this->m_Elastix->GetElxTransformBase()->GetAsITKBaseType()->GetNumberOfParameters(); for( unsigned int i = 0; i < numberofparameters; i++ ) { xout["transpar"] << preParameters[i] << " "; } xout["transpar"]<< ")" << std::endl; double threshold = this->GetThreshold(); xout["transpar"] << "(Threshold " << threshold << ")" << std::endl; } // end WriteToFile() } // end namespace elastix #endif // end #ifndef __elxRayCastResampleInterpolator_hxx <commit_msg>SK:<commit_after>/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __elxRayCastResampleInterpolator_hxx #define __elxRayCastResampleInterpolator_hxx #include "elxRayCastResampleInterpolator.h" #include "itkImageFileWriter.h" namespace elastix { using namespace itk; /* * ***************** BeforeAll ***************** */ template <class TElastix> void RayCastResampleInterpolator<TElastix> ::InitializeRayCastInterpolator( void ) { this->m_CombinationTransform = CombinationTransformType::New(); this->m_CombinationTransform->SetUseComposition( true ); typedef typename elastix::OptimizerBase< TElastix>::ITKBaseType::ParametersType ParametersType; this->m_PreTransform = EulerTransformType::New(); unsigned int numberofparameters = this->m_PreTransform->GetNumberOfParameters(); TransformParametersType preParameters( numberofparameters ); preParameters.Fill( 0.0 ); for ( unsigned int i = 0; i < numberofparameters; i++ ) { bool ret = this->GetConfiguration()->ReadParameter( preParameters[ i ], "PreParameters", this->GetComponentLabel(), i, 0 ); if ( !ret ) { std::cerr << " Error, not enough PreParameters are given" << std::endl; } } typename EulerTransformType::InputPointType centerofrotation; centerofrotation.Fill( 0.0 ); for( unsigned int i = 0; i < this->m_Elastix->GetMovingImage()->GetImageDimension() ; i++ ) { this->GetConfiguration()->ReadParameter( centerofrotation[ i ], "CenterOfRotationPoint", this->GetComponentLabel(), i, 0 ); } this->m_PreTransform->SetParameters( preParameters ); this->m_PreTransform->SetCenter( centerofrotation ); this->m_CombinationTransform->SetInitialTransform( this->m_PreTransform ); this->m_CombinationTransform->SetCurrentTransform( this->m_Elastix->GetElxTransformBase()->GetAsITKBaseType() ); this->SetTransform( this->m_CombinationTransform ); this->SetInputImage( this->m_Elastix->GetMovingImage() ); PointType focalPoint; focalPoint.Fill( 0.0 ); for ( unsigned int i = 0; i < this->m_Elastix->GetFixedImage()->GetImageDimension(); i++ ) { bool ret = this->GetConfiguration()->ReadParameter( focalPoint[ i ], "FocalPoint", this->GetComponentLabel(), i, 0 ); if ( !ret ) { std::cerr << " Error, FocalPoint not assigned" << std::endl; } } this->SetFocalPoint( focalPoint ); this->m_Elastix->GetElxResamplerBase()->GetAsITKBaseType()->SetTransform( this->m_CombinationTransform ); double threshold = 0.; this->GetConfiguration()->ReadParameter( threshold, "Threshold", 0 ); this->SetThreshold( threshold ); } // end InitializeRayCastInterpolator() /* * ***************** BeforeAll ***************** */ template <class TElastix> int RayCastResampleInterpolator<TElastix> ::BeforeAll( void ) { // Check if 2D-3D if ( this->m_Elastix->GetFixedImage()->GetImageDimension() != 3 ) { itkExceptionMacro( << "The RayCastInterpolator expects the fixed image to be 3D." ); return 1; } if ( this->m_Elastix->GetMovingImage()->GetImageDimension() != 3 ) { itkExceptionMacro( << "The RayCastInterpolator expects the moving image to be 3D." ); return 1; } return 0; } // end BeforeAll() /* * ***************** BeforeRegistration ***************** */ template <class TElastix> void RayCastResampleInterpolator<TElastix> ::BeforeRegistration( void ) { this->InitializeRayCastInterpolator(); } // end BeforeRegistration() /* * ***************** ReadFromFile ***************** */ template <class TElastix> void RayCastResampleInterpolator<TElastix> ::ReadFromFile( void ) { /** Call ReadFromFile of the ResamplerBase. */ this->Superclass2::ReadFromFile(); this->InitializeRayCastInterpolator(); } // end ReadFromFile() /** * ******************* WriteToFile ****************************** */ template <class TElastix> void RayCastResampleInterpolator<TElastix> ::WriteToFile( void ) const { /** Call WriteToFile of the ResamplerBase. */ this->Superclass2::WriteToFile(); PointType focalpoint = this->GetFocalPoint(); xout["transpar"] << "(" << "FocalPoint "; for( unsigned int i = 0; i < this->m_Elastix->GetMovingImage()->GetImageDimension() ; i++ ) { xout["transpar"] << focalpoint[i] << " "; } xout["transpar"] << ")" << std::endl; typedef typename elastix::OptimizerBase<TElastix>::ITKBaseType::ParametersType ParametersType; TransformParametersType preParameters = this->m_PreTransform->GetParameters(); xout["transpar"] << "(" << "PreParameters "; unsigned int numberofparameters = preParameters.GetSize(); for( unsigned int i = 0; i < numberofparameters; i++ ) { xout["transpar"] << preParameters[i] << " "; } xout["transpar"]<< ")" << std::endl; double threshold = this->GetThreshold(); xout["transpar"] << "(Threshold " << threshold << ")" << std::endl; } // end WriteToFile() } // end namespace elastix #endif // end #ifndef __elxRayCastResampleInterpolator_hxx <|endoftext|>
<commit_before>#include <primio.h> #include <algorithm> #include <bits.h> #include <cassert> #include <charconv> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> #include <exception.h> #include <fcntl.h> #include <kv.h> #include <l.h> #include <o.h> #include <output.h> #include <sym.h> #include <unistd.h> namespace { const index_t BUFFER_SIZE = 4064; H blush(H h); // stdout and stderr are initialized specially so they can be used for // debugging before write_buffers is initialized. We could use the Schwarz // counter to make sure write_buffers is initialized, but we don't want to, // since write_buffers allocates memory from the buddy allocator. List<X>* init_static_buf(void* p) { static_assert(sizeof(List<X>) == 24); assert((bitcast<std::uintptr_t>(p) & 31) == 0); List<X>* const buf = new (static_cast<char*>(p) + 8) List<X>; buf->a = Attr::none; buf->apadv = Opcode(0); buf->arity = 0; buf->r = 1; buf->n = 0; buf->type = ObjectTraits<X>::typet(); return buf; } alignas(32) char ebuf[BUFFER_SIZE + 32]; List<X>* err() { static List<X>* buf; if (!buf) buf = init_static_buf(ebuf); return buf; } alignas(32) char obuf[BUFFER_SIZE + 32]; List<X>* out() { static List<X>* buf; if (!buf) buf = init_static_buf(obuf); return buf; } struct WriteBuffers { WriteBuffers() = default; ~WriteBuffers() { blush(H(1)); blush(H(2)); for (H h: d.key()) blush(h); } WriteBuffers(const WriteBuffers&) = delete; WriteBuffers& operator=(const WriteBuffers&) = delete; List<X>* operator[](H h) { return h == H(1)? out() : h == H(2)? err() : d.has(h) ? d[h].get() : /* else */ nullptr; } void add(H h) { d.add(h, new_buffer()); } void remove(H h) { d.remove(h); } private: KV<H, L<X>> d; static L<X> new_buffer() { return L<X>(make_empty_list<X>(BUFFER_SIZE)); } } write_buffers; ssize_t writeall(int fd, const void* buf, index_t n) { const char* const p = static_cast<const char*>(buf); index_t total = 0; while (total < n) { const ssize_t written = write(fd, p + total, std::size_t(n - total)); if (0 <= written) total += written; else if (errno != EINTR) return written; } return total; } H bblush(H h, char* buf, index_t* tail) { if (writeall(H::rep(h), buf, *tail) < 0) throw Exception("'os"); *tail = 0; return h; } H blush(H h) { List<X>* const buf = write_buffers[h]; if (!buf) return h; return bblush(h, reinterpret_cast<char*>(buf->begin()), &buf->n); } H bbrite(H h, const void* p, index_t n, char* buf, index_t* tail) { const index_t avail = BUFFER_SIZE - *tail; if (n <= avail) { memcpy(buf + *tail, p, std::size_t(n)); *tail += n; } else if (n <= BUFFER_SIZE + avail) { memcpy(buf + *tail, p, std::size_t(avail)); *tail += avail; bblush(h, buf, tail); memcpy(buf, static_cast<const char*>(p) + avail, std::size_t(n - avail)); *tail = n - avail; } else { bblush(h, buf, tail); if (writeall(H::rep(h), p, n) < 0) throw Exception("'os"); } return h; } H brite(H h, const void* p, index_t n) { List<X>* const buf = write_buffers[h]; if (buf) bbrite(h, p, n, reinterpret_cast<char*>(buf->begin()), &buf->n); else if (writeall(H::rep(h), p, n) < 0) throw Exception("'os"); return h; } H hopen(const char* path, int flags) { const int allrw = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH; const int fd = open(path, flags, allrw); if (fd != -1) write_buffers.add(H(fd)); return H(fd); } } // unnamed H hopen(const char* path) { return hopen(path, O_CREAT|O_RDWR); } H hopen(const char* path, Truncate) { return hopen(path, O_CREAT|O_RDWR|O_TRUNC); } void hclose(H h) { blush(h); write_buffers.remove(h); close(H::rep(h)); } H escape(H h, C x) { return escapec(h, x); } H flush(H h) { return blush(h); } H operator<<(H h, H(*f)(H)) { return f(h); } H operator<<(H h, const char* s) { return brite(h, s , index_t(strlen(s))); } H operator<<(H h, char c) { return brite(h, &c, 1); } H operator<<(H h, uint8_t x) { return brite(h, &x, 1); } H operator<<(H h, double x) { return write_double(h, x); } H operator<<(H h, int32_t x) { return write_int64(h, x); } H operator<<(H h, int64_t x) { return write_int64(h, x); } H operator<<(H h, uint32_t x) { return write_uint64(h, x); } H operator<<(H h, uint64_t x) { return write_uint64(h, x); } #ifndef __GNUG__ // TODO need to test if std::is_same_v<uin64_t, std::size_t> // or just make one of them unnecessary H operator<<(H h, std::size_t x) { return write_uint64(h, x); } #endif H operator<<(H h, const void* x) { return write_pointer(h, x); } H operator<<(H h, std::pair<const char*, const char*> x) { return brite(h, x.first, x.second - x.first); } H operator<<(H h, B x) { return h << "01"[B::rep(x)] << 'b'; } H operator<<(H h, C x) { return h << C::rep(x); } H operator<<(H h, D x) { return write_date(h, x); } H operator<<(H h, F x) { return h << F::rep(x); } H operator<<(H h, H x) { return h << H::rep(x); } H operator<<(H h, I x) { return x.is_null()? h << "0Ni" : x == WI ? h << "0Wi" : x == -WI ? h << "-0Wi" : /* else */ h << I::rep(x); } H operator<<(H h, J x) { return x.is_null()? h << "0N" : x == WJ ? h << "0W" : x == -WJ ? h << "-0W" : /* else */ h << J::rep(x); } H operator<<(H h, S x) { return h << '`' << c_str(x); } H operator<<(H h, T x) { return write_time(h, x); } H operator<<(H h, X x) { return write_byte(h, x); } H operator<<(H h, std::pair<const C*, const C*> x) { assert(x.first <= x.second); return brite(h, x.first, x.second - x.first); } <commit_msg>Revert AP change to primio.cpp<commit_after>#include <primio.h> #include <algorithm> #include <bits.h> #include <cassert> #include <charconv> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> #include <exception.h> #include <fcntl.h> #include <kv.h> #include <l.h> #include <o.h> #include <output.h> #include <sym.h> #include <unistd.h> namespace { const index_t BUFFER_SIZE = 4064; H blush(H h); // stdout and stderr are initialized specially so they can be used for // debugging before write_buffers is initialized. We could use the Schwarz // counter to make sure write_buffers is initialized, but we don't want to, // since write_buffers allocates memory from the buddy allocator. List<X>* init_static_buf(void* p) { static_assert(sizeof(List<X>) == 24); assert((bitcast<std::uintptr_t>(p) & 31) == 0); List<X>* const buf = new (static_cast<char*>(p) + 8) List<X>; buf->a = Attr::none; buf->m = 0; buf->r = 1; buf->n = 0; buf->type = ObjectTraits<X>::typet(); return buf; } alignas(32) char ebuf[BUFFER_SIZE + 32]; List<X>* err() { static List<X>* buf; if (!buf) buf = init_static_buf(ebuf); return buf; } alignas(32) char obuf[BUFFER_SIZE + 32]; List<X>* out() { static List<X>* buf; if (!buf) buf = init_static_buf(obuf); return buf; } struct WriteBuffers { WriteBuffers() = default; ~WriteBuffers() { blush(H(1)); blush(H(2)); for (H h: d.key()) blush(h); } WriteBuffers(const WriteBuffers&) = delete; WriteBuffers& operator=(const WriteBuffers&) = delete; List<X>* operator[](H h) { return h == H(1)? out() : h == H(2)? err() : d.has(h) ? d[h].get() : /* else */ nullptr; } void add(H h) { d.add(h, new_buffer()); } void remove(H h) { d.remove(h); } private: KV<H, L<X>> d; static L<X> new_buffer() { return L<X>(make_empty_list<X>(BUFFER_SIZE)); } } write_buffers; ssize_t writeall(int fd, const void* buf, index_t n) { const char* const p = static_cast<const char*>(buf); index_t total = 0; while (total < n) { const ssize_t written = write(fd, p + total, std::size_t(n - total)); if (0 <= written) total += written; else if (errno != EINTR) return written; } return total; } H bblush(H h, char* buf, index_t* tail) { if (writeall(H::rep(h), buf, *tail) < 0) throw Exception("'os"); *tail = 0; return h; } H blush(H h) { List<X>* const buf = write_buffers[h]; if (!buf) return h; return bblush(h, reinterpret_cast<char*>(buf->begin()), &buf->n); } H bbrite(H h, const void* p, index_t n, char* buf, index_t* tail) { const index_t avail = BUFFER_SIZE - *tail; if (n <= avail) { memcpy(buf + *tail, p, std::size_t(n)); *tail += n; } else if (n <= BUFFER_SIZE + avail) { memcpy(buf + *tail, p, std::size_t(avail)); *tail += avail; bblush(h, buf, tail); memcpy(buf, static_cast<const char*>(p) + avail, std::size_t(n - avail)); *tail = n - avail; } else { bblush(h, buf, tail); if (writeall(H::rep(h), p, n) < 0) throw Exception("'os"); } return h; } H brite(H h, const void* p, index_t n) { List<X>* const buf = write_buffers[h]; if (buf) bbrite(h, p, n, reinterpret_cast<char*>(buf->begin()), &buf->n); else if (writeall(H::rep(h), p, n) < 0) throw Exception("'os"); return h; } H hopen(const char* path, int flags) { const int allrw = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH; const int fd = open(path, flags, allrw); if (fd != -1) write_buffers.add(H(fd)); return H(fd); } } // unnamed H hopen(const char* path) { return hopen(path, O_CREAT|O_RDWR); } H hopen(const char* path, Truncate) { return hopen(path, O_CREAT|O_RDWR|O_TRUNC); } void hclose(H h) { blush(h); write_buffers.remove(h); close(H::rep(h)); } H escape(H h, C x) { return escapec(h, x); } H flush(H h) { return blush(h); } H operator<<(H h, H(*f)(H)) { return f(h); } H operator<<(H h, const char* s) { return brite(h, s , index_t(strlen(s))); } H operator<<(H h, char c) { return brite(h, &c, 1); } H operator<<(H h, uint8_t x) { return brite(h, &x, 1); } H operator<<(H h, double x) { return write_double(h, x); } H operator<<(H h, int32_t x) { return write_int64(h, x); } H operator<<(H h, int64_t x) { return write_int64(h, x); } H operator<<(H h, uint32_t x) { return write_uint64(h, x); } H operator<<(H h, uint64_t x) { return write_uint64(h, x); } #ifndef __GNUG__ // TODO need to test if std::is_same_v<uin64_t, std::size_t> // or just make one of them unnecessary H operator<<(H h, std::size_t x) { return write_uint64(h, x); } #endif H operator<<(H h, const void* x) { return write_pointer(h, x); } H operator<<(H h, std::pair<const char*, const char*> x) { return brite(h, x.first, x.second - x.first); } H operator<<(H h, B x) { return h << "01"[B::rep(x)] << 'b'; } H operator<<(H h, C x) { return h << C::rep(x); } H operator<<(H h, D x) { return write_date(h, x); } H operator<<(H h, F x) { return h << F::rep(x); } H operator<<(H h, H x) { return h << H::rep(x); } H operator<<(H h, I x) { return x.is_null()? h << "0Ni" : x == WI ? h << "0Wi" : x == -WI ? h << "-0Wi" : /* else */ h << I::rep(x); } H operator<<(H h, J x) { return x.is_null()? h << "0N" : x == WJ ? h << "0W" : x == -WJ ? h << "-0W" : /* else */ h << J::rep(x); } H operator<<(H h, S x) { return h << '`' << c_str(x); } H operator<<(H h, T x) { return write_time(h, x); } H operator<<(H h, X x) { return write_byte(h, x); } H operator<<(H h, std::pair<const C*, const C*> x) { assert(x.first <= x.second); return brite(h, x.first, x.second - x.first); } <|endoftext|>
<commit_before>struct Client1; struct Client2; typedef Visitor<Client1, Client2> BaseClientVisitor; struct Client1 : BaseClientVisitor::Visitable<Client1> { }; struct Client2 : BaseClientVisitor::Visitable<Client2> { }; struct Client2a; struct Client2b; typedef Visitor<Client2a, Client2b> Client2Visitor; struct Client2a : Client2, Client2Visitor::Visitable<Clien2a> { }; struct Client2b : Client2, Client2Visitor::Visitable<Clien2b> { }; struct AllClientsVisitor : BaseClientVisitor, Client2Visitor { virtual void visit( Client2 & t ) { t.accept( static_cast<Client2Visitor&>(*this) ); } }; <commit_msg>Update visitor_test.cpp<commit_after>struct Client1; struct Client2; typedef Visitor<Client1, Client2> BaseClientVisitor; struct Client1 : BaseClientVisitor::Visitable<Client1> { }; struct Client2 : BaseClientVisitor::Visitable<Client2> { }; struct Client2a; struct Client2b; typedef Visitor<Client2a, Client2b> Client2Visitor; struct Client2a : Client2, Client2Visitor::Visitable<Clien2a> { }; struct Client2b : Client2, Client2Visitor::Visitable<Clien2b> { }; struct AllClientsVisitor : BaseClientVisitor, Client2Visitor { virtual void visit( Client2 & t ) { t.accept( static_cast<Client2Visitor&>(*this) ); } }; <|endoftext|>
<commit_before>#include "wide_graph_with_listener.h" #include "../src/transwarp.h" #include <iostream> #include <fstream> #include <random> #include <numeric> namespace tw = transwarp; namespace { std::mt19937 gen{1}; std::mutex mutex; // protect the generator using data_t = std::shared_ptr<std::vector<double>>; data_t transform(data_t data) { std::uniform_real_distribution<double> dist(0.5, 1.5); for (auto& v : *data) { std::lock_guard<std::mutex> lock{mutex}; v *= dist(gen); } return data; } double mean(data_t data) { return std::accumulate(data->begin(), data->end(), 0.) / static_cast<double>(data->size()); } class listener : public tw::listener { public: // Note: this is called on the thread the task is run on for the after_finished event void handle_event(tw::event_type event, const std::shared_ptr<tw::node>&) { if (event == tw::event_type::after_finished) { // task has finished } } }; std::shared_ptr<tw::task<double>> build_graph(std::shared_ptr<tw::task<data_t>> input) { std::vector<std::shared_ptr<tw::task<data_t>>> parents; for (int i=0; i<8; ++i) { auto t = tw::make_task(tw::consume, transform, input)->then(tw::consume, transform); parents.emplace_back(t); } auto final = tw::make_task(tw::consume, [](const std::vector<data_t>& parents) { double res = 0; for (const auto p : parents) { res += mean(p); } return res; }, parents); return final; } } namespace examples { // This example demonstrates the scheduling of an extra wide graph. // It also shows how the listener interface can be used to handle task events. // Increase iterations and size and observe your CPU load. // In this example, new data cannot be scheduled until the last result // was retrieved. However, this can be changed to use a pool of graphs // to process every data input as soon as possible. void wide_graph_with_listener(std::ostream& os, std::size_t iterations, std::size_t size) { tw::parallel exec{8}; // thread pool with 8 threads // The data input task at the root of the graph auto input = tw::make_value_task(std::make_shared<std::vector<double>>()); // Build graph and return the final task auto final = build_graph(input); final->add_listener(std::make_shared<listener>()); // Output the graph for visualization const auto graph = final->get_graph(); std::ofstream("wide_graph_with_listener.dot") << tw::to_string(graph); // This is to generate random data std::uniform_int_distribution<std::size_t> dist(size, size * 10); for (std::size_t i=0; i<iterations; ++i) { auto data = std::make_shared<std::vector<double>>(dist(gen), 1); input->set_value(data); // New data arrive final->schedule_all(exec); // Schedule the graph immediately after data arrived os << final->get() << std::endl; // Print result } } } #ifndef UNITTEST int main() { std::cout << "Running example: wide_graph_with_listener ..." << std::endl; examples::wide_graph_with_listener(std::cout); } #endif <commit_msg>fix mean calc<commit_after>#include "wide_graph_with_listener.h" #include "../src/transwarp.h" #include <iostream> #include <fstream> #include <random> #include <numeric> namespace tw = transwarp; namespace { std::mt19937 gen{1}; std::mutex mutex; // protect the generator using data_t = std::shared_ptr<std::vector<double>>; data_t transform(data_t data) { std::uniform_real_distribution<double> dist(0.5, 1.5); for (auto& v : *data) { std::lock_guard<std::mutex> lock{mutex}; v *= dist(gen); } return data; } double mean(data_t data) { return std::accumulate(data->begin(), data->end(), 0.) / static_cast<double>(data->size()); } class listener : public tw::listener { public: // Note: this is called on the thread the task is run on for the after_finished event void handle_event(tw::event_type event, const std::shared_ptr<tw::node>&) { if (event == tw::event_type::after_finished) { // task has finished } } }; std::shared_ptr<tw::task<double>> build_graph(std::shared_ptr<tw::task<data_t>> input) { std::vector<std::shared_ptr<tw::task<data_t>>> parents; for (int i=0; i<8; ++i) { auto t = tw::make_task(tw::consume, transform, input)->then(tw::consume, transform); parents.emplace_back(t); } auto final = tw::make_task(tw::consume, [](const std::vector<data_t>& parents) { double res = 0; for (const auto p : parents) { res += mean(p); } return res / parents.size(); }, parents); return final; } } namespace examples { // This example demonstrates the scheduling of an extra wide graph. // It also shows how the listener interface can be used to handle task events. // Increase iterations and size and observe your CPU load. // In this example, new data cannot be scheduled until the last result // was retrieved. However, this can be changed to use a pool of graphs // to process every data input as soon as possible. void wide_graph_with_listener(std::ostream& os, std::size_t iterations, std::size_t size) { tw::parallel exec{8}; // thread pool with 8 threads // The data input task at the root of the graph auto input = tw::make_value_task(std::make_shared<std::vector<double>>()); // Build graph and return the final task auto final = build_graph(input); final->add_listener(std::make_shared<listener>()); // Output the graph for visualization const auto graph = final->get_graph(); std::ofstream("wide_graph_with_listener.dot") << tw::to_string(graph); // This is to generate random data std::uniform_int_distribution<std::size_t> dist(size, size * 10); for (std::size_t i=0; i<iterations; ++i) { auto data = std::make_shared<std::vector<double>>(dist(gen), 1); input->set_value(data); // New data arrive final->schedule_all(exec); // Schedule the graph immediately after data arrived os << final->get() << std::endl; // Print result } } } #ifndef UNITTEST int main() { std::cout << "Running example: wide_graph_with_listener ..." << std::endl; examples::wide_graph_with_listener(std::cout); } #endif <|endoftext|>
<commit_before>// Copyright © 2012, Université catholique de Louvain // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "mozart.hh" namespace mozart { struct SuspendTrailEntry { SuspendTrailEntry(StableNode* left, StableNode* right) : left(left), right(right) {} StableNode* left; StableNode* right; }; typedef VMAllocatedList<SuspendTrailEntry> SuspendTrail; typedef VMAllocatedList<NodeBackup> RebindTrail; struct StructuralDualWalk { public: enum Kind { wkUnify, wkEquals, wkPatternMatch }; public: StructuralDualWalk(VM vm, Kind kind, StaticArray<UnstableNode> captures = nullptr): vm(vm), kind(kind), captures(captures) {} OpResult run(RichNode left, RichNode right); private: inline OpResult processPair(VM vm, RichNode left, RichNode right); inline void rebind(VM vm, RichNode left, RichNode right); inline void undoBindings(VM vm); inline void doCapture(VM vm, RichNode value, RichNode capture); inline void doConjunction(VM vm, RichNode value, RichNode conjunction); inline OpResult doOpenRecord(VM vm, RichNode value, RichNode pattern); VM vm; Kind kind; WalkStack stack; RebindTrail rebindTrail; SuspendTrail suspendTrail; StaticArray<UnstableNode> captures; }; ///////////////// // Entry point // ///////////////// OpResult fullUnify(VM vm, RichNode left, RichNode right) { StructuralDualWalk walk(vm, StructuralDualWalk::wkUnify); return walk.run(left, right); } OpResult fullEquals(VM vm, RichNode left, RichNode right, bool& result) { StructuralDualWalk walk(vm, StructuralDualWalk::wkEquals); return walk.run(left, right).mapProceedFailToTrueFalse(result); } OpResult fullPatternMatch(VM vm, RichNode value, RichNode pattern, StaticArray<UnstableNode> captures, bool& result) { StructuralDualWalk walk(vm, StructuralDualWalk::wkPatternMatch, captures); return walk.run(value, pattern).mapProceedFailToTrueFalse(result); } //////////////////// // The real thing // //////////////////// OpResult StructuralDualWalk::run(RichNode left, RichNode right) { VM vm = this->vm; while (true) { // Process the pair OpResult pairResult = processPair(vm, left, right); switch (pairResult.kind()) { case OpResult::orFail: case OpResult::orRaise: { stack.clear(vm); suspendTrail.clear(vm); undoBindings(vm); return pairResult; } case OpResult::orWaitBefore: case OpResult::orWaitQuietBefore: { if (!RichNode(*pairResult.getWaiteeNode()).is<FailedValue>()) { // TODO Do we need to actually support the *quiet* here? suspendTrail.push_back_new(vm, left.getStableRef(vm), right.getStableRef(vm)); break; } else { stack.clear(vm); suspendTrail.clear(vm); undoBindings(vm); return pairResult; } } case OpResult::orProceed: { // nothing to do } } // Finished? if (stack.empty()) break; // Pop next pair left = *stack.front().left; right = *stack.front().right; // Go to next item stack.remove_front(vm); } // Do we need to suspend on something? if (!suspendTrail.empty()) { // Undo temporary bindings undoBindings(vm); // Create the control variable UnstableNode unstableControlVar = Variable::build(vm); RichNode controlVar = unstableControlVar; controlVar.ensureStable(vm); // Reduce the remaining unifications size_t count = suspendTrail.size(); if (count == 1) { left = *suspendTrail.front().left; right = *suspendTrail.front().right; if (left.isTransient()) DataflowVariable(left).addToSuspendList(vm, controlVar); if (right.isTransient()) DataflowVariable(right).addToSuspendList(vm, controlVar); } else { UnstableNode label = Atom::build(vm, vm->coreatoms.pipe); UnstableNode unstableLeft = Tuple::build(vm, count, label); UnstableNode unstableRight = Tuple::build(vm, count, label); auto leftTuple = RichNode(unstableLeft).as<Tuple>(); auto rightTuple = RichNode(unstableRight).as<Tuple>(); size_t i = 0; for (auto iter = suspendTrail.begin(); iter != suspendTrail.end(); i++, ++iter) { UnstableNode leftTemp(vm, *iter->left); leftTuple.initElement(vm, i, leftTemp); RichNode richLeftTemp = leftTemp; if (richLeftTemp.isTransient()) DataflowVariable(richLeftTemp).addToSuspendList(vm, controlVar); UnstableNode rightTemp(vm, *iter->right); rightTuple.initElement(vm, i, rightTemp); RichNode richRightTemp = rightTemp; if (richRightTemp.isTransient()) DataflowVariable(richRightTemp).addToSuspendList(vm, controlVar); } } suspendTrail.clear(vm); // TODO Replace initial operands by unstableLeft and unstableRight return OpResult::waitFor(vm, controlVar); } /* No need to undo temporary bindings here, even if we are in wkEquals mode. * In fact, we should not undo them in that case, as that compactifies * the store, and speeds up subsequent tests and/or unifications. * * However, the above is *wrong* when in a subspace, because of speculative * bindings. * * The above would also be *wrong* when in wkPatternMatch mode. But in that * mode we do not perform temporary bindings in the first place. */ if (!vm->isOnTopLevel()) undoBindings(vm); return OpResult::proceed(); } OpResult StructuralDualWalk::processPair(VM vm, RichNode left, RichNode right) { // Identical nodes if (left.isSameNode(right)) return OpResult::proceed(); auto leftType = left.type(); auto rightType = right.type(); StructuralBehavior leftBehavior = leftType.getStructuralBehavior(); StructuralBehavior rightBehavior = rightType.getStructuralBehavior(); // Handle captures if (kind == wkPatternMatch) { if (rightType == PatMatCapture::type()) { doCapture(vm, left, right); return OpResult::proceed(); } else if (rightType == PatMatConjunction::type()) { doConjunction(vm, left, right); return OpResult::proceed(); } else if (rightType == PatMatOpenRecord::type()) { return doOpenRecord(vm, left, right); } } // One of them is a variable switch (kind) { case wkUnify: { if (leftBehavior == sbVariable) { if (rightBehavior == sbVariable) { if (leftType.getBindingPriority() > rightType.getBindingPriority()) return DataflowVariable(left).bind(vm, right); else return DataflowVariable(right).bind(vm, left); } else { return DataflowVariable(left).bind(vm, right); } } else if (rightBehavior == sbVariable) { return DataflowVariable(right).bind(vm, left); } break; } case wkEquals: case wkPatternMatch: { if (leftBehavior == sbVariable) { assert(leftType.isTransient()); return OpResult::waitFor(vm, left); } else if (rightBehavior == sbVariable) { assert(rightType.isTransient()); return OpResult::waitFor(vm, right); } break; } } // If we reach this, both left and right are non-var if (leftType != rightType) return OpResult::fail(); switch (leftBehavior) { case sbValue: { bool success = ValueEquatable(left).equals(vm, right); return success ? OpResult::proceed() : OpResult::fail(); } case sbStructural: { bool success = StructuralEquatable(left).equals(vm, right, stack); if (success) { if (kind != wkPatternMatch) rebind(vm, left, right); return OpResult::proceed(); } else { return OpResult::fail(); } } case sbTokenEq: { assert(!left.isSameNode(right)); // this was tested earlier return OpResult::fail(); } case sbVariable: { assert(false); return OpResult::fail(); } } // We should not reach this point assert(false); return OpResult::proceed(); } void StructuralDualWalk::rebind(VM vm, RichNode left, RichNode right) { rebindTrail.push_back(vm, left.makeBackup()); left.reinit(vm, right); } void StructuralDualWalk::undoBindings(VM vm) { while (!rebindTrail.empty()) { rebindTrail.front().restore(); rebindTrail.remove_front(vm); } } void StructuralDualWalk::doCapture(VM vm, RichNode value, RichNode capture) { nativeint index = capture.as<PatMatCapture>().index(); if (index >= 0) captures[(size_t) index].copy(vm, value); } void StructuralDualWalk::doConjunction(VM vm, RichNode value, RichNode conjunction) { auto conj = conjunction.as<PatMatConjunction>(); StableNode* stableValue = value.getStableRef(vm); for (size_t i = conj.getCount(); i > 0; i--) stack.push(vm, stableValue, conj.getElement(i-1)); } OpResult StructuralDualWalk::doOpenRecord(VM vm, RichNode value, RichNode pattern) { bool boolResult = false; auto pat = pattern.as<PatMatOpenRecord>(); auto arity = RichNode(*pat.getArity()).as<Arity>(); // Check that the value is a record MOZART_CHECK_OPRESULT(RecordLike(value).isRecord(vm, boolResult)); if (!boolResult) return OpResult::fail(); // Check that the labels match UnstableNode recordLabel; MOZART_CHECK_OPRESULT(RecordLike(value).label(vm, recordLabel)); MOZART_CHECK_OPRESULT(equals(vm, *arity.getLabel(), recordLabel, boolResult)); if (!boolResult) return OpResult::fail(); // Now iterate over the features of the pattern for (size_t i = 0; i < arity.getArraySize(); i++) { RichNode feature = *arity.getElement(i); MOZART_CHECK_OPRESULT(Dottable(value).hasFeature(vm, feature, boolResult)); if (!boolResult) return OpResult::fail(); UnstableNode lhsValue; MOZART_CHECK_OPRESULT(Dottable(value).dot(vm, feature, lhsValue)); StableNode* rhsValue = pat.getElement(i); stack.push(vm, RichNode(lhsValue).getStableRef(vm), rhsValue); } return OpResult::proceed(); } } <commit_msg>Fixed: unify must mark the waitees as needed.<commit_after>// Copyright © 2012, Université catholique de Louvain // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "mozart.hh" namespace mozart { struct SuspendTrailEntry { SuspendTrailEntry(StableNode* left, StableNode* right) : left(left), right(right) {} StableNode* left; StableNode* right; }; typedef VMAllocatedList<SuspendTrailEntry> SuspendTrail; typedef VMAllocatedList<NodeBackup> RebindTrail; struct StructuralDualWalk { public: enum Kind { wkUnify, wkEquals, wkPatternMatch }; public: StructuralDualWalk(VM vm, Kind kind, StaticArray<UnstableNode> captures = nullptr): vm(vm), kind(kind), captures(captures) {} OpResult run(RichNode left, RichNode right); private: inline OpResult processPair(VM vm, RichNode left, RichNode right); inline void rebind(VM vm, RichNode left, RichNode right); inline void undoBindings(VM vm); inline void doCapture(VM vm, RichNode value, RichNode capture); inline void doConjunction(VM vm, RichNode value, RichNode conjunction); inline OpResult doOpenRecord(VM vm, RichNode value, RichNode pattern); VM vm; Kind kind; WalkStack stack; RebindTrail rebindTrail; SuspendTrail suspendTrail; StaticArray<UnstableNode> captures; }; ///////////////// // Entry point // ///////////////// OpResult fullUnify(VM vm, RichNode left, RichNode right) { StructuralDualWalk walk(vm, StructuralDualWalk::wkUnify); return walk.run(left, right); } OpResult fullEquals(VM vm, RichNode left, RichNode right, bool& result) { StructuralDualWalk walk(vm, StructuralDualWalk::wkEquals); return walk.run(left, right).mapProceedFailToTrueFalse(result); } OpResult fullPatternMatch(VM vm, RichNode value, RichNode pattern, StaticArray<UnstableNode> captures, bool& result) { StructuralDualWalk walk(vm, StructuralDualWalk::wkPatternMatch, captures); return walk.run(value, pattern).mapProceedFailToTrueFalse(result); } //////////////////// // The real thing // //////////////////// OpResult StructuralDualWalk::run(RichNode left, RichNode right) { VM vm = this->vm; while (true) { // Process the pair OpResult pairResult = processPair(vm, left, right); switch (pairResult.kind()) { case OpResult::orFail: case OpResult::orRaise: { stack.clear(vm); suspendTrail.clear(vm); undoBindings(vm); return pairResult; } case OpResult::orWaitBefore: case OpResult::orWaitQuietBefore: { if (!RichNode(*pairResult.getWaiteeNode()).is<FailedValue>()) { // TODO Do we need to actually support the *quiet* here? suspendTrail.push_back_new(vm, left.getStableRef(vm), right.getStableRef(vm)); break; } else { stack.clear(vm); suspendTrail.clear(vm); undoBindings(vm); return pairResult; } } case OpResult::orProceed: { // nothing to do } } // Finished? if (stack.empty()) break; // Pop next pair left = *stack.front().left; right = *stack.front().right; // Go to next item stack.remove_front(vm); } // Do we need to suspend on something? if (!suspendTrail.empty()) { // Undo temporary bindings undoBindings(vm); // Create the control variable UnstableNode unstableControlVar = Variable::build(vm); RichNode controlVar = unstableControlVar; controlVar.ensureStable(vm); // Reduce the remaining unifications size_t count = suspendTrail.size(); if (count == 1) { left = *suspendTrail.front().left; right = *suspendTrail.front().right; if (left.isTransient()) { DataflowVariable(left).markNeeded(vm); DataflowVariable(left).addToSuspendList(vm, controlVar); } if (right.isTransient()) { DataflowVariable(right).markNeeded(vm); DataflowVariable(right).addToSuspendList(vm, controlVar); } } else { UnstableNode label = Atom::build(vm, vm->coreatoms.pipe); UnstableNode unstableLeft = Tuple::build(vm, count, label); UnstableNode unstableRight = Tuple::build(vm, count, label); auto leftTuple = RichNode(unstableLeft).as<Tuple>(); auto rightTuple = RichNode(unstableRight).as<Tuple>(); size_t i = 0; for (auto iter = suspendTrail.begin(); iter != suspendTrail.end(); i++, ++iter) { UnstableNode leftTemp(vm, *iter->left); leftTuple.initElement(vm, i, leftTemp); RichNode richLeftTemp = leftTemp; if (richLeftTemp.isTransient()) { DataflowVariable(richLeftTemp).markNeeded(vm); DataflowVariable(richLeftTemp).addToSuspendList(vm, controlVar); } UnstableNode rightTemp(vm, *iter->right); rightTuple.initElement(vm, i, rightTemp); RichNode richRightTemp = rightTemp; if (richRightTemp.isTransient()) { DataflowVariable(richRightTemp).markNeeded(vm); DataflowVariable(richRightTemp).addToSuspendList(vm, controlVar); } } } suspendTrail.clear(vm); // TODO Replace initial operands by unstableLeft and unstableRight return OpResult::waitFor(vm, controlVar); } /* No need to undo temporary bindings here, even if we are in wkEquals mode. * In fact, we should not undo them in that case, as that compactifies * the store, and speeds up subsequent tests and/or unifications. * * However, the above is *wrong* when in a subspace, because of speculative * bindings. * * The above would also be *wrong* when in wkPatternMatch mode. But in that * mode we do not perform temporary bindings in the first place. */ if (!vm->isOnTopLevel()) undoBindings(vm); return OpResult::proceed(); } OpResult StructuralDualWalk::processPair(VM vm, RichNode left, RichNode right) { // Identical nodes if (left.isSameNode(right)) return OpResult::proceed(); auto leftType = left.type(); auto rightType = right.type(); StructuralBehavior leftBehavior = leftType.getStructuralBehavior(); StructuralBehavior rightBehavior = rightType.getStructuralBehavior(); // Handle captures if (kind == wkPatternMatch) { if (rightType == PatMatCapture::type()) { doCapture(vm, left, right); return OpResult::proceed(); } else if (rightType == PatMatConjunction::type()) { doConjunction(vm, left, right); return OpResult::proceed(); } else if (rightType == PatMatOpenRecord::type()) { return doOpenRecord(vm, left, right); } } // One of them is a variable switch (kind) { case wkUnify: { if (leftBehavior == sbVariable) { if (rightBehavior == sbVariable) { if (leftType.getBindingPriority() > rightType.getBindingPriority()) return DataflowVariable(left).bind(vm, right); else return DataflowVariable(right).bind(vm, left); } else { return DataflowVariable(left).bind(vm, right); } } else if (rightBehavior == sbVariable) { return DataflowVariable(right).bind(vm, left); } break; } case wkEquals: case wkPatternMatch: { if (leftBehavior == sbVariable) { assert(leftType.isTransient()); return OpResult::waitFor(vm, left); } else if (rightBehavior == sbVariable) { assert(rightType.isTransient()); return OpResult::waitFor(vm, right); } break; } } // If we reach this, both left and right are non-var if (leftType != rightType) return OpResult::fail(); switch (leftBehavior) { case sbValue: { bool success = ValueEquatable(left).equals(vm, right); return success ? OpResult::proceed() : OpResult::fail(); } case sbStructural: { bool success = StructuralEquatable(left).equals(vm, right, stack); if (success) { if (kind != wkPatternMatch) rebind(vm, left, right); return OpResult::proceed(); } else { return OpResult::fail(); } } case sbTokenEq: { assert(!left.isSameNode(right)); // this was tested earlier return OpResult::fail(); } case sbVariable: { assert(false); return OpResult::fail(); } } // We should not reach this point assert(false); return OpResult::proceed(); } void StructuralDualWalk::rebind(VM vm, RichNode left, RichNode right) { rebindTrail.push_back(vm, left.makeBackup()); left.reinit(vm, right); } void StructuralDualWalk::undoBindings(VM vm) { while (!rebindTrail.empty()) { rebindTrail.front().restore(); rebindTrail.remove_front(vm); } } void StructuralDualWalk::doCapture(VM vm, RichNode value, RichNode capture) { nativeint index = capture.as<PatMatCapture>().index(); if (index >= 0) captures[(size_t) index].copy(vm, value); } void StructuralDualWalk::doConjunction(VM vm, RichNode value, RichNode conjunction) { auto conj = conjunction.as<PatMatConjunction>(); StableNode* stableValue = value.getStableRef(vm); for (size_t i = conj.getCount(); i > 0; i--) stack.push(vm, stableValue, conj.getElement(i-1)); } OpResult StructuralDualWalk::doOpenRecord(VM vm, RichNode value, RichNode pattern) { bool boolResult = false; auto pat = pattern.as<PatMatOpenRecord>(); auto arity = RichNode(*pat.getArity()).as<Arity>(); // Check that the value is a record MOZART_CHECK_OPRESULT(RecordLike(value).isRecord(vm, boolResult)); if (!boolResult) return OpResult::fail(); // Check that the labels match UnstableNode recordLabel; MOZART_CHECK_OPRESULT(RecordLike(value).label(vm, recordLabel)); MOZART_CHECK_OPRESULT(equals(vm, *arity.getLabel(), recordLabel, boolResult)); if (!boolResult) return OpResult::fail(); // Now iterate over the features of the pattern for (size_t i = 0; i < arity.getArraySize(); i++) { RichNode feature = *arity.getElement(i); MOZART_CHECK_OPRESULT(Dottable(value).hasFeature(vm, feature, boolResult)); if (!boolResult) return OpResult::fail(); UnstableNode lhsValue; MOZART_CHECK_OPRESULT(Dottable(value).dot(vm, feature, lhsValue)); StableNode* rhsValue = pat.getElement(i); stack.push(vm, RichNode(lhsValue).getStableRef(vm), rhsValue); } return OpResult::proceed(); } } <|endoftext|>
<commit_before>/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at LICENSE-CDDL * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE-CDDL. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2013, OmniTI Computer Consulting, Inc. All rights reserved. * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1995, Theo Schlossnagle. All rights reserved. * Copyright (c) 1990 Mentat Inc. */ #include "ife.h" #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <inet/mib2.h> #include <sys/stream.h> #include <stropts.h> #include <sys/strstat.h> #include <sys/tihdr.h> static int arpcache_psize = 0; static arp_entry *arpcache_private = NULL; const unsigned char ff_ff_ff_ff_ff_ff[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; #define ROUNDUP(a) \ ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long)) int sample_arp_cache(arp_entry **l) { int s=-1, getcode, flags, count = 0; char buf[512], *dbuf = NULL; struct opthdr *req; struct strbuf ctlbuf, databuf; struct T_optmgmt_req *tor = (struct T_optmgmt_req *)buf; struct T_optmgmt_ack *toa = (struct T_optmgmt_ack *)buf; struct T_error_ack *tea = (struct T_error_ack *)buf; mib2_ipNetToMediaEntry_t *np; mib2_ip_t *ip = NULL; if(l) *l = NULL; if(!arpcache_private) { arpcache_psize = 2; arpcache_private = (arp_entry *)calloc(sizeof(*arpcache_private), arpcache_psize); arpcache_private[0].ipaddr.s_addr = 0; } if(s < 0) { if((s = open("/dev/arp", O_RDWR)) < 0) { return -1; } if(ioctl(s, I_PUSH, "tcp") || ioctl(s, I_PUSH, "udp") || ioctl(s, I_PUSH, "icmp") ) goto error; } tor->PRIM_type = T_SVR4_OPTMGMT_REQ; tor->OPT_offset = sizeof (struct T_optmgmt_req); tor->OPT_length = sizeof (struct opthdr); tor->MGMT_flags = T_CURRENT; req = (struct opthdr *)&tor[1]; req->level = EXPER_IP_AND_ALL_IRES; req->name = 0; req->len = 1; ctlbuf.buf = (char *)buf; ctlbuf.len = tor->OPT_length + tor->OPT_offset; flags = 0; if (putmsg(s, &ctlbuf, (struct strbuf *)0, flags) == -1) goto error; req = (struct opthdr *)&toa[1]; ctlbuf.maxlen = sizeof (buf); for (;;) { flags = 0; getcode = getmsg(s, &ctlbuf, (struct strbuf *)0, &flags); if (getcode == -1) goto error; if (getcode == 0 && ctlbuf.len >= (int)sizeof (struct T_optmgmt_ack) && toa->PRIM_type == T_OPTMGMT_ACK && toa->MGMT_flags == T_SUCCESS && req->len == 0) { break; /* ?? */ } if (ctlbuf.len >= (int)sizeof (struct T_error_ack) && tea->PRIM_type == T_ERROR_ACK) { goto error; } if (getcode != MOREDATA || ctlbuf.len < (int)sizeof (struct T_optmgmt_ack) || toa->PRIM_type != T_OPTMGMT_ACK || toa->MGMT_flags != T_SUCCESS) { goto error; } dbuf = (char *)malloc(req->len); if(dbuf == NULL) goto error; databuf.maxlen = req->len; databuf.buf = (char *)dbuf; databuf.len = 0; flags = 0; getcode = getmsg(s, (struct strbuf *)0, &databuf, &flags); if(getcode != 0) goto error; if(req->level == MIB2_IP && req->name == 0) { ip = (mib2_ip_t *)dbuf; } if(ip && req->level == MIB2_IP && req->name == MIB2_IP_MEDIA) { for(np = (mib2_ipNetToMediaEntry_t *)dbuf; (char *)np < (char *)dbuf + databuf.len; np = (mib2_ipNetToMediaEntry_t *)((char *)np + ip->ipNetToMediaEntrySize)) { if(count >= arpcache_psize) { arpcache_psize <<= 1; arpcache_private = (arp_entry *)realloc(arpcache_private, sizeof(arp_entry)*(arpcache_psize+1)); } if(np->ipNetToMediaPhysAddress.o_length == ETH_ALEN) { arpcache_private[count].ipaddr.s_addr = np->ipNetToMediaNetAddress; memcpy(arpcache_private[count].mac, np->ipNetToMediaPhysAddress.o_bytes, ETH_ALEN); count++; } } } free(dbuf); dbuf = NULL; } if(l) *l = arpcache_private; close(s); return count; error: if(dbuf) free(dbuf); close(s); return -1; } <commit_msg>prevent an infinite loop when the ip->ipNetToMediaEntrySize is 0<commit_after>/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at LICENSE-CDDL * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE-CDDL. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2013, OmniTI Computer Consulting, Inc. All rights reserved. * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1995, Theo Schlossnagle. All rights reserved. * Copyright (c) 1990 Mentat Inc. */ #include "ife.h" #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <inet/mib2.h> #include <sys/stream.h> #include <stropts.h> #include <sys/strstat.h> #include <sys/tihdr.h> static int arpcache_psize = 0; static arp_entry *arpcache_private = NULL; const unsigned char ff_ff_ff_ff_ff_ff[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; #define ROUNDUP(a) \ ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long)) int sample_arp_cache(arp_entry **l) { int s=-1, getcode, flags, count = 0; char buf[512], *dbuf = NULL; struct opthdr *req; struct strbuf ctlbuf, databuf; struct T_optmgmt_req *tor = (struct T_optmgmt_req *)buf; struct T_optmgmt_ack *toa = (struct T_optmgmt_ack *)buf; struct T_error_ack *tea = (struct T_error_ack *)buf; mib2_ipNetToMediaEntry_t *np; mib2_ip_t *ip = NULL; if(l) *l = NULL; if(!arpcache_private) { arpcache_psize = 2; arpcache_private = (arp_entry *)calloc(sizeof(*arpcache_private), arpcache_psize); arpcache_private[0].ipaddr.s_addr = 0; } if(s < 0) { if((s = open("/dev/arp", O_RDWR)) < 0) { return -1; } if(ioctl(s, I_PUSH, "tcp") || ioctl(s, I_PUSH, "udp") || ioctl(s, I_PUSH, "icmp") ) goto error; } tor->PRIM_type = T_SVR4_OPTMGMT_REQ; tor->OPT_offset = sizeof (struct T_optmgmt_req); tor->OPT_length = sizeof (struct opthdr); tor->MGMT_flags = T_CURRENT; req = (struct opthdr *)&tor[1]; req->level = EXPER_IP_AND_ALL_IRES; req->name = 0; req->len = 1; ctlbuf.buf = (char *)buf; ctlbuf.len = tor->OPT_length + tor->OPT_offset; flags = 0; if (putmsg(s, &ctlbuf, (struct strbuf *)0, flags) == -1) goto error; req = (struct opthdr *)&toa[1]; ctlbuf.maxlen = sizeof (buf); for (;;) { flags = 0; getcode = getmsg(s, &ctlbuf, (struct strbuf *)0, &flags); if (getcode == -1) goto error; if (getcode == 0 && ctlbuf.len >= (int)sizeof (struct T_optmgmt_ack) && toa->PRIM_type == T_OPTMGMT_ACK && toa->MGMT_flags == T_SUCCESS && req->len == 0) { break; /* ?? */ } if (ctlbuf.len >= (int)sizeof (struct T_error_ack) && tea->PRIM_type == T_ERROR_ACK) { goto error; } if (getcode != MOREDATA || ctlbuf.len < (int)sizeof (struct T_optmgmt_ack) || toa->PRIM_type != T_OPTMGMT_ACK || toa->MGMT_flags != T_SUCCESS) { goto error; } dbuf = (char *)malloc(req->len); if(dbuf == NULL) goto error; databuf.maxlen = req->len; databuf.buf = (char *)dbuf; databuf.len = 0; flags = 0; getcode = getmsg(s, (struct strbuf *)0, &databuf, &flags); if(getcode != 0) goto error; if(req->level == MIB2_IP && req->name == 0) { ip = (mib2_ip_t *)dbuf; } if(ip && req->level == MIB2_IP && req->name == MIB2_IP_MEDIA) { for(np = (mib2_ipNetToMediaEntry_t *)dbuf; (char *)np < (char *)dbuf + databuf.len; np = (mib2_ipNetToMediaEntry_t *)((char *)np + ip->ipNetToMediaEntrySize)) { if(ip->ipNetToMediaEntrySize == 0) break; if(count >= arpcache_psize) { arpcache_psize <<= 1; arpcache_private = (arp_entry *)realloc(arpcache_private, sizeof(arp_entry)*(arpcache_psize+1)); } if(np->ipNetToMediaPhysAddress.o_length == ETH_ALEN) { arpcache_private[count].ipaddr.s_addr = np->ipNetToMediaNetAddress; memcpy(arpcache_private[count].mac, np->ipNetToMediaPhysAddress.o_bytes, ETH_ALEN); count++; } } } free(dbuf); dbuf = NULL; } if(l) *l = arpcache_private; close(s); return count; error: if(dbuf) free(dbuf); close(s); return -1; } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 Arthur O'Dwyer * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <cassert> #include <set> #include <string> #include <vector> #include "diffn.h" void do_print_ifdefs_recursively(std::vector<FileInfo> &files, const std::vector<std::string> &macro_names, const std::string &output_name) { const size_t num_files = files.size(); /* If what's in "files" is all regular files, diff them. * Otherwise, try stepping through each directory in parallel. */ FileInfo *sample_regular = NULL; FileInfo *sample_directory = NULL; for (size_t i=0; i < num_files; ++i) { if (files[i].fp == NULL) { files[i].fp = fopen(files[i].name.c_str(), "r"); if (files[i].fp == NULL) continue; } fstat(fileno(files[i].fp), &files[i].stat); if (S_ISDIR(files[i].stat.st_mode)) { sample_directory = &files[i]; } else if (S_ISREG(files[i].stat.st_mode)) { sample_regular = &files[i]; } } if (sample_regular != NULL && sample_directory != NULL) { do_error("Input paths '%s' and '%s' cannot be merged because one is a directory\n" "and the other is a regular file.\n" "Incomplete output may have been left in the output directory.", sample_directory->name.c_str(), sample_regular->name.c_str()); } if (sample_regular != NULL) { /* Let's diff these files! */ Difdef difdef(num_files); for (size_t i=0; i < num_files; ++i) { if (files[i].fp == NULL) { /* This file couldn't be opened, above. */ continue; } assert(!S_ISDIR(files[i].stat.st_mode)); if (S_ISREG(files[i].stat.st_mode)) { difdef.replace_file(i, files[i].fp); } else { difdef.replace_file(i, NULL); } fclose(files[i].fp); } Difdef::Diff diff = difdef.merge(); /* Try to open the output file. */ FILE *out = fopen(output_name.c_str(), "w"); if (out == NULL) { do_error("Output file '%s': Cannot create file", output_name.c_str()); } /* Print out the diff. */ verify_properly_nested_directives(diff, &files[0]); do_print_using_ifdefs(diff, macro_names, out); fclose(out); } else { /* Recursively diff the contents of these directories. */ if (mkdir(output_name.c_str(), 0777)) { do_error("Output path '%s': Cannot create directory", output_name.c_str()); } std::set<std::string> processed_filenames; processed_filenames.insert("."); processed_filenames.insert(".."); for (size_t i=0; i < num_files; ++i) { if (files[i].fp == NULL) continue; #if (_POSIX_C_SOURCE >= 200809L) DIR *dir = fdopendir(fileno(files[i].fp)); #else DIR *dir = opendir(files[i].name.c_str()); #endif /* __GNUC__ */ while (struct dirent *file = readdir(dir)) { std::string relative_name = file->d_name; if (processed_filenames.find(relative_name) != processed_filenames.end()) { /* This filename was matched and handled earlier. */ continue; } processed_filenames.insert(relative_name); std::vector<FileInfo> subfiles(files.size()); for (size_t j=0; j < num_files; ++j) { subfiles[j].name = files[j].name + "/" + relative_name; } std::string suboutput_name = output_name + "/" + relative_name; do_print_ifdefs_recursively(subfiles, macro_names, suboutput_name); } } } } <commit_msg>Remove the #if protecting fdopendir()/opendir().<commit_after>/* * Copyright (C) 2012 Arthur O'Dwyer * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <cassert> #include <set> #include <string> #include <vector> #include "diffn.h" void do_print_ifdefs_recursively(std::vector<FileInfo> &files, const std::vector<std::string> &macro_names, const std::string &output_name) { const size_t num_files = files.size(); /* If what's in "files" is all regular files, diff them. * Otherwise, try stepping through each directory in parallel. */ FileInfo *sample_regular = NULL; FileInfo *sample_directory = NULL; for (size_t i=0; i < num_files; ++i) { if (files[i].fp == NULL) { files[i].fp = fopen(files[i].name.c_str(), "r"); if (files[i].fp == NULL) continue; } fstat(fileno(files[i].fp), &files[i].stat); if (S_ISDIR(files[i].stat.st_mode)) { sample_directory = &files[i]; } else if (S_ISREG(files[i].stat.st_mode)) { sample_regular = &files[i]; } } if (sample_regular != NULL && sample_directory != NULL) { do_error("Input paths '%s' and '%s' cannot be merged because one is a directory\n" "and the other is a regular file.\n" "Incomplete output may have been left in the output directory.", sample_directory->name.c_str(), sample_regular->name.c_str()); } if (sample_regular != NULL) { /* Let's diff these files! */ Difdef difdef(num_files); for (size_t i=0; i < num_files; ++i) { if (files[i].fp == NULL) { /* This file couldn't be opened, above. */ continue; } assert(!S_ISDIR(files[i].stat.st_mode)); if (S_ISREG(files[i].stat.st_mode)) { difdef.replace_file(i, files[i].fp); } else { difdef.replace_file(i, NULL); } fclose(files[i].fp); } Difdef::Diff diff = difdef.merge(); /* Try to open the output file. */ FILE *out = fopen(output_name.c_str(), "w"); if (out == NULL) { do_error("Output file '%s': Cannot create file", output_name.c_str()); } /* Print out the diff. */ verify_properly_nested_directives(diff, &files[0]); do_print_using_ifdefs(diff, macro_names, out); fclose(out); } else { /* Recursively diff the contents of these directories. */ if (mkdir(output_name.c_str(), 0777)) { do_error("Output path '%s': Cannot create directory", output_name.c_str()); } std::set<std::string> processed_filenames; processed_filenames.insert("."); processed_filenames.insert(".."); for (size_t i=0; i < num_files; ++i) { if (files[i].fp == NULL) continue; DIR *dir = opendir(files[i].name.c_str()); while (struct dirent *file = readdir(dir)) { std::string relative_name = file->d_name; if (processed_filenames.find(relative_name) != processed_filenames.end()) { /* This filename was matched and handled earlier. */ continue; } processed_filenames.insert(relative_name); std::vector<FileInfo> subfiles(files.size()); for (size_t j=0; j < num_files; ++j) { subfiles[j].name = files[j].name + "/" + relative_name; } std::string suboutput_name = output_name + "/" + relative_name; do_print_ifdefs_recursively(subfiles, macro_names, suboutput_name); } } } } <|endoftext|>
<commit_before>#include <falcon/ctmatch.hpp> #include <iostream> #include <type_traits> template<int i> struct i_ : std::integral_constant<int, i> {}; class my_true_type {}; std::true_type normalize_branch_value(my_true_type) { return {}; } template<class T, int i> struct Fi { i_<i> operator()(T) const { return {}; } }; template<class T> struct type_ { template<class U> std::enable_if_t<std::is_same<std::decay_t<U>, T>::value, std::true_type> operator()(U const &) const { return {}; } }; int main() { using namespace falcon::ctmatch; i_<1> a; i_<2> b; Fi<int, 1> fa; Fi<int, 2> fb; type_<int> only_int; type_<bool> only_bool; std::true_type true_; std::false_type false_; auto dyn_error = [](auto &&) { throw 1; }; a = match_invoke(1, fa); a = match_invoke(1, match_if(fa, fa)); a = match_invoke(1, match_if(fa) >> fa); a = 1 >>= match | match_if([](int) { return my_true_type{}; }, fa); match_invoke(1, match_value(1, fa), dyn_error); match_invoke(1, match_value(1) >> fa, dyn_error); b = match_invoke(1, match_if(only_bool, fa), match_if(only_int, fb)); b = match_invoke(1, match_if(only_bool) >> fa, match_if(only_int) >> fb); b = 1 >>= match | match_if(only_bool) >> fa | match_if(only_int) >> fb ; 3 >>= match | match_always; true_ = 3 >>= match | only_int; only_bool( 1 >>= match.result<bool>() | match_value(only_int, []() { return 1; }) | match_value(only_int, []() { return 2; }) | [](int){ return 3; } ); a = pmatch_invoke(1, [](auto x) -> std::enable_if_t<std::is_pointer<decltype(x)>::value> { #ifndef _MSC_VER static_assert(!sizeof(x), ""); #endif return x; // msvc }, [a](int) { return a; }, [](auto x) { static_assert(!sizeof(x), ""); } ); true_ = (pmatch(1) | match_always | match_error).is_invoked(); true_ = (pmatch(1) | only_bool | only_int | match_error).is_invoked(); false_ = (pmatch(1) | only_bool).is_invoked(); } <commit_msg>[msvc] fixed compilation<commit_after>#include <falcon/ctmatch.hpp> #include <iostream> #include <type_traits> template<int i> struct i_ : std::integral_constant<int, i> {}; class my_true_type {}; std::true_type normalize_branch_value(my_true_type) { return {}; } template<class T, int i> struct Fi { i_<i> operator()(T) const { return {}; } }; template<class T> struct type_ { template<class U> std::enable_if_t<std::is_same<std::decay_t<U>, T>::value, std::true_type> operator()(U const &) const { return {}; } }; int main() { using namespace falcon::ctmatch; i_<1> a; i_<2> b; Fi<int, 1> fa; Fi<int, 2> fb; type_<int> only_int; type_<bool> only_bool; std::true_type true_; std::false_type false_; auto dyn_error = [](auto &&) { throw 1; }; a = match_invoke(1, fa); a = match_invoke(1, match_if(fa, fa)); a = match_invoke(1, match_if(fa) >> fa); a = 1 >>= match | match_if([](int) { return my_true_type{}; }, fa); match_invoke(1, match_value(1, fa), dyn_error); match_invoke(1, match_value(1) >> fa, dyn_error); b = match_invoke(1, match_if(only_bool, fa), match_if(only_int, fb)); b = match_invoke(1, match_if(only_bool) >> fa, match_if(only_int) >> fb); b = 1 >>= match | match_if(only_bool) >> fa | match_if(only_int) >> fb ; 3 >>= match | match_always; true_ = 3 >>= match | only_int; only_bool( 1 >>= match.result<bool>() | match_value(only_int, []() { return 1; }) | match_value(only_int, []() { return 2; }) | [](int){ return 3; } ); a = pmatch_invoke(1, [](auto x) -> std::enable_if_t<std::is_pointer<decltype(x)>::value> { }, [a](int) { return a; }, [](auto x) { static_assert(!sizeof(x), ""); } ); true_ = (pmatch(1) | match_always | match_error).is_invoked(); true_ = (pmatch(1) | only_bool | only_int | match_error).is_invoked(); false_ = (pmatch(1) | only_bool).is_invoked(); } <|endoftext|>
<commit_before>#include "audio_player.h" #include <QDebug> void endTrackSync(HSYNC handle, DWORD channel, DWORD data, void * user) { // BASS_ChannelStop(channel); // BASS_ChannelRemoveSync(channel, handle); AudioPlayer * player = static_cast<AudioPlayer *>(user); emit player -> playbackEnded(); } AudioPlayer::AudioPlayer(QObject * parent) : QObject(parent) { qRegisterMetaType<AudioPlayer::MediaStatus>("MediaStatus"); qRegisterMetaType<AudioPlayer::MediaState>("MediaState"); // cheat for cross treadhing connect(this, SIGNAL(playbackEnded()), this, SLOT(endOfPlayback())); duration = -1; notifyInterval = 100; currentState = StoppedState; if (HIWORD(BASS_GetVersion()) != BASSVERSION) { throw "An incorrect version of BASS.DLL was loaded"; } if (HIWORD(BASS_FX_GetVersion()) != BASSVERSION) { throw "An incorrect version of BASS_FX.DLL was loaded"; } if (!BASS_Init(-1, 44100, 0, NULL, NULL)) qDebug() << "Init error: " << BASS_ErrorGetCode(); // throw "Cannot initialize device"; /////////////////////////////////////////////// /// load plugins /////////////////////////////////////////////// QFileInfoList list = QDir(QCoreApplication::applicationDirPath() + "/libs/bass/plugins").entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden); foreach(QFileInfo file, list) { /*int res = */BASS_PluginLoad(file.filePath().toLatin1(), 0); // if (res == 0) // qDebug() << file.filePath() << BASS_ErrorGetCode(); // else // qDebug() << file.filePath() << res; } /////////////////////////////////////////////// notifyTimer = new NotifyTimer(this); connect(notifyTimer, SIGNAL(timeout()), this, SLOT(signalUpdate())); connect(notifyTimer, SIGNAL(started()), this, SLOT(started())); connect(notifyTimer, SIGNAL(stoped()), this, SLOT(stoped())); } AudioPlayer::~AudioPlayer() { BASS_PluginFree(0); notifyTimer -> stop(); delete notifyTimer; } int AudioPlayer::getDuration() const { return duration; } int AudioPlayer::getNotifyInterval() { return notifyInterval; } void AudioPlayer::setNotifyInterval(signed int milis) { notifyInterval = milis; if (notifyTimer -> isActive()) notifyTimer -> setInterval(notifyInterval); } void AudioPlayer::setMedia(QUrl mediaPath) { mediaUri = mediaPath; } AudioPlayer::MediaState AudioPlayer::state() const { return currentState; } //////////////////////////////////////////////////////////////////////// /// PRIVATE //////////////////////////////////////////////////////////////////////// int AudioPlayer::openRemoteChannel(QString path) { BASS_ChannelStop(chan); chan = BASS_StreamCreateURL(path.toStdWString().c_str(), 0, 0, NULL, 0); // BASS_Encode_Start(channel, "output.wav", BASS_ENCODE_PCM, NULL, 0); // BASS_Encode_StartCAFile(channel, 'mp4f', 'aac ', 0, 128000, "output.mp4"); // only macos // BASS_Encode_StartCAFile(channel, 'm4af', 'alac', 0, 0, "output.m4a"); // only macos if (!chan) qDebug() << "Can't play stream" << BASS_ErrorGetCode() << path.toUtf8(); return chan; } int AudioPlayer::openChannel(QString path) { BASS_ChannelStop(chan); if (!(chan = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_FLOAT | BASS_ASYNCFILE))) // if (!(stream = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP)) // && !(chan = BASS_MusicLoad(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP | BASS_MUSIC_POSRESET | BASS_MUSIC_STOPBACK | BASS_STREAM_PRESCAN | BASS_MUSIC_AUTOFREE, 1))) qDebug() << "Can't play file " << BASS_ErrorGetCode() << path.toUtf8(); return chan; } void AudioPlayer::closeChannel() { qDebug() << "close channel"; BASS_ChannelStop(chan); BASS_ChannelRemoveSync(chan, syncHandle); BASS_StreamFree(chan); // BASS_MusicFree(chan); } //////////////////////////////////////////////////////////////////////// /// SLOTS //////////////////////////////////////////////////////////////////////// void AudioPlayer::started() { currentState = PlayingState; emit stateChanged(PlayingState); } void AudioPlayer::stoped() { currentState = StoppedState; closeChannel(); } void AudioPlayer::signalUpdate() { int curr_pos = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetPosition(chan, BASS_POS_BYTE)) * 1000; emit positionChanged(curr_pos); // if (duration - curr_pos < 500) // endOfPlayback(); } //////////////////////////////////////////////////////////////////////// void AudioPlayer::play() { if (currentState == PausedState) { resume(); } else { closeChannel(); if (mediaUri.isEmpty()) { emit mediaStatusChanged(NoMedia); } else { if (openChannel(mediaUri.toLocalFile())) { duration = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetLength(chan, BASS_POS_BYTE)) * 1000; durationChanged(duration); BASS_ChannelPlay(chan, true); notifyTimer -> start(notifyInterval); //TODO: remove sync and check end of file by timer syncHandle = BASS_ChannelSetSync(chan, BASS_SYNC_END, 0, &endTrackSync, this); } else { qDebug() << "Can't play file"; } } } } void AudioPlayer::pause() { notifyTimer -> stop(); BASS_ChannelPause(chan); emit stateChanged(PausedState); currentState = PausedState; } void AudioPlayer::resume() { if (!BASS_ChannelPlay(chan, false)) { emit mediaStatusChanged(StalledMedia); qDebug() << "Error resuming"; } else { notifyTimer -> start(notifyInterval); } } void AudioPlayer::stop() { BASS_ChannelStop(chan); notifyTimer -> stop(); emit stateChanged(StoppedState); } void AudioPlayer::endOfPlayback() { stop(); closeChannel(); emit mediaStatusChanged(EndOfMedia); } void AudioPlayer::setPosition(int position) { BASS_ChannelSetPosition(chan, BASS_ChannelSeconds2Bytes(chan, position / 1000.0), BASS_POS_BYTE); } <commit_msg>fix pause state<commit_after>#include "audio_player.h" #include <QDebug> void endTrackSync(HSYNC handle, DWORD channel, DWORD data, void * user) { // BASS_ChannelStop(channel); // BASS_ChannelRemoveSync(channel, handle); AudioPlayer * player = static_cast<AudioPlayer *>(user); emit player -> playbackEnded(); } AudioPlayer::AudioPlayer(QObject * parent) : QObject(parent) { qRegisterMetaType<AudioPlayer::MediaStatus>("MediaStatus"); qRegisterMetaType<AudioPlayer::MediaState>("MediaState"); // cheat for cross treadhing connect(this, SIGNAL(playbackEnded()), this, SLOT(endOfPlayback())); duration = -1; notifyInterval = 100; currentState = StoppedState; if (HIWORD(BASS_GetVersion()) != BASSVERSION) { throw "An incorrect version of BASS.DLL was loaded"; } if (HIWORD(BASS_FX_GetVersion()) != BASSVERSION) { throw "An incorrect version of BASS_FX.DLL was loaded"; } if (!BASS_Init(-1, 44100, 0, NULL, NULL)) qDebug() << "Init error: " << BASS_ErrorGetCode(); // throw "Cannot initialize device"; /////////////////////////////////////////////// /// load plugins /////////////////////////////////////////////// QFileInfoList list = QDir(QCoreApplication::applicationDirPath() + "/libs/bass/plugins").entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden); foreach(QFileInfo file, list) { /*int res = */BASS_PluginLoad(file.filePath().toLatin1(), 0); // if (res == 0) // qDebug() << file.filePath() << BASS_ErrorGetCode(); // else // qDebug() << file.filePath() << res; } /////////////////////////////////////////////// notifyTimer = new NotifyTimer(this); connect(notifyTimer, SIGNAL(timeout()), this, SLOT(signalUpdate())); connect(notifyTimer, SIGNAL(started()), this, SLOT(started())); connect(notifyTimer, SIGNAL(stoped()), this, SLOT(stoped())); } AudioPlayer::~AudioPlayer() { BASS_PluginFree(0); notifyTimer -> stop(); delete notifyTimer; } int AudioPlayer::getDuration() const { return duration; } int AudioPlayer::getNotifyInterval() { return notifyInterval; } void AudioPlayer::setNotifyInterval(signed int milis) { notifyInterval = milis; if (notifyTimer -> isActive()) notifyTimer -> setInterval(notifyInterval); } void AudioPlayer::setMedia(QUrl mediaPath) { mediaUri = mediaPath; } AudioPlayer::MediaState AudioPlayer::state() const { return currentState; } //////////////////////////////////////////////////////////////////////// /// PRIVATE //////////////////////////////////////////////////////////////////////// int AudioPlayer::openRemoteChannel(QString path) { BASS_ChannelStop(chan); chan = BASS_StreamCreateURL(path.toStdWString().c_str(), 0, 0, NULL, 0); // BASS_Encode_Start(channel, "output.wav", BASS_ENCODE_PCM, NULL, 0); // BASS_Encode_StartCAFile(channel, 'mp4f', 'aac ', 0, 128000, "output.mp4"); // only macos // BASS_Encode_StartCAFile(channel, 'm4af', 'alac', 0, 0, "output.m4a"); // only macos if (!chan) qDebug() << "Can't play stream" << BASS_ErrorGetCode() << path.toUtf8(); return chan; } int AudioPlayer::openChannel(QString path) { BASS_ChannelStop(chan); if (!(chan = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_FLOAT | BASS_ASYNCFILE))) // if (!(stream = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP)) // && !(chan = BASS_MusicLoad(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP | BASS_MUSIC_POSRESET | BASS_MUSIC_STOPBACK | BASS_STREAM_PRESCAN | BASS_MUSIC_AUTOFREE, 1))) qDebug() << "Can't play file " << BASS_ErrorGetCode() << path.toUtf8(); return chan; } void AudioPlayer::closeChannel() { qDebug() << "close channel"; BASS_ChannelStop(chan); BASS_ChannelRemoveSync(chan, syncHandle); BASS_StreamFree(chan); // BASS_MusicFree(chan); } //////////////////////////////////////////////////////////////////////// /// SLOTS //////////////////////////////////////////////////////////////////////// void AudioPlayer::started() { currentState = PlayingState; emit stateChanged(PlayingState); } void AudioPlayer::stoped() { currentState = StoppedState; } void AudioPlayer::signalUpdate() { int curr_pos = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetPosition(chan, BASS_POS_BYTE)) * 1000; emit positionChanged(curr_pos); // if (duration - curr_pos < 500) // endOfPlayback(); } //////////////////////////////////////////////////////////////////////// void AudioPlayer::play() { if (currentState == PausedState) { resume(); } else { closeChannel(); if (mediaUri.isEmpty()) { emit mediaStatusChanged(NoMedia); } else { if (openChannel(mediaUri.toLocalFile())) { duration = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetLength(chan, BASS_POS_BYTE)) * 1000; durationChanged(duration); BASS_ChannelPlay(chan, true); notifyTimer -> start(notifyInterval); //TODO: remove sync and check end of file by timer syncHandle = BASS_ChannelSetSync(chan, BASS_SYNC_END, 0, &endTrackSync, this); } else { qDebug() << "Can't play file"; } } } } void AudioPlayer::pause() { notifyTimer -> stop(); BASS_ChannelPause(chan); emit stateChanged(PausedState); currentState = PausedState; } void AudioPlayer::resume() { if (!BASS_ChannelPlay(chan, false)) { emit mediaStatusChanged(StalledMedia); qDebug() << "Error resuming"; } else { notifyTimer -> start(notifyInterval); } } void AudioPlayer::stop() { closeChannel(); notifyTimer -> stop(); emit stateChanged(StoppedState); } void AudioPlayer::endOfPlayback() { stop(); closeChannel(); emit mediaStatusChanged(EndOfMedia); } void AudioPlayer::setPosition(int position) { BASS_ChannelSetPosition(chan, BASS_ChannelSeconds2Bytes(chan, position / 1000.0), BASS_POS_BYTE); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itk{{cookiecutter.filter_name}}.h" #include "itkCommand.h" #include "itkImageFileWriter.h" #include "itkTestingMacros.h" namespace{ class ShowProgress : public itk::Command { public: itkNewMacro( ShowProgress ); void Execute( itk::Object* caller, const itk::EventObject& event ) override { Execute( (const itk::Object*)caller, event ); } void Execute( const itk::Object* caller, const itk::EventObject& event ) override { if ( !itk::ProgressEvent().CheckEvent( &event ) ) { return; } const auto* processObject = dynamic_cast< const itk::ProcessObject* >( caller ); if ( !processObject ) { return; } std::cout << " " << processObject->GetProgress(); } }; } int itk{{cookiecutter.filter_name}}Test( int argc, char * argv[] ) { if( argc < 2 ) { std::cerr << "Usage: " << argv[0]; std::cerr << " outputImage"; std::cerr << std::endl; return EXIT_FAILURE; } const char * outputImageFileName = argv[1]; const unsigned int Dimension = 2; using PixelType = float; using ImageType = itk::Image< PixelType, Dimension >; using FilterType = itk::{{cookiecutter.filter_name}}< ImageType, ImageType >; FilterType::Pointer filter = FilterType::New(); EXERCISE_BASIC_OBJECT_METHODS( filter, {{cookiecutter.filter_name}}, ImageToImageFilter ); // Create input image to avoid test dependencies. ImageType::SizeType size; size.Fill( 128 ); ImageType::Pointer image = ImageType::New(); image->SetRegions( size ); image->Allocate(); image->FillBuffer(1.1f); ShowProgress::Pointer showProgress = ShowProgress::New(); filter->AddObserver( itk::ProgressEvent(), showProgress ); filter->SetInput(image); typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputImageFileName ); writer->SetInput( filter->GetOutput() ); writer->SetUseCompression(true); TRY_EXPECT_NO_EXCEPTION( writer->Update() ); return EXIT_SUCCESS; } <commit_msg>STYLE: Conform to the ITK SW Guide when reporting in tests.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itk{{cookiecutter.filter_name}}.h" #include "itkCommand.h" #include "itkImageFileWriter.h" #include "itkTestingMacros.h" namespace{ class ShowProgress : public itk::Command { public: itkNewMacro( ShowProgress ); void Execute( itk::Object* caller, const itk::EventObject& event ) override { Execute( (const itk::Object*)caller, event ); } void Execute( const itk::Object* caller, const itk::EventObject& event ) override { if ( !itk::ProgressEvent().CheckEvent( &event ) ) { return; } const auto* processObject = dynamic_cast< const itk::ProcessObject* >( caller ); if ( !processObject ) { return; } std::cout << " " << processObject->GetProgress(); } }; } int itk{{cookiecutter.filter_name}}Test( int argc, char * argv[] ) { if( argc < 2 ) { std::cerr << "Missing parameters." << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " outputImage"; std::cerr << std::endl; return EXIT_FAILURE; } const char * outputImageFileName = argv[1]; const unsigned int Dimension = 2; using PixelType = float; using ImageType = itk::Image< PixelType, Dimension >; using FilterType = itk::{{cookiecutter.filter_name}}< ImageType, ImageType >; FilterType::Pointer filter = FilterType::New(); EXERCISE_BASIC_OBJECT_METHODS( filter, {{cookiecutter.filter_name}}, ImageToImageFilter ); // Create input image to avoid test dependencies. ImageType::SizeType size; size.Fill( 128 ); ImageType::Pointer image = ImageType::New(); image->SetRegions( size ); image->Allocate(); image->FillBuffer(1.1f); ShowProgress::Pointer showProgress = ShowProgress::New(); filter->AddObserver( itk::ProgressEvent(), showProgress ); filter->SetInput(image); typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputImageFileName ); writer->SetInput( filter->GetOutput() ); writer->SetUseCompression(true); TRY_EXPECT_NO_EXCEPTION( writer->Update() ); std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <boost/noncopyable.hpp> #include <boost/python.hpp> #include <Box2D/Collision/Shapes/b2CircleShape.h> #include <Box2D/Collision/Shapes/b2PolygonShape.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Dynamics/b2World.h> #include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Joints/b2Joint.h> using namespace boost::python; b2Fixture* (b2Body::*b2BodyCreateFixture1)(const b2FixtureDef*) = &b2Body::CreateFixture; b2Fixture* (b2Body::*b2BodyCreateFixture2)(const b2Shape*, float32) = &b2Body::CreateFixture; b2Fixture* (b2Body::*b2BodyGetFixtureList)() = &b2Body::GetFixtureList; b2JointEdge* (b2Body::*b2BodyGetJointList)() = &b2Body::GetJointList; b2ContactEdge* (b2Body::*b2BodyGetContactList)() = &b2Body::GetContactList; b2Body* (b2Body::*b2BodyGetNext)() = &b2Body::GetNext; b2World* (b2Body::*b2BodyGetWorld)() = &b2Body::GetWorld; BOOST_PYTHON_MODULE(box2d) { class_<b2World>("World", init<const b2Vec2&, bool>()) .def("create_body", &b2World::CreateBody, return_internal_reference<>()) .def("destroy_body", &b2World::DestroyBody) ; class_<b2Vec2>("Vec2", init<float32, float32>()) .def_readwrite("x", &b2Vec2::x) .def_readwrite("y", &b2Vec2::y) ; enum_<b2BodyType>("BodyType") .value("static_body", b2_staticBody) .value("kinematic_body", b2_kinematicBody) .value("dynamic_body", b2_dynamicBody) .export_values() ; class_<b2BodyDef>("BodyDef") .def_readwrite("user_data", &b2BodyDef::userData) .def_readwrite("position", &b2BodyDef::position) .def_readwrite("angle", &b2BodyDef::angle) .def_readwrite("linear_velocity", &b2BodyDef::linearVelocity) .def_readwrite("angular_velocity", &b2BodyDef::angularVelocity) .def_readwrite("linear_damping", &b2BodyDef::linearDamping) .def_readwrite("angular_damping", &b2BodyDef::angularDamping) .def_readwrite("allow_sleep", &b2BodyDef::allowSleep) .def_readwrite("awake", &b2BodyDef::awake) .def_readwrite("fixed_rotation", &b2BodyDef::fixedRotation) .def_readwrite("bullet", &b2BodyDef::bullet) .def_readwrite("type", &b2BodyDef::type) .def_readwrite("active", &b2BodyDef::active) .def_readwrite("inertia_scale", &b2BodyDef::inertiaScale) ; class_<b2Body, boost::noncopyable>("Body", no_init) .def("CreateFixture", b2BodyCreateFixture1, return_internal_reference<>()) .def("CreateFixture", b2BodyCreateFixture2, return_internal_reference<>()) .def("DestroyFixture", &b2Body::DestroyFixture) .def("SetTransform", &b2Body::SetTransform) .def("GetTransform", &b2Body::GetTransform, return_value_policy<copy_const_reference>()) .def("GetPosition", &b2Body::GetPosition, return_value_policy<copy_const_reference>()) .def("GetAngle", &b2Body::GetAngle) .def("GetWorldCenter", &b2Body::GetWorldCenter, return_value_policy<copy_const_reference>()) .def("GetLocalCenter", &b2Body::GetLocalCenter, return_value_policy<copy_const_reference>()) .def("SetLinearVelocity", &b2Body::SetLinearVelocity) .def("GetLinearVelocity", &b2Body::GetLinearVelocity) .def("SetAngularVelocity", &b2Body::SetAngularVelocity) .def("GetAngularVelocity", &b2Body::GetAngularVelocity) .def("ApplyForce", &b2Body::ApplyForce) .def("ApplyTorque", &b2Body::ApplyTorque) // .def("ApplyImpulse", &b2Body::ApplyImpulse) .def("GetMass", &b2Body::GetMass) .def("GetInertia", &b2Body::GetInertia) .def("GetMassData", &b2Body::GetMassData) .def("SetMassData", &b2Body::SetMassData) .def("ResetMassData", &b2Body::ResetMassData) .def("GetWorldPoint", &b2Body::GetWorldPoint) .def("GetWorldVector", &b2Body::GetWorldVector) .def("GetLocalPoint", &b2Body::GetLocalPoint) .def("GetLocalVector", &b2Body::GetLocalVector) .def("GetLinearVelocityFromWorldPoint", &b2Body::GetLinearVelocityFromWorldPoint) .def("GetLinearVelocityFromLocalPoint", &b2Body::GetLinearVelocityFromLocalPoint) .def("GetLinearDamping", &b2Body::GetLinearDamping) .def("SetLinearDamping", &b2Body::SetLinearDamping) .def("GetAngularDamping", &b2Body::GetAngularDamping) .def("SetAngularDamping", &b2Body::SetAngularDamping) .def("SetType", &b2Body::SetType) .def("GetType", &b2Body::GetType) .def("SetBullet", &b2Body::SetBullet) .def("IsBullet", &b2Body::IsBullet) .def("SetSleepingAllowed", &b2Body::SetSleepingAllowed) .def("IsSleepingAllowed", &b2Body::IsSleepingAllowed) .def("SetAwake", &b2Body::SetAwake) .def("IsAwake", &b2Body::IsAwake) .def("SetActive", &b2Body::SetActive) .def("IsActive", &b2Body::IsActive) .def("SetFixedRotation", &b2Body::SetFixedRotation) .def("IsFixedRotation", &b2Body::IsFixedRotation) .def("GetFixtureList", b2BodyGetFixtureList, return_internal_reference<>()) .def("GetJointList", b2BodyGetJointList, return_internal_reference<>()) .def("GetContactList", b2BodyGetContactList, return_internal_reference<>()) .def("GetNext", b2BodyGetNext, return_internal_reference<>()) // .def("GetUserData", &b2Body::GetUserData) // .def("SetUserData", &b2Body::SetUserData) .def("GetWorld", b2BodyGetWorld, return_internal_reference<>()) ; class_<b2FixtureDef>("FixtureDef") ; class_<b2Fixture, boost::noncopyable>("Fixture", no_init) ; class_<b2CircleShape>("CircleShape") ; class_<b2PolygonShape>("PolygonShape") ; } <commit_msg>made wrapper declarations more pythonic<commit_after>#include <boost/noncopyable.hpp> #include <boost/python.hpp> #include <Box2D/Collision/Shapes/b2CircleShape.h> #include <Box2D/Collision/Shapes/b2PolygonShape.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Dynamics/b2World.h> #include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Joints/b2Joint.h> using namespace boost::python; b2Fixture* (b2Body::*b2BodyCreateFixture1)(const b2FixtureDef*) = &b2Body::CreateFixture; b2Fixture* (b2Body::*b2BodyCreateFixture2)(const b2Shape*, float32) = &b2Body::CreateFixture; b2Fixture* (b2Body::*b2BodyGetFixtureList)() = &b2Body::GetFixtureList; b2JointEdge* (b2Body::*b2BodyGetJointList)() = &b2Body::GetJointList; b2ContactEdge* (b2Body::*b2BodyGetContactList)() = &b2Body::GetContactList; b2Body* (b2Body::*b2BodyGetNext)() = &b2Body::GetNext; b2World* (b2Body::*b2BodyGetWorld)() = &b2Body::GetWorld; BOOST_PYTHON_MODULE(box2d) { class_<b2World>("World", init<const b2Vec2&, bool>()) .def("create_body", &b2World::CreateBody, return_internal_reference<>()) .def("destroy_body", &b2World::DestroyBody) ; class_<b2Vec2>("Vec2", init<float32, float32>()) .def_readwrite("x", &b2Vec2::x) .def_readwrite("y", &b2Vec2::y) ; enum_<b2BodyType>("BodyType") .value("static_body", b2_staticBody) .value("kinematic_body", b2_kinematicBody) .value("dynamic_body", b2_dynamicBody) .export_values() ; class_<b2BodyDef>("BodyDef") .def_readwrite("user_data", &b2BodyDef::userData) .def_readwrite("position", &b2BodyDef::position) .def_readwrite("angle", &b2BodyDef::angle) .def_readwrite("linear_velocity", &b2BodyDef::linearVelocity) .def_readwrite("angular_velocity", &b2BodyDef::angularVelocity) .def_readwrite("linear_damping", &b2BodyDef::linearDamping) .def_readwrite("angular_damping", &b2BodyDef::angularDamping) .def_readwrite("allow_sleep", &b2BodyDef::allowSleep) .def_readwrite("awake", &b2BodyDef::awake) .def_readwrite("fixed_rotation", &b2BodyDef::fixedRotation) .def_readwrite("bullet", &b2BodyDef::bullet) .def_readwrite("type", &b2BodyDef::type) .def_readwrite("active", &b2BodyDef::active) .def_readwrite("inertia_scale", &b2BodyDef::inertiaScale) ; class_<b2Body, boost::noncopyable>("Body", no_init) .def("create_fixture", b2BodyCreateFixture1, return_internal_reference<>()) .def("create_fixture", b2BodyCreateFixture2, return_internal_reference<>()) .def("destroy_fixture", &b2Body::DestroyFixture) .add_property("transform", make_function(&b2Body::GetTransform, return_value_policy<copy_const_reference>()), &b2Body::SetTransform) .add_property("position", make_function(&b2Body::GetPosition, return_value_policy<copy_const_reference>())) .add_property("angle", &b2Body::GetAngle) .add_property("world_center", make_function(&b2Body::GetWorldCenter, return_value_policy<copy_const_reference>())) .add_property("local_center", make_function(&b2Body::GetLocalCenter, return_value_policy<copy_const_reference>())) .add_property("linear_velocity", &b2Body::GetLinearVelocity, &b2Body::SetLinearVelocity) .add_property("angular_velocity", &b2Body::GetAngularVelocity, &b2Body::SetAngularVelocity) .def("apply_force", &b2Body::ApplyForce) .def("apply_torque", &b2Body::ApplyTorque) // .def("ApplyImpulse", &b2Body::ApplyImpulse) .add_property("mass", &b2Body::GetMass) .add_property("inertia", &b2Body::GetInertia) .add_property("mass_data", &b2Body::GetMassData, &b2Body::SetMassData) .def("reset_mass_data", &b2Body::ResetMassData) .def("get_world_point", &b2Body::GetWorldPoint) .def("get_world_vector", &b2Body::GetWorldVector) .def("get_local_point", &b2Body::GetLocalPoint) .def("get_local_vector", &b2Body::GetLocalVector) .def("get_linear_velocity_from_world_point", &b2Body::GetLinearVelocityFromWorldPoint) .def("get_linear_velocity_from_local_point", &b2Body::GetLinearVelocityFromLocalPoint) .add_property("linear_damping", &b2Body::GetLinearDamping, &b2Body::SetLinearDamping) .add_property("angular_damping", &b2Body::GetAngularDamping, &b2Body::SetAngularDamping) .add_property("type", &b2Body::GetType, &b2Body::SetType) .add_property("bullet", &b2Body::IsBullet, &b2Body::SetBullet) .add_property("sleeping_allowed", &b2Body::IsSleepingAllowed, &b2Body::SetSleepingAllowed) .add_property("awake", &b2Body::IsAwake, &b2Body::SetAwake) .add_property("active", &b2Body::IsActive, &b2Body::SetActive) .add_property("fixed_rotation", &b2Body::IsFixedRotation, &b2Body::SetFixedRotation) .add_property("fixture_list", make_function(b2BodyGetFixtureList, return_internal_reference<>())) .add_property("joint_list", make_function(b2BodyGetJointList, return_internal_reference<>())) .add_property("contact_list", make_function(b2BodyGetContactList, return_internal_reference<>())) .add_property("next", make_function(b2BodyGetNext, return_internal_reference<>())) // .def("GetUserData", &b2Body::GetUserData) // .def("SetUserData", &b2Body::SetUserData) .add_property("world", make_function(b2BodyGetWorld, return_internal_reference<>())) ; class_<b2FixtureDef>("FixtureDef") ; class_<b2Fixture, boost::noncopyable>("Fixture", no_init) ; class_<b2CircleShape>("CircleShape") ; class_<b2PolygonShape>("PolygonShape") ; } <|endoftext|>
<commit_before>// Copyright (c) 2013, Adam Simpkins #include "keyboard_v2.h" #include <avrpp/progmem.h> #include <avrpp/usb_hid_keyboard.h> #include <avrpp/util.h> #include <util/delay.h> #if 0 /* * Maltron's standard QWERTY layout used by recent (2013) 89-series keyboards */ static const uint8_t PROGMEM factory_key_table[18 * 8] = { // Row 0 KEY_RIGHT, KEY_NONE, KEY_LEFT_GUI, KEY_BACKSLASH, KEY_LEFT_BRACE, KEY_MINUS, KEY_BACKSPACE, KEY_LEFT, // Row 1 KEY_END, KEY_N, KEY_M, KEY_COMMA, KEY_PERIOD, KEY_QUOTE, KEY_RIGHT_SHIFT, KEY_NONE, // Row 2 KEY_NONE, KEY_Y, KEY_U, KEY_I, KEY_O, KEY_P, KEY_MUTE, KEY_NONE, // Row 3 KEY_NONE, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_NONE, // Row 4 KEY_MENU, KEYPAD_MINUS, KEYPAD_1, KEYPAD_2, KEYPAD_3, KEYPAD_PLUS, KEY_RIGHT_ALT, KEY_NONE, // Row 5 KEY_CAPS_LOCK, KEY_NUM_LOCK, KEYPAD_7, KEYPAD_8, KEYPAD_9, KEYPAD_ASTERIX, KEY_F14, KEY_NONE, // Row 6 KEY_NONE, KEY_VOLUME_UP, KEY_A, KEY_S, KEY_D, KEY_F, KEY_G, KEY_ENTER, // Row 7 KEY_NONE, KEY_ESC, KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_NONE, // Row 8 KEY_SPACE, KEY_DELETE, KEY_EQUAL, KEY_RIGHT_BRACE, KEY_SLASH, KEY_RIGHT_GUI, KEY_NONE, KEY_UP, // Row 9 KEY_DOWN, KEY_H, KEY_J, KEY_K, KEY_L, KEY_SEMICOLON, KEY_VOLUME_DOWN, KEY_NONE, // Row 10 KEY_NONE, KEY_6, KEY_7, KEY_8, KEY_9, KEY_0, KEY_TILDE, KEY_NONE, // Row 11 KEY_PAGE_UP, KEYPAD_ENTER, KEYPAD_0, KEY_INSERT, KEY_BACKSPACE, KEYPAD_PERIOD, KEY_PAGE_DOWN, KEY_NONE, // Row 12 KEY_F13, KEYPAD_EQUAL, KEYPAD_4, KEYPAD_5, KEYPAD_6, KEYPAD_SLASH, KEY_F15, KEY_NONE, // Row 13 KEY_NONE, KEY_LEFT_SHIFT, KEY_Z, KEY_X, KEY_C, KEY_V, KEY_B, KEY_TAB, // Row 14 KEY_NONE, KEY_NON_US_BACKSLASH, KEY_Q, KEY_W, KEY_E, KEY_R, KEY_T, KEY_NONE, // Row 15 KEY_NONE, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_NONE, // Row 16 KEY_ENTER, KEY_NONE, KEY_NONE, KEY_LEFT_CTRL, KEY_NONE, KEY_NONE, KEY_NONE, KEY_RIGHT_CTRL, // Row 17 KEY_LEFT_ALT, KEY_NONE, KEY_NONE, KEY_NONE, KEY_RIGHT_ALT, KEY_NONE, KEY_NONE, KEY_HOME, }; static const uint8_t PROGMEM factory_modifier_table[18 * 8] = { 0, 0, MOD_LEFT_GUI, 0, 0, 0, 0, 0, // Row 0 0, 0, 0, 0, 0, 0, MOD_RIGHT_SHIFT, 0, // Row 1 0, 0, 0, 0, 0, 0, 0, 0, // Row 2 0, 0, 0, 0, 0, 0, 0, 0, // Row 3 0, 0, 0, 0, 0, 0, MOD_RIGHT_ALT, 0, // Row 4 0, 0, 0, 0, 0, 0, 0, 0, // Row 5 0, 0, 0, 0, 0, 0, 0, 0, // Row 6 0, 0, 0, 0, 0, 0, 0, 0, // Row 7 0, 0, 0, 0, 0, MOD_RIGHT_GUI, 0, 0, // Row 8 0, 0, 0, 0, 0, 0, 0, 0, // Row 9 0, 0, 0, 0, 0, 0, 0, 0, // Row 10 0, 0, 0, 0, 0, 0, 0, 0, // Row 11 0, 0, 0, 0, 0, 0, 0, 0, // Row 12 0, MOD_LEFT_SHIFT, 0, 0, 0, 0, 0, 0, // Row 13 0, 0, 0, 0, 0, 0, 0, 0, // Row 14 0, 0, 0, 0, 0, 0, 0, 0, // Row 15 0, 0, 0, MOD_LEFT_CTRL, 0, 0, 0, MOD_RIGHT_CTRL, // Row 16 MOD_LEFT_ALT, 0, 0, 0, MOD_RIGHT_ALT, 0, 0, 0, // Row 17 }; #endif /* * My preferred keyboard layout */ static const uint8_t PROGMEM default_key_table[18 * 8] = { // Row 0 KEY_TAB, KEY_NONE, KEY_HOME, KEY_BACKSLASH, KEY_LEFT_BRACE, KEY_MINUS, KEY_BACKSPACE, KEY_LEFT_GUI, // Row 1 KEY_RIGHT, KEY_N, KEY_M, KEY_COMMA, KEY_PERIOD, KEY_QUOTE, KEY_RIGHT_SHIFT, KEY_NONE, // Row 2 KEY_NONE, KEY_Y, KEY_U, KEY_I, KEY_O, KEY_P, KEY_RIGHT_GUI, KEY_NONE, // Row 3 KEY_NONE, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_NONE, // Row 4 KEY_APPLICATION, KEYPAD_MINUS, KEYPAD_1, KEYPAD_2, KEYPAD_3, KEYPAD_PLUS, KEY_RIGHT_ALT, KEY_NONE, // Row 5 KEY_CAPS_LOCK, KEY_NUM_LOCK, KEYPAD_7, KEYPAD_8, KEYPAD_9, KEYPAD_ASTERIX, KEY_F14, KEY_NONE, // Row 6 KEY_NONE, KEY_LEFT_CTRL, KEY_A, KEY_S, KEY_D, KEY_F, KEY_G, KEY_ENTER, // Row 7 KEY_NONE, KEY_MENU, KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_NONE, // Row 8 KEY_SPACE, KEY_DELETE, KEY_EQUAL, KEY_RIGHT_BRACE, KEY_SLASH, KEY_END, KEY_NONE, KEY_UP, // Row 9 KEY_DOWN, KEY_H, KEY_J, KEY_K, KEY_L, KEY_SEMICOLON, KEY_RIGHT_CTRL, KEY_NONE, // Row 10 KEY_NONE, KEY_6, KEY_7, KEY_8, KEY_9, KEY_0, KEY_TILDE, KEY_NONE, // Row 11 KEY_PAGE_UP, KEYPAD_ENTER, KEYPAD_0, KEY_INSERT, KEY_BACKSPACE, KEYPAD_PERIOD, KEY_PAGE_DOWN, KEY_NONE, // Row 12 KEY_F13, KEYPAD_EQUAL, KEYPAD_4, KEYPAD_5, KEYPAD_6, KEYPAD_SLASH, KEY_F15, KEY_NONE, // Row 13 KEY_NONE, KEY_LEFT_SHIFT, KEY_Z, KEY_X, KEY_C, KEY_V, KEY_B, KEY_ESC, // Row 14 KEY_NONE, KEY_RIGHT_ALT, KEY_Q, KEY_W, KEY_E, KEY_R, KEY_T, KEY_NONE, // Row 15 KEY_NONE, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_NONE, // Row 16 KEY_ENTER, KEY_NONE, KEY_NONE, KEY_VOLUME_UP, KEY_NONE, KEY_NONE, KEY_NONE, KEY_VOLUME_DOWN, // Row 17 KEY_LEFT_ALT, KEY_NONE, KEY_NONE, KEY_NONE, KEY_MUTE, KEY_NONE, KEY_NONE, KEY_LEFT, }; static const uint8_t PROGMEM default_modifier_table[18 * 8] = { 0, 0, 0, 0, 0, 0, 0, MOD_LEFT_GUI, // Row 0 0, 0, 0, 0, 0, 0, MOD_RIGHT_SHIFT, 0, // Row 1 0, 0, 0, 0, 0, 0, MOD_RIGHT_GUI, 0, // Row 2 0, 0, 0, 0, 0, 0, 0, 0, // Row 3 0, 0, 0, 0, 0, 0, MOD_RIGHT_ALT, 0, // Row 4 0, 0, 0, 0, 0, 0, 0, 0, // Row 5 0, MOD_LEFT_CTRL, 0, 0, 0, 0, 0, 0, // Row 6 0, 0, 0, 0, 0, 0, 0, 0, // Row 7 0, 0, 0, 0, 0, 0, 0, 0, // Row 8 0, 0, 0, 0, 0, 0, MOD_RIGHT_CTRL, 0, // Row 9 0, 0, 0, 0, 0, 0, 0, 0, // Row 10 0, 0, 0, 0, 0, 0, 0, 0, // Row 11 0, 0, 0, 0, 0, 0, 0, 0, // Row 12 0, MOD_LEFT_SHIFT, 0, 0, 0, 0, 0, 0, // Row 13 0, MOD_RIGHT_ALT, 0, 0, 0, 0, 0, 0, // Row 14 0, 0, 0, 0, 0, 0, 0, 0, // Row 15 0, 0, 0, 0, 0, 0, 0, 0, // Row 16 MOD_LEFT_ALT, 0, 0, 0, 0, 0, 0, 0, // Row 17 }; void KeyboardV2::prepareLoop() { // Set LEDs to output, high (which is off for my LEDs) DDRC = 0x3f; PORTC = 0xff; // Set columns to output, low DDRB = 0xff; PORTB = 0x00; // Set rows to input, with pull-up resistors DDRD = 0x00; PORTD = 0xff; DDRF = 0x00; PORTF = 0xff; DDRE = 0x00; PORTE = 0xc0; _numCols = 8; _keyTable = default_key_table; _modifierTable = default_modifier_table; } void KeyboardV2::scanImpl() { for (uint8_t col = 0; col < 8; ++col) { // Turn the specified column pin into an output pin, and bring it low. // // It is important that the other column pins are configured as inputs. // If multiple keys are pressed down, they may create a circuit // connecting to other column pins as well. We don't want an output // voltage on these pins to affect our reading on the column currently // being scanned. DDRB = 0x01 << col; PORTB = 0xff & ~(0x01 << col); // We need a very brief delay here to allow the signal // to propagate to the input pins. _delay_us(5); // Read which row pins are active uint8_t d = ~PIND; uint8_t f = ~PINF; uint8_t e = ~PINE; if (UNLIKELY(d)) { for (uint8_t n = 0; n < 8; ++n) { if (d & (0x1 << n)) { keyPressed(col, n); } } } if (UNLIKELY(f)) { for (uint8_t n = 0; n < 8; ++n) { if (f & (0x1 << n)) { keyPressed(col, n + 8); } } } if (e & 0x40) { keyPressed(col, 16); } if (e & 0x80) { keyPressed(col, 17); } } DDRB = 0x00; PORTB = 0xff; } <commit_msg>[kbd_v2] Delete the factory standard keyboard layout<commit_after>// Copyright (c) 2013, Adam Simpkins #include "keyboard_v2.h" #include <avrpp/progmem.h> #include <avrpp/usb_hid_keyboard.h> #include <avrpp/util.h> #include <util/delay.h> static const uint8_t PROGMEM default_key_table[18 * 8] = { // Row 0 KEY_TAB, KEY_NONE, KEY_HOME, KEY_BACKSLASH, KEY_LEFT_BRACE, KEY_MINUS, KEY_BACKSPACE, KEY_LEFT_GUI, // Row 1 KEY_RIGHT, KEY_N, KEY_M, KEY_COMMA, KEY_PERIOD, KEY_QUOTE, KEY_RIGHT_SHIFT, KEY_NONE, // Row 2 KEY_NONE, KEY_Y, KEY_U, KEY_I, KEY_O, KEY_P, KEY_RIGHT_GUI, KEY_NONE, // Row 3 KEY_NONE, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_NONE, // Row 4 KEY_APPLICATION, KEYPAD_MINUS, KEYPAD_1, KEYPAD_2, KEYPAD_3, KEYPAD_PLUS, KEY_RIGHT_ALT, KEY_NONE, // Row 5 KEY_CAPS_LOCK, KEY_NUM_LOCK, KEYPAD_7, KEYPAD_8, KEYPAD_9, KEYPAD_ASTERIX, KEY_F14, KEY_NONE, // Row 6 KEY_NONE, KEY_LEFT_CTRL, KEY_A, KEY_S, KEY_D, KEY_F, KEY_G, KEY_ENTER, // Row 7 KEY_NONE, KEY_MENU, KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_NONE, // Row 8 KEY_SPACE, KEY_DELETE, KEY_EQUAL, KEY_RIGHT_BRACE, KEY_SLASH, KEY_END, KEY_NONE, KEY_UP, // Row 9 KEY_DOWN, KEY_H, KEY_J, KEY_K, KEY_L, KEY_SEMICOLON, KEY_RIGHT_CTRL, KEY_NONE, // Row 10 KEY_NONE, KEY_6, KEY_7, KEY_8, KEY_9, KEY_0, KEY_TILDE, KEY_NONE, // Row 11 KEY_PAGE_UP, KEYPAD_ENTER, KEYPAD_0, KEY_INSERT, KEY_BACKSPACE, KEYPAD_PERIOD, KEY_PAGE_DOWN, KEY_NONE, // Row 12 KEY_F13, KEYPAD_EQUAL, KEYPAD_4, KEYPAD_5, KEYPAD_6, KEYPAD_SLASH, KEY_F15, KEY_NONE, // Row 13 KEY_NONE, KEY_LEFT_SHIFT, KEY_Z, KEY_X, KEY_C, KEY_V, KEY_B, KEY_ESC, // Row 14 KEY_NONE, KEY_RIGHT_ALT, KEY_Q, KEY_W, KEY_E, KEY_R, KEY_T, KEY_NONE, // Row 15 KEY_NONE, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_NONE, // Row 16 KEY_ENTER, KEY_NONE, KEY_NONE, KEY_VOLUME_UP, KEY_NONE, KEY_NONE, KEY_NONE, KEY_VOLUME_DOWN, // Row 17 KEY_LEFT_ALT, KEY_NONE, KEY_NONE, KEY_NONE, KEY_MUTE, KEY_NONE, KEY_NONE, KEY_LEFT, }; static const uint8_t PROGMEM default_modifier_table[18 * 8] = { 0, 0, 0, 0, 0, 0, 0, MOD_LEFT_GUI, // Row 0 0, 0, 0, 0, 0, 0, MOD_RIGHT_SHIFT, 0, // Row 1 0, 0, 0, 0, 0, 0, MOD_RIGHT_GUI, 0, // Row 2 0, 0, 0, 0, 0, 0, 0, 0, // Row 3 0, 0, 0, 0, 0, 0, MOD_RIGHT_ALT, 0, // Row 4 0, 0, 0, 0, 0, 0, 0, 0, // Row 5 0, MOD_LEFT_CTRL, 0, 0, 0, 0, 0, 0, // Row 6 0, 0, 0, 0, 0, 0, 0, 0, // Row 7 0, 0, 0, 0, 0, 0, 0, 0, // Row 8 0, 0, 0, 0, 0, 0, MOD_RIGHT_CTRL, 0, // Row 9 0, 0, 0, 0, 0, 0, 0, 0, // Row 10 0, 0, 0, 0, 0, 0, 0, 0, // Row 11 0, 0, 0, 0, 0, 0, 0, 0, // Row 12 0, MOD_LEFT_SHIFT, 0, 0, 0, 0, 0, 0, // Row 13 0, MOD_RIGHT_ALT, 0, 0, 0, 0, 0, 0, // Row 14 0, 0, 0, 0, 0, 0, 0, 0, // Row 15 0, 0, 0, 0, 0, 0, 0, 0, // Row 16 MOD_LEFT_ALT, 0, 0, 0, 0, 0, 0, 0, // Row 17 }; void KeyboardV2::prepareLoop() { // Set LEDs to output, high (which is off for my LEDs) DDRC = 0x3f; PORTC = 0xff; // Set columns to output, low DDRB = 0xff; PORTB = 0x00; // Set rows to input, with pull-up resistors DDRD = 0x00; PORTD = 0xff; DDRF = 0x00; PORTF = 0xff; DDRE = 0x00; PORTE = 0xc0; _numCols = 8; _keyTable = default_key_table; _modifierTable = default_modifier_table; } void KeyboardV2::scanImpl() { for (uint8_t col = 0; col < 8; ++col) { // Turn the specified column pin into an output pin, and bring it low. // // It is important that the other column pins are configured as inputs. // If multiple keys are pressed down, they may create a circuit // connecting to other column pins as well. We don't want an output // voltage on these pins to affect our reading on the column currently // being scanned. DDRB = 0x01 << col; PORTB = 0xff & ~(0x01 << col); // We need a very brief delay here to allow the signal // to propagate to the input pins. _delay_us(5); // Read which row pins are active uint8_t d = ~PIND; uint8_t f = ~PINF; uint8_t e = ~PINE; if (UNLIKELY(d)) { for (uint8_t n = 0; n < 8; ++n) { if (d & (0x1 << n)) { keyPressed(col, n); } } } if (UNLIKELY(f)) { for (uint8_t n = 0; n < 8; ++n) { if (f & (0x1 << n)) { keyPressed(col, n + 8); } } } if (e & 0x40) { keyPressed(col, 16); } if (e & 0x80) { keyPressed(col, 17); } } DDRB = 0x00; PORTB = 0xff; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/kernel/bltohbdatamgr.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017 */ /* [+] 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 */ #include <kernel/bltohbdatamgr.H> #include <util/align.H> #include <kernel/console.H> #include <assert.h> #include <arch/memorymap.H> #include <bootloader/bootloaderif.H> // Global and only BlToHbDataManager instance BlToHbDataManager g_BlToHbDataManager; //////////////////////////////////////////////////////////////////////////////// //--------------------------------- Private ----------------------------------// //////////////////////////////////////////////////////////////////////////////// // Set static variables to control use Bootloader::BlToHbData BlToHbDataManager::iv_data; bool BlToHbDataManager::iv_instantiated = false; bool BlToHbDataManager::iv_initialized = false; bool BlToHbDataManager::iv_dataValid = false; size_t BlToHbDataManager::iv_preservedSize = 0; void BlToHbDataManager::validAssert() const { if(!iv_dataValid) { printk("E> BlToHbDataManager is invalid, cannot access\n"); kassert(iv_dataValid); } } void BlToHbDataManager::print() const { printkd("\nBlToHbData (all addr HRMOR relative):\n"); if(iv_data.version >= Bootloader::BLTOHB_SAB) { printkd("-- secureSettings: SAB=%d, SecOvrd=%d, AllowAttrOvrd=%d\n", iv_data.secureAccessBit, iv_data.securityOverride, iv_data.allowAttrOverrides); } if(iv_dataValid) { printkd("-- eyeCatch = 0x%lX (%s)\n", iv_data.eyeCatch, reinterpret_cast<char*>(&iv_data.eyeCatch)); printkd("-- version = 0x%lX\n", iv_data.version); printkd("-- branchtableOffset = 0x%lX\n", iv_data.branchtableOffset); printkd("-- SecureRom Addr = 0x%lX Size = 0x%lX\n", getSecureRomAddr(), iv_data.secureRomSize); printkd("-- HW keys' Hash Addr = 0x%lX Size = 0x%lX\n", getHwKeysHashAddr(), iv_data.hwKeysHashSize); printkd("-- HBB header Addr = 0x%lX Size = 0x%lX\n", getHbbHeaderAddr(), iv_data.hbbHeaderSize); printkd("-- Reserved Size = 0x%lX\n", iv_preservedSize); printkd("\n"); } } //////////////////////////////////////////////////////////////////////////////// //---------------------------------- Public ----------------------------------// //////////////////////////////////////////////////////////////////////////////// BlToHbDataManager::BlToHbDataManager() { // Allow only one instantiation if (iv_instantiated) { printk("E> A BlToHbDataManager class instance already exists\n"); kassert(!iv_instantiated); } iv_instantiated = true; } void BlToHbDataManager::initValid (const Bootloader::BlToHbData& i_data) { // Allow only one initializer call if (iv_initialized) { printk("E> BlToHbDataManager class previously initialized\n"); kassert(!iv_initialized); } // Simple assertion checks kassert(i_data.eyeCatch>0); kassert(i_data.version>0); kassert(i_data.branchtableOffset>0); kassert(i_data.secureRom!=nullptr); kassert(i_data.hwKeysHash!=nullptr); kassert(i_data.hbbHeader!=nullptr); kassert(i_data.secureRomSize>0); kassert(i_data.hwKeysHashSize>0); kassert(i_data.hbbHeaderSize>0); // Set internal static data iv_data.eyeCatch = i_data.eyeCatch; iv_data.version = i_data.version; iv_data.branchtableOffset = i_data.branchtableOffset; iv_data.secureRom = i_data.secureRom; iv_data.secureRomSize = i_data.secureRomSize; iv_data.hwKeysHash = i_data.hwKeysHash; iv_data.hwKeysHashSize = i_data.hwKeysHashSize; iv_data.hbbHeader = i_data.hbbHeader; iv_data.hbbHeaderSize = i_data.hbbHeaderSize; printk("Version=%lX\n",i_data.version); // Ensure Bootloader to HB structure has the Secure Settings if(iv_data.version >= Bootloader::BLTOHB_SAB) { iv_data.secureAccessBit = i_data.secureAccessBit; } if(iv_data.version >= Bootloader::BLTOHB_SECURE_OVERRIDES) { iv_data.securityOverride = i_data.securityOverride; iv_data.allowAttrOverrides = i_data.allowAttrOverrides; } else { iv_data.securityOverride = 0; iv_data.allowAttrOverrides = 0; } // Ensure Bootloader to HB structure has the MMIO members if( iv_data.version >= Bootloader::BLTOHB_MMIOBARS ) { printk("lpc=%lX, xscom=%lX\n", i_data.lpcBAR, i_data.xscomBAR ); kassert(i_data.lpcBAR>0); kassert(i_data.xscomBAR>0); iv_data.lpcBAR = i_data.lpcBAR; iv_data.xscomBAR = i_data.xscomBAR; } else { //default to group0-proc0 values for down-level SBE iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR; iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR; } //@fixme-RTC:149250-Remove this hack iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR; iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR; printk( "Use default LPC/XSCOM\n" ); // Size of data that needs to be preserved and pinned. iv_preservedSize = ALIGN_PAGE(iv_data.secureRomSize + iv_data.hwKeysHashSize + iv_data.hbbHeaderSize ); iv_initialized = true; iv_dataValid = true; print(); } void BlToHbDataManager::initInvalid () { printkd("BlToHbDataManager::initInvalid\n"); // Allow only one initializer call if (iv_initialized) { printk("E> BlToHbDataManager class previously initialized\n"); kassert(!iv_initialized); } //default to group0-proc0 values for down-level SBE iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR; iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR; iv_initialized = true; iv_dataValid = false; print(); } const uint64_t BlToHbDataManager::getBranchtableOffset() const { validAssert(); return iv_data.branchtableOffset; } const void* BlToHbDataManager::getSecureRom() const { validAssert(); return iv_data.secureRom; } const uint64_t BlToHbDataManager::getSecureRomAddr() const { validAssert(); return reinterpret_cast<uint64_t>(iv_data.secureRom); } const size_t BlToHbDataManager::getSecureRomSize() const { validAssert(); return iv_data.secureRomSize; } const void* BlToHbDataManager::getHwKeysHash() const { validAssert(); return iv_data.hwKeysHash; } const uint64_t BlToHbDataManager::getHwKeysHashAddr() const { validAssert(); return reinterpret_cast<uint64_t>(iv_data.hwKeysHash); } const size_t BlToHbDataManager::getHwKeysHashSize() const { validAssert(); return iv_data.hwKeysHashSize; } const void* BlToHbDataManager::getHbbHeader() const { validAssert(); return iv_data.hbbHeader; } const uint64_t BlToHbDataManager::getHbbHeaderAddr() const { validAssert(); return reinterpret_cast<uint64_t>(iv_data.hbbHeader); } const size_t BlToHbDataManager::getHbbHeaderSize() const { validAssert(); return iv_data.hbbHeaderSize; } const bool BlToHbDataManager::getSecureAccessBit() const { validAssert(); return iv_data.secureAccessBit; } const bool BlToHbDataManager::getSecurityOverride() const { validAssert(); return iv_data.securityOverride; } const bool BlToHbDataManager::getAllowAttrOverrides() const { validAssert(); return iv_data.allowAttrOverrides; } const size_t BlToHbDataManager::getPreservedSize() const { validAssert(); return iv_preservedSize; } const bool BlToHbDataManager::isValid() const { return iv_dataValid; } const uint64_t BlToHbDataManager::getLpcBAR() const { return reinterpret_cast<uint64_t>(iv_data.lpcBAR); } const uint64_t BlToHbDataManager::getXscomBAR() const { return reinterpret_cast<uint64_t>(iv_data.xscomBAR); } <commit_msg>Remove asserts on variables that have valid default values<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/kernel/bltohbdatamgr.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017 */ /* [+] 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 */ #include <kernel/bltohbdatamgr.H> #include <util/align.H> #include <kernel/console.H> #include <assert.h> #include <arch/memorymap.H> #include <bootloader/bootloaderif.H> // Global and only BlToHbDataManager instance BlToHbDataManager g_BlToHbDataManager; //////////////////////////////////////////////////////////////////////////////// //--------------------------------- Private ----------------------------------// //////////////////////////////////////////////////////////////////////////////// // Set static variables to control use Bootloader::BlToHbData BlToHbDataManager::iv_data; bool BlToHbDataManager::iv_instantiated = false; bool BlToHbDataManager::iv_initialized = false; bool BlToHbDataManager::iv_dataValid = false; size_t BlToHbDataManager::iv_preservedSize = 0; void BlToHbDataManager::validAssert() const { if(!iv_dataValid) { printk("E> BlToHbDataManager is invalid, cannot access\n"); kassert(iv_dataValid); } } void BlToHbDataManager::print() const { if(iv_dataValid) { printkd("\nBlToHbData (all addr HRMOR relative):\n"); if(iv_data.version >= Bootloader::BLTOHB_SAB) { printkd("-- secureSettings: SAB=%d, SecOvrd=%d, AllowAttrOvrd=%d\n", iv_data.secureAccessBit, iv_data.securityOverride, iv_data.allowAttrOverrides); } printkd("-- eyeCatch = 0x%lX (%s)\n", iv_data.eyeCatch, reinterpret_cast<char*>(&iv_data.eyeCatch)); printkd("-- version = 0x%lX\n", iv_data.version); printkd("-- branchtableOffset = 0x%lX\n", iv_data.branchtableOffset); printkd("-- SecureRom Addr = 0x%lX Size = 0x%lX\n", getSecureRomAddr(), iv_data.secureRomSize); printkd("-- HW keys' Hash Addr = 0x%lX Size = 0x%lX\n", getHwKeysHashAddr(), iv_data.hwKeysHashSize); printkd("-- HBB header Addr = 0x%lX Size = 0x%lX\n", getHbbHeaderAddr(), iv_data.hbbHeaderSize); printkd("-- Reserved Size = 0x%lX\n", iv_preservedSize); printkd("\n"); } } //////////////////////////////////////////////////////////////////////////////// //---------------------------------- Public ----------------------------------// //////////////////////////////////////////////////////////////////////////////// BlToHbDataManager::BlToHbDataManager() { // Allow only one instantiation if (iv_instantiated) { printk("E> A BlToHbDataManager class instance already exists\n"); kassert(!iv_instantiated); } iv_instantiated = true; } void BlToHbDataManager::initValid (const Bootloader::BlToHbData& i_data) { // Allow only one initializer call if (iv_initialized) { printk("E> BlToHbDataManager class previously initialized\n"); kassert(!iv_initialized); } // Simple assertion checks kassert(i_data.eyeCatch>0); kassert(i_data.version>0); kassert(i_data.branchtableOffset>0); kassert(i_data.secureRom!=nullptr); kassert(i_data.hwKeysHash!=nullptr); kassert(i_data.hbbHeader!=nullptr); kassert(i_data.secureRomSize>0); kassert(i_data.hwKeysHashSize>0); kassert(i_data.hbbHeaderSize>0); // Set internal static data iv_data.eyeCatch = i_data.eyeCatch; iv_data.version = i_data.version; iv_data.branchtableOffset = i_data.branchtableOffset; iv_data.secureRom = i_data.secureRom; iv_data.secureRomSize = i_data.secureRomSize; iv_data.hwKeysHash = i_data.hwKeysHash; iv_data.hwKeysHashSize = i_data.hwKeysHashSize; iv_data.hbbHeader = i_data.hbbHeader; iv_data.hbbHeaderSize = i_data.hbbHeaderSize; printk("Version=%lX\n",i_data.version); // Ensure Bootloader to HB structure has the Secure Settings if(iv_data.version >= Bootloader::BLTOHB_SAB) { iv_data.secureAccessBit = i_data.secureAccessBit; } if(iv_data.version >= Bootloader::BLTOHB_SECURE_OVERRIDES) { iv_data.securityOverride = i_data.securityOverride; iv_data.allowAttrOverrides = i_data.allowAttrOverrides; } else { iv_data.securityOverride = 0; iv_data.allowAttrOverrides = 0; } // Ensure Bootloader to HB structure has the MMIO members if( iv_data.version >= Bootloader::BLTOHB_MMIOBARS ) { printk("lpc=%lX, xscom=%lX\n", i_data.lpcBAR, i_data.xscomBAR ); kassert(i_data.lpcBAR>0); kassert(i_data.xscomBAR>0); iv_data.lpcBAR = i_data.lpcBAR; iv_data.xscomBAR = i_data.xscomBAR; } else { //default to group0-proc0 values for down-level SBE iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR; iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR; } //@fixme-RTC:149250-Remove this hack iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR; iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR; printk( "Use default LPC/XSCOM\n" ); // Size of data that needs to be preserved and pinned. iv_preservedSize = ALIGN_PAGE(iv_data.secureRomSize + iv_data.hwKeysHashSize + iv_data.hbbHeaderSize ); iv_initialized = true; iv_dataValid = true; print(); } void BlToHbDataManager::initInvalid () { printkd("BlToHbDataManager::initInvalid\n"); // Allow only one initializer call if (iv_initialized) { printk("E> BlToHbDataManager class previously initialized\n"); kassert(!iv_initialized); } //default to group0-proc0 values for down-level SBE iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR; iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR; iv_initialized = true; iv_dataValid = false; print(); } const uint64_t BlToHbDataManager::getBranchtableOffset() const { return iv_data.branchtableOffset; } const void* BlToHbDataManager::getSecureRom() const { validAssert(); return iv_data.secureRom; } const uint64_t BlToHbDataManager::getSecureRomAddr() const { validAssert(); return reinterpret_cast<uint64_t>(iv_data.secureRom); } const size_t BlToHbDataManager::getSecureRomSize() const { return iv_data.secureRomSize; } const void* BlToHbDataManager::getHwKeysHash() const { validAssert(); return iv_data.hwKeysHash; } const uint64_t BlToHbDataManager::getHwKeysHashAddr() const { validAssert(); return reinterpret_cast<uint64_t>(iv_data.hwKeysHash); } const size_t BlToHbDataManager::getHwKeysHashSize() const { return iv_data.hwKeysHashSize; } const void* BlToHbDataManager::getHbbHeader() const { validAssert(); return iv_data.hbbHeader; } const uint64_t BlToHbDataManager::getHbbHeaderAddr() const { validAssert(); return reinterpret_cast<uint64_t>(iv_data.hbbHeader); } const size_t BlToHbDataManager::getHbbHeaderSize() const { return iv_data.hbbHeaderSize; } const bool BlToHbDataManager::getSecureAccessBit() const { return iv_data.secureAccessBit; } const bool BlToHbDataManager::getSecurityOverride() const { return iv_data.securityOverride; } const bool BlToHbDataManager::getAllowAttrOverrides() const { return iv_data.allowAttrOverrides; } const size_t BlToHbDataManager::getPreservedSize() const { return iv_preservedSize; } const bool BlToHbDataManager::isValid() const { return iv_dataValid; } const uint64_t BlToHbDataManager::getLpcBAR() const { return reinterpret_cast<uint64_t>(iv_data.lpcBAR); } const uint64_t BlToHbDataManager::getXscomBAR() const { return reinterpret_cast<uint64_t>(iv_data.xscomBAR); } <|endoftext|>
<commit_before>/* Q Light Controller - Unit tests qlcphysical_test.cpp Copyright (C) Heikki Junnila Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QtTest> #include <QtXml> #include "qlcphysical_test.h" #include "qlcphysical.h" void QLCPhysical_Test::bulbType() { QVERIFY(p.bulbType().isEmpty()); p.setBulbType("BulbType"); QVERIFY(p.bulbType() == "BulbType"); } void QLCPhysical_Test::bulbLumens() { QVERIFY(p.bulbLumens() == 0); p.setBulbLumens(10000); QVERIFY(p.bulbLumens() == 10000); } void QLCPhysical_Test::bulbColourTemp() { QVERIFY(p.bulbColourTemperature() == 0); p.setBulbColourTemperature(3200); QVERIFY(p.bulbColourTemperature() == 3200); } void QLCPhysical_Test::weight() { QVERIFY(p.weight() == 0); p.setWeight(7); QVERIFY(p.weight() == 7); p.setWeight(5.02837); QCOMPARE(p.weight(), 5.02837); } void QLCPhysical_Test::width() { QVERIFY(p.width() == 0); p.setWidth(600); QVERIFY(p.width() == 600); } void QLCPhysical_Test::height() { QVERIFY(p.height() == 0); p.setHeight(1200); QVERIFY(p.height() == 1200); } void QLCPhysical_Test::depth() { QVERIFY(p.depth() == 0); p.setDepth(250); QVERIFY(p.depth() == 250); } void QLCPhysical_Test::lensName() { QVERIFY(p.lensName() == "Other"); p.setLensName("Fresnel"); QVERIFY(p.lensName() == "Fresnel"); } void QLCPhysical_Test::lensDegreesMin() { QVERIFY(p.lensDegreesMin() == 0); p.setLensDegreesMin(9.4); QVERIFY(p.lensDegreesMin() == 9.4); } void QLCPhysical_Test::lensDegreesMax() { QVERIFY(p.lensDegreesMax() == 0); p.setLensDegreesMax(40.5); QVERIFY(p.lensDegreesMax() == 40.5); } void QLCPhysical_Test::focusType() { QVERIFY(p.focusType() == "Fixed"); p.setFocusType("Head"); QVERIFY(p.focusType() == "Head"); } void QLCPhysical_Test::focusPanMax() { QVERIFY(p.focusPanMax() == 0); p.setFocusPanMax(540); QVERIFY(p.focusPanMax() == 540); } void QLCPhysical_Test::focusTiltMax() { QVERIFY(p.focusTiltMax() == 0); p.setFocusTiltMax(270); QVERIFY(p.focusTiltMax() == 270); } void QLCPhysical_Test::powerConsumption() { QVERIFY(p.powerConsumption() == 0); p.setPowerConsumption(24000); QVERIFY(p.powerConsumption() == 24000); } void QLCPhysical_Test::dmxConnector() { QVERIFY(p.dmxConnector() == "5-pin"); p.setDmxConnector("3-pin"); QVERIFY(p.dmxConnector() == "3-pin"); } void QLCPhysical_Test::copy() { QLCPhysical c = p; QVERIFY(c.bulbType() == p.bulbType()); QVERIFY(c.bulbLumens() == p.bulbLumens()); QVERIFY(c.bulbColourTemperature() == p.bulbColourTemperature()); QVERIFY(c.weight() == p.weight()); QVERIFY(c.width() == p.width()); QVERIFY(c.height() == p.height()); QVERIFY(c.depth() == p.depth()); QVERIFY(c.lensName() == p.lensName()); QVERIFY(c.lensDegreesMin() == p.lensDegreesMin()); QVERIFY(c.lensDegreesMax() == p.lensDegreesMax()); QVERIFY(c.focusType() == p.focusType()); QVERIFY(c.focusPanMax() == p.focusPanMax()); QVERIFY(c.focusTiltMax() == p.focusTiltMax()); QVERIFY(c.powerConsumption() == p.powerConsumption()); QVERIFY(c.dmxConnector() == p.dmxConnector()); } void QLCPhysical_Test::load() { QDomDocument doc; QDomElement root = doc.createElement("Physical"); doc.appendChild(root); /* Bulb */ QDomElement bulb = doc.createElement("Bulb"); bulb.setAttribute("Type", "LED"); bulb.setAttribute("Lumens", 18000); bulb.setAttribute("ColourTemperature", 6500); root.appendChild(bulb); /* Dimensions */ QDomElement dim = doc.createElement("Dimensions"); dim.setAttribute("Weight", 39.4); dim.setAttribute("Width", 530); dim.setAttribute("Height", 320); dim.setAttribute("Depth", 260); root.appendChild(dim); /* Lens */ QDomElement lens = doc.createElement("Lens"); lens.setAttribute("Name", "Fresnel"); lens.setAttribute("DegreesMin", 8); lens.setAttribute("DegreesMax", 38); root.appendChild(lens); /* Focus */ QDomElement focus = doc.createElement("Focus"); focus.setAttribute("Type", "Head"); focus.setAttribute("PanMax", 520); focus.setAttribute("TiltMax", 270); root.appendChild(focus); /* Technical */ QDomElement technical = doc.createElement("Technical"); technical.setAttribute("PowerConsumption", 250); technical.setAttribute("DmxConnector", "5-pin"); root.appendChild(technical); /* Unrecognized tag */ QDomElement homer = doc.createElement("HomerSimpson"); homer.setAttribute("BeerConsumption", 25000); homer.setAttribute("PreferredBrand", "Duff"); root.appendChild(homer); QVERIFY(p.loadXML(root) == true); QVERIFY(p.bulbType() == "LED"); QVERIFY(p.bulbLumens() == 18000); QVERIFY(p.bulbColourTemperature() == 6500); QCOMPARE(p.weight(), 39.4); QVERIFY(p.width() == 530); QVERIFY(p.height() == 320); QVERIFY(p.depth() == 260); QVERIFY(p.lensName() == "Fresnel"); QVERIFY(p.lensDegreesMin() == 8); QVERIFY(p.lensDegreesMax() == 38); QVERIFY(p.focusType() == "Head"); QVERIFY(p.focusPanMax() == 520); QVERIFY(p.focusTiltMax() == 270); QVERIFY(p.powerConsumption() == 250); QVERIFY(p.dmxConnector() == "5-pin"); } void QLCPhysical_Test::loadWrongRoot() { QDomDocument doc; QDomElement root = doc.createElement("Foosical"); doc.appendChild(root); /* Bulb */ QDomElement bulb = doc.createElement("Bulb"); bulb.setAttribute("Type", "LED"); bulb.setAttribute("Lumens", 18000); bulb.setAttribute("ColourTemperature", 6500); root.appendChild(bulb); /* Dimensions */ QDomElement dim = doc.createElement("Dimensions"); dim.setAttribute("Weight", 39.4); dim.setAttribute("Width", 530); dim.setAttribute("Height", 320); dim.setAttribute("Depth", 260); root.appendChild(dim); /* Lens */ QDomElement lens = doc.createElement("Lens"); lens.setAttribute("Name", "Fresnel"); lens.setAttribute("DegreesMin", 8); lens.setAttribute("DegreesMax", 38); root.appendChild(lens); /* Focus */ QDomElement focus = doc.createElement("Focus"); focus.setAttribute("Type", "Head"); focus.setAttribute("PanMax", 520); focus.setAttribute("TiltMax", 270); root.appendChild(focus); /* Technical */ QDomElement technical= doc.createElement("Technical"); technical.setAttribute("PowerConsumption", 250); technical.setAttribute("DmxConnector", "5-pin"); root.appendChild(technical); QVERIFY(p.loadXML(root) == false); } void QLCPhysical_Test::save() { QDomDocument doc; QDomElement root = doc.createElement("Test Root"); bool bulb = false, dim = false, lens = false, focus = false, technical = false; QVERIFY(p.saveXML(&doc, &root) == true); QVERIFY(root.firstChild().toElement().tagName() == "Physical"); QDomNode node = root.firstChild().firstChild(); while (node.isNull() == false) { QDomElement e = node.toElement(); if (e.tagName() == "Bulb") { bulb = true; QVERIFY(e.attribute("Type") == "LED"); QVERIFY(e.attribute("Lumens") == "18000"); QVERIFY(e.attribute("ColourTemperature") == "6500"); } else if (e.tagName() == "Dimensions") { dim = true; QVERIFY(e.attribute("Width") == "530"); QVERIFY(e.attribute("Depth") == "260"); QVERIFY(e.attribute("Height") == "320"); QCOMPARE(e.attribute("Weight").toDouble(), 39.4); } else if (e.tagName() == "Lens") { lens = true; QVERIFY(e.attribute("Name") == "Fresnel"); QVERIFY(e.attribute("DegreesMin") == "8"); QVERIFY(e.attribute("DegreesMax") == "38"); } else if (e.tagName() == "Focus") { focus = true; QVERIFY(e.attribute("Type") == "Head"); QVERIFY(e.attribute("PanMax") == "520"); QVERIFY(e.attribute("TiltMax") == "270"); } else if (e.tagName() == "Technical") { technical = true; QVERIFY(e.attribute("PowerConsumption") == "250"); QVERIFY(e.attribute("DmxConnector") == "5-pin"); } else { QFAIL(QString("Unexpected tag: %1").arg(e.tagName()) .toLatin1()); } node = node.nextSibling(); } QVERIFY(bulb == true); QVERIFY(dim == true); QVERIFY(lens == true); QVERIFY(focus == true); QVERIFY(technical == true); } QTEST_MAIN(QLCPhysical_Test) <commit_msg>Fix QLCPhysical test unit when building with Qt5<commit_after>/* Q Light Controller - Unit tests qlcphysical_test.cpp Copyright (C) Heikki Junnila Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QtTest> #include <QtXml> #include "qlcphysical_test.h" #include "qlcphysical.h" void QLCPhysical_Test::bulbType() { QVERIFY(p.bulbType().isEmpty()); p.setBulbType("BulbType"); QVERIFY(p.bulbType() == "BulbType"); } void QLCPhysical_Test::bulbLumens() { QVERIFY(p.bulbLumens() == 0); p.setBulbLumens(10000); QVERIFY(p.bulbLumens() == 10000); } void QLCPhysical_Test::bulbColourTemp() { QVERIFY(p.bulbColourTemperature() == 0); p.setBulbColourTemperature(3200); QVERIFY(p.bulbColourTemperature() == 3200); } void QLCPhysical_Test::weight() { QVERIFY(p.weight() == 0); p.setWeight(7); QVERIFY(p.weight() == 7); p.setWeight(5.02837); QCOMPARE(p.weight(), 5.02837); } void QLCPhysical_Test::width() { QVERIFY(p.width() == 0); p.setWidth(600); QVERIFY(p.width() == 600); } void QLCPhysical_Test::height() { QVERIFY(p.height() == 0); p.setHeight(1200); QVERIFY(p.height() == 1200); } void QLCPhysical_Test::depth() { QVERIFY(p.depth() == 0); p.setDepth(250); QVERIFY(p.depth() == 250); } void QLCPhysical_Test::lensName() { QVERIFY(p.lensName() == "Other"); p.setLensName("Fresnel"); QVERIFY(p.lensName() == "Fresnel"); } void QLCPhysical_Test::lensDegreesMin() { QVERIFY(p.lensDegreesMin() == 0); p.setLensDegreesMin(9.4); QVERIFY(p.lensDegreesMin() == 9.4); } void QLCPhysical_Test::lensDegreesMax() { QVERIFY(p.lensDegreesMax() == 0); p.setLensDegreesMax(40.5); QVERIFY(p.lensDegreesMax() == 40.5); } void QLCPhysical_Test::focusType() { QVERIFY(p.focusType() == "Fixed"); p.setFocusType("Head"); QVERIFY(p.focusType() == "Head"); } void QLCPhysical_Test::focusPanMax() { QVERIFY(p.focusPanMax() == 0); p.setFocusPanMax(540); QVERIFY(p.focusPanMax() == 540); } void QLCPhysical_Test::focusTiltMax() { QVERIFY(p.focusTiltMax() == 0); p.setFocusTiltMax(270); QVERIFY(p.focusTiltMax() == 270); } void QLCPhysical_Test::powerConsumption() { QVERIFY(p.powerConsumption() == 0); p.setPowerConsumption(24000); QVERIFY(p.powerConsumption() == 24000); } void QLCPhysical_Test::dmxConnector() { QVERIFY(p.dmxConnector() == "5-pin"); p.setDmxConnector("3-pin"); QVERIFY(p.dmxConnector() == "3-pin"); } void QLCPhysical_Test::copy() { QLCPhysical c = p; QVERIFY(c.bulbType() == p.bulbType()); QVERIFY(c.bulbLumens() == p.bulbLumens()); QVERIFY(c.bulbColourTemperature() == p.bulbColourTemperature()); QVERIFY(c.weight() == p.weight()); QVERIFY(c.width() == p.width()); QVERIFY(c.height() == p.height()); QVERIFY(c.depth() == p.depth()); QVERIFY(c.lensName() == p.lensName()); QVERIFY(c.lensDegreesMin() == p.lensDegreesMin()); QVERIFY(c.lensDegreesMax() == p.lensDegreesMax()); QVERIFY(c.focusType() == p.focusType()); QVERIFY(c.focusPanMax() == p.focusPanMax()); QVERIFY(c.focusTiltMax() == p.focusTiltMax()); QVERIFY(c.powerConsumption() == p.powerConsumption()); QVERIFY(c.dmxConnector() == p.dmxConnector()); } void QLCPhysical_Test::load() { QDomDocument doc; QDomElement root = doc.createElement("Physical"); doc.appendChild(root); /* Bulb */ QDomElement bulb = doc.createElement("Bulb"); bulb.setAttribute("Type", "LED"); bulb.setAttribute("Lumens", 18000); bulb.setAttribute("ColourTemperature", 6500); root.appendChild(bulb); /* Dimensions */ QDomElement dim = doc.createElement("Dimensions"); dim.setAttribute("Weight", QString::number(39.4)); dim.setAttribute("Width", 530); dim.setAttribute("Height", 320); dim.setAttribute("Depth", 260); root.appendChild(dim); /* Lens */ QDomElement lens = doc.createElement("Lens"); lens.setAttribute("Name", "Fresnel"); lens.setAttribute("DegreesMin", 8); lens.setAttribute("DegreesMax", 38); root.appendChild(lens); /* Focus */ QDomElement focus = doc.createElement("Focus"); focus.setAttribute("Type", "Head"); focus.setAttribute("PanMax", 520); focus.setAttribute("TiltMax", 270); root.appendChild(focus); /* Technical */ QDomElement technical = doc.createElement("Technical"); technical.setAttribute("PowerConsumption", 250); technical.setAttribute("DmxConnector", "5-pin"); root.appendChild(technical); /* Unrecognized tag */ QDomElement homer = doc.createElement("HomerSimpson"); homer.setAttribute("BeerConsumption", 25000); homer.setAttribute("PreferredBrand", "Duff"); root.appendChild(homer); QVERIFY(p.loadXML(root) == true); QVERIFY(p.bulbType() == "LED"); QVERIFY(p.bulbLumens() == 18000); QVERIFY(p.bulbColourTemperature() == 6500); QCOMPARE(p.weight(), 39.4); QVERIFY(p.width() == 530); QVERIFY(p.height() == 320); QVERIFY(p.depth() == 260); QVERIFY(p.lensName() == "Fresnel"); QVERIFY(p.lensDegreesMin() == 8); QVERIFY(p.lensDegreesMax() == 38); QVERIFY(p.focusType() == "Head"); QVERIFY(p.focusPanMax() == 520); QVERIFY(p.focusTiltMax() == 270); QVERIFY(p.powerConsumption() == 250); QVERIFY(p.dmxConnector() == "5-pin"); } void QLCPhysical_Test::loadWrongRoot() { QDomDocument doc; QDomElement root = doc.createElement("Foosical"); doc.appendChild(root); /* Bulb */ QDomElement bulb = doc.createElement("Bulb"); bulb.setAttribute("Type", "LED"); bulb.setAttribute("Lumens", 18000); bulb.setAttribute("ColourTemperature", 6500); root.appendChild(bulb); /* Dimensions */ QDomElement dim = doc.createElement("Dimensions"); dim.setAttribute("Weight", 39.4); dim.setAttribute("Width", 530); dim.setAttribute("Height", 320); dim.setAttribute("Depth", 260); root.appendChild(dim); /* Lens */ QDomElement lens = doc.createElement("Lens"); lens.setAttribute("Name", "Fresnel"); lens.setAttribute("DegreesMin", 8); lens.setAttribute("DegreesMax", 38); root.appendChild(lens); /* Focus */ QDomElement focus = doc.createElement("Focus"); focus.setAttribute("Type", "Head"); focus.setAttribute("PanMax", 520); focus.setAttribute("TiltMax", 270); root.appendChild(focus); /* Technical */ QDomElement technical= doc.createElement("Technical"); technical.setAttribute("PowerConsumption", 250); technical.setAttribute("DmxConnector", "5-pin"); root.appendChild(technical); QVERIFY(p.loadXML(root) == false); } void QLCPhysical_Test::save() { QDomDocument doc; QDomElement root = doc.createElement("Test Root"); bool bulb = false, dim = false, lens = false, focus = false, technical = false; QVERIFY(p.saveXML(&doc, &root) == true); QVERIFY(root.firstChild().toElement().tagName() == "Physical"); QDomNode node = root.firstChild().firstChild(); while (node.isNull() == false) { QDomElement e = node.toElement(); if (e.tagName() == "Bulb") { bulb = true; QVERIFY(e.attribute("Type") == "LED"); QVERIFY(e.attribute("Lumens") == "18000"); QVERIFY(e.attribute("ColourTemperature") == "6500"); } else if (e.tagName() == "Dimensions") { dim = true; QVERIFY(e.attribute("Width") == "530"); QVERIFY(e.attribute("Depth") == "260"); QVERIFY(e.attribute("Height") == "320"); QCOMPARE(e.attribute("Weight").toDouble(), 39.4); } else if (e.tagName() == "Lens") { lens = true; QVERIFY(e.attribute("Name") == "Fresnel"); QVERIFY(e.attribute("DegreesMin") == "8"); QVERIFY(e.attribute("DegreesMax") == "38"); } else if (e.tagName() == "Focus") { focus = true; QVERIFY(e.attribute("Type") == "Head"); QVERIFY(e.attribute("PanMax") == "520"); QVERIFY(e.attribute("TiltMax") == "270"); } else if (e.tagName() == "Technical") { technical = true; QVERIFY(e.attribute("PowerConsumption") == "250"); QVERIFY(e.attribute("DmxConnector") == "5-pin"); } else { QFAIL(QString("Unexpected tag: %1").arg(e.tagName()) .toLatin1()); } node = node.nextSibling(); } QVERIFY(bulb == true); QVERIFY(dim == true); QVERIFY(lens == true); QVERIFY(focus == true); QVERIFY(technical == true); } QTEST_MAIN(QLCPhysical_Test) <|endoftext|>
<commit_before>/* * Convert GError to a HTTP response. * * author: Max Kellermann <mk@cm4all.com> */ #include "request.hxx" #include "bp_instance.hxx" #include "http_client.hxx" #include "nfs/Quark.hxx" #include "nfs/Error.hxx" #include "ajp/ajp_client.hxx" #include "memcached/memcached_client.hxx" #include "cgi/cgi_quark.h" #include "fcgi/Quark.hxx" #include "was/was_quark.h" #include "widget/Error.hxx" #include "http_response.hxx" #include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "http_quark.h" #include "http/MessageHttpResponse.hxx" #include "HttpMessageResponse.hxx" #include "gerrno.h" #include "pool.hxx" #include "system/Error.hxx" #include "util/Exception.hxx" #include <daemon/log.h> #include <nfsc/libnfs-raw-nfs.h> static MessageHttpResponse Dup(struct pool &pool, http_status_t status, const char *msg) { return {status, p_strdup(&pool, msg)}; } gcc_pure static MessageHttpResponse ToResponse(struct pool &pool, GError &error) { if (error.domain == http_response_quark()) return Dup(pool, http_status_t(error.code), error.message); if (error.domain == widget_quark()) { switch (WidgetErrorCode(error.code)) { case WidgetErrorCode::UNSPECIFIED: break; case WidgetErrorCode::WRONG_TYPE: case WidgetErrorCode::UNSUPPORTED_ENCODING: return {HTTP_STATUS_BAD_GATEWAY, "Malformed widget response"}; case WidgetErrorCode::NO_SUCH_VIEW: return {HTTP_STATUS_NOT_FOUND, "No such view"}; case WidgetErrorCode::NOT_A_CONTAINER: return Dup(pool, HTTP_STATUS_NOT_FOUND, error.message); case WidgetErrorCode::FORBIDDEN: return {HTTP_STATUS_FORBIDDEN, "Forbidden"}; } } if (error.domain == nfs_client_quark()) { switch (error.code) { case NFS3ERR_NOENT: case NFS3ERR_NOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; } } if (error.domain == http_client_quark() || error.domain == ajp_client_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Upstream server failed"}; else if (error.domain == cgi_quark() || error.domain == fcgi_quark() || error.domain == was_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Script failed"}; else if (error.domain == errno_quark()) { switch (error.code) { case ENOENT: case ENOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; break; default: return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } } else if (error.domain == memcached_client_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Cache server failed"}; else return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } gcc_pure static MessageHttpResponse ToResponse(struct pool &pool, std::exception_ptr ep) { try { FindRetrowNested<HttpMessageResponse>(ep); } catch (const HttpMessageResponse &e) { return Dup(pool, e.GetStatus(), e.what()); } try { FindRetrowNested<std::system_error>(ep); } catch (const std::system_error &e) { if (e.code().category() == ErrnoCategory()) { switch (e.code().value()) { case ENOENT: case ENOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; break; } } } try { FindRetrowNested<WidgetError>(ep); } catch (const WidgetError &e) { switch (e.GetCode()) { case WidgetErrorCode::UNSPECIFIED: break; case WidgetErrorCode::WRONG_TYPE: case WidgetErrorCode::UNSUPPORTED_ENCODING: return {HTTP_STATUS_BAD_GATEWAY, "Malformed widget response"}; case WidgetErrorCode::NO_SUCH_VIEW: return {HTTP_STATUS_NOT_FOUND, "No such view"}; case WidgetErrorCode::NOT_A_CONTAINER: return Dup(pool, HTTP_STATUS_NOT_FOUND, e.what()); case WidgetErrorCode::FORBIDDEN: return {HTTP_STATUS_FORBIDDEN, "Forbidden"}; } } try { FindRetrowNested<NfsClientError>(ep); } catch (const NfsClientError &e) { switch (e.GetCode()) { case NFS3ERR_NOENT: case NFS3ERR_NOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; } } return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } void response_dispatch_error(Request &request, GError *error) { auto response = ToResponse(request.pool, *error); if (request.instance.config.verbose_response) response.message = p_strdup(&request.pool, error->message); response_dispatch_message(request, response.status, response.message); } void response_dispatch_log(Request &request, http_status_t status, const char *msg, const char *log_msg) { daemon_log(2, "error on '%s': %s\n", request.request.uri, log_msg); if (request.instance.config.verbose_response) msg = p_strdup(&request.pool, log_msg); response_dispatch_message(request, status, msg); } void response_dispatch_log(Request &request, http_status_t status, const char *log_msg) { response_dispatch_log(request, status, http_status_to_string(status), log_msg); } void response_dispatch_log(Request &request, std::exception_ptr ep) { auto log_msg = GetFullMessage(ep); daemon_log(2, "error on '%s': %s\n", request.request.uri, log_msg.c_str()); auto response = ToResponse(request.pool, ep); if (request.instance.config.verbose_response) response.message = p_strdup(&request.pool, log_msg.c_str()); response_dispatch_message(request, response.status, response.message); } <commit_msg>rerror: translate {Http,Fcgi}ClientError to HTTP_STATUS_BAD_GATEWAY<commit_after>/* * Convert GError to a HTTP response. * * author: Max Kellermann <mk@cm4all.com> */ #include "request.hxx" #include "bp_instance.hxx" #include "http_client.hxx" #include "nfs/Quark.hxx" #include "nfs/Error.hxx" #include "ajp/ajp_client.hxx" #include "memcached/memcached_client.hxx" #include "cgi/cgi_quark.h" #include "fcgi/Quark.hxx" #include "fcgi/Error.hxx" #include "was/was_quark.h" #include "widget/Error.hxx" #include "http_response.hxx" #include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "http_quark.h" #include "http/MessageHttpResponse.hxx" #include "HttpMessageResponse.hxx" #include "gerrno.h" #include "pool.hxx" #include "system/Error.hxx" #include "util/Exception.hxx" #include <daemon/log.h> #include <nfsc/libnfs-raw-nfs.h> static MessageHttpResponse Dup(struct pool &pool, http_status_t status, const char *msg) { return {status, p_strdup(&pool, msg)}; } gcc_pure static MessageHttpResponse ToResponse(struct pool &pool, GError &error) { if (error.domain == http_response_quark()) return Dup(pool, http_status_t(error.code), error.message); if (error.domain == widget_quark()) { switch (WidgetErrorCode(error.code)) { case WidgetErrorCode::UNSPECIFIED: break; case WidgetErrorCode::WRONG_TYPE: case WidgetErrorCode::UNSUPPORTED_ENCODING: return {HTTP_STATUS_BAD_GATEWAY, "Malformed widget response"}; case WidgetErrorCode::NO_SUCH_VIEW: return {HTTP_STATUS_NOT_FOUND, "No such view"}; case WidgetErrorCode::NOT_A_CONTAINER: return Dup(pool, HTTP_STATUS_NOT_FOUND, error.message); case WidgetErrorCode::FORBIDDEN: return {HTTP_STATUS_FORBIDDEN, "Forbidden"}; } } if (error.domain == nfs_client_quark()) { switch (error.code) { case NFS3ERR_NOENT: case NFS3ERR_NOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; } } if (error.domain == http_client_quark() || error.domain == ajp_client_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Upstream server failed"}; else if (error.domain == cgi_quark() || error.domain == fcgi_quark() || error.domain == was_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Script failed"}; else if (error.domain == errno_quark()) { switch (error.code) { case ENOENT: case ENOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; break; default: return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } } else if (error.domain == memcached_client_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Cache server failed"}; else return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } gcc_pure static MessageHttpResponse ToResponse(struct pool &pool, std::exception_ptr ep) { try { FindRetrowNested<HttpMessageResponse>(ep); } catch (const HttpMessageResponse &e) { return Dup(pool, e.GetStatus(), e.what()); } try { FindRetrowNested<std::system_error>(ep); } catch (const std::system_error &e) { if (e.code().category() == ErrnoCategory()) { switch (e.code().value()) { case ENOENT: case ENOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; break; } } } try { FindRetrowNested<WidgetError>(ep); } catch (const WidgetError &e) { switch (e.GetCode()) { case WidgetErrorCode::UNSPECIFIED: break; case WidgetErrorCode::WRONG_TYPE: case WidgetErrorCode::UNSUPPORTED_ENCODING: return {HTTP_STATUS_BAD_GATEWAY, "Malformed widget response"}; case WidgetErrorCode::NO_SUCH_VIEW: return {HTTP_STATUS_NOT_FOUND, "No such view"}; case WidgetErrorCode::NOT_A_CONTAINER: return Dup(pool, HTTP_STATUS_NOT_FOUND, e.what()); case WidgetErrorCode::FORBIDDEN: return {HTTP_STATUS_FORBIDDEN, "Forbidden"}; } } try { FindRetrowNested<HttpClientError>(ep); } catch (...) { return {HTTP_STATUS_BAD_GATEWAY, "Upstream server failed"}; } try { FindRetrowNested<FcgiClientError>(ep); } catch (...) { return {HTTP_STATUS_BAD_GATEWAY, "Script failed"}; } try { FindRetrowNested<NfsClientError>(ep); } catch (const NfsClientError &e) { switch (e.GetCode()) { case NFS3ERR_NOENT: case NFS3ERR_NOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; } } return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } void response_dispatch_error(Request &request, GError *error) { auto response = ToResponse(request.pool, *error); if (request.instance.config.verbose_response) response.message = p_strdup(&request.pool, error->message); response_dispatch_message(request, response.status, response.message); } void response_dispatch_log(Request &request, http_status_t status, const char *msg, const char *log_msg) { daemon_log(2, "error on '%s': %s\n", request.request.uri, log_msg); if (request.instance.config.verbose_response) msg = p_strdup(&request.pool, log_msg); response_dispatch_message(request, status, msg); } void response_dispatch_log(Request &request, http_status_t status, const char *log_msg) { response_dispatch_log(request, status, http_status_to_string(status), log_msg); } void response_dispatch_log(Request &request, std::exception_ptr ep) { auto log_msg = GetFullMessage(ep); daemon_log(2, "error on '%s': %s\n", request.request.uri, log_msg.c_str()); auto response = ToResponse(request.pool, ep); if (request.instance.config.verbose_response) response.message = p_strdup(&request.pool, log_msg.c_str()); response_dispatch_message(request, response.status, response.message); } <|endoftext|>
<commit_before> /** * This file is part of the boostcache package. * * (c) Azat Khuzhin <a3at.mail@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #include "session.h" #include "util/log.h" #include <boost/bind.hpp> #include <boost/spirit/include/qi.hpp> #include <sstream> using namespace boost::spirit::qi; void Session::start() { asyncRead(); } void Session::asyncRead() { m_socket.async_read_some(boost::asio::buffer(m_buffer, MAX_BUFFER_LENGTH), boost::bind(&Session::handleRead, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void Session::handleRead(const boost::system::error_code& error, size_t /* bytesTransferred */) { if (error) { delete this; return; } handleReadParseCommand(); } void Session::handleWrite(const boost::system::error_code& error) { if (error) { delete this; return; } asyncRead(); } /** * TODO: speedup parsing * TODO: more error-friendly parsing * TODO: add logging before every reset() call */ void Session::handleReadParseCommand() { LOG(debug) << "Try to read/parser command " << m_buffer << "with " << m_numberOfArguments << " arguments, " "for " << this; m_commandString += m_buffer; std::string line; std::istringstream stream(m_commandString); stream.seekg(m_commandOffset); // Number of arguments if (m_numberOfArguments < 0) { std::getline(stream, line); parse(line.begin(), line.end(), '*' >> int_ >> "\r", m_numberOfArguments); if (m_numberOfArguments < 0) { LOG(debug) << "Don't have number of arguments, for " << this; reset(); asyncRead(); return; } commandArguments.reserve(m_numberOfArguments); m_numberOfArgumentsLeft = m_numberOfArguments; m_commandOffset = stream.tellg(); LOG(info) << "Have " << m_numberOfArguments << " number of arguments, " << "for " << this; } char crLf[2]; char *argument = NULL; int argumentLength = 0; while (m_numberOfArgumentsLeft && std::getline(stream, line)) { if (!parse(line.begin(), line.end(), '$' >> int_ >> "\r", m_lastArgumentLength) ) { LOG(debug) << "Can't find valid argument length, for " << this; break; } LOG(debug) << "Reading " << m_lastArgumentLength << " bytes, for " << this; if (argumentLength < m_lastArgumentLength) { argument = (char *)realloc(argument, argumentLength + 1 /* NULL byte */ + m_lastArgumentLength); argumentLength += m_lastArgumentLength; } stream.read(argument, m_lastArgumentLength); argument[m_lastArgumentLength] = 0; if (!stream.good()) { LOG(debug) << "Bad stream, for " << this; reset(); break; } // Read CRLF separator stream.read(crLf, 2); if (!stream.good()) { LOG(debug) << "Bad stream, for " << this; reset(); break; } if (memcmp(crLf, "\r\n", 2) != 0) { LOG(debug) << "Malfomed end of argument, for " << this; reset(); break; } // Save command argument LOG(debug) << "Saving " << argument << " argument, for " << this; commandArguments.push_back(argument); m_lastArgumentLength = -1; // Update some counters/offsets --m_numberOfArgumentsLeft; m_commandOffset = stream.tellg(); } if (!m_numberOfArgumentsLeft) { handleCommand(); // Will be called asyncRead() in write callback } else { asyncRead(); } } void Session::handleCommand() { LOG(info) << "Handling new command, for " << this; writeCommand(); reset(); } void Session::writeCommand() { std::string arguments; int i; for_each(commandArguments.begin(), commandArguments.end(), [&arguments, &i] (std::string argument) { arguments += i++; arguments += " "; arguments += argument; arguments += "\n"; } ); boost::asio::async_write(m_socket, boost::asio::buffer(arguments), boost::bind(&Session::handleWrite, this, boost::asio::placeholders::error)); } void Session::reset() { m_commandString = ""; m_commandOffset = 0; m_numberOfArguments = -1; m_numberOfArgumentsLeft = -1; m_lastArgumentLength = -1; commandArguments.clear(); }<commit_msg>[net/session] fix handling message part that recieved in multiple chunks<commit_after> /** * This file is part of the boostcache package. * * (c) Azat Khuzhin <a3at.mail@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #include "session.h" #include "util/log.h" #include <boost/bind.hpp> #include <boost/spirit/include/qi.hpp> #include <sstream> using namespace boost::spirit::qi; void Session::start() { asyncRead(); } void Session::asyncRead() { m_socket.async_read_some(boost::asio::buffer(m_buffer, MAX_BUFFER_LENGTH), boost::bind(&Session::handleRead, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void Session::handleRead(const boost::system::error_code& error, size_t /* bytesTransferred */) { if (error) { delete this; return; } handleReadParseCommand(); } void Session::handleWrite(const boost::system::error_code& error) { if (error) { delete this; return; } asyncRead(); } /** * TODO: speedup parsing * TODO: more error-friendly parsing * TODO: add logging before every reset() call */ void Session::handleReadParseCommand() { LOG(debug) << "Try to read/parser command " << m_buffer << "with " << m_numberOfArguments << " arguments, " "for " << this; m_commandString += m_buffer; std::string line; std::istringstream stream(m_commandString); stream.seekg(m_commandOffset); // Number of arguments if (m_numberOfArguments < 0) { std::getline(stream, line); parse(line.begin(), line.end(), '*' >> int_ >> "\r", m_numberOfArguments); if (m_numberOfArguments < 0) { LOG(debug) << "Don't have number of arguments, for " << this; reset(); asyncRead(); return; } commandArguments.reserve(m_numberOfArguments); m_numberOfArgumentsLeft = m_numberOfArguments; m_commandOffset = stream.tellg(); LOG(info) << "Have " << m_numberOfArguments << " number of arguments, " << "for " << this; } char crLf[2]; char *argument = NULL; int argumentLength = 0; while (m_numberOfArgumentsLeft && std::getline(stream, line)) { if (!parse(line.begin(), line.end(), '$' >> int_ >> "\r", m_lastArgumentLength) ) { LOG(debug) << "Can't find valid argument length, for " << this; break; } LOG(debug) << "Reading " << m_lastArgumentLength << " bytes, for " << this; if (argumentLength < m_lastArgumentLength) { argument = (char *)realloc(argument, argumentLength + 1 /* NULL byte */ + m_lastArgumentLength); argumentLength += m_lastArgumentLength; } stream.read(argument, m_lastArgumentLength); argument[m_lastArgumentLength] = 0; if (!stream.good()) { /** * TODO: add some internal counters for failover, * or smth like this */ if (stream.bad()) { LOG(debug) << "Bad stream, for " << this; reset(); } break; } // Read CRLF separator stream.read(crLf, 2); if (!stream.good()) { /** * TODO: add some internal counters for failover, * or smth like this */ if (stream.bad()) { LOG(debug) << "Bad stream, for " << this; reset(); } break; } if (memcmp(crLf, "\r\n", 2) != 0) { LOG(debug) << "Malfomed end of argument, for " << this; reset(); break; } // Save command argument LOG(debug) << "Saving " << argument << " argument, for " << this; commandArguments.push_back(argument); m_lastArgumentLength = -1; // Update some counters/offsets --m_numberOfArgumentsLeft; m_commandOffset = stream.tellg(); } if (!m_numberOfArgumentsLeft) { handleCommand(); // Will be called asyncRead() in write callback } else { asyncRead(); } } void Session::handleCommand() { LOG(info) << "Handling new command, for " << this; writeCommand(); reset(); } void Session::writeCommand() { std::string arguments; int i; for_each(commandArguments.begin(), commandArguments.end(), [&arguments, &i] (std::string argument) { arguments += i++; arguments += " "; arguments += argument; arguments += "\n"; } ); boost::asio::async_write(m_socket, boost::asio::buffer(arguments), boost::bind(&Session::handleWrite, this, boost::asio::placeholders::error)); } void Session::reset() { m_commandString = ""; m_commandOffset = 0; m_numberOfArguments = -1; m_numberOfArgumentsLeft = -1; m_lastArgumentLength = -1; commandArguments.clear(); }<|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "random.h" #include "crypto/sha512.h" #include "support/cleanse.h" #ifdef WIN32 #include "compat.h" // for Windows API #include <wincrypt.h> #endif #include "util.h" // for LogPrint() #include "utilstrencodings.h" // for GetTime() #include <stdlib.h> #include <limits> #include <chrono> #include <thread> #ifndef WIN32 #include <sys/time.h> #endif #ifdef HAVE_SYS_GETRANDOM #include <sys/syscall.h> #include <linux/random.h> #endif #ifdef HAVE_GETENTROPY #include <unistd.h> #endif #ifdef HAVE_SYSCTL_ARND #include <sys/sysctl.h> #endif #include <mutex> #include <openssl/err.h> #include <openssl/rand.h> static void RandFailure() { LogPrintf("Failed to read randomness, aborting\n"); abort(); } static inline int64_t GetPerformanceCounter() { // Read the hardware time stamp counter when available. // See https://en.wikipedia.org/wiki/Time_Stamp_Counter for more information. #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) return __rdtsc(); #elif !defined(_MSC_VER) && defined(__i386__) uint64_t r = 0; __asm__ volatile ("rdtsc" : "=A"(r)); // Constrain the r variable to the eax:edx pair. return r; #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__)) uint64_t r1 = 0, r2 = 0; __asm__ volatile ("rdtsc" : "=a"(r1), "=d"(r2)); // Constrain r1 to rax and r2 to rdx. return (r2 << 32) | r1; #else // Fall back to using C++11 clock (usually microsecond or nanosecond precision) return std::chrono::high_resolution_clock::now().time_since_epoch().count(); #endif } void RandAddSeed() { // Seed with CPU performance counter int64_t nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memory_cleanse((void*)&nCounter, sizeof(nCounter)); } static void RandAddSeedPerfmon() { RandAddSeed(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); std::vector<unsigned char> vData(250000, 0); long ret = 0; unsigned long nSize = 0; const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data while (true) { nSize = vData.size(); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, vData.data(), &nSize); if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) break; vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially } RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(vData.data(), nSize, nSize / 100.0); memory_cleanse(vData.data(), nSize); LogPrint(BCLog::RAND, "%s: %lu bytes\n", __func__, nSize); } else { static bool warned = false; // Warn only once if (!warned) { LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret); warned = true; } } #endif } #ifndef WIN32 /** Fallback: get 32 bytes of system entropy from /dev/urandom. The most * compatible way to get cryptographic randomness on UNIX-ish platforms. */ void GetDevURandom(unsigned char *ent32) { int f = open("/dev/urandom", O_RDONLY); if (f == -1) { RandFailure(); } int have = 0; do { ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have); if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) { RandFailure(); } have += n; } while (have < NUM_OS_RANDOM_BYTES); close(f); } #endif /** Get 32 bytes of system entropy. */ void GetOSRand(unsigned char *ent32) { #if defined(WIN32) HCRYPTPROV hProvider; int ret = CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (!ret) { RandFailure(); } ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32); if (!ret) { RandFailure(); } CryptReleaseContext(hProvider, 0); #elif defined(HAVE_SYS_GETRANDOM) /* Linux. From the getrandom(2) man page: * "If the urandom source has been initialized, reads of up to 256 bytes * will always return as many bytes as requested and will not be * interrupted by signals." */ int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0); if (rv != NUM_OS_RANDOM_BYTES) { if (rv < 0 && errno == ENOSYS) { /* Fallback for kernel <3.17: the return value will be -1 and errno * ENOSYS if the syscall is not available, in that case fall back * to /dev/urandom. */ GetDevURandom(ent32); } else { RandFailure(); } } #elif defined(HAVE_GETENTROPY) /* On OpenBSD this can return up to 256 bytes of entropy, will return an * error if more are requested. * The call cannot return less than the requested number of bytes. */ if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) { RandFailure(); } #elif defined(HAVE_SYSCTL_ARND) /* FreeBSD and similar. It is possible for the call to return less * bytes than requested, so need to read in a loop. */ static const int name[2] = {CTL_KERN, KERN_ARND}; int have = 0; do { size_t len = NUM_OS_RANDOM_BYTES - have; if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, NULL, 0) != 0) { RandFailure(); } have += len; } while (have < NUM_OS_RANDOM_BYTES); #else /* Fall back to /dev/urandom if there is no specific method implemented to * get system entropy for this OS. */ GetDevURandom(ent32); #endif } void GetRandBytes(unsigned char* buf, int num) { if (RAND_bytes(buf, num) != 1) { RandFailure(); } } static std::mutex cs_rng_state; static unsigned char rng_state[32] = {0}; static uint64_t rng_counter = 0; void GetStrongRandBytes(unsigned char* out, int num) { assert(num <= 32); CSHA512 hasher; unsigned char buf[64]; // First source: OpenSSL's RNG RandAddSeedPerfmon(); GetRandBytes(buf, 32); hasher.Write(buf, 32); // Second source: OS RNG GetOSRand(buf); hasher.Write(buf, 32); // Combine with and update state { std::unique_lock<std::mutex> lock(cs_rng_state); hasher.Write(rng_state, sizeof(rng_state)); hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter)); ++rng_counter; hasher.Finalize(buf); memcpy(rng_state, buf + 32, 32); } // Produce output memcpy(out, buf, num); memory_cleanse(buf, 64); } uint64_t GetRand(uint64_t nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax; uint64_t nRand = 0; do { GetRandBytes((unsigned char*)&nRand, sizeof(nRand)); } while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; GetRandBytes((unsigned char*)&hash, sizeof(hash)); return hash; } void FastRandomContext::RandomSeed() { uint256 seed = GetRandHash(); rng.SetKey(seed.begin(), 32); requires_seed = false; } FastRandomContext::FastRandomContext(const uint256& seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0) { rng.SetKey(seed.begin(), 32); } bool Random_SanityCheck() { uint64_t start = GetPerformanceCounter(); /* This does not measure the quality of randomness, but it does test that * OSRandom() overwrites all 32 bytes of the output given a maximum * number of tries. */ static const ssize_t MAX_TRIES = 1024; uint8_t data[NUM_OS_RANDOM_BYTES]; bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */ int num_overwritten; int tries = 0; /* Loop until all bytes have been overwritten at least once, or max number tries reached */ do { memset(data, 0, NUM_OS_RANDOM_BYTES); GetOSRand(data); for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) { overwritten[x] |= (data[x] != 0); } num_overwritten = 0; for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) { if (overwritten[x]) { num_overwritten += 1; } } tries += 1; } while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES); if (num_overwritten != NUM_OS_RANDOM_BYTES) return false; /* If this failed, bailed out after too many tries */ // Check that GetPerformanceCounter increases at least during a GetOSRand() call + 1ms sleep. std::this_thread::sleep_for(std::chrono::milliseconds(1)); uint64_t stop = GetPerformanceCounter(); if (stop == start) return false; // We called GetPerformanceCounter. Use it as entropy. RAND_add((const unsigned char*)&start, sizeof(start), 1); RAND_add((const unsigned char*)&stop, sizeof(stop), 1); return true; } FastRandomContext::FastRandomContext(bool fDeterministic) : requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0) { if (!fDeterministic) { return; } uint256 seed; rng.SetKey(seed.begin(), 32); } <commit_msg>Add internal method to add new random data to our internal RNG state<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "random.h" #include "crypto/sha512.h" #include "support/cleanse.h" #ifdef WIN32 #include "compat.h" // for Windows API #include <wincrypt.h> #endif #include "util.h" // for LogPrint() #include "utilstrencodings.h" // for GetTime() #include <stdlib.h> #include <limits> #include <chrono> #include <thread> #ifndef WIN32 #include <sys/time.h> #endif #ifdef HAVE_SYS_GETRANDOM #include <sys/syscall.h> #include <linux/random.h> #endif #ifdef HAVE_GETENTROPY #include <unistd.h> #endif #ifdef HAVE_SYSCTL_ARND #include <sys/sysctl.h> #endif #include <mutex> #include <openssl/err.h> #include <openssl/rand.h> static void RandFailure() { LogPrintf("Failed to read randomness, aborting\n"); abort(); } static inline int64_t GetPerformanceCounter() { // Read the hardware time stamp counter when available. // See https://en.wikipedia.org/wiki/Time_Stamp_Counter for more information. #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) return __rdtsc(); #elif !defined(_MSC_VER) && defined(__i386__) uint64_t r = 0; __asm__ volatile ("rdtsc" : "=A"(r)); // Constrain the r variable to the eax:edx pair. return r; #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__)) uint64_t r1 = 0, r2 = 0; __asm__ volatile ("rdtsc" : "=a"(r1), "=d"(r2)); // Constrain r1 to rax and r2 to rdx. return (r2 << 32) | r1; #else // Fall back to using C++11 clock (usually microsecond or nanosecond precision) return std::chrono::high_resolution_clock::now().time_since_epoch().count(); #endif } void RandAddSeed() { // Seed with CPU performance counter int64_t nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memory_cleanse((void*)&nCounter, sizeof(nCounter)); } static void RandAddSeedPerfmon() { RandAddSeed(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); std::vector<unsigned char> vData(250000, 0); long ret = 0; unsigned long nSize = 0; const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data while (true) { nSize = vData.size(); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, vData.data(), &nSize); if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) break; vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially } RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(vData.data(), nSize, nSize / 100.0); memory_cleanse(vData.data(), nSize); LogPrint(BCLog::RAND, "%s: %lu bytes\n", __func__, nSize); } else { static bool warned = false; // Warn only once if (!warned) { LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret); warned = true; } } #endif } #ifndef WIN32 /** Fallback: get 32 bytes of system entropy from /dev/urandom. The most * compatible way to get cryptographic randomness on UNIX-ish platforms. */ void GetDevURandom(unsigned char *ent32) { int f = open("/dev/urandom", O_RDONLY); if (f == -1) { RandFailure(); } int have = 0; do { ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have); if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) { RandFailure(); } have += n; } while (have < NUM_OS_RANDOM_BYTES); close(f); } #endif /** Get 32 bytes of system entropy. */ void GetOSRand(unsigned char *ent32) { #if defined(WIN32) HCRYPTPROV hProvider; int ret = CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (!ret) { RandFailure(); } ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32); if (!ret) { RandFailure(); } CryptReleaseContext(hProvider, 0); #elif defined(HAVE_SYS_GETRANDOM) /* Linux. From the getrandom(2) man page: * "If the urandom source has been initialized, reads of up to 256 bytes * will always return as many bytes as requested and will not be * interrupted by signals." */ int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0); if (rv != NUM_OS_RANDOM_BYTES) { if (rv < 0 && errno == ENOSYS) { /* Fallback for kernel <3.17: the return value will be -1 and errno * ENOSYS if the syscall is not available, in that case fall back * to /dev/urandom. */ GetDevURandom(ent32); } else { RandFailure(); } } #elif defined(HAVE_GETENTROPY) /* On OpenBSD this can return up to 256 bytes of entropy, will return an * error if more are requested. * The call cannot return less than the requested number of bytes. */ if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) { RandFailure(); } #elif defined(HAVE_SYSCTL_ARND) /* FreeBSD and similar. It is possible for the call to return less * bytes than requested, so need to read in a loop. */ static const int name[2] = {CTL_KERN, KERN_ARND}; int have = 0; do { size_t len = NUM_OS_RANDOM_BYTES - have; if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, NULL, 0) != 0) { RandFailure(); } have += len; } while (have < NUM_OS_RANDOM_BYTES); #else /* Fall back to /dev/urandom if there is no specific method implemented to * get system entropy for this OS. */ GetDevURandom(ent32); #endif } void GetRandBytes(unsigned char* buf, int num) { if (RAND_bytes(buf, num) != 1) { RandFailure(); } } static std::mutex cs_rng_state; static unsigned char rng_state[32] = {0}; static uint64_t rng_counter = 0; static void AddDataToRng(void* data, size_t len) { CSHA512 hasher; hasher.Write((const unsigned char*)&len, sizeof(len)); hasher.Write((const unsigned char*)data, len); unsigned char buf[64]; { std::unique_lock<std::mutex> lock(cs_rng_state); hasher.Write(rng_state, sizeof(rng_state)); hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter)); ++rng_counter; hasher.Finalize(buf); memcpy(rng_state, buf + 32, 32); } memory_cleanse(buf, 64); } void GetStrongRandBytes(unsigned char* out, int num) { assert(num <= 32); CSHA512 hasher; unsigned char buf[64]; // First source: OpenSSL's RNG RandAddSeedPerfmon(); GetRandBytes(buf, 32); hasher.Write(buf, 32); // Second source: OS RNG GetOSRand(buf); hasher.Write(buf, 32); // Combine with and update state { std::unique_lock<std::mutex> lock(cs_rng_state); hasher.Write(rng_state, sizeof(rng_state)); hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter)); ++rng_counter; hasher.Finalize(buf); memcpy(rng_state, buf + 32, 32); } // Produce output memcpy(out, buf, num); memory_cleanse(buf, 64); } uint64_t GetRand(uint64_t nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax; uint64_t nRand = 0; do { GetRandBytes((unsigned char*)&nRand, sizeof(nRand)); } while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; GetRandBytes((unsigned char*)&hash, sizeof(hash)); return hash; } void FastRandomContext::RandomSeed() { uint256 seed = GetRandHash(); rng.SetKey(seed.begin(), 32); requires_seed = false; } FastRandomContext::FastRandomContext(const uint256& seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0) { rng.SetKey(seed.begin(), 32); } bool Random_SanityCheck() { uint64_t start = GetPerformanceCounter(); /* This does not measure the quality of randomness, but it does test that * OSRandom() overwrites all 32 bytes of the output given a maximum * number of tries. */ static const ssize_t MAX_TRIES = 1024; uint8_t data[NUM_OS_RANDOM_BYTES]; bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */ int num_overwritten; int tries = 0; /* Loop until all bytes have been overwritten at least once, or max number tries reached */ do { memset(data, 0, NUM_OS_RANDOM_BYTES); GetOSRand(data); for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) { overwritten[x] |= (data[x] != 0); } num_overwritten = 0; for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) { if (overwritten[x]) { num_overwritten += 1; } } tries += 1; } while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES); if (num_overwritten != NUM_OS_RANDOM_BYTES) return false; /* If this failed, bailed out after too many tries */ // Check that GetPerformanceCounter increases at least during a GetOSRand() call + 1ms sleep. std::this_thread::sleep_for(std::chrono::milliseconds(1)); uint64_t stop = GetPerformanceCounter(); if (stop == start) return false; // We called GetPerformanceCounter. Use it as entropy. RAND_add((const unsigned char*)&start, sizeof(start), 1); RAND_add((const unsigned char*)&stop, sizeof(stop), 1); return true; } FastRandomContext::FastRandomContext(bool fDeterministic) : requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0) { if (!fDeterministic) { return; } uint256 seed; rng.SetKey(seed.begin(), 32); } <|endoftext|>
<commit_before>#include "net/socket/socket.h" #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include "glog/logging.h" namespace net { Socket::Socket(Socket&& socket) noexcept : sd_(socket.sd_) { socket.sd_ = INVALID_SOCKET; } Socket::~Socket() { if (!valid()) return; LOG(INFO) << "closing socket=" << sd_; if (::close(sd_) < 0) { PLOG(ERROR) << "failed to close socket"; } } Socket& Socket::operator=(Socket&& socket) noexcept { std::swap(sd_, socket.sd_); return *this; } bool Socket::close() { if (!valid()) return true; // Even close() failed, sd_ gets invalid. Let's close. if (::close(sd_) < 0) { PLOG(ERROR) << "failed to close socket"; sd_ = INVALID_SOCKET; return false; } sd_ = INVALID_SOCKET; return true; } ssize_t Socket::read(void* buf, size_t size) { return ::recv(sd_, buf, size, 0); } bool Socket::read_exactly(void* buf, size_t size) { while (size > 0) { ssize_t s = read(buf, size); if (s <= 0) return false; size -= s; buf = reinterpret_cast<char*>(buf) + s; } return true; } ssize_t Socket::write(const void* buf, size_t size) { return ::send(sd_, buf, size, 0); } bool Socket::write_exactly(const void* buf, size_t size) { while (size > 0) { ssize_t s = write(buf, size); if (s <= 0) return false; size -= s; buf = reinterpret_cast<const char*>(buf) + s; } return true; } } // namespace net <commit_msg>Log when socket communication failed.<commit_after>#include "net/socket/socket.h" #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include "glog/logging.h" namespace net { Socket::Socket(Socket&& socket) noexcept : sd_(socket.sd_) { socket.sd_ = INVALID_SOCKET; } Socket::~Socket() { if (!valid()) return; LOG(INFO) << "closing socket=" << sd_; if (::close(sd_) < 0) { PLOG(ERROR) << "failed to close socket"; } } Socket& Socket::operator=(Socket&& socket) noexcept { std::swap(sd_, socket.sd_); return *this; } bool Socket::close() { if (!valid()) return true; // Even close() failed, sd_ gets invalid. Let's close. if (::close(sd_) < 0) { PLOG(ERROR) << "failed to close socket"; sd_ = INVALID_SOCKET; return false; } sd_ = INVALID_SOCKET; return true; } ssize_t Socket::read(void* buf, size_t size) { return ::recv(sd_, buf, size, 0); } bool Socket::read_exactly(void* buf, size_t size) { while (size > 0) { ssize_t s = read(buf, size); if (s <= 0) { if (s == 0) { PLOG(ERROR) << "unexpected EOF"; return false; } if (errno == EAGAIN) { continue; } PLOG(ERROR) << "failed to read"; return false; } size -= s; buf = reinterpret_cast<char*>(buf) + s; } return true; } ssize_t Socket::write(const void* buf, size_t size) { return ::send(sd_, buf, size, 0); } bool Socket::write_exactly(const void* buf, size_t size) { while (size > 0) { ssize_t s = write(buf, size); if (s <= 0) { if (s == 0) { PLOG(ERROR) << "connection closed"; return false; } if (errno == EAGAIN) { continue; } PLOG(ERROR) << "failed to write"; return false; } size -= s; buf = reinterpret_cast<const char*>(buf) + s; } return true; } } // namespace net <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: undoblk2.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: kz $ $Date: 2006-07-21 14:26:26 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // System - Includes ----------------------------------------------------- #ifndef PCH #include "scitems.hxx" // SearchItem #endif // INCLUDE --------------------------------------------------------------- #include "undoblk.hxx" #include "document.hxx" #include "docsh.hxx" #include "tabvwsh.hxx" #include "olinetab.hxx" #include "globstr.hrc" #include "global.hxx" #include "target.hxx" #include "undoolk.hxx" //! GetUndo ins Document verschieben! // STATIC DATA ----------------------------------------------------------- TYPEINIT1(ScUndoWidthOrHeight, SfxUndoAction); // ----------------------------------------------------------------------- // // Spaltenbreiten oder Zeilenhoehen aendern // ScUndoWidthOrHeight::ScUndoWidthOrHeight( ScDocShell* pNewDocShell, const ScMarkData& rMark, SCCOLROW nNewStart, SCTAB nNewStartTab, SCCOLROW nNewEnd, SCTAB nNewEndTab, ScDocument* pNewUndoDoc, SCCOLROW nNewCnt, SCCOLROW* pNewRanges, ScOutlineTable* pNewUndoTab, ScSizeMode eNewMode, USHORT nNewSizeTwips, BOOL bNewWidth ) : ScSimpleUndo( pNewDocShell ), aMarkData( rMark ), nStart( nNewStart ), nEnd( nNewEnd ), nStartTab( nNewStartTab ), nEndTab( nNewEndTab ), pUndoDoc( pNewUndoDoc ), nRangeCnt( nNewCnt ), pRanges( pNewRanges ), pUndoTab( pNewUndoTab ), eMode( eNewMode ), nNewSize( nNewSizeTwips ), bWidth( bNewWidth ), pDrawUndo( NULL ) { pDrawUndo = GetSdrUndoAction( pDocShell->GetDocument() ); } __EXPORT ScUndoWidthOrHeight::~ScUndoWidthOrHeight() { delete[] pRanges; delete pUndoDoc; delete pUndoTab; DeleteSdrUndoAction( pDrawUndo ); } String __EXPORT ScUndoWidthOrHeight::GetComment() const { // [ "optimale " ] "Spaltenbreite" | "Zeilenhoehe" return ( bWidth ? ( ( eMode == SC_SIZE_OPTIMAL )? ScGlobal::GetRscString( STR_UNDO_OPTCOLWIDTH ) : ScGlobal::GetRscString( STR_UNDO_COLWIDTH ) ) : ( ( eMode == SC_SIZE_OPTIMAL )? ScGlobal::GetRscString( STR_UNDO_OPTROWHEIGHT ) : ScGlobal::GetRscString( STR_UNDO_ROWHEIGHT ) ) ); } void __EXPORT ScUndoWidthOrHeight::Undo() { BeginUndo(); ScDocument* pDoc = pDocShell->GetDocument(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); SCCOLROW nPaintStart = nStart > 0 ? nStart-1 : static_cast<SCCOLROW>(0); if (eMode==SC_SIZE_OPTIMAL) { if (pViewShell) { pViewShell->DoneBlockMode(); pViewShell->InitOwnBlockMode(); pViewShell->GetViewData()->GetMarkData() = aMarkData; // CopyMarksTo nPaintStart = 0; // paint all, because of changed selection } } //! outlines from all tables? if (pUndoTab) // Outlines mit gespeichert? pDoc->SetOutlineTable( nStartTab, pUndoTab ); SCTAB nTabCount = pDoc->GetTableCount(); SCTAB nTab; for (nTab=0; nTab<nTabCount; nTab++) if (aMarkData.GetTableSelect(nTab)) { if (bWidth) // Width { pUndoDoc->CopyToDocument( static_cast<SCCOL>(nStart), 0, nTab, static_cast<SCCOL>(nEnd), MAXROW, nTab, IDF_NONE, FALSE, pDoc ); pDoc->UpdatePageBreaks( nTab ); pDocShell->PostPaint( static_cast<SCCOL>(nPaintStart), 0, nTab, MAXCOL, MAXROW, nTab, PAINT_GRID | PAINT_TOP ); } else // Height { pUndoDoc->CopyToDocument( 0, nStart, nTab, MAXCOL, nEnd, nTab, IDF_NONE, FALSE, pDoc ); pDoc->UpdatePageBreaks( nTab ); pDocShell->PostPaint( 0, nPaintStart, nTab, MAXCOL, MAXROW, nTab, PAINT_GRID | PAINT_LEFT ); } } DoSdrUndoAction( pDrawUndo, pDoc ); if (pViewShell) { pViewShell->UpdateScrollBars(); SCTAB nCurrentTab = pViewShell->GetViewData()->GetTabNo(); if ( nCurrentTab < nStartTab || nCurrentTab > nEndTab ) pViewShell->SetTabNo( nStartTab ); } EndUndo(); } void __EXPORT ScUndoWidthOrHeight::Redo() { BeginRedo(); ScDocument* pDoc = pDocShell->GetDocument(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); BOOL bPaintAll = FALSE; if (eMode==SC_SIZE_OPTIMAL) { if (pViewShell) { pViewShell->DoneBlockMode(); pViewShell->InitOwnBlockMode(); pViewShell->GetViewData()->GetMarkData() = aMarkData; // CopyMarksTo bPaintAll = TRUE; // paint all, because of changed selection } } if (pViewShell) { SCTAB nTab = pViewShell->GetViewData()->GetTabNo(); if ( nTab < nStartTab || nTab > nEndTab ) pViewShell->SetTabNo( nStartTab ); } // SetWidthOrHeight aendert aktuelle Tabelle ! pViewShell->SetWidthOrHeight( bWidth, nRangeCnt, pRanges, eMode, nNewSize, FALSE, TRUE, &aMarkData ); // paint grid if selection was changed directly at the MarkData if (bPaintAll) pDocShell->PostPaint( 0, 0, nStartTab, MAXCOL, MAXROW, nEndTab, PAINT_GRID ); EndRedo(); } void __EXPORT ScUndoWidthOrHeight::Repeat(SfxRepeatTarget& rTarget) { if (rTarget.ISA(ScTabViewTarget)) ((ScTabViewTarget&)rTarget).GetViewShell()->SetMarkedWidthOrHeight( bWidth, eMode, nNewSize, TRUE ); } BOOL __EXPORT ScUndoWidthOrHeight::CanRepeat(SfxRepeatTarget& rTarget) const { return (rTarget.ISA(ScTabViewTarget)); } <commit_msg>INTEGRATION: CWS calcwarnings (1.9.110); FILE MERGED 2006/12/12 17:03:23 nn 1.9.110.2: #i69284# warning-free: ui, unxlngi6 2006/12/01 08:53:39 nn 1.9.110.1: #i69284# warning-free: ui, wntmsci10<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: undoblk2.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: vg $ $Date: 2007-02-27 13:38:50 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // System - Includes ----------------------------------------------------- #ifndef PCH #include "scitems.hxx" // SearchItem #endif // INCLUDE --------------------------------------------------------------- #include "undoblk.hxx" #include "document.hxx" #include "docsh.hxx" #include "tabvwsh.hxx" #include "olinetab.hxx" #include "globstr.hrc" #include "global.hxx" #include "target.hxx" #include "undoolk.hxx" //! GetUndo ins Document verschieben! // STATIC DATA ----------------------------------------------------------- TYPEINIT1(ScUndoWidthOrHeight, SfxUndoAction); // ----------------------------------------------------------------------- // // Spaltenbreiten oder Zeilenhoehen aendern // ScUndoWidthOrHeight::ScUndoWidthOrHeight( ScDocShell* pNewDocShell, const ScMarkData& rMark, SCCOLROW nNewStart, SCTAB nNewStartTab, SCCOLROW nNewEnd, SCTAB nNewEndTab, ScDocument* pNewUndoDoc, SCCOLROW nNewCnt, SCCOLROW* pNewRanges, ScOutlineTable* pNewUndoTab, ScSizeMode eNewMode, USHORT nNewSizeTwips, BOOL bNewWidth ) : ScSimpleUndo( pNewDocShell ), aMarkData( rMark ), nStart( nNewStart ), nEnd( nNewEnd ), nStartTab( nNewStartTab ), nEndTab( nNewEndTab ), pUndoDoc( pNewUndoDoc ), pUndoTab( pNewUndoTab ), nRangeCnt( nNewCnt ), pRanges( pNewRanges ), nNewSize( nNewSizeTwips ), bWidth( bNewWidth ), eMode( eNewMode ), pDrawUndo( NULL ) { pDrawUndo = GetSdrUndoAction( pDocShell->GetDocument() ); } __EXPORT ScUndoWidthOrHeight::~ScUndoWidthOrHeight() { delete[] pRanges; delete pUndoDoc; delete pUndoTab; DeleteSdrUndoAction( pDrawUndo ); } String __EXPORT ScUndoWidthOrHeight::GetComment() const { // [ "optimale " ] "Spaltenbreite" | "Zeilenhoehe" return ( bWidth ? ( ( eMode == SC_SIZE_OPTIMAL )? ScGlobal::GetRscString( STR_UNDO_OPTCOLWIDTH ) : ScGlobal::GetRscString( STR_UNDO_COLWIDTH ) ) : ( ( eMode == SC_SIZE_OPTIMAL )? ScGlobal::GetRscString( STR_UNDO_OPTROWHEIGHT ) : ScGlobal::GetRscString( STR_UNDO_ROWHEIGHT ) ) ); } void __EXPORT ScUndoWidthOrHeight::Undo() { BeginUndo(); ScDocument* pDoc = pDocShell->GetDocument(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); SCCOLROW nPaintStart = nStart > 0 ? nStart-1 : static_cast<SCCOLROW>(0); if (eMode==SC_SIZE_OPTIMAL) { if (pViewShell) { pViewShell->DoneBlockMode(); pViewShell->InitOwnBlockMode(); pViewShell->GetViewData()->GetMarkData() = aMarkData; // CopyMarksTo nPaintStart = 0; // paint all, because of changed selection } } //! outlines from all tables? if (pUndoTab) // Outlines mit gespeichert? pDoc->SetOutlineTable( nStartTab, pUndoTab ); SCTAB nTabCount = pDoc->GetTableCount(); SCTAB nTab; for (nTab=0; nTab<nTabCount; nTab++) if (aMarkData.GetTableSelect(nTab)) { if (bWidth) // Width { pUndoDoc->CopyToDocument( static_cast<SCCOL>(nStart), 0, nTab, static_cast<SCCOL>(nEnd), MAXROW, nTab, IDF_NONE, FALSE, pDoc ); pDoc->UpdatePageBreaks( nTab ); pDocShell->PostPaint( static_cast<SCCOL>(nPaintStart), 0, nTab, MAXCOL, MAXROW, nTab, PAINT_GRID | PAINT_TOP ); } else // Height { pUndoDoc->CopyToDocument( 0, nStart, nTab, MAXCOL, nEnd, nTab, IDF_NONE, FALSE, pDoc ); pDoc->UpdatePageBreaks( nTab ); pDocShell->PostPaint( 0, nPaintStart, nTab, MAXCOL, MAXROW, nTab, PAINT_GRID | PAINT_LEFT ); } } DoSdrUndoAction( pDrawUndo, pDoc ); if (pViewShell) { pViewShell->UpdateScrollBars(); SCTAB nCurrentTab = pViewShell->GetViewData()->GetTabNo(); if ( nCurrentTab < nStartTab || nCurrentTab > nEndTab ) pViewShell->SetTabNo( nStartTab ); } EndUndo(); } void __EXPORT ScUndoWidthOrHeight::Redo() { BeginRedo(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); BOOL bPaintAll = FALSE; if (eMode==SC_SIZE_OPTIMAL) { if (pViewShell) { pViewShell->DoneBlockMode(); pViewShell->InitOwnBlockMode(); pViewShell->GetViewData()->GetMarkData() = aMarkData; // CopyMarksTo bPaintAll = TRUE; // paint all, because of changed selection } } if (pViewShell) { SCTAB nTab = pViewShell->GetViewData()->GetTabNo(); if ( nTab < nStartTab || nTab > nEndTab ) pViewShell->SetTabNo( nStartTab ); } // SetWidthOrHeight aendert aktuelle Tabelle ! pViewShell->SetWidthOrHeight( bWidth, nRangeCnt, pRanges, eMode, nNewSize, FALSE, TRUE, &aMarkData ); // paint grid if selection was changed directly at the MarkData if (bPaintAll) pDocShell->PostPaint( 0, 0, nStartTab, MAXCOL, MAXROW, nEndTab, PAINT_GRID ); EndRedo(); } void __EXPORT ScUndoWidthOrHeight::Repeat(SfxRepeatTarget& rTarget) { if (rTarget.ISA(ScTabViewTarget)) ((ScTabViewTarget&)rTarget).GetViewShell()->SetMarkedWidthOrHeight( bWidth, eMode, nNewSize, TRUE ); } BOOL __EXPORT ScUndoWidthOrHeight::CanRepeat(SfxRepeatTarget& rTarget) const { return (rTarget.ISA(ScTabViewTarget)); } <|endoftext|>
<commit_before>#include <node.h> #include <nan.h> #include <v8.h> #include <vector> #include "mouse.h" #include "deadbeef_rand.h" #include "keypress.h" #include "screen.h" #include "screengrab.h" #include "MMBitmap.h" using namespace v8; /* __ __ | \/ | ___ _ _ ___ ___ | |\/| |/ _ \| | | / __|/ _ \ | | | | (_) | |_| \__ \ __/ |_| |_|\___/ \__,_|___/\___| */ NAN_METHOD(moveMouse) { NanScope(); if (args.Length() < 2) { return NanThrowError("Invalid number of arguments."); } size_t x = args[0]->Int32Value(); size_t y = args[1]->Int32Value(); MMPoint point; point = MMPointMake(x, y); moveMouse(point); NanReturnValue(NanNew("1")); } NAN_METHOD(moveMouseSmooth) { NanScope(); if (args.Length() < 2) { return NanThrowError("Invalid number of arguments."); } size_t x = args[0]->Int32Value(); size_t y = args[1]->Int32Value(); MMPoint point; point = MMPointMake(x, y); smoothlyMoveMouse(point); NanReturnValue(NanNew("1")); } NAN_METHOD(getMousePos) { NanScope(); MMPoint pos = getMousePos(); //Return object with .x and .y. Local<Object> obj = NanNew<Object>(); obj->Set(NanNew<String>("x"), NanNew<Number>(pos.x)); obj->Set(NanNew<String>("y"), NanNew<Number>(pos.y)); NanReturnValue(obj); } NAN_METHOD(mouseClick) { NanScope(); MMMouseButton button = LEFT_BUTTON; if (args.Length() == 1) { char *b = (*v8::String::Utf8Value(args[0]->ToString())); if (strcmp(b, "left") == 0) { button = LEFT_BUTTON; } else if (strcmp(b, "right") == 0) { button = RIGHT_BUTTON; } else if (strcmp(b, "middle") == 0) { button = CENTER_BUTTON; } else { return NanThrowError("Invalid mouse button specified."); } } else if (args.Length() > 1) { return NanThrowError("Invalid number of arguments."); } clickMouse(button); NanReturnValue(NanNew("1")); } NAN_METHOD(mouseToggle) { NanScope(); MMMouseButton button = LEFT_BUTTON; bool down; if (args.Length() > 0) { char *d = (*v8::String::Utf8Value(args[0]->ToString())); if (strcmp(d, "down") == 0) { down = true;; } else if (strcmp(d, "up") == 0) { down = false; } else { return NanThrowError("Invalid mouse button state specified."); } } if (args.Length() == 2) { char *b = (*v8::String::Utf8Value(args[1]->ToString())); if (strcmp(b, "left") == 0) { button = LEFT_BUTTON; } else if (strcmp(b, "right") == 0) { button = RIGHT_BUTTON; } else if (strcmp(b, "middle") == 0) { button = CENTER_BUTTON; } else { return NanThrowError("Invalid mouse button specified."); } } else if (args.Length() > 2) { return NanThrowError("Invalid number of arguments."); } toggleMouse(down, button); NanReturnValue(NanNew("1")); } /* _ __ _ _ | |/ /___ _ _| |__ ___ __ _ _ __ __| | | ' // _ \ | | | '_ \ / _ \ / _` | '__/ _` | | . \ __/ |_| | |_) | (_) | (_| | | | (_| | |_|\_\___|\__, |_.__/ \___/ \__,_|_| \__,_| |___/ */ NAN_METHOD(keyTap) { NanScope(); MMKeyFlags flags = MOD_NONE; const char c = (*v8::String::Utf8Value(args[0]->ToString()))[0]; tapKey(c, flags); NanReturnValue(NanNew("1")); } NAN_METHOD(typeString) { NanScope(); char *str; NanUtf8String string(args[0]); str = *string; typeString(str); NanReturnValue(NanNew("1")); } /* ____ / ___| ___ _ __ ___ ___ _ __ \___ \ / __| '__/ _ \/ _ \ '_ \ ___) | (__| | | __/ __/ | | | |____/ \___|_| \___|\___|_| |_| */ NAN_METHOD(getPixelColor) { NanScope(); MMBitmapRef bitmap; MMRGBHex color; size_t x = args[0]->Int32Value(); size_t y = args[1]->Int32Value(); bitmap = copyMMBitmapFromDisplayInRect(MMRectMake(x, y, 1, 1)); color = MMRGBHexAtPoint(bitmap, 0, 0); char hex [6]; //Length needs to be 7 because snprintf includes a terminating null. //Use %06x to pad hex value with leading 0s. snprintf(hex, 7, "%06x", color); destroyMMBitmap(bitmap); NanReturnValue(NanNew(hex)); } void init(Handle<Object> target) { target->Set(NanNew<String>("moveMouse"), NanNew<FunctionTemplate>(moveMouse)->GetFunction()); target->Set(NanNew<String>("moveMouseSmooth"), NanNew<FunctionTemplate>(moveMouseSmooth)->GetFunction()); target->Set(NanNew<String>("getMousePos"), NanNew<FunctionTemplate>(getMousePos)->GetFunction()); target->Set(NanNew<String>("mouseClick"), NanNew<FunctionTemplate>(mouseClick)->GetFunction()); target->Set(NanNew<String>("mouseToggle"), NanNew<FunctionTemplate>(mouseToggle)->GetFunction()); target->Set(NanNew<String>("keyTap"), NanNew<FunctionTemplate>(keyTap)->GetFunction()); target->Set(NanNew<String>("typeString"), NanNew<FunctionTemplate>(typeString)->GetFunction()); target->Set(NanNew<String>("getPixelColor"), NanNew<FunctionTemplate>(getPixelColor)->GetFunction()); } NODE_MODULE(robotjs, init) <commit_msg>Updated keyTap for correct use. Closes #3.<commit_after>#include <node.h> #include <nan.h> #include <v8.h> #include <vector> #include "mouse.h" #include "deadbeef_rand.h" #include "keypress.h" #include "screen.h" #include "screengrab.h" #include "MMBitmap.h" using namespace v8; /* __ __ | \/ | ___ _ _ ___ ___ | |\/| |/ _ \| | | / __|/ _ \ | | | | (_) | |_| \__ \ __/ |_| |_|\___/ \__,_|___/\___| */ NAN_METHOD(moveMouse) { NanScope(); if (args.Length() < 2) { return NanThrowError("Invalid number of arguments."); } size_t x = args[0]->Int32Value(); size_t y = args[1]->Int32Value(); MMPoint point; point = MMPointMake(x, y); moveMouse(point); NanReturnValue(NanNew("1")); } NAN_METHOD(moveMouseSmooth) { NanScope(); if (args.Length() < 2) { return NanThrowError("Invalid number of arguments."); } size_t x = args[0]->Int32Value(); size_t y = args[1]->Int32Value(); MMPoint point; point = MMPointMake(x, y); smoothlyMoveMouse(point); NanReturnValue(NanNew("1")); } NAN_METHOD(getMousePos) { NanScope(); MMPoint pos = getMousePos(); //Return object with .x and .y. Local<Object> obj = NanNew<Object>(); obj->Set(NanNew<String>("x"), NanNew<Number>(pos.x)); obj->Set(NanNew<String>("y"), NanNew<Number>(pos.y)); NanReturnValue(obj); } NAN_METHOD(mouseClick) { NanScope(); MMMouseButton button = LEFT_BUTTON; if (args.Length() == 1) { char *b = (*v8::String::Utf8Value(args[0]->ToString())); if (strcmp(b, "left") == 0) { button = LEFT_BUTTON; } else if (strcmp(b, "right") == 0) { button = RIGHT_BUTTON; } else if (strcmp(b, "middle") == 0) { button = CENTER_BUTTON; } else { return NanThrowError("Invalid mouse button specified."); } } else if (args.Length() > 1) { return NanThrowError("Invalid number of arguments."); } clickMouse(button); NanReturnValue(NanNew("1")); } NAN_METHOD(mouseToggle) { NanScope(); MMMouseButton button = LEFT_BUTTON; bool down; if (args.Length() > 0) { const char *d = (*v8::String::Utf8Value(args[0]->ToString())); if (strcmp(d, "down") == 0) { down = true;; } else if (strcmp(d, "up") == 0) { down = false; } else { return NanThrowError("Invalid mouse button state specified."); } } if (args.Length() == 2) { char *b = (*v8::String::Utf8Value(args[1]->ToString())); if (strcmp(b, "left") == 0) { button = LEFT_BUTTON; } else if (strcmp(b, "right") == 0) { button = RIGHT_BUTTON; } else if (strcmp(b, "middle") == 0) { button = CENTER_BUTTON; } else { return NanThrowError("Invalid mouse button specified."); } } else if (args.Length() > 2) { return NanThrowError("Invalid number of arguments."); } toggleMouse(down, button); NanReturnValue(NanNew("1")); } /* _ __ _ _ | |/ /___ _ _| |__ ___ __ _ _ __ __| | | ' // _ \ | | | '_ \ / _ \ / _` | '__/ _` | | . \ __/ |_| | |_) | (_) | (_| | | | (_| | |_|\_\___|\__, |_.__/ \___/ \__,_|_| \__,_| |___/ */ NAN_METHOD(keyTap) { NanScope(); if (args.Length() != 1) { return NanThrowError("Invalid number of arguments."); } MMKeyFlags flags = MOD_NONE; MMKeyCode key; char *k = (*v8::String::Utf8Value(args[0]->ToString())); //There's a better way to do this, I just want to get it working. if (strcmp(k, "backspace") == 0) { key = K_BACKSPACE; } else if (strcmp(k, "enter") == 0) { key = K_RETURN; } else if (strcmp(k, "up") == 0) { key = K_UP; } else if (strcmp(k, "down") == 0) { key = K_DOWN; } else if (strcmp(k, "left") == 0) { key = K_LEFT; } else if (strcmp(k, "right") == 0) { key = K_RIGHT; } else if (strcmp(k, "escape") == 0) { key = K_ESCAPE; } else { return NanThrowError("Invalid key specified."); } tapKeyCode(key, flags); NanReturnValue(NanNew("1")); } NAN_METHOD(typeString) { NanScope(); char *str; NanUtf8String string(args[0]); str = *string; typeString(str); NanReturnValue(NanNew("1")); } /* ____ / ___| ___ _ __ ___ ___ _ __ \___ \ / __| '__/ _ \/ _ \ '_ \ ___) | (__| | | __/ __/ | | | |____/ \___|_| \___|\___|_| |_| */ NAN_METHOD(getPixelColor) { NanScope(); MMBitmapRef bitmap; MMRGBHex color; size_t x = args[0]->Int32Value(); size_t y = args[1]->Int32Value(); bitmap = copyMMBitmapFromDisplayInRect(MMRectMake(x, y, 1, 1)); color = MMRGBHexAtPoint(bitmap, 0, 0); char hex [6]; //Length needs to be 7 because snprintf includes a terminating null. //Use %06x to pad hex value with leading 0s. snprintf(hex, 7, "%06x", color); destroyMMBitmap(bitmap); NanReturnValue(NanNew(hex)); } void init(Handle<Object> target) { target->Set(NanNew<String>("moveMouse"), NanNew<FunctionTemplate>(moveMouse)->GetFunction()); target->Set(NanNew<String>("moveMouseSmooth"), NanNew<FunctionTemplate>(moveMouseSmooth)->GetFunction()); target->Set(NanNew<String>("getMousePos"), NanNew<FunctionTemplate>(getMousePos)->GetFunction()); target->Set(NanNew<String>("mouseClick"), NanNew<FunctionTemplate>(mouseClick)->GetFunction()); target->Set(NanNew<String>("mouseToggle"), NanNew<FunctionTemplate>(mouseToggle)->GetFunction()); target->Set(NanNew<String>("keyTap"), NanNew<FunctionTemplate>(keyTap)->GetFunction()); target->Set(NanNew<String>("typeString"), NanNew<FunctionTemplate>(typeString)->GetFunction()); target->Set(NanNew<String>("getPixelColor"), NanNew<FunctionTemplate>(getPixelColor)->GetFunction()); } NODE_MODULE(robotjs, init) <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "net.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; Value getconnectioncount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getconnectioncount\n" "Returns the number of connections to other nodes."); LOCK(cs_vNodes); return (int)vNodes.size(); } static void CopyNodeStats(std::vector<CNodeStats>& vstats) { vstats.clear(); LOCK(cs_vNodes); vstats.reserve(vNodes.size()); BOOST_FOREACH(CNode* pnode, vNodes) { CNodeStats stats; pnode->copyStats(stats); vstats.push_back(stats); } } Value getpeerinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getpeerinfo\n" "Returns data about each connected network node."); vector<CNodeStats> vstats; CopyNodeStats(vstats); Array ret; BOOST_FOREACH(const CNodeStats& stats, vstats) { Object obj; obj.push_back(Pair("addr", stats.addrName)); obj.push_back(Pair("services", strprintf("%08"PRI64x, stats.nServices))); obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend)); obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv)); obj.push_back(Pair("bytessent", (boost::int64_t)stats.nSendBytes)); obj.push_back(Pair("bytesrecv", (boost::int64_t)stats.nRecvBytes)); obj.push_back(Pair("blocksrequested", (boost::int64_t)stats.nBlocksRequested)); obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected)); obj.push_back(Pair("version", stats.nVersion)); // Use the sanitized form of subver here, to avoid tricksy remote peers from // corrupting or modifiying the JSON output by putting special characters in // their ver message. obj.push_back(Pair("subver", stats.cleanSubVer)); obj.push_back(Pair("inbound", stats.fInbound)); obj.push_back(Pair("startingheight", stats.nStartingHeight)); obj.push_back(Pair("banscore", stats.nMisbehavior)); if (stats.fSyncNode) obj.push_back(Pair("syncnode", true)); ret.push_back(obj); } return ret; } Value addnode(const Array& params, bool fHelp) { string strCommand; if (params.size() == 2) strCommand = params[1].get_str(); if (fHelp || params.size() != 2 || (strCommand != "onetry" && strCommand != "add" && strCommand != "remove")) throw runtime_error( "addnode <node> <add|remove|onetry>\n" "Attempts add or remove <node> from the addnode list or try a connection to <node> once."); string strNode = params[0].get_str(); if (strCommand == "onetry") { CAddress addr; ConnectNode(addr, strNode.c_str()); return Value::null; } LOCK(cs_vAddedNodes); vector<string>::iterator it = vAddedNodes.begin(); for(; it != vAddedNodes.end(); it++) if (strNode == *it) break; if (strCommand == "add") { if (it != vAddedNodes.end()) throw JSONRPCError(-23, "Error: Node already added"); vAddedNodes.push_back(strNode); } else if(strCommand == "remove") { if (it == vAddedNodes.end()) throw JSONRPCError(-24, "Error: Node has not been added."); vAddedNodes.erase(it); } return Value::null; } Value getaddednodeinfo(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getaddednodeinfo <dns> [node]\n" "Returns information about the given added node, or all added nodes\n" "(note that onetry addnodes are not listed here)\n" "If dns is false, only a list of added nodes will be provided,\n" "otherwise connected information will also be available."); bool fDns = params[0].get_bool(); list<string> laddedNodes(0); if (params.size() == 1) { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) laddedNodes.push_back(strAddNode); } else { string strNode = params[1].get_str(); LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) if (strAddNode == strNode) { laddedNodes.push_back(strAddNode); break; } if (laddedNodes.size() == 0) throw JSONRPCError(-24, "Error: Node has not been added."); } if (!fDns) { Object ret; BOOST_FOREACH(string& strAddNode, laddedNodes) ret.push_back(Pair("addednode", strAddNode)); return ret; } Array ret; list<pair<string, vector<CService> > > laddedAddreses(0); BOOST_FOREACH(string& strAddNode, laddedNodes) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0)) laddedAddreses.push_back(make_pair(strAddNode, vservNode)); else { Object obj; obj.push_back(Pair("addednode", strAddNode)); obj.push_back(Pair("connected", false)); Array addresses; obj.push_back(Pair("addresses", addresses)); } } LOCK(cs_vNodes); for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++) { Object obj; obj.push_back(Pair("addednode", it->first)); Array addresses; bool fConnected = false; BOOST_FOREACH(CService& addrNode, it->second) { bool fFound = false; Object node; node.push_back(Pair("address", addrNode.ToString())); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addr == addrNode) { fFound = true; fConnected = true; node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound")); break; } if (!fFound) node.push_back(Pair("connected", "false")); addresses.push_back(node); } obj.push_back(Pair("connected", fConnected)); obj.push_back(Pair("addresses", addresses)); ret.push_back(obj); } return ret; } // make a public-private key pair (first introduced in ppcoin) Value makekeypair(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "makekeypair [prefix]\n" "Make a public/private key pair.\n" "[prefix] is optional preferred prefix for the public key.\n"); string strPrefix = ""; if (params.size() > 0) strPrefix = params[0].get_str(); CKey key; CPubKey pubkey; int nCount = 0; do { key.MakeNewKey(false); pubkey = key.GetPubKey(); nCount++; } while (nCount < 10000 && strPrefix != HexStr(pubkey.begin(), pubkey.end()).substr(0, strPrefix.size())); if (strPrefix != HexStr(pubkey.begin(), pubkey.end()).substr(0, strPrefix.size())) return Value::null; Object result; result.push_back(Pair("PublicKey", HexStr(pubkey.begin(), pubkey.end()))); result.push_back(Pair("PrivateKey", CBitcoinSecret(key).ToString())); return result; } // Send alert (first introduced in ppcoin) // There is a known deadlock situation with ThreadMessageHandler // ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages() // ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage() Value sendalert(const Array& params, bool fHelp) { if (fHelp || params.size() < 6) throw runtime_error( "sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n" "<message> is the alert text message\n" "<privatekey> is base58 hex string of alert master private key\n" "<minver> is the minimum applicable internal client version\n" "<maxver> is the maximum applicable internal client version\n" "<priority> is integer priority number\n" "<id> is the alert id\n" "[cancelupto] cancels all alert id's up to this number\n" "Returns true or false."); // Prepare the alert message CAlert alert; alert.strStatusBar = params[0].get_str(); alert.nMinVer = params[2].get_int(); alert.nMaxVer = params[3].get_int(); alert.nPriority = params[4].get_int(); alert.nID = params[5].get_int(); if (params.size() > 6) alert.nCancel = params[6].get_int(); alert.nVersion = PROTOCOL_VERSION; alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60; alert.nExpiration = GetAdjustedTime() + 365*24*60*60; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedAlert)alert; alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end()); // Prepare master key and sign alert message CBitcoinSecret vchSecret; if (!vchSecret.SetString(params[1].get_str())) throw runtime_error("Invalid alert master key"); CKey key = vchSecret.GetKey(); // if key is not correct openssl may crash if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig)) throw runtime_error( "Unable to sign alert, check alert master key?\n"); // Process alert if(!alert.ProcessAlert()) throw runtime_error( "Failed to process alert.\n"); // Relay alert { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } Object result; result.push_back(Pair("strStatusBar", alert.strStatusBar)); result.push_back(Pair("nVersion", alert.nVersion)); result.push_back(Pair("nMinVer", alert.nMinVer)); result.push_back(Pair("nMaxVer", alert.nMaxVer)); result.push_back(Pair("nPriority", alert.nPriority)); result.push_back(Pair("nID", alert.nID)); if (alert.nCancel > 0) result.push_back(Pair("nCancel", alert.nCancel)); return result; } <commit_msg>add includes for sendalert<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "net.h" #include "bitcoinrpc.h" #include "alert.h" #include "base58.h" using namespace json_spirit; using namespace std; Value getconnectioncount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getconnectioncount\n" "Returns the number of connections to other nodes."); LOCK(cs_vNodes); return (int)vNodes.size(); } static void CopyNodeStats(std::vector<CNodeStats>& vstats) { vstats.clear(); LOCK(cs_vNodes); vstats.reserve(vNodes.size()); BOOST_FOREACH(CNode* pnode, vNodes) { CNodeStats stats; pnode->copyStats(stats); vstats.push_back(stats); } } Value getpeerinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getpeerinfo\n" "Returns data about each connected network node."); vector<CNodeStats> vstats; CopyNodeStats(vstats); Array ret; BOOST_FOREACH(const CNodeStats& stats, vstats) { Object obj; obj.push_back(Pair("addr", stats.addrName)); obj.push_back(Pair("services", strprintf("%08"PRI64x, stats.nServices))); obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend)); obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv)); obj.push_back(Pair("bytessent", (boost::int64_t)stats.nSendBytes)); obj.push_back(Pair("bytesrecv", (boost::int64_t)stats.nRecvBytes)); obj.push_back(Pair("blocksrequested", (boost::int64_t)stats.nBlocksRequested)); obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected)); obj.push_back(Pair("version", stats.nVersion)); // Use the sanitized form of subver here, to avoid tricksy remote peers from // corrupting or modifiying the JSON output by putting special characters in // their ver message. obj.push_back(Pair("subver", stats.cleanSubVer)); obj.push_back(Pair("inbound", stats.fInbound)); obj.push_back(Pair("startingheight", stats.nStartingHeight)); obj.push_back(Pair("banscore", stats.nMisbehavior)); if (stats.fSyncNode) obj.push_back(Pair("syncnode", true)); ret.push_back(obj); } return ret; } Value addnode(const Array& params, bool fHelp) { string strCommand; if (params.size() == 2) strCommand = params[1].get_str(); if (fHelp || params.size() != 2 || (strCommand != "onetry" && strCommand != "add" && strCommand != "remove")) throw runtime_error( "addnode <node> <add|remove|onetry>\n" "Attempts add or remove <node> from the addnode list or try a connection to <node> once."); string strNode = params[0].get_str(); if (strCommand == "onetry") { CAddress addr; ConnectNode(addr, strNode.c_str()); return Value::null; } LOCK(cs_vAddedNodes); vector<string>::iterator it = vAddedNodes.begin(); for(; it != vAddedNodes.end(); it++) if (strNode == *it) break; if (strCommand == "add") { if (it != vAddedNodes.end()) throw JSONRPCError(-23, "Error: Node already added"); vAddedNodes.push_back(strNode); } else if(strCommand == "remove") { if (it == vAddedNodes.end()) throw JSONRPCError(-24, "Error: Node has not been added."); vAddedNodes.erase(it); } return Value::null; } Value getaddednodeinfo(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getaddednodeinfo <dns> [node]\n" "Returns information about the given added node, or all added nodes\n" "(note that onetry addnodes are not listed here)\n" "If dns is false, only a list of added nodes will be provided,\n" "otherwise connected information will also be available."); bool fDns = params[0].get_bool(); list<string> laddedNodes(0); if (params.size() == 1) { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) laddedNodes.push_back(strAddNode); } else { string strNode = params[1].get_str(); LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) if (strAddNode == strNode) { laddedNodes.push_back(strAddNode); break; } if (laddedNodes.size() == 0) throw JSONRPCError(-24, "Error: Node has not been added."); } if (!fDns) { Object ret; BOOST_FOREACH(string& strAddNode, laddedNodes) ret.push_back(Pair("addednode", strAddNode)); return ret; } Array ret; list<pair<string, vector<CService> > > laddedAddreses(0); BOOST_FOREACH(string& strAddNode, laddedNodes) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0)) laddedAddreses.push_back(make_pair(strAddNode, vservNode)); else { Object obj; obj.push_back(Pair("addednode", strAddNode)); obj.push_back(Pair("connected", false)); Array addresses; obj.push_back(Pair("addresses", addresses)); } } LOCK(cs_vNodes); for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++) { Object obj; obj.push_back(Pair("addednode", it->first)); Array addresses; bool fConnected = false; BOOST_FOREACH(CService& addrNode, it->second) { bool fFound = false; Object node; node.push_back(Pair("address", addrNode.ToString())); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addr == addrNode) { fFound = true; fConnected = true; node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound")); break; } if (!fFound) node.push_back(Pair("connected", "false")); addresses.push_back(node); } obj.push_back(Pair("connected", fConnected)); obj.push_back(Pair("addresses", addresses)); ret.push_back(obj); } return ret; } // make a public-private key pair (first introduced in ppcoin) Value makekeypair(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "makekeypair [prefix]\n" "Make a public/private key pair.\n" "[prefix] is optional preferred prefix for the public key.\n"); string strPrefix = ""; if (params.size() > 0) strPrefix = params[0].get_str(); CKey key; CPubKey pubkey; int nCount = 0; do { key.MakeNewKey(false); pubkey = key.GetPubKey(); nCount++; } while (nCount < 10000 && strPrefix != HexStr(pubkey.begin(), pubkey.end()).substr(0, strPrefix.size())); if (strPrefix != HexStr(pubkey.begin(), pubkey.end()).substr(0, strPrefix.size())) return Value::null; Object result; result.push_back(Pair("PublicKey", HexStr(pubkey.begin(), pubkey.end()))); result.push_back(Pair("PrivateKey", CBitcoinSecret(key).ToString())); return result; } // Send alert (first introduced in ppcoin) // There is a known deadlock situation with ThreadMessageHandler // ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages() // ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage() Value sendalert(const Array& params, bool fHelp) { if (fHelp || params.size() < 6) throw runtime_error( "sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n" "<message> is the alert text message\n" "<privatekey> is base58 hex string of alert master private key\n" "<minver> is the minimum applicable internal client version\n" "<maxver> is the maximum applicable internal client version\n" "<priority> is integer priority number\n" "<id> is the alert id\n" "[cancelupto] cancels all alert id's up to this number\n" "Returns true or false."); // Prepare the alert message CAlert alert; alert.strStatusBar = params[0].get_str(); alert.nMinVer = params[2].get_int(); alert.nMaxVer = params[3].get_int(); alert.nPriority = params[4].get_int(); alert.nID = params[5].get_int(); if (params.size() > 6) alert.nCancel = params[6].get_int(); alert.nVersion = PROTOCOL_VERSION; alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60; alert.nExpiration = GetAdjustedTime() + 365*24*60*60; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedAlert)alert; alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end()); // Prepare master key and sign alert message CBitcoinSecret vchSecret; if (!vchSecret.SetString(params[1].get_str())) throw runtime_error("Invalid alert master key"); CKey key = vchSecret.GetKey(); // if key is not correct openssl may crash if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig)) throw runtime_error( "Unable to sign alert, check alert master key?\n"); // Process alert if(!alert.ProcessAlert()) throw runtime_error( "Failed to process alert.\n"); // Relay alert { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } Object result; result.push_back(Pair("strStatusBar", alert.strStatusBar)); result.push_back(Pair("nVersion", alert.nVersion)); result.push_back(Pair("nMinVer", alert.nMinVer)); result.push_back(Pair("nMaxVer", alert.nMaxVer)); result.push_back(Pair("nPriority", alert.nPriority)); result.push_back(Pair("nID", alert.nID)); if (alert.nCancel > 0) result.push_back(Pair("nCancel", alert.nCancel)); return result; } <|endoftext|>
<commit_before>//! \file //! ClientConnectedState class implementation #include "MainState.h" #include <sstream> MainStateEnum ClientConnectedState::LocalUpdate() { if (InputHandler::InputTime == 0) { if (Index == 0) { if (InputHandler::LastInput == Down) { Index = 1; } else if (InputHandler::LastInput == Left) { if (SelectedCharacter == PacMan) { SelectedCharacter = Clyde; } else { SelectedCharacter = (Character)(SelectedCharacter - 1); } } else if (InputHandler::LastInput == Right) { if (SelectedCharacter == Clyde) { SelectedCharacter = PacMan; } else { SelectedCharacter = (Character)(SelectedCharacter + 1); } } } else { if (InputHandler::LastInput == Up) { Ready = false; std::vector<char> data_s(PlayerNotReady_size); NetworkManager::Send(NetworkManager::PlayerNotReady, data_s, 0); Index = 0; } else if (InputHandler::LastInput == Right) { Ready = true; std::vector<char> data_s(PlayerReady_size); data_s[PlayerReady_Character] = SelectedCharacter; NetworkManager::Send( NetworkManager::PlayerReady, data_s, 0); } else if (InputHandler::LastInput == Left) { Ready = false; std::vector<char> data_s(PlayerNotReady_size); NetworkManager::Send(NetworkManager::PlayerNotReady, data_s, 0); } } } if (NetworkManager::CurrentConnections[0].Lag > NetworkTimeout) { return Join; } // ping server std::vector<char> data_s(PingServer_size); NetworkManager::Send(NetworkManager::PingServer, data_s, 0); return ClientConnected; } MainStateEnum ClientConnectedState::ProcessPacket(NetworkManager::MessageType mtype, std::vector<char> &data_r, unsigned int id) { if (id == 0) { NetworkManager::CurrentConnections[0].Lag = 0; if (mtype == NetworkManager::PingClient) { // No action needed } else if (mtype == NetworkManager::ConfirmClient) { PlayerNumber = data_r[ConfirmClient_PlayerNumber]; } else if (mtype == NetworkManager::DisconnectClient) { return Join; } else if (mtype == NetworkManager::StartGame) { unsigned char count = data_r[StartGame_PlayerCount]; unsigned char field = data_r[StartGame_Field]; /// \TODO Add field selection Field gameField("../stage1.txt"); Renderer::LoadField(&gameField, "../spritesheet.png"); std::vector<Player *> players; for (unsigned int i = 0; i < count; i++) { Character c = (Character)data_r[StartGame_Character + i]; if (c == PacMan) { players.push_back(new Pacman(PacmanSprite, Position( 14 * TILE_SIZE, 23 * TILE_SIZE + (TILE_SIZE - 1) / 2), Left)); } else if (c == Blinky) { players.push_back(new Ghost(GhostSprites[0], Position( 14 * TILE_SIZE, 11 * TILE_SIZE + (TILE_SIZE - 1) / 2), Left)); } else if (c == Inky) { players.push_back(new Ghost(GhostSprites[2], Position( 12 * TILE_SIZE, 14 * TILE_SIZE + (TILE_SIZE - 1) / 2), Up)); } else if (c == Pinky) { players.push_back(new Ghost(GhostSprites[1], Position( 14 * TILE_SIZE, 14 * TILE_SIZE + (TILE_SIZE - 1) / 2), Down)); } else if (c == Clyde) { players.push_back(new Ghost(GhostSprites[3], Position( 16 * TILE_SIZE, 14 * TILE_SIZE + (TILE_SIZE - 1) / 2), Up)); } } StartingGame = new Game(gameField, players); return Gameplay; } } return ClientConnected; } void ClientConnectedState::Render() const { std::ostringstream ss; ss << "You are Player "; ss << PlayerNumber + 1; std::string str = ss.str(); Renderer::DrawText(0, str, 24, 60, 100); Character c = SelectedCharacter; bool ready = Ready; unsigned int index = Index; if (c == PacMan) { Renderer::DrawText(0, "< Pac-Man >", 18, 60, 140); } else if (c == Blinky) { Renderer::DrawText(0, "< Blinky >", 18, 60, 140); } else if (c == Inky) { Renderer::DrawText(0, "< Inky >", 18, 60, 140); } else if (c == Pinky) { Renderer::DrawText(0, "< Pinky >", 18, 60, 140); } else if (c == Clyde) { Renderer::DrawText(0, "< Clyde >", 18, 60, 140); } if (ready) { Renderer::DrawText(0, "< Ready!", 18, 60, 180); } else { Renderer::DrawText(0, " Ready? >", 18, 60, 180); } Renderer::DrawText(0, ">", 18, 20, 140 + 40 * index); } <commit_msg>Show sprites in character selection<commit_after>//! \file //! ClientConnectedState class implementation #include "MainState.h" #include <sstream> MainStateEnum ClientConnectedState::LocalUpdate() { if (InputHandler::InputTime == 0) { if (Index == 0) { if (InputHandler::LastInput == Down) { Index = 1; } else if (InputHandler::LastInput == Left) { if (SelectedCharacter == PacMan) { SelectedCharacter = Clyde; } else { SelectedCharacter = (Character)(SelectedCharacter - 1); } } else if (InputHandler::LastInput == Right) { if (SelectedCharacter == Clyde) { SelectedCharacter = PacMan; } else { SelectedCharacter = (Character)(SelectedCharacter + 1); } } } else { if (InputHandler::LastInput == Up) { Ready = false; std::vector<char> data_s(PlayerNotReady_size); NetworkManager::Send(NetworkManager::PlayerNotReady, data_s, 0); Index = 0; } else if (InputHandler::LastInput == Right) { Ready = true; std::vector<char> data_s(PlayerReady_size); data_s[PlayerReady_Character] = SelectedCharacter; NetworkManager::Send( NetworkManager::PlayerReady, data_s, 0); } else if (InputHandler::LastInput == Left) { Ready = false; std::vector<char> data_s(PlayerNotReady_size); NetworkManager::Send(NetworkManager::PlayerNotReady, data_s, 0); } } } if (NetworkManager::CurrentConnections[0].Lag > NetworkTimeout) { return Join; } // ping server std::vector<char> data_s(PingServer_size); NetworkManager::Send(NetworkManager::PingServer, data_s, 0); return ClientConnected; } MainStateEnum ClientConnectedState::ProcessPacket(NetworkManager::MessageType mtype, std::vector<char> &data_r, unsigned int id) { if (id == 0) { NetworkManager::CurrentConnections[0].Lag = 0; if (mtype == NetworkManager::PingClient) { // No action needed } else if (mtype == NetworkManager::ConfirmClient) { PlayerNumber = data_r[ConfirmClient_PlayerNumber]; } else if (mtype == NetworkManager::DisconnectClient) { return Join; } else if (mtype == NetworkManager::StartGame) { unsigned char count = data_r[StartGame_PlayerCount]; unsigned char field = data_r[StartGame_Field]; /// \TODO Add field selection Field gameField("../stage1.txt"); Renderer::LoadField(&gameField, "../spritesheet.png"); std::vector<Player *> players; for (unsigned int i = 0; i < count; i++) { Character c = (Character)data_r[StartGame_Character + i]; if (c == PacMan) { players.push_back(new Pacman(PacmanSprite, Position( 14 * TILE_SIZE, 23 * TILE_SIZE + (TILE_SIZE - 1) / 2), Left)); } else if (c == Blinky) { players.push_back(new Ghost(GhostSprites[0], Position( 14 * TILE_SIZE, 11 * TILE_SIZE + (TILE_SIZE - 1) / 2), Left)); } else if (c == Inky) { players.push_back(new Ghost(GhostSprites[2], Position( 12 * TILE_SIZE, 14 * TILE_SIZE + (TILE_SIZE - 1) / 2), Up)); } else if (c == Pinky) { players.push_back(new Ghost(GhostSprites[1], Position( 14 * TILE_SIZE, 14 * TILE_SIZE + (TILE_SIZE - 1) / 2), Down)); } else if (c == Clyde) { players.push_back(new Ghost(GhostSprites[3], Position( 16 * TILE_SIZE, 14 * TILE_SIZE + (TILE_SIZE - 1) / 2), Up)); } } StartingGame = new Game(gameField, players); return Gameplay; } } return ClientConnected; } void ClientConnectedState::Render() const { std::ostringstream ss; ss << "You are Player "; ss << PlayerNumber + 1; std::string str = ss.str(); Renderer::DrawText(0, str, 24, 60, 100); Character c = SelectedCharacter; bool ready = Ready; unsigned int index = Index; if (c == PacMan) { Renderer::DrawText(0, "< Pac-Man >", 18, 60, 140); Renderer::DrawSprite( PacmanSprite, 9 * TILE_SIZE, 5 * TILE_SIZE, 0.f, true, 0, 4); } else if (c == Blinky) { Renderer::DrawText(0, "< Blinky >", 18, 60, 140); Renderer::DrawSprite( GhostSprites[0], 9 * TILE_SIZE, 5 * TILE_SIZE, 0.f, false, 0, 0); } else if (c == Inky) { Renderer::DrawText(0, "< Inky >", 18, 60, 140); Renderer::DrawSprite( GhostSprites[2], 9 * TILE_SIZE, 5 * TILE_SIZE, 0.f, false, 0, 0); } else if (c == Pinky) { Renderer::DrawText(0, "< Pinky >", 18, 60, 140); Renderer::DrawSprite( GhostSprites[1], 9 * TILE_SIZE, 5 * TILE_SIZE, 0.f, false, 0, 0); } else if (c == Clyde) { Renderer::DrawText(0, "< Clyde >", 18, 60, 140); Renderer::DrawSprite( GhostSprites[3], 9 * TILE_SIZE, 5 * TILE_SIZE, 0.f, false, 0, 0); } if (ready) { Renderer::DrawText(0, "< Ready!", 18, 60, 180); } else { Renderer::DrawText(0, " Ready? >", 18, 60, 180); } Renderer::DrawText(0, ">", 18, 20, 140 + 40 * index); } <|endoftext|>
<commit_before>/* The libMesh Finite Element Library. */ /* Copyright (C) 2003 Benjamin S. Kirk */ /* 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 */ // <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1> // // LibMesh provides interfaces to both Triangle and TetGen for generating // Delaunay triangulations and tetrahedralizations in two and three dimensions // (respectively). // Local header files #include "libmesh/elem.h" #include "libmesh/face_tri3.h" #include "libmesh/mesh.h" #include "libmesh/mesh_generation.h" #include "libmesh/mesh_tetgen_interface.h" #include "libmesh/mesh_triangle_holes.h" #include "libmesh/mesh_triangle_interface.h" #include "libmesh/node.h" #include "libmesh/serial_mesh.h" // Bring in everything from the libMesh namespace using namespace libMesh; // Major functions called by main void triangulate_domain(const Parallel::Communicator& comm); void tetrahedralize_domain(const Parallel::Communicator& comm); // Helper routine for tetrahedralize_domain(). Adds the points and elements // of a convex hull generated by TetGen to the input mesh void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit); // Begin the main program. int main (int argc, char** argv) { // Initialize libMesh and any dependent libaries, like in example 2. LibMeshInit init (argc, argv); libmesh_example_assert(2 <= LIBMESH_DIM, "2D support"); std::cout << "Triangulating an L-shaped domain with holes" << std::endl; // 1.) 2D triangulation of L-shaped domain with three holes of different shape triangulate_domain(init.communicator()); libmesh_example_assert(3 <= LIBMESH_DIM, "3D support"); std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl; // 2.) 3D tetrahedralization of rectangular domain with hole. tetrahedralize_domain(init.communicator()); return 0; } void triangulate_domain(const Parallel::Communicator& comm) { #ifdef LIBMESH_HAVE_TRIANGLE // Use typedefs for slightly less typing. typedef TriangleInterface::Hole Hole; typedef TriangleInterface::PolygonHole PolygonHole; typedef TriangleInterface::ArbitraryHole ArbitraryHole; // Libmesh mesh that will eventually be created. Mesh mesh(comm, 2); // The points which make up the L-shape: mesh.add_point(Point( 0. , 0.)); mesh.add_point(Point( 0. , -1.)); mesh.add_point(Point(-1. , -1.)); mesh.add_point(Point(-1. , 1.)); mesh.add_point(Point( 1. , 1.)); mesh.add_point(Point( 1. , 0.)); // Declare the TriangleInterface object. This is where // we can set parameters of the triangulation and where the // actual triangulate function lives. TriangleInterface t(mesh); // Customize the variables for the triangulation t.desired_area() = .01; // A Planar Straight Line Graph (PSLG) is essentially a list // of segments which have to exist in the final triangulation. // For an L-shaped domain, Triangle will compute the convex // hull of boundary points if we do not specify the PSLG. // The PSLG algorithm is also required for triangulating domains // containing holes t.triangulation_type() = TriangleInterface::PSLG; // Turn on/off Laplacian mesh smoothing after generation. // By default this is on. t.smooth_after_generating() = true; // Define holes... // hole_1 is a circle (discretized by 50 points) PolygonHole hole_1(Point(-0.5, 0.5), // center 0.25, // radius 50); // n. points // hole_2 is itself a triangle PolygonHole hole_2(Point(0.5, 0.5), // center 0.1, // radius 3); // n. points // hole_3 is an ellipse of 100 points which we define here Point ellipse_center(-0.5, -0.5); const unsigned int n_ellipse_points=100; std::vector<Point> ellipse_points(n_ellipse_points); const Real dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points), a = .1, b = .2; for (unsigned int i=0; i<n_ellipse_points; ++i) ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta), ellipse_center(1)+b*sin(i*dtheta)); ArbitraryHole hole_3(ellipse_center, ellipse_points); // Create the vector of Hole*'s ... std::vector<Hole*> holes; holes.push_back(&hole_1); holes.push_back(&hole_2); holes.push_back(&hole_3); // ... and attach it to the triangulator object t.attach_hole_list(&holes); // Triangulate! t.triangulate(); // Write the result to file mesh.write("delaunay_l_shaped_hole.e"); #endif // LIBMESH_HAVE_TRIANGLE } void tetrahedralize_domain(const Parallel::Communicator& comm) { #ifdef LIBMESH_HAVE_TETGEN // The algorithm is broken up into several steps: // 1.) A convex hull is constructed for a rectangular hole. // 2.) A convex hull is constructed for the domain exterior. // 3.) Neighbor information is updated so TetGen knows there is a convex hull // 4.) A vector of hole points is created. // 5.) The domain is tetrahedralized, the mesh is written out, etc. // The mesh we will eventually generate SerialMesh mesh(3,comm); // Lower and Upper bounding box limits for a rectangular hole within the unit cube. Point hole_lower_limit(0.2, 0.2, 0.4); Point hole_upper_limit(0.8, 0.8, 0.6); // 1.) Construct a convex hull for the hole add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit); // 2.) Generate elements comprising the outer boundary of the domain. add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.)); // 3.) Update neighbor information so that TetGen can verify there is a convex hull. mesh.find_neighbors(); // 4.) Set up vector of hole points std::vector<Point> hole(1); hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) ); // 5.) Set parameters and tetrahedralize the domain // 0 means "use TetGen default value" Real quality_constraint = 2.0; // The volume constraint determines the max-allowed tetrahedral // volume in the Mesh. TetGen will split cells which are larger than // this size Real volume_constraint = 0.001; // Construct the Delaunay tetrahedralization TetGenMeshInterface t(mesh); t.triangulate_conformingDelaunayMesh_carvehole(hole, quality_constraint, volume_constraint); // Find neighbors, etc in preparation for writing out the Mesh mesh.prepare_for_use(); // Finally, write out the result mesh.write("hole_3D.e"); #endif // LIBMESH_HAVE_TETGEN } void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit) { #ifdef LIBMESH_HAVE_TETGEN SerialMesh cube_mesh(3,mesh.communicator()); unsigned n_elem = 1; MeshTools::Generation::build_cube(cube_mesh, n_elem,n_elem,n_elem, // n. elements in each direction lower_limit(0), upper_limit(0), lower_limit(1), upper_limit(1), lower_limit(2), upper_limit(2), HEX8); // The pointset_convexhull() algorithm will ignore the Hex8s // in the Mesh, and just construct the triangulation // of the convex hull. TetGenMeshInterface t(cube_mesh); t.pointset_convexhull(); // Now add all nodes from the boundary of the cube_mesh to the input mesh. // Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted // with a dummy value, later to be assigned a value by the input mesh. std::map<unsigned,unsigned> node_id_map; typedef std::map<unsigned,unsigned>::iterator iterator; { MeshBase::element_iterator it = cube_mesh.elements_begin(); const MeshBase::element_iterator end = cube_mesh.elements_end(); for ( ; it != end; ++it) { Elem* elem = *it; for (unsigned s=0; s<elem->n_sides(); ++s) if (elem->neighbor(s) == NULL) { // Add the node IDs of this side to the set AutoPtr<Elem> side = elem->side(s); for (unsigned n=0; n<side->n_nodes(); ++n) node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) ); } } } // For each node in the map, insert it into the input mesh and keep // track of the ID assigned. for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it) { // Id of the node in the cube mesh unsigned id = (*it).first; // Pointer to node in the cube mesh Node* old_node = cube_mesh.node_ptr(id); // Add geometric point to input mesh Node* new_node = mesh.add_point ( *old_node ); // Track ID value of new_node in map (*it).second = new_node->id(); } // With the points added and the map data structure in place, we are // ready to add each TRI3 element of the cube_mesh to the input Mesh // with proper node assignments { MeshBase::element_iterator el = cube_mesh.elements_begin(); const MeshBase::element_iterator end_el = cube_mesh.elements_end(); for (; el != end_el; ++el) { Elem* old_elem = *el; if (old_elem->type() == TRI3) { Elem* new_elem = mesh.add_elem(new Tri3); // Assign nodes in new elements. Since this is an example, // we'll do it in several steps. for (unsigned i=0; i<old_elem->n_nodes(); ++i) { // Locate old node ID in the map iterator it = node_id_map.find(old_elem->node(i)); // Check for not found if (it == node_id_map.end()) { libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl; libmesh_error(); } // Mapping to node ID in input mesh unsigned new_node_id = (*it).second; // Node pointer assigned from input mesh new_elem->set_node(i) = mesh.node_ptr(new_node_id); } } } } #endif // LIBMESH_HAVE_TETGEN } <commit_msg>Missed a couple Mesh creations in previous commit<commit_after>/* The libMesh Finite Element Library. */ /* Copyright (C) 2003 Benjamin S. Kirk */ /* 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 */ // <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1> // // LibMesh provides interfaces to both Triangle and TetGen for generating // Delaunay triangulations and tetrahedralizations in two and three dimensions // (respectively). // Local header files #include "libmesh/elem.h" #include "libmesh/face_tri3.h" #include "libmesh/mesh.h" #include "libmesh/mesh_generation.h" #include "libmesh/mesh_tetgen_interface.h" #include "libmesh/mesh_triangle_holes.h" #include "libmesh/mesh_triangle_interface.h" #include "libmesh/node.h" #include "libmesh/serial_mesh.h" // Bring in everything from the libMesh namespace using namespace libMesh; // Major functions called by main void triangulate_domain(const Parallel::Communicator& comm); void tetrahedralize_domain(const Parallel::Communicator& comm); // Helper routine for tetrahedralize_domain(). Adds the points and elements // of a convex hull generated by TetGen to the input mesh void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit); // Begin the main program. int main (int argc, char** argv) { // Initialize libMesh and any dependent libaries, like in example 2. LibMeshInit init (argc, argv); libmesh_example_assert(2 <= LIBMESH_DIM, "2D support"); std::cout << "Triangulating an L-shaped domain with holes" << std::endl; // 1.) 2D triangulation of L-shaped domain with three holes of different shape triangulate_domain(init.communicator()); libmesh_example_assert(3 <= LIBMESH_DIM, "3D support"); std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl; // 2.) 3D tetrahedralization of rectangular domain with hole. tetrahedralize_domain(init.communicator()); return 0; } void triangulate_domain(const Parallel::Communicator& comm) { #ifdef LIBMESH_HAVE_TRIANGLE // Use typedefs for slightly less typing. typedef TriangleInterface::Hole Hole; typedef TriangleInterface::PolygonHole PolygonHole; typedef TriangleInterface::ArbitraryHole ArbitraryHole; // Libmesh mesh that will eventually be created. Mesh mesh(comm, 2); // The points which make up the L-shape: mesh.add_point(Point( 0. , 0.)); mesh.add_point(Point( 0. , -1.)); mesh.add_point(Point(-1. , -1.)); mesh.add_point(Point(-1. , 1.)); mesh.add_point(Point( 1. , 1.)); mesh.add_point(Point( 1. , 0.)); // Declare the TriangleInterface object. This is where // we can set parameters of the triangulation and where the // actual triangulate function lives. TriangleInterface t(mesh); // Customize the variables for the triangulation t.desired_area() = .01; // A Planar Straight Line Graph (PSLG) is essentially a list // of segments which have to exist in the final triangulation. // For an L-shaped domain, Triangle will compute the convex // hull of boundary points if we do not specify the PSLG. // The PSLG algorithm is also required for triangulating domains // containing holes t.triangulation_type() = TriangleInterface::PSLG; // Turn on/off Laplacian mesh smoothing after generation. // By default this is on. t.smooth_after_generating() = true; // Define holes... // hole_1 is a circle (discretized by 50 points) PolygonHole hole_1(Point(-0.5, 0.5), // center 0.25, // radius 50); // n. points // hole_2 is itself a triangle PolygonHole hole_2(Point(0.5, 0.5), // center 0.1, // radius 3); // n. points // hole_3 is an ellipse of 100 points which we define here Point ellipse_center(-0.5, -0.5); const unsigned int n_ellipse_points=100; std::vector<Point> ellipse_points(n_ellipse_points); const Real dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points), a = .1, b = .2; for (unsigned int i=0; i<n_ellipse_points; ++i) ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta), ellipse_center(1)+b*sin(i*dtheta)); ArbitraryHole hole_3(ellipse_center, ellipse_points); // Create the vector of Hole*'s ... std::vector<Hole*> holes; holes.push_back(&hole_1); holes.push_back(&hole_2); holes.push_back(&hole_3); // ... and attach it to the triangulator object t.attach_hole_list(&holes); // Triangulate! t.triangulate(); // Write the result to file mesh.write("delaunay_l_shaped_hole.e"); #endif // LIBMESH_HAVE_TRIANGLE } void tetrahedralize_domain(const Parallel::Communicator& comm) { #ifdef LIBMESH_HAVE_TETGEN // The algorithm is broken up into several steps: // 1.) A convex hull is constructed for a rectangular hole. // 2.) A convex hull is constructed for the domain exterior. // 3.) Neighbor information is updated so TetGen knows there is a convex hull // 4.) A vector of hole points is created. // 5.) The domain is tetrahedralized, the mesh is written out, etc. // The mesh we will eventually generate SerialMesh mesh(comm,3); // Lower and Upper bounding box limits for a rectangular hole within the unit cube. Point hole_lower_limit(0.2, 0.2, 0.4); Point hole_upper_limit(0.8, 0.8, 0.6); // 1.) Construct a convex hull for the hole add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit); // 2.) Generate elements comprising the outer boundary of the domain. add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.)); // 3.) Update neighbor information so that TetGen can verify there is a convex hull. mesh.find_neighbors(); // 4.) Set up vector of hole points std::vector<Point> hole(1); hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) ); // 5.) Set parameters and tetrahedralize the domain // 0 means "use TetGen default value" Real quality_constraint = 2.0; // The volume constraint determines the max-allowed tetrahedral // volume in the Mesh. TetGen will split cells which are larger than // this size Real volume_constraint = 0.001; // Construct the Delaunay tetrahedralization TetGenMeshInterface t(mesh); t.triangulate_conformingDelaunayMesh_carvehole(hole, quality_constraint, volume_constraint); // Find neighbors, etc in preparation for writing out the Mesh mesh.prepare_for_use(); // Finally, write out the result mesh.write("hole_3D.e"); #endif // LIBMESH_HAVE_TETGEN } void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit) { #ifdef LIBMESH_HAVE_TETGEN SerialMesh cube_mesh(mesh.communicator(),3); unsigned n_elem = 1; MeshTools::Generation::build_cube(cube_mesh, n_elem,n_elem,n_elem, // n. elements in each direction lower_limit(0), upper_limit(0), lower_limit(1), upper_limit(1), lower_limit(2), upper_limit(2), HEX8); // The pointset_convexhull() algorithm will ignore the Hex8s // in the Mesh, and just construct the triangulation // of the convex hull. TetGenMeshInterface t(cube_mesh); t.pointset_convexhull(); // Now add all nodes from the boundary of the cube_mesh to the input mesh. // Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted // with a dummy value, later to be assigned a value by the input mesh. std::map<unsigned,unsigned> node_id_map; typedef std::map<unsigned,unsigned>::iterator iterator; { MeshBase::element_iterator it = cube_mesh.elements_begin(); const MeshBase::element_iterator end = cube_mesh.elements_end(); for ( ; it != end; ++it) { Elem* elem = *it; for (unsigned s=0; s<elem->n_sides(); ++s) if (elem->neighbor(s) == NULL) { // Add the node IDs of this side to the set AutoPtr<Elem> side = elem->side(s); for (unsigned n=0; n<side->n_nodes(); ++n) node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) ); } } } // For each node in the map, insert it into the input mesh and keep // track of the ID assigned. for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it) { // Id of the node in the cube mesh unsigned id = (*it).first; // Pointer to node in the cube mesh Node* old_node = cube_mesh.node_ptr(id); // Add geometric point to input mesh Node* new_node = mesh.add_point ( *old_node ); // Track ID value of new_node in map (*it).second = new_node->id(); } // With the points added and the map data structure in place, we are // ready to add each TRI3 element of the cube_mesh to the input Mesh // with proper node assignments { MeshBase::element_iterator el = cube_mesh.elements_begin(); const MeshBase::element_iterator end_el = cube_mesh.elements_end(); for (; el != end_el; ++el) { Elem* old_elem = *el; if (old_elem->type() == TRI3) { Elem* new_elem = mesh.add_elem(new Tri3); // Assign nodes in new elements. Since this is an example, // we'll do it in several steps. for (unsigned i=0; i<old_elem->n_nodes(); ++i) { // Locate old node ID in the map iterator it = node_id_map.find(old_elem->node(i)); // Check for not found if (it == node_id_map.end()) { libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl; libmesh_error(); } // Mapping to node ID in input mesh unsigned new_node_id = (*it).second; // Node pointer assigned from input mesh new_elem->set_node(i) = mesh.node_ptr(new_node_id); } } } } #endif // LIBMESH_HAVE_TETGEN } <|endoftext|>
<commit_before>/* rbOOmit: An implementation of the Certified Reduced Basis method. */ /* Copyright (C) 2009, 2010 David J. Knezevic */ /* This file is part of rbOOmit. */ /* rbOOmit 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. */ /* rbOOmit 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 */ // <h1>Reduced Basis Example 1 - Certified Reduced Basis Method</h1> // In this example problem we use the Certified Reduced Basis method // to solve a steady convection-diffusion problem on the unit square. // The reduced basis method relies on an expansion of the PDE in the // form \sum_q=1^Q_a theta_a^q(\mu) * a^q(u,v) = \sum_q=1^Q_f theta_f^q(\mu) f^q(v) // where theta_a, theta_f are parameter dependent functions and // a^q, f^q are parameter independent operators (\mu denotes a parameter). // We first attach the parameter dependent functions and paramater // independent operators to the RBSystem. Then in Offline mode, a // reduced basis space is generated and written out to the directory // "offline_data". In Online mode, the reduced basis data in "offline_data" // is read in and used to solve the reduced problem for the parameters // specified in reduced_basis_ex1.in. // We also attach four outputs to the system which are averages over certain // subregions of the domain. In Online mode, we print out the values of these // outputs as well as rigorous error bounds with respect to the output // associated with the "truth" finite element discretization. // C++ include files that we need #include <iostream> #include <algorithm> #include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC #include <cmath> #include <set> // Basic include file needed for the mesh functionality. #include "libmesh/libmesh.h" #include "libmesh/mesh.h" #include "libmesh/mesh_generation.h" #include "libmesh/exodusII_io.h" #include "libmesh/equation_systems.h" #include "libmesh/dof_map.h" #include "libmesh/getpot.h" #include "libmesh/elem.h" // local includes #include "rb_classes.h" #include "assembly.h" // Bring in everything from the libMesh namespace using namespace libMesh; // The main program. int main (int argc, char** argv) { // Initialize libMesh. LibMeshInit init (argc, argv); #if !defined(LIBMESH_HAVE_XDR) // We need XDR support to write out reduced bases libmesh_example_assert(false, "--enable-xdr"); #elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION) // XDR binary support requires double precision libmesh_example_assert(false, "--disable-singleprecision"); #endif // FIXME: This example currently segfaults with Trilinos? libmesh_example_assert(libMesh::default_solver_package() == PETSC_SOLVERS, "--enable-petsc"); // Skip this 2D example if libMesh was compiled as 1D-only. libmesh_example_assert(2 <= LIBMESH_DIM, "2D support"); // Parse the input file (reduced_basis_ex1.in) using GetPot std::string parameters_filename = "reduced_basis_ex1.in"; GetPot infile(parameters_filename); unsigned int n_elem = infile("n_elem", 1); // Determines the number of elements in the "truth" mesh const unsigned int dim = 2; // The number of spatial dimensions bool store_basis_functions = infile("store_basis_functions", true); // Do we write the RB basis functions to disk? // Read the "online_mode" flag from the command line GetPot command_line (argc, argv); int online_mode = 0; if ( command_line.search(1, "-online_mode") ) online_mode = command_line.next(online_mode); // Build a mesh on the default MPI communicator. Mesh mesh (init.comm(), dim); MeshTools::Generation::build_square (mesh, n_elem, n_elem, 0., 1., 0., 1., QUAD4); // Create an equation systems object. EquationSystems equation_systems (mesh); // We override RBConstruction with SimpleRBConstruction in order to // specialize a few functions for this particular problem. SimpleRBConstruction & rb_con = equation_systems.add_system<SimpleRBConstruction> ("RBConvectionDiffusion"); // Initialize the data structures for the equation system. equation_systems.init (); // Print out some information about the "truth" discretization equation_systems.print_info(); mesh.print_info(); // Build a new RBEvaluation object which will be used to perform // Reduced Basis calculations. This is required in both the // "Offline" and "Online" stages. SimpleRBEvaluation rb_eval(mesh.comm()); // We need to give the RBConstruction object a pointer to // our RBEvaluation object rb_con.set_rb_evaluation(rb_eval); if(!online_mode) // Perform the Offline stage of the RB method { // Read in the data that defines this problem from the specified text file rb_con.process_parameters_file(parameters_filename); // Print out info that describes the current setup of rb_con rb_con.print_info(); // Prepare rb_con for the Construction stage of the RB method. // This sets up the necessary data structures and performs // initial assembly of the "truth" affine expansion of the PDE. rb_con.initialize_rb_construction(); // Compute the reduced basis space by computing "snapshots", i.e. // "truth" solves, at well-chosen parameter values and employing // these snapshots as basis functions. rb_con.train_reduced_basis(); // Write out the data that will subsequently be required for the Evaluation stage rb_con.get_rb_evaluation().write_offline_data_to_files(); // If requested, write out the RB basis functions for visualization purposes if(store_basis_functions) { // Write out the basis functions rb_con.get_rb_evaluation().write_out_basis_functions(rb_con); } // Basis functions should be orthonormal, so // print out the inner products to check this rb_con.print_basis_function_orthogonality(); } else // Perform the Online stage of the RB method { // Read in the reduced basis data rb_eval.read_offline_data_from_files(); // Read in online_N and initialize online parameters unsigned int online_N = infile("online_N",1); Real online_x_vel = infile("online_x_vel", 0.); Real online_y_vel = infile("online_y_vel", 0.); RBParameters online_mu; online_mu.set_value("x_vel", online_x_vel); online_mu.set_value("y_vel", online_y_vel); rb_eval.set_parameters(online_mu); rb_eval.print_parameters(); // Now do the Online solve using the precomputed reduced basis rb_eval.rb_solve(online_N); // Print out outputs as well as the corresponding output error bounds. std::cout << "output 1, value = " << rb_eval.RB_outputs[0] << ", bound = " << rb_eval.RB_output_error_bounds[0] << std::endl; std::cout << "output 2, value = " << rb_eval.RB_outputs[1] << ", bound = " << rb_eval.RB_output_error_bounds[1] << std::endl; std::cout << "output 3, value = " << rb_eval.RB_outputs[2] << ", bound = " << rb_eval.RB_output_error_bounds[2] << std::endl; std::cout << "output 4, value = " << rb_eval.RB_outputs[3] << ", bound = " << rb_eval.RB_output_error_bounds[3] << std::endl << std::endl; if(store_basis_functions) { // Read in the basis functions rb_eval.read_in_basis_functions(rb_con); // Plot the solution rb_con.load_rb_solution(); #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(mesh).write_equation_systems ("RB_sol.e",equation_systems); #endif // Plot the first basis function that was generated from the train_reduced_basis // call in the Offline stage rb_con.load_basis_function(0); #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(mesh).write_equation_systems ("bf0.e",equation_systems); #endif } } return 0; } <commit_msg>reduced_basis_ex1 works with Eigen sparse linear solvers.<commit_after>/* rbOOmit: An implementation of the Certified Reduced Basis method. */ /* Copyright (C) 2009, 2010 David J. Knezevic */ /* This file is part of rbOOmit. */ /* rbOOmit 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. */ /* rbOOmit 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 */ // <h1>Reduced Basis Example 1 - Certified Reduced Basis Method</h1> // In this example problem we use the Certified Reduced Basis method // to solve a steady convection-diffusion problem on the unit square. // The reduced basis method relies on an expansion of the PDE in the // form \sum_q=1^Q_a theta_a^q(\mu) * a^q(u,v) = \sum_q=1^Q_f theta_f^q(\mu) f^q(v) // where theta_a, theta_f are parameter dependent functions and // a^q, f^q are parameter independent operators (\mu denotes a parameter). // We first attach the parameter dependent functions and paramater // independent operators to the RBSystem. Then in Offline mode, a // reduced basis space is generated and written out to the directory // "offline_data". In Online mode, the reduced basis data in "offline_data" // is read in and used to solve the reduced problem for the parameters // specified in reduced_basis_ex1.in. // We also attach four outputs to the system which are averages over certain // subregions of the domain. In Online mode, we print out the values of these // outputs as well as rigorous error bounds with respect to the output // associated with the "truth" finite element discretization. // C++ include files that we need #include <iostream> #include <algorithm> #include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC #include <cmath> #include <set> // Basic include file needed for the mesh functionality. #include "libmesh/libmesh.h" #include "libmesh/mesh.h" #include "libmesh/mesh_generation.h" #include "libmesh/exodusII_io.h" #include "libmesh/equation_systems.h" #include "libmesh/dof_map.h" #include "libmesh/getpot.h" #include "libmesh/elem.h" // local includes #include "rb_classes.h" #include "assembly.h" // Bring in everything from the libMesh namespace using namespace libMesh; // The main program. int main (int argc, char** argv) { // Initialize libMesh. LibMeshInit init (argc, argv); #if !defined(LIBMESH_HAVE_XDR) // We need XDR support to write out reduced bases libmesh_example_assert(false, "--enable-xdr"); #elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION) // XDR binary support requires double precision libmesh_example_assert(false, "--disable-singleprecision"); #endif // FIXME: This example currently segfaults with Trilinos? It works // with PETSc and Eigen sparse linear solvers though. libmesh_example_assert(libMesh::default_solver_package() != TRILINOS_SOLVERS, "--enable-petsc"); // Skip this 2D example if libMesh was compiled as 1D-only. libmesh_example_assert(2 <= LIBMESH_DIM, "2D support"); // Parse the input file (reduced_basis_ex1.in) using GetPot std::string parameters_filename = "reduced_basis_ex1.in"; GetPot infile(parameters_filename); unsigned int n_elem = infile("n_elem", 1); // Determines the number of elements in the "truth" mesh const unsigned int dim = 2; // The number of spatial dimensions bool store_basis_functions = infile("store_basis_functions", true); // Do we write the RB basis functions to disk? // Read the "online_mode" flag from the command line GetPot command_line (argc, argv); int online_mode = 0; if ( command_line.search(1, "-online_mode") ) online_mode = command_line.next(online_mode); // Build a mesh on the default MPI communicator. Mesh mesh (init.comm(), dim); MeshTools::Generation::build_square (mesh, n_elem, n_elem, 0., 1., 0., 1., QUAD4); // Create an equation systems object. EquationSystems equation_systems (mesh); // We override RBConstruction with SimpleRBConstruction in order to // specialize a few functions for this particular problem. SimpleRBConstruction & rb_con = equation_systems.add_system<SimpleRBConstruction> ("RBConvectionDiffusion"); // Initialize the data structures for the equation system. equation_systems.init (); // Print out some information about the "truth" discretization equation_systems.print_info(); mesh.print_info(); // Build a new RBEvaluation object which will be used to perform // Reduced Basis calculations. This is required in both the // "Offline" and "Online" stages. SimpleRBEvaluation rb_eval(mesh.comm()); // We need to give the RBConstruction object a pointer to // our RBEvaluation object rb_con.set_rb_evaluation(rb_eval); if(!online_mode) // Perform the Offline stage of the RB method { // Read in the data that defines this problem from the specified text file rb_con.process_parameters_file(parameters_filename); // Print out info that describes the current setup of rb_con rb_con.print_info(); // Prepare rb_con for the Construction stage of the RB method. // This sets up the necessary data structures and performs // initial assembly of the "truth" affine expansion of the PDE. rb_con.initialize_rb_construction(); // Compute the reduced basis space by computing "snapshots", i.e. // "truth" solves, at well-chosen parameter values and employing // these snapshots as basis functions. rb_con.train_reduced_basis(); // Write out the data that will subsequently be required for the Evaluation stage rb_con.get_rb_evaluation().write_offline_data_to_files(); // If requested, write out the RB basis functions for visualization purposes if(store_basis_functions) { // Write out the basis functions rb_con.get_rb_evaluation().write_out_basis_functions(rb_con); } // Basis functions should be orthonormal, so // print out the inner products to check this rb_con.print_basis_function_orthogonality(); } else // Perform the Online stage of the RB method { // Read in the reduced basis data rb_eval.read_offline_data_from_files(); // Read in online_N and initialize online parameters unsigned int online_N = infile("online_N",1); Real online_x_vel = infile("online_x_vel", 0.); Real online_y_vel = infile("online_y_vel", 0.); RBParameters online_mu; online_mu.set_value("x_vel", online_x_vel); online_mu.set_value("y_vel", online_y_vel); rb_eval.set_parameters(online_mu); rb_eval.print_parameters(); // Now do the Online solve using the precomputed reduced basis rb_eval.rb_solve(online_N); // Print out outputs as well as the corresponding output error bounds. std::cout << "output 1, value = " << rb_eval.RB_outputs[0] << ", bound = " << rb_eval.RB_output_error_bounds[0] << std::endl; std::cout << "output 2, value = " << rb_eval.RB_outputs[1] << ", bound = " << rb_eval.RB_output_error_bounds[1] << std::endl; std::cout << "output 3, value = " << rb_eval.RB_outputs[2] << ", bound = " << rb_eval.RB_output_error_bounds[2] << std::endl; std::cout << "output 4, value = " << rb_eval.RB_outputs[3] << ", bound = " << rb_eval.RB_output_error_bounds[3] << std::endl << std::endl; if(store_basis_functions) { // Read in the basis functions rb_eval.read_in_basis_functions(rb_con); // Plot the solution rb_con.load_rb_solution(); #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(mesh).write_equation_systems ("RB_sol.e",equation_systems); #endif // Plot the first basis function that was generated from the train_reduced_basis // call in the Offline stage rb_con.load_basis_function(0); #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(mesh).write_equation_systems ("bf0.e",equation_systems); #endif } } return 0; } <|endoftext|>
<commit_before>//C++ libs #include <iostream> #include <string> #include <queue> #include <vector> #include <algorithm> //C libs #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> using namespace std; const string cmd_delimiter = ";|&#"; void splice_input(queue<string> &cmds, queue<char> &conns, const string &input); bool run_command(string &input, char &conn); void tokenize(vector<char*> &comms, string &input); void trim_lead_and_trail(string &str); int main() { string input; char logic; queue<string> commands; queue<char> connectors; bool running = true; char *hostname = new char[20]; if(gethostname(hostname, 20) == -1) { perror("Error with getting hostname!"); } //Continue prompting while(1) { cout << getlogin() << "@" << hostname << "$ "; getline(cin, input); splice_input(commands, connectors, input); //After getting input from the user begin dequeing //until the queue of commands is empty or logic //returns to stop running while(!commands.empty() && running) { //Get command from queue input = commands.front(); commands.pop(); //Get connector from queue if(!connectors.empty()) { logic = connectors.front(); connectors.pop(); } //Check if input is exit //And begin handling command if(input.find("exit") == string::npos) running = run_command(input, logic); else exit(1); //Clear queues if(!running) { connectors = queue<char>(); commands = queue<string>(); } } //Reset running running = true; } return 0; } //Splits the commands and connectors into seperate queues. void splice_input(queue<string> &cmds, queue<char> &conns, const string &input) { int pos = 0; char logic; string new_cmd; string parse = input; while(pos != -1) { pos = parse.find_first_of(cmd_delimiter); new_cmd = parse.substr(0, pos); logic = parse[pos]; trim_lead_and_trail(new_cmd); if(logic == '&' || logic == '|') { if(parse[pos + 1] == logic) cmds.push(new_cmd); parse.erase(0, pos + 2); } else if(logic == ';') { if(parse[pos + 1] == logic) cmds.push(new_cmd); parse.erase(0, pos + 1); } else cmds.push(new_cmd); if(logic == '#') return; conns.push(logic); } } bool run_command(string &input, char &conn) { int pid = fork(); vector<char*> tokens; int status = 0; if(pid == -1) { perror("Error with fork()"); exit(1); } else if(pid == 0) { tokenize(tokens, input); char **cmds = &tokens[0]; execvp(cmds[0], cmds); perror("Execvp failed!"); exit(1); } else { wait(&status); //Deallocating memory for( size_t i = 0; i < tokens.size(); i++ ) delete tokens[i]; //Cleaning up vector tokens.clear(); //Checking if the connector was AND if(conn == '&') { //If the previous cmd failed stop running if(status > 0) return false; } //Checking if the connector was OR if(conn == '|') { //No need to continue running since first cmd was true if(status <= 0) return false; } } //Continue getting commands return true; } void tokenize(vector<char*> &comms, string &input) { string convert; string tokenizer = input; size_t pos = 0; trim_lead_and_trail(tokenizer); while(pos != string::npos ) { pos = tokenizer.find(' '); convert = pos == string::npos ? tokenizer \ : tokenizer.substr(0, pos); trim_lead_and_trail(convert); if(!convert.empty()) { char *tmp = new char[convert.length() + 1]; strcpy(tmp, convert.c_str()); comms.push_back(tmp); tokenizer.erase(0, pos + 1); } } comms.push_back(NULL); return; } void trim_lead_and_trail(string &str) { str.erase(str.begin(), std::find_if(str.begin(), str.end(), std::bind1st(std::not_equal_to<char>(), ' '))); str.erase(std::find_if(str.rbegin(), str.rend(), std::bind1st(std::not_equal_to<char>(), ' ')).base(), str.end()); } <commit_msg>Fixed bug introduced from previous patch<commit_after>//C++ libs #include <iostream> #include <string> #include <queue> #include <vector> #include <algorithm> //C libs #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> using namespace std; const string cmd_delimiter = ";|&#"; void splice_input(queue<string> &cmds, queue<char> &conns, const string &input); bool run_command(string &input, char &conn); void tokenize(vector<char*> &comms, string &input); void trim_lead_and_trail(string &str); int main() { string input; char logic; queue<string> commands; queue<char> connectors; bool running = true; char *hostname = new char[20]; if(gethostname(hostname, 20) == -1) { perror("Error with getting hostname!"); } //Continue prompting while(1) { cout << getlogin() << "@" << hostname << "$ "; getline(cin, input); splice_input(commands, connectors, input); //After getting input from the user begin dequeing //until the queue of commands is empty or logic //returns to stop running while(!commands.empty() && running) { //Get command from queue input = commands.front(); commands.pop(); //Get connector from queue if(!connectors.empty()) { logic = connectors.front(); connectors.pop(); } //Check if input is exit //And begin handling command if(input.find("exit") == string::npos) running = run_command(input, logic); else exit(1); //Clear queues if(!running) { connectors = queue<char>(); commands = queue<string>(); } } //Reset running running = true; } return 0; } //Splits the commands and connectors into seperate queues. void splice_input(queue<string> &cmds, queue<char> &conns, const string &input) { int pos = 0; char logic; string new_cmd; string parse = input; while(pos != -1) { pos = parse.find_first_of(cmd_delimiter); new_cmd = parse.substr(0, pos); logic = parse[pos]; trim_lead_and_trail(new_cmd); if(logic == '&' || logic == '|') { if(parse[pos + 1] == logic) cmds.push(new_cmd); parse.erase(0, pos + 2); } else if(logic == ';') { cmds.push(new_cmd); parse.erase(0, pos + 1); } else cmds.push(new_cmd); if(logic == '#') return; conns.push(logic); } } bool run_command(string &input, char &conn) { int pid = fork(); vector<char*> tokens; int status = 0; if(pid == -1) { perror("Error with fork()"); exit(1); } else if(pid == 0) { tokenize(tokens, input); char **cmds = &tokens[0]; execvp(cmds[0], cmds); perror("Execvp failed!"); exit(1); } else { wait(&status); //Deallocating memory for( size_t i = 0; i < tokens.size(); i++ ) delete tokens[i]; //Cleaning up vector tokens.clear(); //Checking if the connector was AND if(conn == '&') { //If the previous cmd failed stop running if(status > 0) return false; } //Checking if the connector was OR if(conn == '|') { //No need to continue running since first cmd was true if(status <= 0) return false; } } //Continue getting commands return true; } void tokenize(vector<char*> &comms, string &input) { string convert; string tokenizer = input; size_t pos = 0; trim_lead_and_trail(tokenizer); while(pos != string::npos ) { pos = tokenizer.find(' '); convert = pos == string::npos ? tokenizer \ : tokenizer.substr(0, pos); trim_lead_and_trail(convert); if(!convert.empty()) { char *tmp = new char[convert.length() + 1]; strcpy(tmp, convert.c_str()); comms.push_back(tmp); tokenizer.erase(0, pos + 1); } } comms.push_back(NULL); return; } void trim_lead_and_trail(string &str) { str.erase(str.begin(), std::find_if(str.begin(), str.end(), std::bind1st(std::not_equal_to<char>(), ' '))); str.erase(std::find_if(str.rbegin(), str.rend(), std::bind1st(std::not_equal_to<char>(), ' ')).base(), str.end()); } <|endoftext|>
<commit_before>#include <algorithm> #include <boost/tokenizer.hpp> #include <iostream> #include <list> #include <map> #include <memory> #include <sstream> #include <stdio.h> #include <string.h> #include <string> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <vector> #include <pwd.h> const std::multimap<std::string, int> DEFINED_OPS = { std::make_pair("&", 2), std::make_pair("|", 2), std::make_pair(";", 1) }; const std::vector<std::string> IMPLEMENTED_OPS{ "&&", "||", ";" }; // handles what to do with finalized input state void Execute(std::list<std::string> &input); // assumes an operator in the first position of the input list // extracts and pops it for determination of shell command flow bool UseOperator(std::list<std::string> &input, bool prevcommandstate); // used when an UseOperator returns false ie asdf && ls // the first command is false and && must force a properly inputted second // command // to not execute. the command is extracted from the input list and nothing // is done with it. void DumpCommand(std::list<std::string> &input); // assumes non operator in first position of the list // tokens are extracted from the list until an operator or the end of // the list is reached. the command is forked and execvp'd bool UseCommand(std::list<std::string> &input); // helper function that searched through global const IMPLEMENTED_OPS // checks inputted string to see if it matches any within the vector bool ContainsImplementedOp(std::string token); // Returns true on >1 operators occuring back to back // e.g. "&&&&&", ";;", etc. bool FoundRepeat(const std::list<std::string> &input); // assumes all like-operators have been merged together // this finds 'strings' of operators that are too long // rebuilds a std pair from the global const map DEFINED_OPS // uses it as param to string::find on each element of the input list // if its found that means it CONTAINS the operator. checking if it // doesn't equal at this point means it's using operator symbols of an // incorrect type. bool InvalidRepeatOp(const std::list<std::string> &input, std::pair<std::string, int> op); // helper function that calls RebuildOps with each element of global const // DEFINED_OPS as 2nd parameter (the single instances of & | ;) void CombineDefinedOps(std::list<std::string> &input); // unused check for unimplemented operators bool UnimplementedOp(const std::list<std::string> &input, std::string op); // uses unix calls to get username and hostname // returns 'shellish' formatted str ie usrname@host:~$ std::string UserHostInfo(); // output username@hostname$ and wait for command input std::string Prompt(); // separates string by delimeters into vector elements // if # is found it excludes it and anything beyond in the string std::list<std::string> Split(const std::string &input); // debugging inputlist outputter void Output(std::list<std::string> &input); // takes the input list and an operator character and merges all repeating // instances of that character within the list // operators in shell can use the same symbol a different amount of times to // represent different things // ie bitwise & vs and && // the delimiter method I used to separate the arguments in the first place only // had single character delimiting available // since the function is general it will: // avoid having to create new handcrafted parses when more features have to be // added // make bug checking general and simple (is & implemented? is &&& implemented? // if not theyre bugs) void RebuildOps(std::list<std::string> &input, std::string op); // does a search in input list for a known operator and checks if the next // element is also // a known operator. bool FoundAdjOp(std::list<std::string> &input); int main() { while (true) { auto cmd = Prompt(); auto input = Split(cmd); CombineDefinedOps(input); Execute(input); } } std::string UserHostInfo() { auto userinfo = getpwuid(getuid()); if (errno != 0) { perror("error in getpwuid"); exit(1); } std::string login(userinfo->pw_name); char *rawhost = new char[100]; auto status = gethostname(rawhost, 100); if (status == -1) { perror("gethostname failed"); } std::string hostname(rawhost); delete[] rawhost; char *rawpwd = get_current_dir_name(); if (rawpwd == NULL) { perror("get_current_dir_name returned NULL"); exit(1); } std::string pwd(rawpwd); delete rawpwd; // handles /home/username -> ~/ shortcut std::string target = userinfo->pw_dir; if (pwd.find(target) == 0) { pwd.erase(0, target.size()); pwd = "~" + pwd; } return login + "@" + hostname + ":" + pwd + "$ "; } std::string Prompt() { std::cout << "->" << UserHostInfo(); std::string input; std::getline(std::cin, input); return input; } std::list<std::string> Split(const std::string &input) { using namespace boost; using namespace std; list<string> input_split; char_separator<char> sep(" ", "#&|;"); typedef tokenizer<char_separator<char> > tokener; tokener tokens(input, sep); // complexity increases if I handle # as bash does. for (const auto &t : tokens) { if (t == "#") break; input_split.push_back(t); } return input_split; } void Output(std::list<std::string> &input) { using namespace std; for (const auto &e : input) cout << e << endl; } void RebuildOps(std::list<std::string> &input, std::string op) { using namespace std; auto front = input.begin(); auto back = input.end(); while (front != back) { auto element = find(front, back, op); int count = 0; while (element != back) { if (*element == op) { element = input.erase(element); count++; } else { break; } } std::string tempstr = ""; while (count--) { tempstr += op; } if (!tempstr.empty()) front = input.insert(element, tempstr); front++; } } void CombineDefinedOps(std::list<std::string> &input) { for (const auto &op : DEFINED_OPS) { RebuildOps(input, op.first); } } bool FoundRepeat(const std::list<std::string> &input) { using namespace std; for (const auto &op : DEFINED_OPS) { if (InvalidRepeatOp(input, op)) { cout << "Invalid '" << op.first << "' usage found" << endl << "known operator used an invalid amount of consecutive" << endl << "times: e.g. '&&&' -> '&&' ?" << endl; return true; } } return false; } bool InvalidRepeatOp(const std::list<std::string> &input, std::pair<std::string, int> pair) { std::string rebuilt_op = ""; auto op_size = pair.second; while (op_size--) { rebuilt_op += pair.first; } auto front = input.begin(); auto back = input.end(); while (front != back) { auto itr = std::find_if(front, back, [&](std::string elem) { if (elem.find(rebuilt_op) == std::string::npos) return false; else return true; }); if (itr == back) return false; else if (*itr != rebuilt_op) break; else { front = itr; front++; } } return true; } bool UnimplementedOp(const std::list<std::string> &input, std::string op) { using namespace std; auto itr = find(input.begin(), input.end(), op); if (itr == input.end()) { cout << "operator '" << op << "' is unimplemented" << endl; return false; } return true; } bool UseCommand(std::list<std::string> &input) { using namespace std; // Take list of strings, make copies of their c_strs, and put into vector // a vector of char* can be used as char** if used as such vector<char *> vectorcommand; while (!input.empty() && !ContainsImplementedOp(input.front())) { string transferstr = input.front(); input.pop_front(); char *cstrcopy = new char[transferstr.size() + 1]; memcpy(cstrcopy, transferstr.c_str(), transferstr.size() + 1); cstrcopy[transferstr.size()] = 0; vectorcommand.push_back(cstrcopy); } vectorcommand.push_back(NULL); char **rawcommand = &vectorcommand[0]; int exitvalue = 0; auto pid = fork(); if (pid == -1) { perror("Error on fork"); exit(1); } // child state else if (pid == 0) { execvp(rawcommand[0], rawcommand); if (errno != 0) { perror("Error in execvp. Likely a nonexisting command?"); exit(1); } for (size_t i = 0; i < vectorcommand.size(); i++) delete[] rawcommand[i]; } // parent else { int status; auto wait_val = wait(&status); if (wait_val == -1) { perror("Error on waiting for child process to finish"); exit(1); } exitvalue = WEXITSTATUS(status); for (size_t i = 0; i < vectorcommand.size(); i++) delete[] rawcommand[i]; } if (exitvalue == 0) return true; else return false; } bool ContainsImplementedOp(std::string token) { auto match = find(IMPLEMENTED_OPS.begin(), IMPLEMENTED_OPS.end(), token); if (match != IMPLEMENTED_OPS.end()) return true; return false; } bool UseOperator(std::list<std::string> &input, bool prevcommandstate) { using namespace std; if (input.empty()) return false; string op = input.front(); input.pop_front(); if (prevcommandstate == true) { if (op == ";") return true; else if (op == "&&") return true; else if (op == "||") return false; } else { if (op == ";") return true; else if (op == "&&") return false; else if (op == "||") return true; } // proper input ensures we never get down here, so im killing warning message // fixing this 'properly' would make it annoying to add more operators later cout << "what in god's name" << endl; return false; } void Execute(std::list<std::string> &input) { if (input.empty() || FoundRepeat(input) || FoundAdjOp(input)) return; bool cmdstate = true; while (!input.empty()) { if (input.front() == "exit") exit(0); if (cmdstate) cmdstate = UseCommand(input); else DumpCommand(input); cmdstate = UseOperator(input, cmdstate); } } void DumpCommand(std::list<std::string> &input) { while (!input.empty() && !ContainsImplementedOp(input.front())) { input.pop_front(); } } bool FoundAdjOp(std::list<std::string> &input) { using namespace std; for (const auto &op : IMPLEMENTED_OPS) { auto element = input.begin(); auto front = input.begin(); auto next = input.begin(); auto back = input.end(); while (element != input.end()) { element = find(front, back, op); if (element == input.end()) continue; next = element; next++; if (next == input.end()) continue; else if (find(IMPLEMENTED_OPS.begin(), IMPLEMENTED_OPS.end(), *next) != IMPLEMENTED_OPS.end()) { cout << "Two operators are adjacent to each other e.g. '&&;' ?" << endl; return true; } front = next; front++; } } return false; } <commit_msg>> >> and < work<commit_after>#include <fcntl.h> #include <algorithm> #include <boost/tokenizer.hpp> #include <iostream> #include <list> #include <map> #include <memory> #include <sstream> #include <stdio.h> #include <string.h> #include <string> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <vector> #include <pwd.h> const std::multimap<std::string, int> DEFINED_OPS = { std::make_pair("&", 2), std::make_pair("|", 2), std::make_pair(";", 1), std::make_pair("<", 1), std::make_pair(">", 2) }; const std::vector<std::string> IMPLEMENTED_OPS{ "&&", "||", ";", "|", ">>", ">", "<" }; void PeekForRedirection(std::list<std::string> &input); // handles what to do with finalized input state void Execute(std::list<std::string> &input); // assumes an operator in the first position of the input list // extracts and pops it for determination of shell command flow bool UseOperator(std::list<std::string> &input, bool prevcommandstate); // used when an UseOperator returns false ie asdf && ls // the first command is false and && must force a properly inputted second // command // to not execute. the command is extracted from the input list and nothing // is done with it. void DumpCommand(std::list<std::string> &input); // assumes non operator in first position of the list // tokens are extracted from the list until an operator or the end of // the list is reached. the command is forked and execvp'd bool UseCommand(std::list<std::string> &input); // helper function that searched through global const IMPLEMENTED_OPS // checks inputted string to see if it matches any within the vector bool ContainsImplementedOp(std::string token); // Returns true on >1 operators occuring back to back // e.g. "&&&&&", ";;", etc. bool FoundRepeat(const std::list<std::string> &input); // assumes all like-operators have been merged together // this finds 'strings' of operators that are too long // rebuilds a std pair from the global const map DEFINED_OPS // uses it as param to string::find on each element of the input list // if its found that means it CONTAINS the operator. checking if it // doesn't equal at this point means it's using operator symbols of an // incorrect type. bool InvalidRepeatOp(const std::list<std::string> &input, std::pair<std::string, int> op); // helper function that calls with each element of global const // DEFINED_OPS as 2nd parameter (the single instances of & | ;) void CombineDefinedOps(std::list<std::string> &input); // unused check for unimplemented operators bool UnimplementedOp(const std::list<std::string> &input, std::string op); // uses unix calls to get username and hostname // returns 'shellish' formatted str ie usrname@host:~$ std::string UserHostInfo(); // output username@hostname$ and wait for command input std::string Prompt(); // separates string by delimeters into vector elements // if # is found it excludes it and anything beyond in the string std::list<std::string> Split(const std::string &input); // debugging inputlist outputter void Output(std::list<std::string> &input); // takes the input list and an operator character and merges all repeating // instances of that character within the list // operators in shell can use the same symbol a different amount of times to // represent different things // ie bitwise & vs and && // the delimiter method I used to separate the arguments in the first place only // had single character delimiting available // since the function is general it will: // avoid having to create new handcrafted parses when more features have to be // added // make bug checking general and simple (is & implemented? is &&& implemented? // if not theyre bugs) void RebuildOps(std::list<std::string> &input, std::string op); // does a search in input list for a known operator and checks if the next // element is also // a known operator. bool FoundAdjOp(std::list<std::string> &input); int main() { while (true) { auto cmd = Prompt(); auto input = Split(cmd); CombineDefinedOps(input); Execute(input); } } std::string UserHostInfo() { auto userinfo = getpwuid(getuid()); if (errno != 0) { perror("error in getpwuid"); exit(1); } std::string login(userinfo->pw_name); char *rawhost = new char[100]; auto status = gethostname(rawhost, 100); if (status == -1) { perror("gethostname failed"); } std::string hostname(rawhost); delete[] rawhost; char *rawpwd = get_current_dir_name(); if (rawpwd == NULL) { perror("get_current_dir_name returned NULL"); exit(1); } std::string pwd(rawpwd); delete rawpwd; // handles /home/username -> ~/ shortcut std::string target = userinfo->pw_dir; if (pwd.find(target) == 0) { pwd.erase(0, target.size()); pwd = "~" + pwd; } return login + "@" + hostname + ":" + pwd + "$ "; } std::string Prompt() { std::cout << "->" << UserHostInfo(); std::string input; std::getline(std::cin, input); return input; } std::list<std::string> Split(const std::string &input) { using namespace boost; using namespace std; list<string> input_split; char_separator<char> sep(" ", "#&|;><"); typedef tokenizer<char_separator<char> > tokener; tokener tokens(input, sep); // complexity increases if I handle # as bash does. for (const auto &t : tokens) { if (t == "#") break; input_split.push_back(t); } return input_split; } void Output(std::list<std::string> &input) { using namespace std; for (const auto &e : input) cout << e << endl; } void RebuildOps(std::list<std::string> &input, std::string op) { using namespace std; auto front = input.begin(); auto back = input.end(); while (front != back) { auto element = find(front, back, op); int count = 0; while (element != back) { if (*element == op) { element = input.erase(element); count++; } else { break; } } std::string tempstr = ""; while (count--) { tempstr += op; } if (!tempstr.empty()) front = input.insert(element, tempstr); front++; } } void CombineDefinedOps(std::list<std::string> &input) { for (const auto &op : DEFINED_OPS) { RebuildOps(input, op.first); } } bool FoundRepeat(const std::list<std::string> &input) { using namespace std; for (const auto &op : DEFINED_OPS) { if (InvalidRepeatOp(input, op)) { cout << "Invalid '" << op.first << "' usage found" << endl << "known operator used an invalid amount of consecutive" << endl << "times: e.g. '&&&' -> '&&' ?" << endl; return true; } } return false; } bool InvalidRepeatOp(const std::list<std::string> &input, std::pair<std::string, int> pair) { std::string rebuilt_op = ""; auto op_size = pair.second; while (op_size--) { rebuilt_op += pair.first; } auto front = input.begin(); auto back = input.end(); while (front != back) { auto itr = std::find_if(front, back, [&](std::string elem) { if (elem.find(rebuilt_op) == std::string::npos) return false; else return true; }); if (itr == back) return false; else if (*itr != rebuilt_op) break; else { front = itr; front++; } } return true; } bool UnimplementedOp(const std::list<std::string> &input, std::string op) { using namespace std; auto itr = find(input.begin(), input.end(), op); if (itr == input.end()) { cout << "operator '" << op << "' is unimplemented" << endl; return false; } return true; } bool UseCommand(std::list<std::string> &input) { using namespace std; // Take list of strings, make copies of their c_strs, and put into vector // a vector of char* can be used as char** if used as such vector<char *> vectorcommand; while (!input.empty() && !ContainsImplementedOp(input.front())) { string transferstr = input.front(); input.pop_front(); char *cstrcopy = new char[transferstr.size() + 1]; memcpy(cstrcopy, transferstr.c_str(), transferstr.size() + 1); cstrcopy[transferstr.size()] = 0; vectorcommand.push_back(cstrcopy); } vectorcommand.push_back(NULL); char **rawcommand = &vectorcommand[0]; int exitvalue = 0; auto pid = fork(); if (pid == -1) { perror("Error on fork"); exit(1); } // child state else if (pid == 0) { //TODO search operators inplace of input vector? if (!input.empty()) { PeekForRedirection(input); } execvp(rawcommand[0], rawcommand); if (errno != 0) { perror("Error in execvp. Likely a nonexisting command?"); exit(1); } for (size_t i = 0; i < vectorcommand.size(); i++) delete[] rawcommand[i]; } // parent else { int status; auto wait_val = wait(&status); if (wait_val == -1) { perror("Error on waiting for child process to finish"); exit(1); } exitvalue = WEXITSTATUS(status); for (size_t i = 0; i < vectorcommand.size(); i++) delete[] rawcommand[i]; } if (exitvalue == 0) return true; else return false; } bool ContainsImplementedOp(std::string token) { auto match = find(IMPLEMENTED_OPS.begin(), IMPLEMENTED_OPS.end(), token); if (match != IMPLEMENTED_OPS.end()) return true; return false; } bool UseOperator(std::list<std::string> &input, bool prevcommandstate) { using namespace std; if (input.empty()) return false; string op = input.front(); input.pop_front(); if (prevcommandstate == true) { if (op == ";") return true; else if (op == "&&") return true; else if (op == "||") return false; } else { if (op == ";") return true; else if (op == "&&") return false; else if (op == "||") return true; } // proper input ensures we never get down here, so im killing warning message // fixing this 'properly' would make it annoying to add more operators later //TODO make that not wrong^ return true; } void Execute(std::list<std::string> &input) { if (input.empty() || FoundRepeat(input) || FoundAdjOp(input)) return; bool cmdstate = true; while (!input.empty()) { if (input.front() == "exit") exit(0); if (cmdstate) { cmdstate = UseCommand(input); } else DumpCommand(input); cmdstate = UseOperator(input, cmdstate); } } void DumpCommand(std::list<std::string> &input) { while (!input.empty() && !ContainsImplementedOp(input.front())) { input.pop_front(); } } bool FoundAdjOp(std::list<std::string> &input) { using namespace std; for (const auto &op : IMPLEMENTED_OPS) { auto element = input.begin(); auto front = input.begin(); auto next = input.begin(); auto back = input.end(); while (element != input.end()) { element = find(front, back, op); if (element == input.end()) continue; next = element; next++; if (next == input.end()) continue; else if (find(IMPLEMENTED_OPS.begin(), IMPLEMENTED_OPS.end(), *next) != IMPLEMENTED_OPS.end()) { cout << "Two operators are adjacent to each other e.g. '&&;' ?" << endl; return true; } front = next; front++; } } return false; } void PeekForRedirection(std::list<std::string> &input) { std::string op = input.front(); input.pop_front(); std::string target = input.front(); input.pop_front(); int fd = -1; if (op == ">") { fd = open(target.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0644); close(1); dup2(fd, 1); } else if (op == ">>") { fd = open(target.c_str(), O_RDWR | O_CREAT | O_APPEND, 0644); close(1); dup2(fd, 1); } else if (op == "<") { fd = open(target.c_str(), O_RDONLY, 0644); close(0); dup2(fd, 0); } } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "KytheVFS.h" #include "kythe/cxx/common/proto_conversions.h" #include "llvm/Support/Path.h" #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" namespace kythe { IndexVFS::IndexVFS(const std::string &working_directory, const std::vector<proto::FileData> &virtual_files) : virtual_files_(virtual_files), working_directory_(working_directory) { assert(llvm::sys::path::is_absolute(working_directory) && "Working directory must be absolute."); for (const auto &data : virtual_files_) { if (auto *record = FileRecordForPath(ToStringRef(data.info().path()), BehaviorOnMissing::kCreateFile, data.content().size())) { record->data = llvm::StringRef(data.content()); } } } IndexVFS::~IndexVFS() { for (auto &entry : uid_to_record_map_) { delete entry.second; } } llvm::ErrorOr<clang::vfs::Status> IndexVFS::status(const llvm::Twine &path) { if (const auto *record = FileRecordForPath(path.str(), BehaviorOnMissing::kReturnError, 0)) { return record->status; } return make_error_code(llvm::errc::no_such_file_or_directory); } llvm::ErrorOr<std::unique_ptr<clang::vfs::File>> IndexVFS::openFileForRead( const llvm::Twine &path) { if (FileRecord *record = FileRecordForPath(path.str(), BehaviorOnMissing::kReturnError, 0)) { if (record->status.getType() == llvm::sys::fs::file_type::regular_file) { return std::unique_ptr<clang::vfs::File>(new File(record)); } } return make_error_code(llvm::errc::no_such_file_or_directory); } clang::vfs::directory_iterator IndexVFS::dir_begin( const llvm::Twine &dir, std::error_code &error_code) { llvm_unreachable("unimplemented"); } void IndexVFS::SetVName(const std::string &path, const proto::VName &vname) { if (FileRecord *record = FileRecordForPath(path, BehaviorOnMissing::kReturnError, 0)) { if (record->status.getType() == llvm::sys::fs::file_type::regular_file) { record->vname.CopyFrom(vname); record->has_vname = true; } } } bool IndexVFS::get_vname(const clang::FileEntry *entry, proto::VName *merge_with) { auto record = uid_to_record_map_.find(entry->getUniqueID()); if (record != uid_to_record_map_.end()) { if (record->second->status.getType() == llvm::sys::fs::file_type::regular_file && record->second->has_vname) { merge_with->CopyFrom(record->second->vname); return true; } } return false; } std::string IndexVFS::get_debug_uid_string(const llvm::sys::fs::UniqueID &uid) { auto record = uid_to_record_map_.find(uid); if (record != uid_to_record_map_.end()) { return record->second->status.getName(); } return "uid(device: " + std::to_string(uid.getDevice()) + " file: " + std::to_string(uid.getFile()) + ")"; } IndexVFS::FileRecord *IndexVFS::FileRecordForPathRoot(const llvm::Twine &path, bool create_if_missing) { std::string path_str(path.str()); bool is_absolute = true; auto root_name = llvm::sys::path::root_name(path_str); if (root_name.empty()) { root_name = llvm::sys::path::root_name(working_directory_); if (!root_name.empty()) { // This index comes from a filesystem with significant root names. is_absolute = false; } } auto root_dir = llvm::sys::path::root_directory(path_str); if (root_dir.empty()) { root_dir = llvm::sys::path::root_directory(working_directory_); is_absolute = false; } if (!is_absolute) { // This terminates: the working directory must be an absolute path. return FileRecordForPath(working_directory_, create_if_missing ? BehaviorOnMissing::kCreateDirectory : BehaviorOnMissing::kReturnError, 0); } FileRecord *name_record = nullptr; auto name_found = root_name_to_root_map_.find(root_name); if (name_found != root_name_to_root_map_.end()) { name_record = name_found->second; } else if (!create_if_missing) { return nullptr; } else { name_record = new FileRecord( {clang::vfs::Status( root_name, root_name, clang::vfs::getNextVirtualUniqueID(), llvm::sys::TimeValue(), 0, 0, 0, llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_read), false, root_name}); root_name_to_root_map_[root_name] = name_record; uid_to_record_map_[name_record->status.getUniqueID()] = name_record; } return AllocOrReturnFileRecord(name_record, create_if_missing, root_dir, llvm::sys::fs::file_type::directory_file, 0); } IndexVFS::FileRecord *IndexVFS::FileRecordForPath(const llvm::StringRef path, BehaviorOnMissing behavior, size_t size) { using namespace llvm::sys::path; std::vector<llvm::StringRef> path_components; int skip_count = 0; auto eventual_type = (behavior == BehaviorOnMissing::kCreateFile ? llvm::sys::fs::file_type::regular_file : llvm::sys::fs::file_type::directory_file); bool create_if_missing = (behavior != BehaviorOnMissing::kReturnError); size_t eventual_size = (behavior == BehaviorOnMissing::kCreateFile ? size : 0); for (auto node = llvm::sys::path::rbegin(path), node_end = rend(path); node != node_end; ++node) { if (*node == "..") { ++skip_count; } else if (*node != ".") { if (skip_count > 0) { --skip_count; } else { path_components.push_back(*node); } } } FileRecord *current_record = FileRecordForPathRoot(path, create_if_missing); for (auto node = path_components.crbegin(), node_end = path_components.crend(); current_record != nullptr && node != node_end;) { llvm::StringRef label = *node; bool is_last = (++node == node_end); current_record = AllocOrReturnFileRecord( current_record, create_if_missing, label, is_last ? eventual_type : llvm::sys::fs::file_type::directory_file, is_last ? eventual_size : 0); } return current_record; } IndexVFS::FileRecord *IndexVFS::AllocOrReturnFileRecord( FileRecord *parent, bool create_if_missing, llvm::StringRef label, llvm::sys::fs::file_type type, size_t size) { assert(parent != nullptr); for (auto &record : parent->children) { if (record->label == label) { if (create_if_missing && (record->status.getSize() != size || record->status.getType() != type)) { fprintf(stderr, "Warning: path %s/%s: defined inconsistently (%d/%d)\n", parent->status.getName().str().c_str(), label.str().c_str(), type, record->status.getType()); return nullptr; } return record; } } if (!create_if_missing) { return nullptr; } llvm::SmallString<1024> out_path(llvm::StringRef(parent->status.getName())); llvm::sys::path::append(out_path, label); FileRecord *new_record = new FileRecord{ clang::vfs::Status( out_path, out_path, clang::vfs::getNextVirtualUniqueID(), llvm::sys::TimeValue(), 0, 0, size, type, llvm::sys::fs::all_read), false, label}; parent->children.push_back(new_record); uid_to_record_map_[new_record->status.getUniqueID()] = new_record; return new_record; } } // namespace kythe <commit_msg>Make a conversion to StringRef explicit.<commit_after>/* * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "KytheVFS.h" #include "kythe/cxx/common/proto_conversions.h" #include "llvm/Support/Path.h" #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" namespace kythe { IndexVFS::IndexVFS(const std::string &working_directory, const std::vector<proto::FileData> &virtual_files) : virtual_files_(virtual_files), working_directory_(working_directory) { assert(llvm::sys::path::is_absolute(working_directory) && "Working directory must be absolute."); for (const auto &data : virtual_files_) { if (auto *record = FileRecordForPath(ToStringRef(data.info().path()), BehaviorOnMissing::kCreateFile, data.content().size())) { record->data = llvm::StringRef(data.content().data(), data.content().size()); } } } IndexVFS::~IndexVFS() { for (auto &entry : uid_to_record_map_) { delete entry.second; } } llvm::ErrorOr<clang::vfs::Status> IndexVFS::status(const llvm::Twine &path) { if (const auto *record = FileRecordForPath(path.str(), BehaviorOnMissing::kReturnError, 0)) { return record->status; } return make_error_code(llvm::errc::no_such_file_or_directory); } llvm::ErrorOr<std::unique_ptr<clang::vfs::File>> IndexVFS::openFileForRead( const llvm::Twine &path) { if (FileRecord *record = FileRecordForPath(path.str(), BehaviorOnMissing::kReturnError, 0)) { if (record->status.getType() == llvm::sys::fs::file_type::regular_file) { return std::unique_ptr<clang::vfs::File>(new File(record)); } } return make_error_code(llvm::errc::no_such_file_or_directory); } clang::vfs::directory_iterator IndexVFS::dir_begin( const llvm::Twine &dir, std::error_code &error_code) { llvm_unreachable("unimplemented"); } void IndexVFS::SetVName(const std::string &path, const proto::VName &vname) { if (FileRecord *record = FileRecordForPath(path, BehaviorOnMissing::kReturnError, 0)) { if (record->status.getType() == llvm::sys::fs::file_type::regular_file) { record->vname.CopyFrom(vname); record->has_vname = true; } } } bool IndexVFS::get_vname(const clang::FileEntry *entry, proto::VName *merge_with) { auto record = uid_to_record_map_.find(entry->getUniqueID()); if (record != uid_to_record_map_.end()) { if (record->second->status.getType() == llvm::sys::fs::file_type::regular_file && record->second->has_vname) { merge_with->CopyFrom(record->second->vname); return true; } } return false; } std::string IndexVFS::get_debug_uid_string(const llvm::sys::fs::UniqueID &uid) { auto record = uid_to_record_map_.find(uid); if (record != uid_to_record_map_.end()) { return record->second->status.getName(); } return "uid(device: " + std::to_string(uid.getDevice()) + " file: " + std::to_string(uid.getFile()) + ")"; } IndexVFS::FileRecord *IndexVFS::FileRecordForPathRoot(const llvm::Twine &path, bool create_if_missing) { std::string path_str(path.str()); bool is_absolute = true; auto root_name = llvm::sys::path::root_name(path_str); if (root_name.empty()) { root_name = llvm::sys::path::root_name(working_directory_); if (!root_name.empty()) { // This index comes from a filesystem with significant root names. is_absolute = false; } } auto root_dir = llvm::sys::path::root_directory(path_str); if (root_dir.empty()) { root_dir = llvm::sys::path::root_directory(working_directory_); is_absolute = false; } if (!is_absolute) { // This terminates: the working directory must be an absolute path. return FileRecordForPath(working_directory_, create_if_missing ? BehaviorOnMissing::kCreateDirectory : BehaviorOnMissing::kReturnError, 0); } FileRecord *name_record = nullptr; auto name_found = root_name_to_root_map_.find(root_name); if (name_found != root_name_to_root_map_.end()) { name_record = name_found->second; } else if (!create_if_missing) { return nullptr; } else { name_record = new FileRecord( {clang::vfs::Status( root_name, root_name, clang::vfs::getNextVirtualUniqueID(), llvm::sys::TimeValue(), 0, 0, 0, llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_read), false, root_name}); root_name_to_root_map_[root_name] = name_record; uid_to_record_map_[name_record->status.getUniqueID()] = name_record; } return AllocOrReturnFileRecord(name_record, create_if_missing, root_dir, llvm::sys::fs::file_type::directory_file, 0); } IndexVFS::FileRecord *IndexVFS::FileRecordForPath(const llvm::StringRef path, BehaviorOnMissing behavior, size_t size) { using namespace llvm::sys::path; std::vector<llvm::StringRef> path_components; int skip_count = 0; auto eventual_type = (behavior == BehaviorOnMissing::kCreateFile ? llvm::sys::fs::file_type::regular_file : llvm::sys::fs::file_type::directory_file); bool create_if_missing = (behavior != BehaviorOnMissing::kReturnError); size_t eventual_size = (behavior == BehaviorOnMissing::kCreateFile ? size : 0); for (auto node = llvm::sys::path::rbegin(path), node_end = rend(path); node != node_end; ++node) { if (*node == "..") { ++skip_count; } else if (*node != ".") { if (skip_count > 0) { --skip_count; } else { path_components.push_back(*node); } } } FileRecord *current_record = FileRecordForPathRoot(path, create_if_missing); for (auto node = path_components.crbegin(), node_end = path_components.crend(); current_record != nullptr && node != node_end;) { llvm::StringRef label = *node; bool is_last = (++node == node_end); current_record = AllocOrReturnFileRecord( current_record, create_if_missing, label, is_last ? eventual_type : llvm::sys::fs::file_type::directory_file, is_last ? eventual_size : 0); } return current_record; } IndexVFS::FileRecord *IndexVFS::AllocOrReturnFileRecord( FileRecord *parent, bool create_if_missing, llvm::StringRef label, llvm::sys::fs::file_type type, size_t size) { assert(parent != nullptr); for (auto &record : parent->children) { if (record->label == label) { if (create_if_missing && (record->status.getSize() != size || record->status.getType() != type)) { fprintf(stderr, "Warning: path %s/%s: defined inconsistently (%d/%d)\n", parent->status.getName().str().c_str(), label.str().c_str(), type, record->status.getType()); return nullptr; } return record; } } if (!create_if_missing) { return nullptr; } llvm::SmallString<1024> out_path(llvm::StringRef(parent->status.getName())); llvm::sys::path::append(out_path, label); FileRecord *new_record = new FileRecord{ clang::vfs::Status( out_path, out_path, clang::vfs::getNextVirtualUniqueID(), llvm::sys::TimeValue(), 0, 0, size, type, llvm::sys::fs::all_read), false, label}; parent->children.push_back(new_record); uid_to_record_map_[new_record->status.getUniqueID()] = new_record; return new_record; } } // namespace kythe <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <string> #include <memory> #include <vector> #include <sstream> #include <boost/tokenizer.hpp> std::string UserHostInfo(); void Prompt(); void Parse(const char** argslist); std::vector<std::string> ParseDashArg(const std::string& dashlist); bool ContainsHome(const std::string& pwd, const std::string& loginname); int main() { std::string list = "ls"; const char** test = new const char*[10]; //execvp(list.c_str(), args); } //uses unix calls to get username and hostname //returns 'shellish' formatted str ie U@H: std::string UserHostInfo() { std::string loginname(getlogin()); char* rawhost= new char[100]; gethostname(rawhost,100); std::string hostname(rawhost); delete [] rawhost; std::string cwd(get_current_dir_name()); if(ContainsHome) std::cout << "hey"; return loginname+"@"+hostname+":"+cwd+"$ "; } bool ContainsHome(const std::string& pwd, const std::string& loginname) { std::string target = "/home/"+loginname+"/"; if (pwd.find(target) == 0) return true; return false; } void ArgsFill(const char** argslist) { } void Prompt() { std::cout << UserHostInfo(); std::string input; std::cin >> input; } std::vector<std::string> ParseDashArg(const std::string& dashlist) { } <commit_msg>fix tinkerings to make it build-- more formal from here on out<commit_after>#include <iostream> #include <unistd.h> #include <string> #include <memory> #include <vector> #include <sstream> #include <boost/tokenizer.hpp> std::string UserHostInfo(); void Prompt(); bool ContainsHome(const std::string& pwd, const std::string& loginname); int main() { std::cout << UserHostInfo(); //execvp(list.c_str(), args); } //uses unix calls to get username and hostname //returns 'shellish' formatted str ie U@H: std::string UserHostInfo() { std::string loginname(getlogin()); char* rawhost= new char[100]; gethostname(rawhost,100); std::string hostname(rawhost); delete [] rawhost; std::string cwd(get_current_dir_name()); if(ContainsHome(cwd, loginname)) std::cout << "hey"; return loginname+"@"+hostname+":"+cwd+"$ "; } bool ContainsHome(const std::string& pwd, const std::string& loginname) { std::string target = "/home/"+loginname+"/"; if (pwd.find(target) == 0) { return true; } return false; } void Prompt() { std::cout << UserHostInfo(); std::string input; std::cin >> input; } <|endoftext|>
<commit_before>#include "catch.hpp" #include "../src/population.hpp" #include "../src/random.hpp" #include "../src/sequence.hpp" TEST_CASE( "Test for random", "[random]" ) { random::set_seed(1); SECTION ( "random float inside range" ) { float rand_f = random::f_range(0, 0.5); REQUIRE(rand_f < 0.5); REQUIRE(rand_f > 0.0); } SECTION ( "random integer inside positive range" ) { int rand_i = random::i_range(0, 5); REQUIRE(rand_i <= 5); REQUIRE(rand_i >= 0); } SECTION ( "random integer inside negative range" ) { int rand_i = random::i_range(-10, -5); REQUIRE(rand_i <= -5); REQUIRE(rand_i >= -10); } SECTION ( "random integer range with both" ) { int rand_neg = random::i_range(-5, 5); REQUIRE(rand_neg <= 5); REQUIRE(rand_neg >= -5); } SECTION ( "repeat random integers not equal" ) { int rand_1 = random::i_range(0, 100); int rand_2 = random::i_range(0, 100); REQUIRE(rand_1 != rand_2); } SECTION ( "random reset produces repeatable results" ) { random::reset(); int rand_1 = random::i_range(0, 100); random::reset(); int rand_2 = random::i_range(0, 100); REQUIRE(rand_1 == rand_2); } SECTION ( "different seeds, different results" ) { random::set_seed(2); int rand_1 = random::i_range(0, 100); random::set_seed(3); int rand_2 = random::i_range(0, 100); REQUIRE(rand_1 != rand_2); } } TEST_CASE( "Test for genetic::sequence", "[sequence]" ) { // Predictable random tests (that passed before) random::set_seed(1); SECTION ( "genes of two rand inits are different" ) { genetic::sequence a, b; // Two random individuals don't match REQUIRE_FALSE(a == b); REQUIRE_FALSE(a.get_fitness() == b.get_fitness()); } SECTION ( "mutations with different rates" ) { // Copy constructor genetic::sequence a; genetic::sequence a_dup = a; REQUIRE(a_dup == a); // Mutate (0 = none) a.mutate(0.0); REQUIRE(a_dup == a); REQUIRE(a_dup.get_fitness() == a.get_fitness()); // Mutation > 0.0 should modify genes a.mutate(0.5); REQUIRE_FALSE(a_dup == a); REQUIRE(a_dup.get_fitness() != a.get_fitness()); // Mutation == 1.0 should modify again a.mutate(1.0); REQUIRE_FALSE(a_dup == a); REQUIRE(a_dup.get_fitness() != a.get_fitness()); } SECTION ( "crossover results in differnet children" ) { genetic::sequence a,b; // Crossover (child) doesn't exactly match either parent genetic::sequence child = genetic::sequence::crossover(a, b); REQUIRE_FALSE(child == a); REQUIRE_FALSE(child == b); // Crossover (siblings) shouldn't match genetic::sequence sibling = genetic::sequence::crossover(a, b); REQUIRE_FALSE(sibling == child); REQUIRE_FALSE(sibling == a); } } TEST_CASE( "Test for genetic::population", "[population]" ) { // Predictable random tests (that passed before) random::set_seed(1); SECTION ( "population size constant through evoluation, factor of 3" ) { genetic::population<genetic::sequence> pop(99); REQUIRE(pop.get_size() == 99); pop.evolve(1, genetic::sequence::get_max_fitness(), 0.2, true); REQUIRE(pop.get_size() == 99); } SECTION ( "population size constant through evoluation, non-factor of 3" ) { genetic::population<genetic::sequence> pop_odd(101); REQUIRE(pop_odd.get_size() == 101); pop_odd.evolve(1, genetic::sequence::get_max_fitness(), 0.2, true); REQUIRE(pop_odd.get_size() == 101); } SECTION ( "evoluation should improve fitness" ) { genetic::population<genetic::sequence> pop(99); auto pop_old = pop; pop.evolve(1, genetic::sequence::get_max_fitness(), 0.2, true); REQUIRE(pop.get_fittest().get_fitness() >= pop_old.get_fittest().get_fitness()); REQUIRE(pop.get_fitness() >= pop_old.get_fitness()); } SECTION ( "20 evoluation cycles" ) { genetic::population<genetic::sequence> pop(99); auto pop_old = pop; pop.evolve(20, genetic::sequence::get_max_fitness(), 0.1, true); REQUIRE(pop.get_fittest().get_fitness() >= pop_old.get_fittest().get_fitness()); REQUIRE(pop.get_fitness() >= pop_old.get_fitness()); REQUIRE(pop.get_size() >= pop_old.get_size()); } }<commit_msg>add test for previous results of easy solution to prevent convergence degredation<commit_after>#include "catch.hpp" #include "../src/population.hpp" #include "../src/random.hpp" #include "../src/sequence.hpp" TEST_CASE( "Test for random", "[random]" ) { random::set_seed(1); SECTION ( "random float inside range" ) { float rand_f = random::f_range(0, 0.5); REQUIRE(rand_f < 0.5); REQUIRE(rand_f > 0.0); } SECTION ( "random integer inside positive range" ) { int rand_i = random::i_range(0, 5); REQUIRE(rand_i <= 5); REQUIRE(rand_i >= 0); } SECTION ( "random integer inside negative range" ) { int rand_i = random::i_range(-10, -5); REQUIRE(rand_i <= -5); REQUIRE(rand_i >= -10); } SECTION ( "random integer range with both" ) { int rand_neg = random::i_range(-5, 5); REQUIRE(rand_neg <= 5); REQUIRE(rand_neg >= -5); } SECTION ( "repeat random integers not equal" ) { int rand_1 = random::i_range(0, 100); int rand_2 = random::i_range(0, 100); REQUIRE(rand_1 != rand_2); } SECTION ( "random reset produces repeatable results" ) { random::reset(); int rand_1 = random::i_range(0, 100); random::reset(); int rand_2 = random::i_range(0, 100); REQUIRE(rand_1 == rand_2); } SECTION ( "different seeds, different results" ) { random::set_seed(2); int rand_1 = random::i_range(0, 100); random::set_seed(3); int rand_2 = random::i_range(0, 100); REQUIRE(rand_1 != rand_2); } } TEST_CASE( "Test for genetic::sequence", "[sequence]" ) { // Predictable random tests (that passed before) random::set_seed(1); SECTION ( "genes of two rand inits are different" ) { genetic::sequence a, b; // Two random individuals don't match REQUIRE_FALSE(a == b); REQUIRE_FALSE(a.get_fitness() == b.get_fitness()); } SECTION ( "mutations with different rates" ) { // Copy constructor genetic::sequence a; genetic::sequence a_dup = a; REQUIRE(a_dup == a); // Mutate (0 = none) a.mutate(0.0); REQUIRE(a_dup == a); REQUIRE(a_dup.get_fitness() == a.get_fitness()); // Mutation > 0.0 should modify genes a.mutate(0.5); REQUIRE_FALSE(a_dup == a); REQUIRE(a_dup.get_fitness() != a.get_fitness()); // Mutation == 1.0 should modify again a.mutate(1.0); REQUIRE_FALSE(a_dup == a); REQUIRE(a_dup.get_fitness() != a.get_fitness()); } SECTION ( "crossover results in differnet children" ) { genetic::sequence a,b; // Crossover (child) doesn't exactly match either parent genetic::sequence child = genetic::sequence::crossover(a, b); REQUIRE_FALSE(child == a); REQUIRE_FALSE(child == b); // Crossover (siblings) shouldn't match genetic::sequence sibling = genetic::sequence::crossover(a, b); REQUIRE_FALSE(sibling == child); REQUIRE_FALSE(sibling == a); } } TEST_CASE( "Test for genetic::population", "[population]" ) { // Predictable random tests (that passed before) random::set_seed(1); SECTION ( "population size constant through evoluation, factor of 3" ) { genetic::population<genetic::sequence> pop(99); REQUIRE(pop.get_size() == 99); pop.evolve(1, genetic::sequence::get_max_fitness(), 0.2, true); REQUIRE(pop.get_size() == 99); } SECTION ( "population size constant through evoluation, non-factor of 3" ) { genetic::population<genetic::sequence> pop_odd(101); REQUIRE(pop_odd.get_size() == 101); pop_odd.evolve(1, genetic::sequence::get_max_fitness(), 0.2, true); REQUIRE(pop_odd.get_size() == 101); } SECTION ( "evoluation should improve fitness" ) { genetic::population<genetic::sequence> pop(99); auto pop_old = pop; pop.evolve(1, genetic::sequence::get_max_fitness(), 0.2, true); REQUIRE(pop.get_fittest().get_fitness() >= pop_old.get_fittest().get_fitness()); REQUIRE(pop.get_fitness() >= pop_old.get_fitness()); } SECTION ( "20 evoluation cycles" ) { genetic::population<genetic::sequence> pop(99); auto pop_old = pop; pop.evolve(20, genetic::sequence::get_max_fitness(), 0.1, true); REQUIRE(pop.get_fittest().get_fitness() >= pop_old.get_fittest().get_fitness()); REQUIRE(pop.get_fitness() >= pop_old.get_fitness()); REQUIRE(pop.get_size() >= pop_old.get_size()); } } TEST_CASE( "Test for previous results", "[results]" ) { // Predictable random tests (that passed before) random::set_seed(1); SECTION ( "'easy' solution" ) { genetic::sequence::set_solution("easy"); genetic::population<genetic::sequence> pop(99); REQUIRE(pop.evolve(50, genetic::sequence::get_max_fitness(), 0.08, true)); } }<|endoftext|>