<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * 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
 *
 *****************************************************************************/

//$Id$

#if !defined LABEL_COLLISION_DETECTOR
#define LABEL_COLLISION_DETECTOR
// mapnik
#include <mapnik/quad_tree.hpp>
// stl
#include <vector>

namespace mapnik
{
   //this needs to be tree structure
   //as a proof of a concept _only_ we use sequential scan

   struct label_collision_detector
   {
         typedef std::vector<Envelope<double> > label_placements;

         bool has_plasement(Envelope<double> const& box)
         {
            label_placements::const_iterator itr=labels_.begin();
            for( ; itr !=labels_.end();++itr)
            {
               if (itr->intersects(box))
               {
                  return false;
               }
            }
            labels_.push_back(box);
            return true;
         }
         void clear()
         {
            labels_.clear();
         }

      private:

         label_placements labels_;
   };

   // quad_tree based label collision detector
   class label_collision_detector2 : boost::noncopyable
   {
         typedef quad_tree<Envelope<double> > tree_t;
         tree_t tree_;
      public:

         explicit label_collision_detector2(Envelope<double> const& extent)
            : tree_(extent) {}

         bool has_placement(Envelope<double> const& box)
         {
            tree_t::query_iterator itr = tree_.query_in_box(box);
            tree_t::query_iterator end = tree_.query_end();

            for ( ;itr != end; ++itr)
            {
               if (itr->intersects(box))
               {
                  return false;
               }
            }

            tree_.insert(box,box);
            return true;
         }

         void clear()
         {
            tree_.clear();
         }

   };

   // quad_tree based label collision detector with seperate check/insert
   class label_collision_detector3 : boost::noncopyable
   {
         typedef quad_tree< Envelope<double> > tree_t;
         tree_t tree_;
      public:

         explicit label_collision_detector3(Envelope<double> const& extent)
            : tree_(extent) {}

         bool has_placement(Envelope<double> const& box)
         {
            tree_t::query_iterator itr = tree_.query_in_box(box);
            tree_t::query_iterator end = tree_.query_end();

            for ( ;itr != end; ++itr)
            {
               if (itr->intersects(box))
               {
                  return false;
               }
            }

            return true;
         }

         void insert(Envelope<double> const& box)
         {
            tree_.insert(box, box);
         }

         void clear()
         {
            tree_.clear();
         }
   };

    //quad tree based label collission detector so labels dont appear within a given distance
    class label_collision_detector4 : boost::noncopyable
    {
        struct label
        {
            label(Envelope<double> const& b) : box(b) {}
            label(Envelope<double> const& b, std::wstring const& t) : box(b), text(t) {}

            Envelope<double> box;
            std::wstring text;
        };

        typedef quad_tree< label > tree_t;
        tree_t tree_;
    public:

        explicit label_collision_detector4(Envelope<double> const& extent)
            : tree_(extent) {}

        bool has_placement(Envelope<double> const& box)
        {
            tree_t::query_iterator itr = tree_.query_in_box(box);
            tree_t::query_iterator end = tree_.query_end();

            for ( ;itr != end; ++itr)
            {
               if (itr->box.intersects(box))
               {
                  return false;
               }
            }

            return true;
        }

        bool has_placement(Envelope<double> const& box, std::wstring const& text, double distance)
        {
            Envelope<double> bigger_box(box.minx() - distance, box.miny() - distance, box.maxx() + distance, box.maxy() + distance);

            tree_t::query_iterator itr = tree_.query_in_box(bigger_box);
            tree_t::query_iterator end = tree_.query_end();

            for ( ;itr != end; ++itr)
            {
                if (itr->box.intersects(box) || (text == itr->text && itr->box.intersects(bigger_box)))
                {
                    return false;
                }
            }

            return true;
        }

         void insert(Envelope<double> const& box)
         {
            tree_.insert(label(box), box);
         }

         void insert(Envelope<double> const& box, std::wstring const& text)
         {
            tree_.insert(label(box, text), box);
         }

         void clear()
         {
            tree_.clear();
         }
    };
}

#endif
<commit_msg>added missing extent() method<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * 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
 *
 *****************************************************************************/

//$Id$

#if !defined LABEL_COLLISION_DETECTOR
#define LABEL_COLLISION_DETECTOR
// mapnik
#include <mapnik/quad_tree.hpp>
// stl
#include <vector>

namespace mapnik
{
   //this needs to be tree structure
   //as a proof of a concept _only_ we use sequential scan

   struct label_collision_detector
   {
         typedef std::vector<Envelope<double> > label_placements;

         bool has_plasement(Envelope<double> const& box)
         {
            label_placements::const_iterator itr=labels_.begin();
            for( ; itr !=labels_.end();++itr)
            {
               if (itr->intersects(box))
               {
                  return false;
               }
            }
            labels_.push_back(box);
            return true;
         }
         void clear()
         {
            labels_.clear();
         }

      private:

         label_placements labels_;
   };

   // quad_tree based label collision detector
   class label_collision_detector2 : boost::noncopyable
   {
         typedef quad_tree<Envelope<double> > tree_t;
         tree_t tree_;
      public:

         explicit label_collision_detector2(Envelope<double> const& extent)
            : tree_(extent) {}

         bool has_placement(Envelope<double> const& box)
         {
            tree_t::query_iterator itr = tree_.query_in_box(box);
            tree_t::query_iterator end = tree_.query_end();

            for ( ;itr != end; ++itr)
            {
               if (itr->intersects(box))
               {
                  return false;
               }
            }

            tree_.insert(box,box);
            return true;
         }

         void clear()
         {
            tree_.clear();
         }

   };

   // quad_tree based label collision detector with seperate check/insert
   class label_collision_detector3 : boost::noncopyable
   {
         typedef quad_tree< Envelope<double> > tree_t;
         tree_t tree_;
      public:

         explicit label_collision_detector3(Envelope<double> const& extent)
            : tree_(extent) {}

         bool has_placement(Envelope<double> const& box)
         {
            tree_t::query_iterator itr = tree_.query_in_box(box);
            tree_t::query_iterator end = tree_.query_end();

            for ( ;itr != end; ++itr)
            {
               if (itr->intersects(box))
               {
                  return false;
               }
            }

            return true;
         }

         void insert(Envelope<double> const& box)
         {
            tree_.insert(box, box);
         }

         void clear()
         {
            tree_.clear();
         }
   };

   //quad tree based label collission detector so labels dont appear within a given distance
   class label_collision_detector4 : boost::noncopyable
   {
         struct label
         {
               label(Envelope<double> const& b) : box(b) {}
               label(Envelope<double> const& b, std::wstring const& t) : box(b), text(t) {}

               Envelope<double> box;
               std::wstring text;
         };

         typedef quad_tree< label > tree_t;
         Envelope<double> extent_;
         tree_t tree_;

    public:

        explicit label_collision_detector4(Envelope<double> const& extent)
           : extent_(extent),
             tree_(extent) {}

        bool has_placement(Envelope<double> const& box)
        {
            tree_t::query_iterator itr = tree_.query_in_box(box);
            tree_t::query_iterator end = tree_.query_end();

            for ( ;itr != end; ++itr)
            {
               if (itr->box.intersects(box))
               {
                  return false;
               }
            }

            return true;
        }

        bool has_placement(Envelope<double> const& box, std::wstring const& text, double distance)
        {
            Envelope<double> bigger_box(box.minx() - distance, box.miny() - distance, box.maxx() + distance, box.maxy() + distance);

            tree_t::query_iterator itr = tree_.query_in_box(bigger_box);
            tree_t::query_iterator end = tree_.query_end();

            for ( ;itr != end; ++itr)
            {
                if (itr->box.intersects(box) || (text == itr->text && itr->box.intersects(bigger_box)))
                {
                    return false;
                }
            }

            return true;
        }

         void insert(Envelope<double> const& box)
         {
            tree_.insert(label(box), box);
         }

         void insert(Envelope<double> const& box, std::wstring const& text)
         {
            tree_.insert(label(box, text), box);
         }

         void clear()
         {
            tree_.clear();
         }
         Envelope<double> const& extent() const
         {
            return extent_;
         }
    };
}

#endif
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/eval/tensor/dense/dense_dot_product_function.h>
#include <vespa/eval/tensor/dense/dense_tensor.h>
#include <vespa/eval/tensor/dense/dense_tensor_builder.h>
#include <vespa/eval/tensor/dense/dense_tensor_view.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/stash.h>

#include <vespa/log/log.h>
LOG_SETUP("dense_dot_product_function_test");

using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::tensor;

tensor::Tensor::UP
makeTensor(size_t numCells, double cellBias)
{
    DenseTensorBuilder builder;
    DenseTensorBuilder::Dimension dim = builder.defineDimension("x", numCells);
    for (size_t i = 0; i < numCells; ++i) {
        builder.addLabel(dim, i).addCell(i + cellBias);
    }
    return builder.build();
}

double
calcDotProduct(const DenseTensor &lhs, const DenseTensor &rhs)
{
    size_t numCells = std::min(lhs.cells().size(), rhs.cells().size());
    double result = 0;
    for (size_t i = 0; i < numCells; ++i) {
        result += (lhs.cells()[i] * rhs.cells()[i]);
    }
    return result;
}

const DenseTensor &
asDenseTensor(const tensor::Tensor &tensor)
{
    return dynamic_cast<const DenseTensor &>(tensor);
}

class FunctionInput
{
private:
    tensor::Tensor::UP _lhsTensor;
    tensor::Tensor::UP _rhsTensor;
    const DenseTensor &_lhsDenseTensor;
    const DenseTensor &_rhsDenseTensor;
    std::vector<Value::CREF> _params;

public:
    FunctionInput(size_t lhsNumCells, size_t rhsNumCells)
        : _lhsTensor(makeTensor(lhsNumCells, 3.0)),
          _rhsTensor(makeTensor(rhsNumCells, 5.0)),
          _lhsDenseTensor(asDenseTensor(*_lhsTensor)),
          _rhsDenseTensor(asDenseTensor(*_rhsTensor))
    {
        _params.emplace_back(_lhsDenseTensor);
        _params.emplace_back(_rhsDenseTensor);
    }
    SimpleObjectParams get() const { return SimpleObjectParams(_params); }
    const Value &param(size_t idx) const { return _params[idx]; }
    double expectedDotProduct() const {
        return calcDotProduct(_lhsDenseTensor, _rhsDenseTensor);
    }
};

struct Fixture
{
    FunctionInput input;
    tensor_function::Inject a;
    tensor_function::Inject b;
    DenseDotProductFunction function;
    Fixture(size_t lhsNumCells, size_t rhsNumCells);
    ~Fixture();
    double eval() const {
        Stash stash;
        const Value &result = function.eval(DefaultTensorEngine::ref(), input.get(), stash);
        ASSERT_TRUE(result.is_double());
        LOG(info, "eval(): (%s) * (%s) = %f",
            input.param(0).type().to_spec().c_str(),
            input.param(1).type().to_spec().c_str(),
            result.as_double());
        return result.as_double();
    }
};

Fixture::Fixture(size_t lhsNumCells, size_t rhsNumCells)
    : input(lhsNumCells, rhsNumCells),
      a(input.param(0).type(), 0),
      b(input.param(1).type(), 1),
      function(a, b)
{ }

Fixture::~Fixture() { }

void
assertDotProduct(size_t numCells)
{
    Fixture f(numCells, numCells);
    EXPECT_EQUAL(f.input.expectedDotProduct(), f.eval());
}

void
assertDotProduct(size_t lhsNumCells, size_t rhsNumCells)
{
    Fixture f(lhsNumCells, rhsNumCells);
    EXPECT_EQUAL(f.input.expectedDotProduct(), f.eval());
}

TEST_F("require that empty dot product is correct", Fixture(0, 0))
{
    EXPECT_EQUAL(0.0, f.eval());
}

TEST_F("require that basic dot product with equal sizes is correct", Fixture(2, 2))
{
    EXPECT_EQUAL((3.0 * 5.0) + (4.0 * 6.0), f.eval());
}

TEST_F("require that basic dot product with un-equal sizes is correct", Fixture(2, 3))
{
    EXPECT_EQUAL((3.0 * 5.0) + (4.0 * 6.0), f.eval());
}

TEST_F("require that basic dot product with un-equal sizes is correct", Fixture(3, 2))
{
    EXPECT_EQUAL((3.0 * 5.0) + (4.0 * 6.0), f.eval());
}

TEST("require that dot product with equal sizes is correct")
{
    TEST_DO(assertDotProduct(8));
    TEST_DO(assertDotProduct(16));
    TEST_DO(assertDotProduct(32));
    TEST_DO(assertDotProduct(64));
    TEST_DO(assertDotProduct(128));
    TEST_DO(assertDotProduct(256));
    TEST_DO(assertDotProduct(512));
    TEST_DO(assertDotProduct(1024));

    TEST_DO(assertDotProduct(8 + 3));
    TEST_DO(assertDotProduct(16 + 3));
    TEST_DO(assertDotProduct(32 + 3));
    TEST_DO(assertDotProduct(64 + 3));
    TEST_DO(assertDotProduct(128 + 3));
    TEST_DO(assertDotProduct(256 + 3));
    TEST_DO(assertDotProduct(512 + 3));
    TEST_DO(assertDotProduct(1024 + 3));
}

TEST("require that dot product with un-equal sizes is correct")
{
    TEST_DO(assertDotProduct(8, 8 + 3));
    TEST_DO(assertDotProduct(16, 16 + 3));
    TEST_DO(assertDotProduct(32, 32 + 3));
    TEST_DO(assertDotProduct(64, 64 + 3));
    TEST_DO(assertDotProduct(128, 128 + 3));
    TEST_DO(assertDotProduct(256, 256 + 3));
    TEST_DO(assertDotProduct(512, 512 + 3));
    TEST_DO(assertDotProduct(1024, 1024 + 3));
}

TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>use interpreted function to evaluate tensor function<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/eval/tensor/dense/dense_dot_product_function.h>
#include <vespa/eval/tensor/dense/dense_tensor.h>
#include <vespa/eval/tensor/dense/dense_tensor_builder.h>
#include <vespa/eval/tensor/dense/dense_tensor_view.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/stash.h>

#include <vespa/log/log.h>
LOG_SETUP("dense_dot_product_function_test");

using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::tensor;

tensor::Tensor::UP
makeTensor(size_t numCells, double cellBias)
{
    DenseTensorBuilder builder;
    DenseTensorBuilder::Dimension dim = builder.defineDimension("x", numCells);
    for (size_t i = 0; i < numCells; ++i) {
        builder.addLabel(dim, i).addCell(i + cellBias);
    }
    return builder.build();
}

double
calcDotProduct(const DenseTensor &lhs, const DenseTensor &rhs)
{
    size_t numCells = std::min(lhs.cells().size(), rhs.cells().size());
    double result = 0;
    for (size_t i = 0; i < numCells; ++i) {
        result += (lhs.cells()[i] * rhs.cells()[i]);
    }
    return result;
}

const DenseTensor &
asDenseTensor(const tensor::Tensor &tensor)
{
    return dynamic_cast<const DenseTensor &>(tensor);
}

class FunctionInput
{
private:
    tensor::Tensor::UP _lhsTensor;
    tensor::Tensor::UP _rhsTensor;
    const DenseTensor &_lhsDenseTensor;
    const DenseTensor &_rhsDenseTensor;
    std::vector<Value::CREF> _params;

public:
    FunctionInput(size_t lhsNumCells, size_t rhsNumCells)
        : _lhsTensor(makeTensor(lhsNumCells, 3.0)),
          _rhsTensor(makeTensor(rhsNumCells, 5.0)),
          _lhsDenseTensor(asDenseTensor(*_lhsTensor)),
          _rhsDenseTensor(asDenseTensor(*_rhsTensor))
    {
        _params.emplace_back(_lhsDenseTensor);
        _params.emplace_back(_rhsDenseTensor);
    }
    SimpleObjectParams get() const { return SimpleObjectParams(_params); }
    const Value &param(size_t idx) const { return _params[idx]; }
    double expectedDotProduct() const {
        return calcDotProduct(_lhsDenseTensor, _rhsDenseTensor);
    }
};

struct Fixture
{
    FunctionInput input;
    tensor_function::Inject a;
    tensor_function::Inject b;
    DenseDotProductFunction function;
    Fixture(size_t lhsNumCells, size_t rhsNumCells);
    ~Fixture();
    double eval() const {
        InterpretedFunction ifun(DefaultTensorEngine::ref(), function);
        InterpretedFunction::Context ictx(ifun);
        const Value &result = ifun.eval(ictx, input.get());
        ASSERT_TRUE(result.is_double());
        LOG(info, "eval(): (%s) * (%s) = %f",
            input.param(0).type().to_spec().c_str(),
            input.param(1).type().to_spec().c_str(),
            result.as_double());
        return result.as_double();
    }
};

Fixture::Fixture(size_t lhsNumCells, size_t rhsNumCells)
    : input(lhsNumCells, rhsNumCells),
      a(input.param(0).type(), 0),
      b(input.param(1).type(), 1),
      function(a, b)
{ }

Fixture::~Fixture() { }

void
assertDotProduct(size_t numCells)
{
    Fixture f(numCells, numCells);
    EXPECT_EQUAL(f.input.expectedDotProduct(), f.eval());
}

void
assertDotProduct(size_t lhsNumCells, size_t rhsNumCells)
{
    Fixture f(lhsNumCells, rhsNumCells);
    EXPECT_EQUAL(f.input.expectedDotProduct(), f.eval());
}

TEST_F("require that empty dot product is correct", Fixture(0, 0))
{
    EXPECT_EQUAL(0.0, f.eval());
}

TEST_F("require that basic dot product with equal sizes is correct", Fixture(2, 2))
{
    EXPECT_EQUAL((3.0 * 5.0) + (4.0 * 6.0), f.eval());
}

TEST_F("require that basic dot product with un-equal sizes is correct", Fixture(2, 3))
{
    EXPECT_EQUAL((3.0 * 5.0) + (4.0 * 6.0), f.eval());
}

TEST_F("require that basic dot product with un-equal sizes is correct", Fixture(3, 2))
{
    EXPECT_EQUAL((3.0 * 5.0) + (4.0 * 6.0), f.eval());
}

TEST("require that dot product with equal sizes is correct")
{
    TEST_DO(assertDotProduct(8));
    TEST_DO(assertDotProduct(16));
    TEST_DO(assertDotProduct(32));
    TEST_DO(assertDotProduct(64));
    TEST_DO(assertDotProduct(128));
    TEST_DO(assertDotProduct(256));
    TEST_DO(assertDotProduct(512));
    TEST_DO(assertDotProduct(1024));

    TEST_DO(assertDotProduct(8 + 3));
    TEST_DO(assertDotProduct(16 + 3));
    TEST_DO(assertDotProduct(32 + 3));
    TEST_DO(assertDotProduct(64 + 3));
    TEST_DO(assertDotProduct(128 + 3));
    TEST_DO(assertDotProduct(256 + 3));
    TEST_DO(assertDotProduct(512 + 3));
    TEST_DO(assertDotProduct(1024 + 3));
}

TEST("require that dot product with un-equal sizes is correct")
{
    TEST_DO(assertDotProduct(8, 8 + 3));
    TEST_DO(assertDotProduct(16, 16 + 3));
    TEST_DO(assertDotProduct(32, 32 + 3));
    TEST_DO(assertDotProduct(64, 64 + 3));
    TEST_DO(assertDotProduct(128, 128 + 3));
    TEST_DO(assertDotProduct(256, 256 + 3));
    TEST_DO(assertDotProduct(512, 512 + 3));
    TEST_DO(assertDotProduct(1024, 1024 + 3));
}

TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>


<commit_before>#include "Mod.h"
#include "GCD.h"
#include "Random.h"
#include "PollardRho.h"

namespace Math {
  namespace {
    int fI(int x, int a, int n) {
      return mod(x * x + a, n);
    }
  }

  int pollardRhoI(int n) {
    int a, s, g, u, v;

    Random rnd;
    a = rnd.getRange(1, n - 3);
    s = rnd.getRange(0, n - 1);

    u = v = s;

    do {
      u = fI(u, a, n);
      v = fI(fI(v, a, n), a, n);
      g = gcd(mod(u - v, n), n);
    } while (g == 1);

    if (g == n) {
      return pollardRhoI(n);
    }

    return g;
  }
}
<commit_msg>Small changed to Pollard Rho.<commit_after>#include "Mod.h"
#include "GCD.h"
#include "Random.h"
#include "PollardRho.h"

namespace Math {
  namespace {
    int fI(int x, int a, int n) {
      return mod(x * x + a, n);
    }
  }

  int pollardRhoI(int n) {
    Random rnd;
    int a = rnd.getRange(1, n - 3),
      s = rnd.getRange(0, n - 1);

    int g, u, v;
    u = v = s;

    do {
      u = fI(u, a, n);
      v = fI(fI(v, a, n), a, n);
      g = gcd(mod(u - v, n), n);
    } while (g == 1);

    if (g == n) {
      return pollardRhoI(n);
    }

    return g;
  }
}
<|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2019 projectchrono.org
// All rights 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: Asher Elmquist
// =============================================================================
//
//
// =============================================================================

#include "chrono_sensor/filters/ChFilterSave.h"
#include "chrono_sensor/ChSensor.h"

#include "chrono_thirdparty/nothings/stb_image_write.h"
#include "chrono_thirdparty/filesystem/path.h"

#include <vector>
#include <sstream>

namespace chrono {
namespace sensor {

CH_SENSOR_API ChFilterSave::ChFilterSave(std::string data_path) : ChFilter("") {
    m_path = data_path;
}

CH_SENSOR_API ChFilterSave::~ChFilterSave() {}

CH_SENSOR_API void ChFilterSave::Apply(std::shared_ptr<ChSensor> pSensor, std::shared_ptr<SensorBuffer>& bufferInOut) {
    std::shared_ptr<SensorOptixBuffer> pOptix = std::dynamic_pointer_cast<SensorOptixBuffer>(bufferInOut);
    std::shared_ptr<SensorDeviceR8Buffer> pR8 = std::dynamic_pointer_cast<SensorDeviceR8Buffer>(bufferInOut);
    std::shared_ptr<SensorDeviceRGBA8Buffer> pRGBA8 = std::dynamic_pointer_cast<SensorDeviceRGBA8Buffer>(bufferInOut);

    if (!pOptix && !pR8 && !pRGBA8)
        throw std::runtime_error("This buffer type cannot be saved as png");

    std::string filename = m_path + "frame_" + std::to_string(m_frame_number) + ".png";
    m_frame_number++;

    // openGL buffers are bottom to top...so flip when writing png.
    stbi_flip_vertically_on_write(1);

    if (pOptix) {
        optix::Buffer buffer = pOptix->Buffer;

        // Query buffer information
        RTsize buffer_width_rts, buffer_height_rts;
        buffer->getSize(buffer_width_rts, buffer_height_rts);
        uint32_t width = static_cast<int>(buffer_width_rts);
        uint32_t height = static_cast<int>(buffer_height_rts);
        RTformat buffer_format = buffer->getFormat();

        int comp = 1;
        if (buffer_format == RT_FORMAT_UNSIGNED_BYTE4) {
            comp = 4;
        }
        void* imageData = buffer->map(0, RT_BUFFER_MAP_READ);

        // int stbi_write_png(char const* filename, int w, int h, int comp, const void* data, int stride_in_bytes);
        if (!stbi_write_png(filename.c_str(), width, height, comp, imageData, comp * width)) {
            std::cerr << "Failed to write image: " << filename << "\n";
        }

        buffer->unmap();
    } else if (pR8) {
        char* buf = new char[pR8->Width * pR8->Height];
        cudaMemcpy(buf, pR8->Buffer.get(), pR8->Width * pR8->Height, cudaMemcpyDeviceToHost);

        // write a grayscale png
        if (!stbi_write_png(filename.c_str(), pR8->Width, pR8->Height, 1, buf, pR8->Width)) {
            std::cerr << "Failed to write image: " << filename << "\n";
        }

        delete buf;
    } else if (pRGBA8) {
        char* buf = new char[pRGBA8->Width * pRGBA8->Height * 4];
        cudaMemcpy(buf, pRGBA8->Buffer.get(), pRGBA8->Width * pRGBA8->Height * 4, cudaMemcpyDeviceToHost);

        // write a grayscale png
        if (!stbi_write_png(filename.c_str(), pRGBA8->Width, pRGBA8->Height, 4, buf, 4 * pRGBA8->Width)) {
            std::cerr << "Failed to write image: " << filename << "\n";
        }

        delete buf;
    }
}

CH_SENSOR_API void ChFilterSave::Initialize(std::shared_ptr<ChSensor> pSensor) {
    std::vector<std::string> split_string;

#ifdef _WIN32
    std::istringstream istring(m_path);

    std::string substring;
    while (std::getline(istring, substring, '\\')) {
        split_string.push_back(substring);
    }

    std::string partial_path = "";
    for (auto s : split_string) {
        if (s != "") {
            partial_path += s + "\\";
            if (!filesystem::path(partial_path).exists()) {
                if (!filesystem::create_directory(filesystem::path(partial_path))) {
                    std::cerr << "Could not create directory: " << partial_path << std::endl;
                } else {
                    std::cout << "Created directory for sensor data: " << partial_path << std::endl;
                }
            }
        }
    }
#else

    std::istringstream istring(m_path);

    std::string substring;
    while (std::getline(istring, substring, '/')) {
        split_string.push_back(substring);
    }

    std::string partial_path = "";
    for (auto s : split_string) {
        if (s != "") {
            partial_path += s + "/";
            if (!filesystem::path(partial_path).exists()) {
                if (!filesystem::create_directory(filesystem::path(partial_path))) {
                    std::cerr << "Could not create directory: " << partial_path << std::endl;
                } else {
                    std::cout << "Created directory for sensor data: " << partial_path << std::endl;
                }
            }
        }
    }
#endif
}

}  // namespace sensor
}  // namespace chrono
<commit_msg>ChFilterSave now adds trailing slash to output file path if one is not present<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2019 projectchrono.org
// All rights 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: Asher Elmquist
// =============================================================================
//
//
// =============================================================================

#include "chrono_sensor/filters/ChFilterSave.h"
#include "chrono_sensor/ChSensor.h"

#include "chrono_thirdparty/nothings/stb_image_write.h"
#include "chrono_thirdparty/filesystem/path.h"

#include <vector>
#include <sstream>

namespace chrono {
namespace sensor {

CH_SENSOR_API ChFilterSave::ChFilterSave(std::string data_path) : ChFilter("") {
    m_path = data_path;
}

CH_SENSOR_API ChFilterSave::~ChFilterSave() {}

CH_SENSOR_API void ChFilterSave::Apply(std::shared_ptr<ChSensor> pSensor, std::shared_ptr<SensorBuffer>& bufferInOut) {
    std::shared_ptr<SensorOptixBuffer> pOptix = std::dynamic_pointer_cast<SensorOptixBuffer>(bufferInOut);
    std::shared_ptr<SensorDeviceR8Buffer> pR8 = std::dynamic_pointer_cast<SensorDeviceR8Buffer>(bufferInOut);
    std::shared_ptr<SensorDeviceRGBA8Buffer> pRGBA8 = std::dynamic_pointer_cast<SensorDeviceRGBA8Buffer>(bufferInOut);

    if (!pOptix && !pR8 && !pRGBA8)
        throw std::runtime_error("This buffer type cannot be saved as png");

    std::string filename = m_path + "frame_" + std::to_string(m_frame_number) + ".png";
    m_frame_number++;

    // openGL buffers are bottom to top...so flip when writing png.
    stbi_flip_vertically_on_write(1);

    if (pOptix) {
        optix::Buffer buffer = pOptix->Buffer;

        // Query buffer information
        RTsize buffer_width_rts, buffer_height_rts;
        buffer->getSize(buffer_width_rts, buffer_height_rts);
        uint32_t width = static_cast<int>(buffer_width_rts);
        uint32_t height = static_cast<int>(buffer_height_rts);
        RTformat buffer_format = buffer->getFormat();

        int comp = 1;
        if (buffer_format == RT_FORMAT_UNSIGNED_BYTE4) {
            comp = 4;
        }
        void* imageData = buffer->map(0, RT_BUFFER_MAP_READ);

        // int stbi_write_png(char const* filename, int w, int h, int comp, const void* data, int stride_in_bytes);
        if (!stbi_write_png(filename.c_str(), width, height, comp, imageData, comp * width)) {
            std::cerr << "Failed to write image: " << filename << "\n";
        }

        buffer->unmap();
    } else if (pR8) {
        char* buf = new char[pR8->Width * pR8->Height];
        cudaMemcpy(buf, pR8->Buffer.get(), pR8->Width * pR8->Height, cudaMemcpyDeviceToHost);

        // write a grayscale png
        if (!stbi_write_png(filename.c_str(), pR8->Width, pR8->Height, 1, buf, pR8->Width)) {
            std::cerr << "Failed to write image: " << filename << "\n";
        }

        delete buf;
    } else if (pRGBA8) {
        char* buf = new char[pRGBA8->Width * pRGBA8->Height * 4];
        cudaMemcpy(buf, pRGBA8->Buffer.get(), pRGBA8->Width * pRGBA8->Height * 4, cudaMemcpyDeviceToHost);

        // write a grayscale png
        if (!stbi_write_png(filename.c_str(), pRGBA8->Width, pRGBA8->Height, 4, buf, 4 * pRGBA8->Width)) {
            std::cerr << "Failed to write image: " << filename << "\n";
        }

        delete buf;
    }
}

CH_SENSOR_API void ChFilterSave::Initialize(std::shared_ptr<ChSensor> pSensor) {
    std::vector<std::string> split_string;

#ifdef _WIN32
    std::istringstream istring(m_path);

    std::string substring;
    while (std::getline(istring, substring, '\\')) {
        split_string.push_back(substring);
    }

    std::string partial_path = "";
    for (auto s : split_string) {
        if (s != "") {
            partial_path += s + "\\";
            if (!filesystem::path(partial_path).exists()) {
                if (!filesystem::create_directory(filesystem::path(partial_path))) {
                    std::cerr << "Could not create directory: " << partial_path << std::endl;
                } else {
                    std::cout << "Created directory for sensor data: " << partial_path << std::endl;
                }
            }
        }
    }

    if (m_path.back() != '\\')
        m_path += '\\';
#else

    std::istringstream istring(m_path);

    std::string substring;
    while (std::getline(istring, substring, '/')) {
        split_string.push_back(substring);
    }

    std::string partial_path = "";
    for (auto s : split_string) {
        if (s != "") {
            partial_path += s + "/";
            if (!filesystem::path(partial_path).exists()) {
                if (!filesystem::create_directory(filesystem::path(partial_path))) {
                    std::cerr << "Could not create directory: " << partial_path << std::endl;
                } else {
                    std::cout << "Created directory for sensor data: " << partial_path << std::endl;
                }
            }
        }
    }

    if (m_path.back() != '/')
        m_path += '/';
#endif
}

}  // namespace sensor
}  // namespace chrono
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "../VisualStudio/resource.h"

#define MAX_LOADSTRING 100

// Global Variables:
HWND hWnd;
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name
HACCEL hAccelTable;

static void ShowLastError()
{
	wchar_t* msg;
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&msg, 0, nullptr);
	MessageBox(hWnd, msg, L"", MB_OK);
	LocalFree(msg);
}

// WindowMessage
static BOOL ProcessWindowMessage(){
	MSG msg;
	for (;;){
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
			if (msg.message == WM_QUIT){
				return FALSE;
			}
			if (!TranslateAccelerator(hWnd, hAccelTable, &msg)) {
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}

		BOOL active = !IsIconic(hWnd) && GetForegroundWindow() == hWnd;

		if (!active){
			WaitMessage();
			continue;
		}

		return TRUE;
	}
}

// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

#ifdef _DEBUG
int main(int, char**)
#else
int APIENTRY wWinMain(_In_ HINSTANCE,
	_In_opt_ HINSTANCE hPrevInstance,
	_In_ LPTSTR    lpCmdLine,
	_In_ int)
#endif

{
	HINSTANCE hInstance = GetModuleHandle(nullptr);

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_DX12PLAYGROUND, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_DX12PLAYGROUND));

	deviceMan.Create(hWnd);

	int lastW = 0;
	int lastH = 0;

	// Main message loop:
	for (;;) {
		if (!ProcessWindowMessage()) {
			break;
		}

		RECT rc;
		GetClientRect(hWnd, &rc);
		int w = rc.right - rc.left;
		int h = rc.bottom - rc.top;
		if (w != lastW || h != lastH) {
			lastW = w;
			lastH = h;
			app.Destroy();
		//	deviceMan.Destroy();
		//	deviceMan.Create(hWnd);
			app.Init();

		}
		app.Update();
		app.Draw();
		deviceMan.Present();
		Sleep(1);
	}
	return 0;
}

//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_DX12PLAYGROUND));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_DX12PLAYGROUND);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance)
{
   hInst = hInstance; // Store instance handle in our global variable

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, SW_SHOWNORMAL);
   UpdateWindow(hWnd);

   DragAcceptFiles(hWnd, TRUE);
   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	IVec2 screenSize = systemMisc.GetScreenSize();
	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);

		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			SendMessage(hWnd, WM_CLOSE, 0, 0);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		EndPaint(hWnd, &ps);
		break;
	case WM_CLOSE:
		app.Destroy();
		deviceMan.Destroy();
		DestroyWindow(hWnd);
		return 0;
	case WM_DROPFILES:
	{
		HDROP hDrop = (HDROP)wParam;
		char fileName[MAX_PATH];
		DragQueryFileA(hDrop, 0, fileName, MAX_PATH);
		DragFinish(hDrop);
//		app.LoadMesh(fileName);
		break;
	}
	case WM_LBUTTONDOWN:
		SetCapture(hWnd);
		devCamera.LButtonDown(LOWORD(lParam) / (float)screenSize.x, HIWORD(lParam) / (float)screenSize.y);
		systemMisc.mouseDown = true;
		break;
	case WM_LBUTTONUP:
		ReleaseCapture();
		devCamera.LButtonUp(LOWORD(lParam) / (float)screenSize.x, HIWORD(lParam) / (float)screenSize.y);
		systemMisc.mouseDown = false;
		break;
	case WM_MOUSEMOVE:
		systemMisc.SetMousePos(IVec2(MAKEPOINTS(lParam).x, MAKEPOINTS(lParam).y));
		devCamera.MouseMove(MAKEPOINTS(lParam).x / (float)screenSize.x, MAKEPOINTS(lParam).y / (float)screenSize.y);
		break;
	case WM_MOUSEWHEEL:
		devCamera.MouseWheel((short)HIWORD(wParam) / (float)WHEEL_DELTA);
		break;
	case WM_SIZE:
		systemMisc.SetScreenSize(IVec2(LOWORD(lParam), HIWORD(lParam)));
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}
<commit_msg>Recreate device when the window resized.<commit_after>#include "stdafx.h"
#include "../VisualStudio/resource.h"

#define MAX_LOADSTRING 100

// Global Variables:
HWND hWnd;
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name
HACCEL hAccelTable;

static void ShowLastError()
{
	wchar_t* msg;
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&msg, 0, nullptr);
	MessageBox(hWnd, msg, L"", MB_OK);
	LocalFree(msg);
}

// WindowMessage
static BOOL ProcessWindowMessage(){
	MSG msg;
	for (;;){
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
			if (msg.message == WM_QUIT){
				return FALSE;
			}
			if (!TranslateAccelerator(hWnd, hAccelTable, &msg)) {
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}

		BOOL active = !IsIconic(hWnd) && GetForegroundWindow() == hWnd;

		if (!active){
			WaitMessage();
			continue;
		}

		return TRUE;
	}
}

// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

#ifdef _DEBUG
int main(int, char**)
#else
int APIENTRY wWinMain(_In_ HINSTANCE,
	_In_opt_ HINSTANCE hPrevInstance,
	_In_ LPTSTR    lpCmdLine,
	_In_ int)
#endif

{
	HINSTANCE hInstance = GetModuleHandle(nullptr);

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_DX12PLAYGROUND, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_DX12PLAYGROUND));

	int lastW = 0;
	int lastH = 0;

	// Main message loop:
	for (;;) {
		if (!ProcessWindowMessage()) {
			break;
		}

		RECT rc;
		GetClientRect(hWnd, &rc);
		int w = rc.right - rc.left;
		int h = rc.bottom - rc.top;
		if (w != lastW || h != lastH) {
			lastW = w;
			lastH = h;
			app.Destroy();
			deviceMan.Destroy();
			deviceMan.Create(hWnd);
			app.Init();
		}
		app.Update();
		app.Draw();
		deviceMan.Present();
		Sleep(1);
	}
	return 0;
}

//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_DX12PLAYGROUND));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_DX12PLAYGROUND);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance)
{
   hInst = hInstance; // Store instance handle in our global variable

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }
   ShowWindow(hWnd, SW_SHOWNORMAL);

   DragAcceptFiles(hWnd, TRUE);
   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	IVec2 screenSize = systemMisc.GetScreenSize();
	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);

		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			SendMessage(hWnd, WM_CLOSE, 0, 0);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		EndPaint(hWnd, &ps);
		break;
	case WM_CLOSE:
		app.Destroy();
		deviceMan.Destroy();
		DestroyWindow(hWnd);
		return 0;
	case WM_DROPFILES:
	{
		HDROP hDrop = (HDROP)wParam;
		char fileName[MAX_PATH];
		DragQueryFileA(hDrop, 0, fileName, MAX_PATH);
		DragFinish(hDrop);
//		app.LoadMesh(fileName);
		break;
	}
	case WM_LBUTTONDOWN:
		SetCapture(hWnd);
		devCamera.LButtonDown(LOWORD(lParam) / (float)screenSize.x, HIWORD(lParam) / (float)screenSize.y);
		systemMisc.mouseDown = true;
		break;
	case WM_LBUTTONUP:
		ReleaseCapture();
		devCamera.LButtonUp(LOWORD(lParam) / (float)screenSize.x, HIWORD(lParam) / (float)screenSize.y);
		systemMisc.mouseDown = false;
		break;
	case WM_MOUSEMOVE:
		systemMisc.SetMousePos(IVec2(MAKEPOINTS(lParam).x, MAKEPOINTS(lParam).y));
		devCamera.MouseMove(MAKEPOINTS(lParam).x / (float)screenSize.x, MAKEPOINTS(lParam).y / (float)screenSize.y);
		break;
	case WM_MOUSEWHEEL:
		devCamera.MouseWheel((short)HIWORD(wParam) / (float)WHEEL_DELTA);
		break;
	case WM_SIZE:
		systemMisc.SetScreenSize(IVec2(LOWORD(lParam), HIWORD(lParam)));
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}
<|endoftext|>


<commit_before>/*
  Push Server code for CMPT 276 Group Assignment, Spring 2016.

  This server pushes status updates to all a user’s friends in the network.

  This server supports a single operation: push a status update to all friends
  of this user.

  This server handles disallowed method malformed request.
*/

#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <string>

#include <cpprest/base_uri.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>

#include <pplx/pplxtasks.h>

#include <was/common.h>
#include <was/storage_account.h>
#include <was/table.h>

#include "../include/TableCache.h"

#include "../include/make_unique.h"

#include "../include/azure_keys.h"

#include "../include/ServerUtils.h"

using azure::storage::cloud_storage_account;
using azure::storage::storage_credentials;
using azure::storage::storage_exception;
using azure::storage::cloud_table;
using azure::storage::cloud_table_client;
using azure::storage::edm_type;
using azure::storage::entity_property;
using azure::storage::table_entity;
using azure::storage::table_operation;
using azure::storage::table_query;
using azure::storage::table_query_iterator;
using azure::storage::table_result;

using pplx::extensibility::critical_section_t;
using pplx::extensibility::scoped_critical_section_t;

using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::make_pair;
using std::pair;
using std::string;
using std::unordered_map;
using std::vector;

using web::http::http_headers;
using web::http::http_request;
using web::http::methods;
using web::http::status_codes;
using web::http::uri;

using web::json::value;

using web::http::experimental::listener::http_listener;

using prop_vals_t = vector<pair<string,value>>;

constexpr const char* def_url = "http://localhost:34574";<commit_msg>Add handle_post() and main() to PushServer<commit_after>/*
  Push Server code for CMPT 276 Group Assignment, Spring 2016.

  This server pushes status updates to all a user’s friends in the network.

  This server supports a single operation: push a status update to all friends
  of this user.

  This server handles disallowed method malformed request.
*/

#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <string>

#include <cpprest/base_uri.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>

#include <pplx/pplxtasks.h>

#include <was/common.h>
#include <was/storage_account.h>
#include <was/table.h>

#include "../include/TableCache.h"

#include "../include/make_unique.h"

#include "../include/azure_keys.h"

#include "../include/ServerUtils.h"

using azure::storage::cloud_storage_account;
using azure::storage::storage_credentials;
using azure::storage::storage_exception;
using azure::storage::cloud_table;
using azure::storage::cloud_table_client;
using azure::storage::edm_type;
using azure::storage::entity_property;
using azure::storage::table_entity;
using azure::storage::table_operation;
using azure::storage::table_query;
using azure::storage::table_query_iterator;
using azure::storage::table_result;

using pplx::extensibility::critical_section_t;
using pplx::extensibility::scoped_critical_section_t;

using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::make_pair;
using std::pair;
using std::string;
using std::unordered_map;
using std::vector;

using web::http::http_headers;
using web::http::http_request;
using web::http::methods;
using web::http::status_codes;
using web::http::uri;

using web::json::value;

using web::http::experimental::listener::http_listener;

using prop_vals_t = vector<pair<string,value>>;

constexpr const char* def_url = "http://localhost:34574";

TableCache table_cache {};

void handle_post (http_request message) {
  //TODO Not implemented yet!
  message.reply(status_codes::NotImplemented);
  return;
}

int main (int argc, char const * argv[]) {
  cout << "Parsing connection string" << endl;
  table_cache.init (storage_connection_string);

  cout << "Opening listener" << endl;
  http_listener listener {def_url};
  listener.support(methods::POST, &handle_post); // Push a status update to friends
  listener.open().wait();

  cout << "Enter carriage return to stop server." << endl;
  string line;
  getline(std::cin, line);

  // Shut it down
  listener.close().wait();
  cout << "Closed" << endl;
}
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIOgreTextureTarget.cpp
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUIOgreTextureTarget.h"
#include "CEGUIOgreTexture.h"

#include <OgreTextureManager.h>
#include <OgreHardwarePixelBuffer.h>
#include <OgreRenderTexture.h>
#include <OgreRenderSystem.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float OgreTextureTarget::DEFAULT_SIZE = 128.0f;

//----------------------------------------------------------------------------//
OgreTextureTarget::OgreTextureTarget(OgreRenderer& owner,
                                     Ogre::RenderSystem& rs) :
    OgreRenderTarget(owner, rs),
    d_CEGUITexture(0)
{
    d_CEGUITexture = static_cast<OgreTexture*>(&d_owner.createTexture());

    // setup area and cause the initial texture to be generated.
    declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));
}

//----------------------------------------------------------------------------//
OgreTextureTarget::~OgreTextureTarget()
{
    d_owner.destroyTexture(*d_CEGUITexture);
}

//----------------------------------------------------------------------------//
bool OgreTextureTarget::isImageryCache() const
{
    return true;
}

//----------------------------------------------------------------------------//
void OgreTextureTarget::clear()
{
    if (!d_viewportValid)
        updateViewport();

    d_renderSystem._setViewport(d_viewport);
    d_renderSystem.clearFrameBuffer(Ogre::FBT_COLOUR,
                                    Ogre::ColourValue(0, 0, 0, 0));
}

//----------------------------------------------------------------------------//
Texture& OgreTextureTarget::getTexture() const
{
    return *d_CEGUITexture;
}

//----------------------------------------------------------------------------//
void OgreTextureTarget::declareRenderSize(const Size& sz)
{
    // exit if current size is enough
    if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >=sz.d_height))
        return;

    Ogre::TexturePtr rttTex = Ogre::TextureManager::getSingleton().createManual(
        OgreTexture::getUniqueName(),
        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
        Ogre::TEX_TYPE_2D, sz.d_width, sz.d_height, 1, 0, Ogre::PF_A8R8G8B8,
        Ogre::TU_RENDERTARGET);

    d_renderTarget = rttTex->getBuffer()->getRenderTarget();

    Rect init_area(
        Vector2(0, 0),
        Size(d_renderTarget->getWidth(), d_renderTarget->getHeight())
    );

    setArea(init_area);

    // delete viewport and reset ptr so a new one is generated.  This is
    // required because we have changed d_renderTarget so need a new VP also.
    delete d_viewport;
    d_viewport = 0;

    // because Texture takes ownership, the act of setting the new ogre texture
    // also ensures any previous ogre texture is released.
    d_CEGUITexture->setOgreTexture(rttTex, true);

    clear();
}

//----------------------------------------------------------------------------//
bool OgreTextureTarget::isRenderingInverted() const
{
    return false;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<commit_msg>FIX: CEGUI::OgreTextureTarget::clear sets the Ogre system view port.  This call can occur outside the regular rendering sequence and if the OgreTextureTarget is then deleted, Ogre and other parts of the CEGUI::OgreRenderer may try to access the deleted viewport. IMPORTANT: This fix only works on Ogre 1.8 and above. See: http://www.cegui.org.uk/mantis/view.php?id=745<commit_after>/***********************************************************************
    filename:   CEGUIOgreTextureTarget.cpp
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUIOgreTextureTarget.h"
#include "CEGUIOgreTexture.h"

#include <OgreTextureManager.h>
#include <OgreHardwarePixelBuffer.h>
#include <OgreRenderTexture.h>
#include <OgreRenderSystem.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float OgreTextureTarget::DEFAULT_SIZE = 128.0f;

//----------------------------------------------------------------------------//
OgreTextureTarget::OgreTextureTarget(OgreRenderer& owner,
                                     Ogre::RenderSystem& rs) :
    OgreRenderTarget(owner, rs),
    d_CEGUITexture(0)
{
    d_CEGUITexture = static_cast<OgreTexture*>(&d_owner.createTexture());

    // setup area and cause the initial texture to be generated.
    declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));
}

//----------------------------------------------------------------------------//
OgreTextureTarget::~OgreTextureTarget()
{
    d_owner.destroyTexture(*d_CEGUITexture);
}

//----------------------------------------------------------------------------//
bool OgreTextureTarget::isImageryCache() const
{
    return true;
}

//----------------------------------------------------------------------------//
void OgreTextureTarget::clear()
{
    if (!d_viewportValid)
        updateViewport();

#if OGRE_VERSION >= 0x10800
    Ogre::Viewport* const saved_vp = d_renderSystem._getViewport();
#endif

    d_renderSystem._setViewport(d_viewport);
    d_renderSystem.clearFrameBuffer(Ogre::FBT_COLOUR,
                                    Ogre::ColourValue(0, 0, 0, 0));

#if OGRE_VERSION >= 0x10800
    d_renderSystem._setViewport(saved_vp);
#endif
}

//----------------------------------------------------------------------------//
Texture& OgreTextureTarget::getTexture() const
{
    return *d_CEGUITexture;
}

//----------------------------------------------------------------------------//
void OgreTextureTarget::declareRenderSize(const Size& sz)
{
    // exit if current size is enough
    if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >=sz.d_height))
        return;

    Ogre::TexturePtr rttTex = Ogre::TextureManager::getSingleton().createManual(
        OgreTexture::getUniqueName(),
        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
        Ogre::TEX_TYPE_2D, sz.d_width, sz.d_height, 1, 0, Ogre::PF_A8R8G8B8,
        Ogre::TU_RENDERTARGET);

    d_renderTarget = rttTex->getBuffer()->getRenderTarget();

    Rect init_area(
        Vector2(0, 0),
        Size(d_renderTarget->getWidth(), d_renderTarget->getHeight())
    );

    setArea(init_area);

    // delete viewport and reset ptr so a new one is generated.  This is
    // required because we have changed d_renderTarget so need a new VP also.
    delete d_viewport;
    d_viewport = 0;

    // because Texture takes ownership, the act of setting the new ogre texture
    // also ensures any previous ogre texture is released.
    d_CEGUITexture->setOgreTexture(rttTex, true);

    clear();
}

//----------------------------------------------------------------------------//
bool OgreTextureTarget::isRenderingInverted() const
{
    return false;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.51
Copyright (C) 2018  GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "Simulation.h"
#include "Setup.h"          //For setup object

#include "EnergyTypes.h"
#include "PSFOutput.h"
#include <iostream>
#include <iomanip>

Simulation::Simulation(char const*const configFileName, MultiSim const*const& multisim):ms(multisim)
{
  startStep = 0;
  //NOTE:
  //IMPORTANT! Keep this order...
  //as system depends on staticValues, and cpu sometimes depends on both.
  set.Init(configFileName, multisim);
  totalSteps = set.config.sys.step.total;
  staticValues = new StaticVals(set);
  system = new System(*staticValues);
  staticValues->Init(set, *system);
  system->Init(set, startStep);
  //recal Init for static value for initializing ewald since ewald is
  //initialized in system
  staticValues->InitOver(set, *system);
  cpu = new CPUSide(*system, *staticValues);
  cpu->Init(set.pdb, set.config.out, set.config.sys.step.equil,
            totalSteps, startStep);

  //Dump combined PSF
  PSFOutput psfOut(staticValues->mol, *system, set.mol.kindMap,
                   set.pdb.atoms.resKindNames);
  psfOut.PrintPSF(set.config.out.state.files.psf.name);
  std::cout << "Printed combined psf to file "
            << set.config.out.state.files.psf.name << '\n';

  if(totalSteps == 0) {
    frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name);
  }
#if GOMC_LIB_MPI
  PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq): NULL;
  exchangeResults.resize(ms->worldSize, false);
#endif
}

Simulation::~Simulation()
{
  delete cpu;
  delete system;
  delete staticValues;
}

void Simulation::RunSimulation(void)
{
  double startEnergy = system->potential.totalEnergy.total;
  if(totalSteps == 0) {
    for(int i = 0; i < frameSteps.size(); i++) {
      if(i == 0) {
        cpu->Output(frameSteps[0] - 1);
        continue;
      }
      system->RecalculateTrajectory(set, i + 1);
      cpu->Output(frameSteps[i] - 1);
    }
  }
  for (ulong step = startStep; step < totalSteps; step++) {
    system->moveSettings.AdjustMoves(step);
    system->ChooseAndRunMove(step);
    cpu->Output(step);

    if((step + 1) == cpu->equilSteps) {
      double currEnergy = system->potential.totalEnergy.total;
      if(abs(currEnergy - startEnergy) > 1.0e+10) {
        printf("Info: Recalculating the total energies to insure the accuracy"
               " of the computed \n"
               "      running energies.\n\n");
        system->calcEwald->Init();
        system->potential = system->calcEnergy.SystemTotal();
      }
    }
  #if GOMC_LIB_MPI
    //
    if( step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0){

   // if( staticValues->simEventFreq.parallelTemp && step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0){
      //std::cout << "Entered outer if for pt " << step << std::endl;

      system->potential = system->calcEnergy.SystemTotal();

      if (staticValues->simEventFreq.parallelTemp){

        exchangeResults = PTUtils->evaluateExchangeCriteria(step);

       // std::cout << "Entered inner if for pt " << step << std::endl;

        if (exchangeResults[ms->worldRank] == true){

          std::cout << "A swap took place on step " << step << std::endl;

          PTUtils->conductExchanges(system->coordinates, system->com, ms, exchangeResults);

        } else if(ms->worldRank+1 != ms->worldSize && exchangeResults[ms->worldRank+1] == true) {

          std::cout << "A swap took place on step " << step << std::endl;

          PTUtils->conductExchanges(system->coordinates, system->com, ms, exchangeResults);

        }
      }
      system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);

      system->potential = system->calcEnergy.SystemTotal();

    }
  #endif

#ifndef NDEBUG
    if((step + 1) % 1000 == 0)
      RunningCheck(step);
#endif
  }
  system->PrintAcceptance();
  system->PrintTime();
}

#ifndef NDEBUG
void Simulation::RunningCheck(const uint step)
{
  system->calcEwald->UpdateVectorsAndRecipTerms();
  SystemPotential pot = system->calcEnergy.SystemTotal();

  std::cout
      << "================================================================="
      << std::endl << "-------------------------" << std::endl
      << " STEP: " << step + 1
      << std::endl << "-------------------------" << std::endl
      << "Energy       INTRA B |     INTRA NB |        INTER |           TC |         REAL |         SELF |   CORRECTION |        RECIP"
      << std::endl
      << "System: "
      << std::setw(12) << system->potential.totalEnergy.intraBond << " | "
      << std::setw(12) << system->potential.totalEnergy.intraNonbond << " | "
      << std::setw(12) << system->potential.totalEnergy.inter << " | "
      << std::setw(12) << system->potential.totalEnergy.tc << " | "
      << std::setw(12) << system->potential.totalEnergy.real << " | "
      << std::setw(12) << system->potential.totalEnergy.self << " | "
      << std::setw(12) << system->potential.totalEnergy.correction << " | "
      << std::setw(12) << system->potential.totalEnergy.recip << std::endl
      << "Recalc: "
      << std::setw(12) << pot.totalEnergy.intraBond << " | "
      << std::setw(12) << pot.totalEnergy.intraNonbond << " | "
      << std::setw(12) << pot.totalEnergy.inter << " | "
      << std::setw(12) << pot.totalEnergy.tc << " | "
      << std::setw(12) << pot.totalEnergy.real << " | "
      << std::setw(12) << pot.totalEnergy.self << " | "
      << std::setw(12) << pot.totalEnergy.correction << " | "
      << std::setw(12) << pot.totalEnergy.recip << std::endl
      << "================================================================"
      << std::endl << std::endl;

}

#endif
<commit_msg>to plot swap positions<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.51
Copyright (C) 2018  GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "Simulation.h"
#include "Setup.h"          //For setup object

#include "EnergyTypes.h"
#include "PSFOutput.h"
#include <iostream>
#include <iomanip>

Simulation::Simulation(char const*const configFileName, MultiSim const*const& multisim):ms(multisim)
{
  startStep = 0;
  //NOTE:
  //IMPORTANT! Keep this order...
  //as system depends on staticValues, and cpu sometimes depends on both.
  set.Init(configFileName, multisim);
  totalSteps = set.config.sys.step.total;
  staticValues = new StaticVals(set);
  system = new System(*staticValues);
  staticValues->Init(set, *system);
  system->Init(set, startStep);
  //recal Init for static value for initializing ewald since ewald is
  //initialized in system
  staticValues->InitOver(set, *system);
  cpu = new CPUSide(*system, *staticValues);
  cpu->Init(set.pdb, set.config.out, set.config.sys.step.equil,
            totalSteps, startStep);

  //Dump combined PSF
  PSFOutput psfOut(staticValues->mol, *system, set.mol.kindMap,
                   set.pdb.atoms.resKindNames);
  psfOut.PrintPSF(set.config.out.state.files.psf.name);
  std::cout << "Printed combined psf to file "
            << set.config.out.state.files.psf.name << '\n';

  if(totalSteps == 0) {
    frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name);
  }
#if GOMC_LIB_MPI
  PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq): NULL;
  exchangeResults.resize(ms->worldSize, false);
#endif
}

Simulation::~Simulation()
{
  delete cpu;
  delete system;
  delete staticValues;
}

void Simulation::RunSimulation(void)
{
  double startEnergy = system->potential.totalEnergy.total;
  if(totalSteps == 0) {
    for(int i = 0; i < frameSteps.size(); i++) {
      if(i == 0) {
        cpu->Output(frameSteps[0] - 1);
        continue;
      }
      system->RecalculateTrajectory(set, i + 1);
      cpu->Output(frameSteps[i] - 1);
    }
  }
  for (ulong step = startStep; step < totalSteps; step++) {
    system->moveSettings.AdjustMoves(step);
    system->ChooseAndRunMove(step);
    cpu->Output(step);

    if((step + 1) == cpu->equilSteps) {
      double currEnergy = system->potential.totalEnergy.total;
      if(abs(currEnergy - startEnergy) > 1.0e+10) {
        printf("Info: Recalculating the total energies to insure the accuracy"
               " of the computed \n"
               "      running energies.\n\n");
        system->calcEwald->Init();
        system->potential = system->calcEnergy.SystemTotal();
      }
    }
  #if GOMC_LIB_MPI
    //
    if( step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0){

   // if( staticValues->simEventFreq.parallelTemp && step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0){
      //std::cout << "Entered outer if for pt " << step << std::endl;

      system->potential = system->calcEnergy.SystemTotal();

      if (staticValues->simEventFreq.parallelTemp){

        exchangeResults = PTUtils->evaluateExchangeCriteria(step);

       // std::cout << "Entered inner if for pt " << step << std::endl;

        if (exchangeResults[ms->worldRank] == true){

          std::cout << "swap\t" << system->potential.totalEnergy.total << std::endl;

          PTUtils->conductExchanges(system->coordinates, system->com, ms, exchangeResults);

        } else if(ms->worldRank+1 != ms->worldSize && exchangeResults[ms->worldRank+1] == true) {

          std::cout << "swap\t" << system->potential.totalEnergy.total << std::endl;

          PTUtils->conductExchanges(system->coordinates, system->com, ms, exchangeResults);

        }
      }
      system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup);

      system->potential = system->calcEnergy.SystemTotal();

    }
  #endif

#ifndef NDEBUG
    if((step + 1) % 1000 == 0)
      RunningCheck(step);
#endif
  }
  system->PrintAcceptance();
  system->PrintTime();
}

#ifndef NDEBUG
void Simulation::RunningCheck(const uint step)
{
  system->calcEwald->UpdateVectorsAndRecipTerms();
  SystemPotential pot = system->calcEnergy.SystemTotal();

  std::cout
      << "================================================================="
      << std::endl << "-------------------------" << std::endl
      << " STEP: " << step + 1
      << std::endl << "-------------------------" << std::endl
      << "Energy       INTRA B |     INTRA NB |        INTER |           TC |         REAL |         SELF |   CORRECTION |        RECIP"
      << std::endl
      << "System: "
      << std::setw(12) << system->potential.totalEnergy.intraBond << " | "
      << std::setw(12) << system->potential.totalEnergy.intraNonbond << " | "
      << std::setw(12) << system->potential.totalEnergy.inter << " | "
      << std::setw(12) << system->potential.totalEnergy.tc << " | "
      << std::setw(12) << system->potential.totalEnergy.real << " | "
      << std::setw(12) << system->potential.totalEnergy.self << " | "
      << std::setw(12) << system->potential.totalEnergy.correction << " | "
      << std::setw(12) << system->potential.totalEnergy.recip << std::endl
      << "Recalc: "
      << std::setw(12) << pot.totalEnergy.intraBond << " | "
      << std::setw(12) << pot.totalEnergy.intraNonbond << " | "
      << std::setw(12) << pot.totalEnergy.inter << " | "
      << std::setw(12) << pot.totalEnergy.tc << " | "
      << std::setw(12) << pot.totalEnergy.real << " | "
      << std::setw(12) << pot.totalEnergy.self << " | "
      << std::setw(12) << pot.totalEnergy.correction << " | "
      << std::setw(12) << pot.totalEnergy.recip << std::endl
      << "================================================================"
      << std::endl << std::endl;

}

#endif
<|endoftext|>


<commit_before>/******************************************************************************
 *  Copyright (c) 2015 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project: PageRank
 *  Filename: convert_to_bin.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hoojamis@gmail.com
 *  Date: Jul 11, 2015
 *  Time: 16:42:09
 *  Description:
 *****************************************************************************/
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_map>

std::unordered_map<std::string, uint32_t> dict;
std::vector<std::string> inverted_dict;

std::ofstream bin_input;

inline uint32_t find_no(const std::string& url) {
    auto ite = dict.find(url);
    if (ite == dict.end()) {
        uint32_t no = dict.size();
        dict.emplace(url, no);
        inverted_dict.emplace_back(url);
        return no;
    }
    return ite->second;
}

inline void output_uint32(const uint32_t x) {
    bin_input.put(x >> 24);
    bin_input.put(x >> 16);
    bin_input.put(x >>  8);
    bin_input.put(x >>  0);
}

inline void output_float(const float x) {
    uint8_t* xx = (uint8_t*)(&x);
    bin_input.put(xx[0]);
    bin_input.put(xx[1]);
    bin_input.put(xx[2]);
    bin_input.put(xx[3]);
}

inline void input(const char* line, const size_t line_length) {
    const char* header = "<page>    <title>";
    const char* tailer = "</title>";
    const size_t header_length = 17;
    const size_t tailer_length = 8;

    if (line_length < header_length + tailer_length) return;

    size_t i;

    for (i = 0; i < header_length; ++i)
        if (line[i] != header[i]) return;

    size_t match_length = 0;
    for (i = header_length; i < line_length; ++i)
        if (line[i] == tailer[match_length]) {
            ++match_length;
            if (match_length == tailer_length) break;
        } else {
            match_length = 0;
        }

    if (match_length != tailer_length) return;

    ++i;

    std::string URL(line + header_length, i - header_length - tailer_length);

    uint32_t URL_no = find_no(URL);

    output_uint32(URL_no);
    bin_input.put('\t');
    output_float(1.0f);

    while (i < line_length) {
        for (; i < line_length - 1; ++i)
            if (line[i] == '[' && line[i + 1] == '[') break;
        size_t j;
        for (j = i + 2; j < line_length - 1; ++j)
            if (line[j] == ']' && line[j + 1] == ']') {
                // [i, j] is a url
                uint32_t url_no = find_no(std::string(line + i + 2, j - i - 2));
                output_uint32(url_no);
                i = j + 2;
                break;
            }

        if (j >= line_length - 1) break;
    }
    bin_input.put('A');
    bin_input.put('B');
    bin_input.put('C');
    bin_input.put('D');
    bin_input.put('E');
    bin_input.put('F');
    bin_input.put('\n');
}

int main(int argc, char** argv) {
    std::ios_base::sync_with_stdio(false);

    if (argc < 2) return 0;

    std::ifstream fin(argv[1]);

    bin_input.open("bin_input");

    size_t counter = 0;

    std::string line;
    while (getline(fin, line)) {
        if (counter % 8 == 0)
            std::cout << counter++ << std::endl;
        input(line.data(), line.length());
    }

    // output dict
    std::ofstream fout("dictionary");
    for (const auto& i: inverted_dict)
        fout << i << '\n';
}
<commit_msg>update counter<commit_after>/******************************************************************************
 *  Copyright (c) 2015 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project: PageRank
 *  Filename: convert_to_bin.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hoojamis@gmail.com
 *  Date: Jul 11, 2015
 *  Time: 16:42:09
 *  Description:
 *****************************************************************************/
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_map>

std::unordered_map<std::string, uint32_t> dict;
std::vector<std::string> inverted_dict;

std::ofstream bin_input;

inline uint32_t find_no(const std::string& url) {
    auto ite = dict.find(url);
    if (ite == dict.end()) {
        uint32_t no = dict.size();
        dict.emplace(url, no);
        inverted_dict.emplace_back(url);
        return no;
    }
    return ite->second;
}

inline void output_uint32(const uint32_t x) {
    bin_input.put(x >> 24);
    bin_input.put(x >> 16);
    bin_input.put(x >>  8);
    bin_input.put(x >>  0);
}

inline void output_float(const float x) {
    uint8_t* xx = (uint8_t*)(&x);
    bin_input.put(xx[0]);
    bin_input.put(xx[1]);
    bin_input.put(xx[2]);
    bin_input.put(xx[3]);
}

inline void input(const char* line, const size_t line_length) {
    const char* header = "<page>    <title>";
    const char* tailer = "</title>";
    const size_t header_length = 17;
    const size_t tailer_length = 8;

    if (line_length < header_length + tailer_length) return;

    size_t i;

    for (i = 0; i < header_length; ++i)
        if (line[i] != header[i]) return;

    size_t match_length = 0;
    for (i = header_length; i < line_length; ++i)
        if (line[i] == tailer[match_length]) {
            ++match_length;
            if (match_length == tailer_length) break;
        } else {
            match_length = 0;
        }

    if (match_length != tailer_length) return;

    ++i;

    std::string URL(line + header_length, i - header_length - tailer_length);

    uint32_t URL_no = find_no(URL);

    output_uint32(URL_no);
    bin_input.put('\t');
    output_float(1.0f);

    while (i < line_length) {
        for (; i < line_length - 1; ++i)
            if (line[i] == '[' && line[i + 1] == '[') break;
        size_t j;
        for (j = i + 2; j < line_length - 1; ++j)
            if (line[j] == ']' && line[j + 1] == ']') {
                // [i, j] is a url
                uint32_t url_no = find_no(std::string(line + i + 2, j - i - 2));
                output_uint32(url_no);
                i = j + 2;
                break;
            }

        if (j >= line_length - 1) break;
    }
    bin_input.put('A');
    bin_input.put('B');
    bin_input.put('C');
    bin_input.put('D');
    bin_input.put('E');
    bin_input.put('F');
    bin_input.put('\n');
}

int main(int argc, char** argv) {
    std::ios_base::sync_with_stdio(false);

    if (argc < 2) return 0;

    std::ifstream fin(argv[1]);

    bin_input.open("bin_input");

    size_t counter = 0;

    std::string line;
    while (getline(fin, line)) {
        counter++;
        if (counter % 8192 == 0)
            std::cout << counter << std::endl;
        input(line.data(), line.length());
    }

    // output dict
    std::ofstream fout("dictionary");
    for (const auto& i: inverted_dict)
        fout << i << '\n';
}
<|endoftext|>


<commit_before>//
// BatchEncoder (Audio Conversion GUI)
// Copyright (C) 2005-2017 Wiesław Šoltés <wieslaw.soltes@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; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//

#include "StdAfx.h"
#include "BatchEncoder.h"
#include "Utf8String.h"
#include "UnicodeUtf8.h"

CUtf8String::CUtf8String()
{
    szBuffUtf8 = NULL;
}

CUtf8String::~CUtf8String()
{
    Clear();
}

char *CUtf8String::Create(CString szData)
{
#ifdef _UNICODE
    // UNICODE to UTF-8
    if (szData.GetLength() > 0)
    {
        szBuffUtf8 = (char *)MakeUtf8String(szData);
    }
    else
    {
        szBuffUtf8 = (char *)malloc(1);
        szBuffUtf8[0] = '\0';
    }

    return szBuffUtf8;
#else
    // ANSI to UTF-8
    if (szData.GetLength() > 0)
    {
        Utf8Encode(szData, &szBuffUtf8);
    }
    else
    {
        szBuffUtf8 = (char *)malloc(1);
        szBuffUtf8[0] = '\0';
    }

    return szBuffUtf8;
#endif
}

void CUtf8String::Clear()
{
    if (szBuffUtf8 != NULL)
    {
        free(szBuffUtf8);
        szBuffUtf8 = NULL;
    }
}
<commit_msg>Update Utf8String.cpp<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "StdAfx.h"
#include "BatchEncoder.h"
#include "Utf8String.h"
#include "UnicodeUtf8.h"

CUtf8String::CUtf8String()
{
    szBuffUtf8 = NULL;
}

CUtf8String::~CUtf8String()
{
    Clear();
}

char *CUtf8String::Create(CString szData)
{
#ifdef _UNICODE
    // UNICODE to UTF-8
    if (szData.GetLength() > 0)
    {
        szBuffUtf8 = (char *)MakeUtf8String(szData);
    }
    else
    {
        szBuffUtf8 = (char *)malloc(1);
        szBuffUtf8[0] = '\0';
    }

    return szBuffUtf8;
#else
    // ANSI to UTF-8
    if (szData.GetLength() > 0)
    {
        Utf8Encode(szData, &szBuffUtf8);
    }
    else
    {
        szBuffUtf8 = (char *)malloc(1);
        szBuffUtf8[0] = '\0';
    }

    return szBuffUtf8;
#endif
}

void CUtf8String::Clear()
{
    if (szBuffUtf8 != NULL)
    {
        free(szBuffUtf8);
        szBuffUtf8 = NULL;
    }
}
<|endoftext|>


<commit_before>#include "master.hpp"

namespace factor
{

profiling_sample_count profiling_sample_count::record_counts() volatile
{
	atomic::fence();
	profiling_sample_count returned(
		sample_count,
		gc_sample_count,
		foreign_sample_count,
		foreign_thread_sample_count);
	atomic::subtract(&sample_count, returned.sample_count);
	atomic::subtract(&gc_sample_count, returned.gc_sample_count);
	atomic::subtract(&foreign_sample_count, returned.foreign_sample_count);
	atomic::subtract(&foreign_thread_sample_count, returned.foreign_thread_sample_count);
	return returned;
}

void profiling_sample_count::clear() volatile
{
	sample_count = 0;
	gc_sample_count = 0;
	foreign_sample_count = 0;
	foreign_thread_sample_count = 0;
	atomic::fence();
}

profiling_sample::profiling_sample(factor_vm *vm,
	profiling_sample_count const &counts,
	context *ctx)
	:
	counts(counts),
	ctx(ctx)
{
	vm->record_callstack_sample(&callstack_begin, &callstack_end);
}

void factor_vm::record_sample()
{
	profiling_sample_count counts = safepoint_sample_counts.record_counts();
	if (!counts.empty())
		samples.push_back(profiling_sample(this, counts, ctx));
}

void factor_vm::record_callstack_sample(cell *begin, cell *end)
{
	*begin = sample_callstacks.size();
	stack_frame *frame = ctx->bottom_frame();

	while (frame >= ctx->callstack_top) {
		sample_callstacks.push_back(frame_code(frame));
		frame = frame_successor(frame);
	}

	*end = sample_callstacks.size();
}

void factor_vm::set_sampling_profiler(fixnum rate)
{
	bool sampling_p = !!rate;
	if (sampling_p == sampling_profiler_p)
		return;

	if (sampling_p)
		start_sampling_profiler(rate);
	else
		end_sampling_profiler();
}

void factor_vm::clear_samples()
{
	// Swapping into temporaries releases the vector's allocated storage,
	// whereas clear() would leave the allocation as-is
	std::vector<profiling_sample> sample_graveyard;
	std::vector<code_block*> sample_callstack_graveyard;
	samples.swap(sample_graveyard);
	sample_callstacks.swap(sample_callstack_graveyard);
}

void factor_vm::start_sampling_profiler(fixnum rate)
{
	samples_per_second = rate;
	safepoint_sample_counts.clear();
	clear_samples();
	samples.reserve(10*rate);
	sample_callstacks.reserve(100*rate);
	sampling_profiler_p = true;
	start_sampling_profiler_timer();
}

void factor_vm::end_sampling_profiler()
{
	sampling_profiler_p = false;
	atomic::fence();
	end_sampling_profiler_timer();
	record_sample();
}

void factor_vm::primitive_sampling_profiler()
{
	set_sampling_profiler(to_fixnum(ctx->pop()));
}

void factor_vm::primitive_get_samples()
{
	if (sampling_profiler_p || samples.empty()) {
		ctx->push(false_object);
	} else {
		data_root<array> samples_array(allot_array(samples.size(), false_object),this);
		std::vector<profiling_sample>::const_iterator from_iter = samples.begin();
		cell to_i = 0;

		for (; from_iter != samples.end(); ++from_iter, ++to_i)
		{
			data_root<array> sample(allot_array(6, false_object),this);

			set_array_nth(sample.untagged(),0,from_unsigned_cell(from_iter->counts.sample_count));
			set_array_nth(sample.untagged(),1,from_unsigned_cell(from_iter->counts.gc_sample_count));
			set_array_nth(sample.untagged(),2,from_unsigned_cell(from_iter->counts.foreign_sample_count));
			set_array_nth(sample.untagged(),3,from_unsigned_cell(from_iter->counts.foreign_thread_sample_count));
			set_array_nth(sample.untagged(),4,allot_alien((void*)from_iter->ctx));

			cell callstack_size = from_iter->callstack_end - from_iter->callstack_begin;
			data_root<array> callstack(allot_array(callstack_size,false_object),this);

			std::vector<code_block*>::const_iterator
				callstacks_begin = sample_callstacks.begin(),
				c_from_iter = callstacks_begin + from_iter->callstack_begin,
				c_from_iter_end = callstacks_begin + from_iter->callstack_end;
			cell c_to_i = 0;

			for (; c_from_iter != c_from_iter_end; ++c_from_iter, ++c_to_i)
				set_array_nth(callstack.untagged(),c_to_i,(*c_from_iter)->owner);

			set_array_nth(sample.untagged(),5,callstack.value());

			set_array_nth(samples_array.untagged(),to_i,sample.value());
		}
		ctx->push(samples_array.value());
	}
}

void factor_vm::primitive_clear_samples()
{
	clear_samples();
}

void factor_vm::enqueue_safepoint_sample(cell samples, cell pc, bool foreign_thread_p)
{
	if (atomic::fence(), sampling_profiler_p)
	{
		atomic::add(&safepoint_sample_counts.sample_count, samples);
		if (foreign_thread_p)
			atomic::add(&safepoint_sample_counts.foreign_thread_sample_count, samples);
		else {
			if (atomic::fence(), current_gc)
				atomic::add(&safepoint_sample_counts.gc_sample_count, samples);
			if (pc != 0 && !code->seg->in_segment_p(pc))
				atomic::add(&safepoint_sample_counts.foreign_sample_count, samples);
		}
		code->guard_safepoint();
	}
}

}
<commit_msg>vm: fix data roots in get-samples primitive<commit_after>#include "master.hpp"

namespace factor
{

profiling_sample_count profiling_sample_count::record_counts() volatile
{
	atomic::fence();
	profiling_sample_count returned(
		sample_count,
		gc_sample_count,
		foreign_sample_count,
		foreign_thread_sample_count);
	atomic::subtract(&sample_count, returned.sample_count);
	atomic::subtract(&gc_sample_count, returned.gc_sample_count);
	atomic::subtract(&foreign_sample_count, returned.foreign_sample_count);
	atomic::subtract(&foreign_thread_sample_count, returned.foreign_thread_sample_count);
	return returned;
}

void profiling_sample_count::clear() volatile
{
	sample_count = 0;
	gc_sample_count = 0;
	foreign_sample_count = 0;
	foreign_thread_sample_count = 0;
	atomic::fence();
}

profiling_sample::profiling_sample(factor_vm *vm,
	profiling_sample_count const &counts,
	context *ctx)
	:
	counts(counts),
	ctx(ctx)
{
	vm->record_callstack_sample(&callstack_begin, &callstack_end);
}

void factor_vm::record_sample()
{
	profiling_sample_count counts = safepoint_sample_counts.record_counts();
	if (!counts.empty())
		samples.push_back(profiling_sample(this, counts, ctx));
}

void factor_vm::record_callstack_sample(cell *begin, cell *end)
{
	*begin = sample_callstacks.size();
	stack_frame *frame = ctx->bottom_frame();

	while (frame >= ctx->callstack_top) {
		sample_callstacks.push_back(frame_code(frame));
		frame = frame_successor(frame);
	}

	*end = sample_callstacks.size();
}

void factor_vm::set_sampling_profiler(fixnum rate)
{
	bool sampling_p = !!rate;
	if (sampling_p == sampling_profiler_p)
		return;

	if (sampling_p)
		start_sampling_profiler(rate);
	else
		end_sampling_profiler();
}

void factor_vm::clear_samples()
{
	// Swapping into temporaries releases the vector's allocated storage,
	// whereas clear() would leave the allocation as-is
	std::vector<profiling_sample> sample_graveyard;
	std::vector<code_block*> sample_callstack_graveyard;
	samples.swap(sample_graveyard);
	sample_callstacks.swap(sample_callstack_graveyard);
}

void factor_vm::start_sampling_profiler(fixnum rate)
{
	samples_per_second = rate;
	safepoint_sample_counts.clear();
	clear_samples();
	samples.reserve(10*rate);
	sample_callstacks.reserve(100*rate);
	sampling_profiler_p = true;
	start_sampling_profiler_timer();
}

void factor_vm::end_sampling_profiler()
{
	sampling_profiler_p = false;
	atomic::fence();
	end_sampling_profiler_timer();
	record_sample();
}

void factor_vm::primitive_sampling_profiler()
{
	set_sampling_profiler(to_fixnum(ctx->pop()));
}

void factor_vm::primitive_get_samples()
{
	if (sampling_profiler_p || samples.empty()) {
		ctx->push(false_object);
	} else {
		data_root<array> samples_array(allot_array(samples.size(), false_object),this);
		std::vector<profiling_sample>::const_iterator from_iter = samples.begin();
		cell to_i = 0;

		for (; from_iter != samples.end(); ++from_iter, ++to_i)
		{
			data_root<array> sample(allot_array(6, false_object),this);

			set_array_nth(sample.untagged(),0,tag_fixnum(from_iter->counts.sample_count));
			set_array_nth(sample.untagged(),1,tag_fixnum(from_iter->counts.gc_sample_count));
			set_array_nth(sample.untagged(),2,tag_fixnum(from_iter->counts.foreign_sample_count));
			set_array_nth(sample.untagged(),3,tag_fixnum(from_iter->counts.foreign_thread_sample_count));

			cell ctx = allot_alien((void*)from_iter->ctx);
			set_array_nth(sample.untagged(),4,ctx);

			cell callstack_size = from_iter->callstack_end - from_iter->callstack_begin;
			data_root<array> callstack(allot_array(callstack_size,false_object),this);

			std::vector<code_block*>::const_iterator
				callstacks_begin = sample_callstacks.begin(),
				c_from_iter = callstacks_begin + from_iter->callstack_begin,
				c_from_iter_end = callstacks_begin + from_iter->callstack_end;
			cell c_to_i = 0;

			for (; c_from_iter != c_from_iter_end; ++c_from_iter, ++c_to_i)
				set_array_nth(callstack.untagged(),c_to_i,(*c_from_iter)->owner);

			set_array_nth(sample.untagged(),5,callstack.value());

			set_array_nth(samples_array.untagged(),to_i,sample.value());
		}
		ctx->push(samples_array.value());
	}
}

void factor_vm::primitive_clear_samples()
{
	clear_samples();
}

void factor_vm::enqueue_safepoint_sample(cell samples, cell pc, bool foreign_thread_p)
{
	if (atomic::fence(), sampling_profiler_p)
	{
		atomic::add(&safepoint_sample_counts.sample_count, samples);
		if (foreign_thread_p)
			atomic::add(&safepoint_sample_counts.foreign_thread_sample_count, samples);
		else {
			if (atomic::fence(), current_gc)
				atomic::add(&safepoint_sample_counts.gc_sample_count, samples);
			if (pc != 0 && !code->seg->in_segment_p(pc))
				atomic::add(&safepoint_sample_counts.foreign_sample_count, samples);
		}
		code->guard_safepoint();
	}
}

}
<|endoftext|>


<commit_before>/**
 * A file that contains methods for validating input.
 *
 * @author Ryan Crawford
 * @author Khalil Fazal
 * @author Joseph Heron
 * @author Carly Marshall
 */
#include "../include/Validation.h"

// Cast to string
// match with [0-9]+\.[0-9]{2}
// < Account.MAX_CREDIT and >= 0 and has a max of 2 decimal points.
// size of > 0 and =< Account.MAX_CREDIT_SIZE
// decided whether we round or truncate
bool validBalance(double balance) {
   return true;
	/**
	 * This method is current un-implemented but in the final build will be used
	 * to determine if a users balance is valid
	 */
}

// must be Account.MAX_USERNAME_LENGTH characters
// [A-z], _ and must not contain 'quit'
bool validUsername(string username) {
	if (username.length() <= 0 ||  username.length() >
			Account::MAX_USERNAME_LENGTH) {
		// Username to long
		return false;
	}

	//smatch m;
	regex userRegex ("[A-z_]+");

	if (regex_match(username, userRegex)) {
		return true;
	}
	return false;
}

// must be Ticket.MAX_EVENT_LENGTH characters
// [A-z], _ and must not contain 'quit'
bool validEventName(string event) {
	if (event.length() <= 0 || event.length() >
			Ticket::MAX_EVENT_LENGTH) {
		// Event name to long
		return false;
	}

	smatch m;
	regex EventRegex ("[A-z_]+");

	return regex_search(event, m, EventRegex);
}

// Account.ADMIN or Account.SELL or Account.BUY or Account.FULL and length 2
bool validAccountType(string type) {
	if (type.length() != 2) {
		// Account type too long
		return false;
	}

	smatch m;
	regex AccountRegex (Account::ADMIN + "|" + Account::FULL + "|" +
			Account::SELL + "|" + Account::BUY);

	return regex_search(type, m, AccountRegex);
}

// \d and > 0 and <= Ticket.MAX_TICKET
bool validTicketNumber(int ticketNum) {
	return true;
}

// \d and < Ticket.MAX_PRICE and >= 0.00 and will contain max of 2 decimal points
// must be of size > 0 and =< Ticket.MAX_PRICE_SIZE
// also decide whether to round or truncate
bool validPrice(double price) {
	return true;
	/**
	 * This method is current un-implemented but in the final build will be used
	 * to determine if a price is valid
	 */
}
<commit_msg>MODIFIED: commented out regular expression<commit_after>/**
 * A file that contains methods for validating input.
 *
 * @author Ryan Crawford
 * @author Khalil Fazal
 * @author Joseph Heron
 * @author Carly Marshall
 */
#include "../include/Validation.h"

// Cast to string
// match with [0-9]+\.[0-9]{2}
// < Account.MAX_CREDIT and >= 0 and has a max of 2 decimal points.
// size of > 0 and =< Account.MAX_CREDIT_SIZE
// decided whether we round or truncate
bool validBalance(double balance) {
   return true;
	/**
	 * This method is current un-implemented but in the final build will be used
	 * to determine if a users balance is valid
	 */
}

// must be Account.MAX_USERNAME_LENGTH characters
// [A-z], _ and must not contain 'quit'
bool validUsername(string username) {
	if (username.length() <= 0 ||  username.length() >
			Account::MAX_USERNAME_LENGTH) {
		// Username to long
		return false;
	}

	//smatch m;
	/*regex userRegex ("[A-z_]+");

	if (regex_match(username, userRegex)) {
		return true;
	}
	return false;*/
	return true;
}

// must be Ticket.MAX_EVENT_LENGTH characters
// [A-z], _ and must not contain 'quit'
bool validEventName(string event) {
	if (event.length() <= 0 || event.length() >
			Ticket::MAX_EVENT_LENGTH) {
		// Event name to long
		return false;
	}

	/*smatch m;
	regex EventRegex ("[A-z_]+");

	return regex_search(event, m, EventRegex);*/
	return true;
}

// Account.ADMIN or Account.SELL or Account.BUY or Account.FULL and length 2
bool validAccountType(string type) {
	if (type.length() != 2) {
		// Account type too long
		return false;
	}

	/*smatch m;
	regex AccountRegex (Account::ADMIN + "|" + Account::FULL + "|" +
			Account::SELL + "|" + Account::BUY);

	return regex_search(type, m, AccountRegex);*/
	return true;
}

// \d and > 0 and <= Ticket.MAX_TICKET
bool validTicketNumber(int ticketNum) {
	return true;
}

// \d and < Ticket.MAX_PRICE and >= 0.00 and will contain max of 2 decimal points
// must be of size > 0 and =< Ticket.MAX_PRICE_SIZE
// also decide whether to round or truncate
bool validPrice(double price) {
	return true;
	/**
	 * This method is current un-implemented but in the final build will be used
	 * to determine if a price is valid
	 */
}
<|endoftext|>