<commit_before>#pragma once

#include <memory>

#include <Gui/TransformEditor/TransformEditor.hpp>
#include <Gui/Utils/KeyMappingManager.hpp>
#include <Gui/Viewer/Gizmo/Gizmo.hpp>
#include <QMouseEvent>
#include <QObject>

namespace Ra {
namespace Engine {
struct ItemEntry;
}
} // namespace Ra
namespace Ra {
namespace Gui {
/// This class interfaces the gizmos with the ui commands.
/// It allows to change the gizmo type when editing an editable transform object
/// Note :  currently the scale gizmo is not implemented so it will just return a null pointer
class RA_GUI_API GizmoManager : public QObject,
                                public Gui::TransformEditor,
                                public KeyMappingManageable<GizmoManager>
{
    Q_OBJECT
    friend class KeyMappingManageable<GizmoManager>;

  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    enum GizmoType { NONE, TRANSLATION, ROTATION, SCALE };

    explicit GizmoManager( QObject* parent = nullptr );
    ~GizmoManager() = default;

  public:
    /// Receive mouse events and transmit them to the gizmos.
    virtual bool handleMousePressEvent( QMouseEvent* event,
                                        const Qt::MouseButtons& buttons,
                                        const Qt::KeyboardModifiers& modifiers,
                                        int key );
    virtual bool handleMouseReleaseEvent( QMouseEvent* event );
    virtual bool handleMouseMoveEvent( QMouseEvent* event,
                                       const Qt::MouseButtons& buttons,
                                       const Qt::KeyboardModifiers& modifiers,
                                       int key );

  public slots:
    /// Set the object being currently edited
    void setEditable( const Engine::Scene::ItemEntry& ent ) override;

    /// Destroy all gizmos
    void cleanup();

    /// Callback when a drawable is picked.
    void handlePickingResult( int drawableId );

    /// Change mode from local axis to global
    void setLocal( bool useLocal );

    /// Change gizmo type (rotation or translation)
    void changeGizmoType( GizmoType type );

    /// Retrieve the transform from the editable and update the gizmos.
    void updateValues() override;

  private:
    bool isValidAction( const Gui::KeyMappingManager::KeyMappingAction& action ) const;

    // Helper method to change the current gizmo
    void updateGizmo();

    // Returs the current gizmo
    Gizmo* currentGizmo();

  private:
    std::array<std::unique_ptr<Gizmo>, 3> m_gizmos; //! Owning pointers to the gizmos
    GizmoType m_currentGizmoType;                   //! Type of the gizmo
    Gizmo::Mode m_mode;                             //! Local/global axis mode.

    static void configureKeyMapping_impl();

#define KeyMappingGizmo                    \
    KMA_VALUE( GIZMOMANAGER_MANIPULATION ) \
    KMA_VALUE( GIZMOMANAGER_STEP )         \
    KMA_VALUE( GIZMOMANAGER_WHOLE )        \
    KMA_VALUE( GIZMOMANAGER_STEP_WHOLE )

#define KMA_VALUE( XX ) static KeyMappingManager::KeyMappingAction XX;
    KeyMappingGizmo
#undef KMA_VALUE
};
} // namespace Gui
} // namespace Ra
<commit_msg>predefine the struct ItemEntry in the right namespace<commit_after>#pragma once

#include <memory>

#include <Gui/TransformEditor/TransformEditor.hpp>
#include <Gui/Utils/KeyMappingManager.hpp>
#include <Gui/Viewer/Gizmo/Gizmo.hpp>
#include <QMouseEvent>
#include <QObject>

namespace Ra {
namespace Engine {
namespace Scene {
struct ItemEntry;
} // namespace Scene
} // namespace Engine
} // namespace Ra
namespace Ra {
namespace Gui {
/// This class interfaces the gizmos with the ui commands.
/// It allows to change the gizmo type when editing an editable transform object
/// Note :  currently the scale gizmo is not implemented so it will just return a null pointer
class RA_GUI_API GizmoManager : public QObject,
                                public Gui::TransformEditor,
                                public KeyMappingManageable<GizmoManager>
{
    Q_OBJECT
    friend class KeyMappingManageable<GizmoManager>;

  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    enum GizmoType { NONE, TRANSLATION, ROTATION, SCALE };

    explicit GizmoManager( QObject* parent = nullptr );
    ~GizmoManager() = default;

  public:
    /// Receive mouse events and transmit them to the gizmos.
    virtual bool handleMousePressEvent( QMouseEvent* event,
                                        const Qt::MouseButtons& buttons,
                                        const Qt::KeyboardModifiers& modifiers,
                                        int key );
    virtual bool handleMouseReleaseEvent( QMouseEvent* event );
    virtual bool handleMouseMoveEvent( QMouseEvent* event,
                                       const Qt::MouseButtons& buttons,
                                       const Qt::KeyboardModifiers& modifiers,
                                       int key );

  public slots:
    /// Set the object being currently edited
    void setEditable( const Engine::Scene::ItemEntry& ent ) override;

    /// Destroy all gizmos
    void cleanup();

    /// Callback when a drawable is picked.
    void handlePickingResult( int drawableId );

    /// Change mode from local axis to global
    void setLocal( bool useLocal );

    /// Change gizmo type (rotation or translation)
    void changeGizmoType( GizmoType type );

    /// Retrieve the transform from the editable and update the gizmos.
    void updateValues() override;

  private:
    bool isValidAction( const Gui::KeyMappingManager::KeyMappingAction& action ) const;

    // Helper method to change the current gizmo
    void updateGizmo();

    // Returs the current gizmo
    Gizmo* currentGizmo();

  private:
    std::array<std::unique_ptr<Gizmo>, 3> m_gizmos; //! Owning pointers to the gizmos
    GizmoType m_currentGizmoType;                   //! Type of the gizmo
    Gizmo::Mode m_mode;                             //! Local/global axis mode.

    static void configureKeyMapping_impl();

#define KeyMappingGizmo                    \
    KMA_VALUE( GIZMOMANAGER_MANIPULATION ) \
    KMA_VALUE( GIZMOMANAGER_STEP )         \
    KMA_VALUE( GIZMOMANAGER_WHOLE )        \
    KMA_VALUE( GIZMOMANAGER_STEP_WHOLE )

#define KMA_VALUE( XX ) static KeyMappingManager::KeyMappingAction XX;
    KeyMappingGizmo
#undef KMA_VALUE
};
} // namespace Gui
} // namespace Ra
<|endoftext|>


<commit_before>/*
 * bridge.cpp
 *
 *  Created on: Jun 11, 2015
 *      Author: Jinwoong Kim
 */

extern "C"{
#include "postgres.h"

#include "access/heapam.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
}

class Bridge {

 public:

  /**
   * @brief Getting the relation name.
   * @param relation id relation id
   */
  static char* GetRelationName(Oid relation_id) {
      Relation relation;
      char *relation_name;

      relation = relation_open(relation_id, NoLock);

      // Get name for given relation
      relation_name = quote_qualified_identifier(get_namespace_name(RelationGetNamespace(relation)), RelationGetRelationName(relation));

      relation_close(relation, NoLock);

      return relation_name;
   }

};

<commit_msg>Add GetNumberOfAttributes function in src/postgres/bridge<commit_after>/*
 * bridge.cpp
 *
 *  Created on: Jun 11, 2015
 *      Author: Jinwoong Kim
 */

extern "C"{
#include "postgres.h"

#include "access/heapam.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
}

class Bridge {

 public:

  /**
   * @brief Getting the relation name.
   * @param relation_id relation id
   */
  static char* GetRelationName(Oid relation_id) {
      Relation relation;
      char *relation_name;

      relation = relation_open(relation_id, NoLock);

      // Get name for given relation
     relation_name = quote_qualified_identifier(get_namespace_name(RelationGetNamespace(relation)), RelationGetRelationName(relation));

      // Simply version of above function
     // relation_name = RelationGetRelationName(relation);

      relation_close(relation, NoLock);

      return relation_name;
   }

  /**
   * @brief Getting the number of attributes.
   * @param relation_id relation id
   */
  int GetNumberOfAttributes(Oid relation_id) {
      Relation relation;
      AttrNumber numOfAttris;

      relation = relation_open(relation_id, NoLock);

      //Get the number of attributes
      numOfAttris = RelationGetNumberOfAttributes(relation);

      relation_close(relation, NoLock);

      return numOfAttris;
  }
};

<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * lxqt-connman-applet - a gui frontend for connman
 *
 * Copyright: 2014-2015 Christian Surlykke
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>

#include "strings.h"

#include "dialog.h"

Dialog::Dialog(QString service, QVariantMap request, QWidget *parent) :
    QDialog(parent), Ui::Dialog()
{
    setupUi(this);
    headingLabel->setText(headingLabel->text().arg(service));

    foreach (QString key, request.keys())
    {
        QLabel *label = new QLabel(string(key), this);
        QLineEdit *lineEdit = new QLineEdit(this);
        inputFields[key] = lineEdit;
        inputFieldsLayout->addRow(label, lineEdit);
    }
}

Dialog::~Dialog()
{
}

QVariantMap Dialog::collectedInput()
{
    QVariantMap collected;

    foreach (QString key, inputFields.keys())
    {
        collected[key] = inputFields[key]->text(); // FIXME Handle bytearrays
    }

    return collected;
}

<commit_msg>Only send fields from agent if they are none empty<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * lxqt-connman-applet - a gui frontend for connman
 *
 * Copyright: 2014-2015 Christian Surlykke
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QDebug>
#include "strings.h"

#include "dialog.h"

Dialog::Dialog(QString service, QVariantMap request, QWidget *parent) :
    QDialog(parent), Ui::Dialog()
{
    setupUi(this);
    headingLabel->setText(headingLabel->text().arg(service));

    foreach (QString key, request.keys())
    {
        QLabel *label = new QLabel(string(key), this);
        QLineEdit *lineEdit = new QLineEdit(this);
        inputFields[key] = lineEdit;
        inputFieldsLayout->addRow(label, lineEdit);
    }
}

Dialog::~Dialog()
{
}

QVariantMap Dialog::collectedInput()
{
    QVariantMap collected;

    foreach (QString key, inputFields.keys())
    {
        if (!inputFields[key]->text().trimmed().isEmpty())
        {
            collected[key] = inputFields[key]->text(); // FIXME Handle bytearrays
        }
    }

    qDebug() << "Dialog returning: " << collected << "\n";
    return collected;
}

<|endoftext|>


<commit_before>
#include "numerics/elliptic_functions.hpp"

#include <filesystem>
#include <fstream>
#include <utility>

#include "glog/logging.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "serialization/numerics.pb.h"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/is_near.hpp"

namespace principia {

using testing_utilities::AlmostEquals;
using testing_utilities::IsNear;

namespace numerics {

class EllipticFunctionsTest : public ::testing::Test {
 protected:
  serialization::TabulatedData ReadTabulatedData(
      std::filesystem::path const& tabulated_data_filename) {
    serialization::TabulatedData tabulated_data;
    std::ifstream tabulated_data_ifstream(tabulated_data_filename);
    CHECK(tabulated_data_ifstream.good());
    google::protobuf::io::IstreamInputStream tabulated_data_zcs(
        &tabulated_data_ifstream);
    CHECK(google::protobuf::TextFormat::Parse(&tabulated_data_zcs,
                                              &tabulated_data));
    CHECK_LT(0, tabulated_data.entry_size());
    return tabulated_data;
  }
};

TEST_F(EllipticFunctionsTest, Xgscd) {
  // These expected values come from the output given by Fukushima at the end of
  // his xgscd.txt.  For our purpose, an unit test with assertions is more
  // useful than eyeballing the output.
  auto xgscd_expected =
      ReadTabulatedData(SOLUTION_DIR / "numerics" / "xgscd.proto.txt");
  constexpr double PI = 3.1415926535897932384626433;
  constexpr double PIHALF = PI * 0.5;
  double dmc, mc, m, du, u, s, c, d;
  int jend, iend;
  jend = 10;
  iend = 8;
  dmc = 1.0 / static_cast<double>(jend);
  std::printf("%10s%10s%25s%25s%25s\n", "m", "u", "s", "c", "d");
  int expected_index = 0;
  for (int j = 1; j <= jend; ++j) {
    mc = static_cast<double>(j) * dmc;
    m = 1.0 - mc;
    du = Elk(mc) / static_cast<double>(iend);
    for (int i = 0; i <= iend * 8; ++i) {
      u = du * static_cast<double>(i);
      Gscd(u, mc, s, c, d);
      std::printf("%10.5f%10.5f%25.15e%25.15e%25.15e\n", m, u, s, c, d);

      auto const& expected_entry = xgscd_expected.entry(expected_index);
      auto const expected_argument_u = expected_entry.argument(0);
      auto const expected_argument_mc = expected_entry.argument(1);
      auto const expected_value_s = expected_entry.value(0);
      auto const expected_value_c = expected_entry.value(1);
      auto const expected_value_d = expected_entry.value(2);
      EXPECT_THAT(u, IsNear(expected_argument_u, 1.001));
      EXPECT_THAT(mc, IsNear(expected_argument_mc, 1.001));
      EXPECT_THAT(s, AlmostEquals(expected_value_s, 0, 0));
      EXPECT_THAT(c, AlmostEquals(expected_value_c, 0, 0));
      EXPECT_THAT(d, AlmostEquals(expected_value_d, 0, 0));
      ++expected_index;
    }
    std::printf("\n");
  }
}

}  // namespace numerics
}  // namespace principia
<commit_msg>The test passes.<commit_after>
#include "numerics/elliptic_functions.hpp"

#include <filesystem>
#include <fstream>
#include <utility>

#include "glog/logging.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "serialization/numerics.pb.h"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/is_near.hpp"

namespace principia {

using testing_utilities::AlmostEquals;
using testing_utilities::IsNear;

namespace numerics {

class EllipticFunctionsTest : public ::testing::Test {
 protected:
  serialization::TabulatedData ReadTabulatedData(
      std::filesystem::path const& tabulated_data_filename) {
    serialization::TabulatedData tabulated_data;
    std::ifstream tabulated_data_ifstream(tabulated_data_filename);
    CHECK(tabulated_data_ifstream.good());
    google::protobuf::io::IstreamInputStream tabulated_data_zcs(
        &tabulated_data_ifstream);
    CHECK(google::protobuf::TextFormat::Parse(&tabulated_data_zcs,
                                              &tabulated_data));
    CHECK_LT(0, tabulated_data.entry_size());
    return tabulated_data;
  }
};

TEST_F(EllipticFunctionsTest, Xgscd) {
  // These expected values come from the output given by Fukushima at the end of
  // his xgscd.txt.  For our purpose, an unit test with assertions is more
  // useful than eyeballing the output.
  auto xgscd_expected =
      ReadTabulatedData(SOLUTION_DIR / "numerics" / "xgscd.proto.txt");
  constexpr double PI = 3.1415926535897932384626433;
  constexpr double PIHALF = PI * 0.5;
  double dmc, mc, m, du, u, s, c, d;
  int jend, iend;
  jend = 10;
  iend = 8;
  dmc = 1.0 / static_cast<double>(jend);
  std::printf("%10s%10s%25s%25s%25s\n", "m", "u", "s", "c", "d");
  int expected_index = 0;
  for (int j = 1; j <= jend; ++j) {
    mc = static_cast<double>(j) * dmc;
    m = 1.0 - mc;
    du = Elk(mc) / static_cast<double>(iend);
    for (int i = 0; i <= iend * 8; ++i) {
      u = du * static_cast<double>(i);
      Gscd(u, mc, s, c, d);
      std::printf("%10.5f%10.5f%25.15e%25.15e%25.15e\n", m, u, s, c, d);

      auto const& expected_entry = xgscd_expected.entry(expected_index);
      auto const expected_argument_m = expected_entry.argument(0);
      auto const expected_argument_u = expected_entry.argument(1);
      auto const expected_value_s = expected_entry.value(0);
      auto const expected_value_c = expected_entry.value(1);
      auto const expected_value_d = expected_entry.value(2);
      EXPECT_THAT(m, IsNear(expected_argument_m, 1.001));
      EXPECT_THAT(u, IsNear(expected_argument_u, 1.001));
      EXPECT_THAT(s, AlmostEquals(expected_value_s, 0, 2));
      EXPECT_THAT(c, AlmostEquals(expected_value_c, 0, 3));
      EXPECT_THAT(d, AlmostEquals(expected_value_d, 0, 1));
      ++expected_index;
    }
    std::printf("\n");
  }
}

}  // namespace numerics
}  // namespace principia
<|endoftext|>


<commit_before>
// Note - pyconfig.h must be included before condor_common to avoid
// re-definition warnings.
# include <pyconfig.h>

#include "condor_common.h"
#include "condor_config.h"
#include "condor_version.h"
#include "param_info.h"

#include <boost/python.hpp>

#include "old_boost.h"

using namespace boost::python;

struct Param
{
    bool contains(const std::string &attr)
    {
        std::string result;
        return param(result, attr.c_str());
    }

    static object param_to_py(const char *attr, const MACRO_META *pmeta, const char *raw_string)
    {
        param_info_t_type_t ty = param_default_type_by_id(pmeta->param_id);
        object pyresult;
        switch (ty)
        {
        case PARAM_TYPE_STRING:
        {
            std::string result;
            if (!param(result, attr)) { THROW_EX(ValueError, ("Unable to convert value for param " + std::string(attr) + " to string (raw value " + raw_string + ")").c_str()); }
            pyresult = object(result);
            break;
        }
        case PARAM_TYPE_INT:
        {
            int result = param_integer(attr);
            pyresult = object(result);
            break;
        }
        case PARAM_TYPE_BOOL:
        {
            bool result = param_boolean(attr, result);
            pyresult = object(result);
            break;
        }
        case PARAM_TYPE_DOUBLE:
        {
            double result = param_double(attr);
            pyresult = object(result);
            break;
        }
        case PARAM_TYPE_LONG:
        {
            long long result = param_integer(attr, result);
            pyresult = object(result);
            break;
        }
        }
        return pyresult;
    }

    object getitem_impl(const std::string &attr, object default_val, bool throw_exception)
    {
        MyString name_used;
        const char *pdef_value;
        const MACRO_META *pmeta;
        const char * result_str = param_get_info(attr.c_str(), NULL, NULL, name_used, &pdef_value, &pmeta);
        if (!result_str)
        {
            if (throw_exception)
            {
                THROW_EX(KeyError, attr.c_str());
            }
            else
            {
                return default_val;
            }
        }
        try
        {
            return param_to_py(attr.c_str(), pmeta, result_str);
        }
        catch (error_already_set)
        {
            PyErr_Clear();
            return object(result_str);
        }
    }

    object getitem(const std::string &attr)
    {
        return getitem_impl(attr, object(), true);
    }

    object get(const std::string &attr, object default_val)
    {
        return getitem_impl(attr, default_val, false);
    }

    void setitem(const std::string &attr, const std::string &val)
    {
        param_insert(attr.c_str(), val.c_str());
    }

    std::string setdefault(const std::string &attr, const std::string &def)
    {
        std::string result;
        if (!param(result, attr.c_str()))
        {
           param_insert(attr.c_str(), def.c_str());
           return def;
        }
        return result;
    }

    static bool keys_processor(void* user, HASHITER& it)
    {
        if (PyErr_Occurred()) { return true; }

        list &results = *static_cast<list*>(user);
        const char * name = hash_iter_key(it);
        const char * value = hash_iter_value(it);
        if (!name || !value) { return true; }
        try
        {
            results.append(name);
        }
        catch (error_already_set)
        {
            // Suppress the C++ exception.  The HTCondor code is not thread safe.
        }
        return true;
    }

    list keys()
    {
        list results;
        void *results_ptr = static_cast<void*>(&results);
        foreach_param(0, &keys_processor, results_ptr);
        if (PyErr_Occurred())
        {
            throw_error_already_set();
        }
        return results;
    }

    object iter()
    {
        return keys().attr("__iter__")();
    }

    static bool len_processor(void* user, HASHITER& it)
    {
        if (PyErr_Occurred()) { return true; }

        unsigned long &result = *static_cast<unsigned long*>(user);
        const char * name = hash_iter_key(it);
        const char * value = hash_iter_value(it);
        if (!name || !value) { return true; }
        result++;
        return true;
    }

    unsigned long len()
    {
        unsigned long result = 0;
        void *result_ptr = static_cast<void*>(&result);
        foreach_param(0, &len_processor, result_ptr);
        if (PyErr_Occurred())
        {
            throw_error_already_set();
        }
        return result;
    }

    static bool items_processor(void* user, HASHITER& it)
    {
        if (PyErr_Occurred()) return true;

        list &results = *static_cast<list*>(user);
        const char * name = hash_iter_key(it);
        const char * value = hash_iter_value(it);
        if (!name || !value) { return true; }
        try
        {
            MACRO_META *pmeta = hash_iter_meta(it);
            object pyvalue;
            try
            {
                pyvalue = param_to_py(name, pmeta, value);
            }
            catch (error_already_set)
            {
                PyErr_Clear();
                pyvalue = object(value);
            }
            results.append(make_tuple<std::string, object>(name, pyvalue));
        }
        catch (error_already_set)
        {
            // Suppress the python-to-C++ exception.  The HTCondor code is not thread safe.
            // This will set PyErr_Occurred so eventually the python exception fires.
        }
        return true;
    }

    list items()
    {
        list results;
        void *results_ptr = static_cast<void*>(&results);
        foreach_param(0, &items_processor, results_ptr);
        if (PyErr_Occurred())
        {
            throw_error_already_set();
        }
        return results;
    }

    void update(boost::python::object source)
    {
        // See if we have a dictionary-like object.
        if (py_hasattr(source, "items"))
        {
            return this->update(source.attr("items")());
        }
        if (!py_hasattr(source, "__iter__")) { THROW_EX(ValueError, "Must provide a dictionary-like object to update()"); }

        object iter = source.attr("__iter__")();
        while (true) {
            PyObject *pyobj = PyIter_Next(iter.ptr());
            if (!pyobj) break;
            if (PyErr_Occurred()) {
                throw_error_already_set();
            }

            object obj = object(handle<>(pyobj));

            tuple tup = extract<tuple>(obj);
            std::string attr = extract<std::string>(tup[0]);
            std::string value = extract<std::string>(tup[1]);
            setitem(attr, value);
        }
    }

};

std::string CondorVersionWrapper() { return CondorVersion(); }

std::string CondorPlatformWrapper() { return CondorPlatform(); }

//BOOST_PYTHON_FUNCTION_OVERLOADS(config_overloads, config, 0, 3);
void configWrapper() { config(); }

void export_config()
{
    config_ex(CONFIG_OPT_NO_EXIT | CONFIG_OPT_WANT_META);
    def("version", CondorVersionWrapper, "Returns the version of HTCondor this module is linked against.");
    def("platform", CondorPlatformWrapper, "Returns the platform of HTCondor this module is running on.");
    def("reload_config", configWrapper, "Reload the HTCondor configuration from disk.");
    class_<Param>("_Param")
        .def("__getitem__", &Param::getitem)
        .def("__setitem__", &Param::setitem)
        .def("__contains__", &Param::contains)
        .def("setdefault", &Param::setdefault)
        .def("get", &Param::get, "Returns the value associated with the key; if the key is not a defined parameter, returns the default argument.  Default is None.", (arg("self"), arg("key"), arg("default")=object()))
        .def("keys", &Param::keys)
        .def("__iter__", &Param::iter)
        .def("__len__", &Param::len)
        .def("items", &Param::items)
        .def("update", &Param::update)
        ;
    object param = object(Param());
    param.attr("__doc__") = "A dictionary-like object containing the HTCondor configuration.";
    scope().attr("param") = param;
}
<commit_msg>Avoid warnings on Fedora. #4336<commit_after>
// Note - pyconfig.h must be included before condor_common to avoid
// re-definition warnings.
# include <pyconfig.h>

#include "condor_common.h"
#include "condor_config.h"
#include "condor_version.h"
#include "param_info.h"

#include <boost/python.hpp>

#include "old_boost.h"

using namespace boost::python;

struct Param
{
    bool contains(const std::string &attr)
    {
        std::string result;
        return param(result, attr.c_str());
    }

    static object param_to_py(const char *attr, const MACRO_META *pmeta, const char *raw_string)
    {
        param_info_t_type_t ty = param_default_type_by_id(pmeta->param_id);
        object pyresult;
        switch (ty)
        {
        case PARAM_TYPE_STRING:
        {
            std::string result;
            if (!param(result, attr)) { THROW_EX(ValueError, ("Unable to convert value for param " + std::string(attr) + " to string (raw value " + raw_string + ")").c_str()); }
            pyresult = object(result);
            break;
        }
        case PARAM_TYPE_INT:
        {
            int result = param_integer(attr);
            pyresult = object(result);
            break;
        }
        case PARAM_TYPE_BOOL:
        {
            bool result = param_boolean(attr, false);
            pyresult = object(result);
            break;
        }
        case PARAM_TYPE_DOUBLE:
        {
            double result = param_double(attr);
            pyresult = object(result);
            break;
        }
        case PARAM_TYPE_LONG:
        {
            long long result = param_integer(attr);
            pyresult = object(result);
            break;
        }
        }
        return pyresult;
    }

    object getitem_impl(const std::string &attr, object default_val, bool throw_exception)
    {
        MyString name_used;
        const char *pdef_value;
        const MACRO_META *pmeta;
        const char * result_str = param_get_info(attr.c_str(), NULL, NULL, name_used, &pdef_value, &pmeta);
        if (!result_str)
        {
            if (throw_exception)
            {
                THROW_EX(KeyError, attr.c_str());
            }
            else
            {
                return default_val;
            }
        }
        try
        {
            return param_to_py(attr.c_str(), pmeta, result_str);
        }
        catch (error_already_set)
        {
            PyErr_Clear();
            return object(result_str);
        }
    }

    object getitem(const std::string &attr)
    {
        return getitem_impl(attr, object(), true);
    }

    object get(const std::string &attr, object default_val)
    {
        return getitem_impl(attr, default_val, false);
    }

    void setitem(const std::string &attr, const std::string &val)
    {
        param_insert(attr.c_str(), val.c_str());
    }

    std::string setdefault(const std::string &attr, const std::string &def)
    {
        std::string result;
        if (!param(result, attr.c_str()))
        {
           param_insert(attr.c_str(), def.c_str());
           return def;
        }
        return result;
    }

    static bool keys_processor(void* user, HASHITER& it)
    {
        if (PyErr_Occurred()) { return true; }

        list &results = *static_cast<list*>(user);
        const char * name = hash_iter_key(it);
        const char * value = hash_iter_value(it);
        if (!name || !value) { return true; }
        try
        {
            results.append(name);
        }
        catch (error_already_set)
        {
            // Suppress the C++ exception.  The HTCondor code is not thread safe.
        }
        return true;
    }

    list keys()
    {
        list results;
        void *results_ptr = static_cast<void*>(&results);
        foreach_param(0, &keys_processor, results_ptr);
        if (PyErr_Occurred())
        {
            throw_error_already_set();
        }
        return results;
    }

    object iter()
    {
        return keys().attr("__iter__")();
    }

    static bool len_processor(void* user, HASHITER& it)
    {
        if (PyErr_Occurred()) { return true; }

        unsigned long &result = *static_cast<unsigned long*>(user);
        const char * name = hash_iter_key(it);
        const char * value = hash_iter_value(it);
        if (!name || !value) { return true; }
        result++;
        return true;
    }

    unsigned long len()
    {
        unsigned long result = 0;
        void *result_ptr = static_cast<void*>(&result);
        foreach_param(0, &len_processor, result_ptr);
        if (PyErr_Occurred())
        {
            throw_error_already_set();
        }
        return result;
    }

    static bool items_processor(void* user, HASHITER& it)
    {
        if (PyErr_Occurred()) return true;

        list &results = *static_cast<list*>(user);
        const char * name = hash_iter_key(it);
        const char * value = hash_iter_value(it);
        if (!name || !value) { return true; }
        try
        {
            MACRO_META *pmeta = hash_iter_meta(it);
            object pyvalue;
            try
            {
                pyvalue = param_to_py(name, pmeta, value);
            }
            catch (error_already_set)
            {
                PyErr_Clear();
                pyvalue = object(value);
            }
            results.append(make_tuple<std::string, object>(name, pyvalue));
        }
        catch (error_already_set)
        {
            // Suppress the python-to-C++ exception.  The HTCondor code is not thread safe.
            // This will set PyErr_Occurred so eventually the python exception fires.
        }
        return true;
    }

    list items()
    {
        list results;
        void *results_ptr = static_cast<void*>(&results);
        foreach_param(0, &items_processor, results_ptr);
        if (PyErr_Occurred())
        {
            throw_error_already_set();
        }
        return results;
    }

    void update(boost::python::object source)
    {
        // See if we have a dictionary-like object.
        if (py_hasattr(source, "items"))
        {
            return this->update(source.attr("items")());
        }
        if (!py_hasattr(source, "__iter__")) { THROW_EX(ValueError, "Must provide a dictionary-like object to update()"); }

        object iter = source.attr("__iter__")();
        while (true) {
            PyObject *pyobj = PyIter_Next(iter.ptr());
            if (!pyobj) break;
            if (PyErr_Occurred()) {
                throw_error_already_set();
            }

            object obj = object(handle<>(pyobj));

            tuple tup = extract<tuple>(obj);
            std::string attr = extract<std::string>(tup[0]);
            std::string value = extract<std::string>(tup[1]);
            setitem(attr, value);
        }
    }

};

std::string CondorVersionWrapper() { return CondorVersion(); }

std::string CondorPlatformWrapper() { return CondorPlatform(); }

//BOOST_PYTHON_FUNCTION_OVERLOADS(config_overloads, config, 0, 3);
void configWrapper() { config(); }

void export_config()
{
    config_ex(CONFIG_OPT_NO_EXIT | CONFIG_OPT_WANT_META);
    def("version", CondorVersionWrapper, "Returns the version of HTCondor this module is linked against.");
    def("platform", CondorPlatformWrapper, "Returns the platform of HTCondor this module is running on.");
    def("reload_config", configWrapper, "Reload the HTCondor configuration from disk.");
    class_<Param>("_Param")
        .def("__getitem__", &Param::getitem)
        .def("__setitem__", &Param::setitem)
        .def("__contains__", &Param::contains)
        .def("setdefault", &Param::setdefault)
        .def("get", &Param::get, "Returns the value associated with the key; if the key is not a defined parameter, returns the default argument.  Default is None.", (arg("self"), arg("key"), arg("default")=object()))
        .def("keys", &Param::keys)
        .def("__iter__", &Param::iter)
        .def("__len__", &Param::len)
        .def("items", &Param::items)
        .def("update", &Param::update)
        ;
    object param = object(Param());
    param.attr("__doc__") = "A dictionary-like object containing the HTCondor configuration.";
    scope().attr("param") = param;
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  lab2
//
//  Created by Dylan Brown on 2/5/14.
//  Copyright (c) 2014 Dylan Brown. All rights reserved.
//

#include <iostream>
#include "BitMap.h"
#include "FreeList.h"

int main(int argc, const char * argv[])
{

    /* Create a BitMap object and blocks array */
    BitMap map = BitMap();
    const int numBlocks = 10;
    unsigned int blocks[numBlocks] = {0};

    /* Output the blocks array, or error if search failed */
    if (map.search(numBlocks, blocks)) {
        std::cout << "List of " << numBlocks << " available blocks: ";
        for (int i = 0; i < numBlocks; i++) {
            std::cout << blocks[i] << " ";
        }
        std::cout << "\n";
    } else {
        std::cout << "Insufficient disk space available!\n";
    }

    /* Test writeBlocks and deleteBlocks */
    map.writeBlocks(numBlocks, blocks);
    unsigned int testBlocks[numBlocks];
    if (map.search(numBlocks, testBlocks)) {
        std::cout << "List of " << numBlocks << " available blocks: ";
        for (int i = 0; i < numBlocks; i++) {
            std::cout << testBlocks[i] << " ";
        }
        std::cout << "\n";
    } else {
        std::cout << "Insufficient disk space available!\n";
    }
    map.deleteBlocks(numBlocks, blocks);
    if (map.search(numBlocks, testBlocks)) {
        std::cout << "List of " << numBlocks << " available blocks: ";
        for (int i = 0; i < numBlocks; i++) {
            std::cout << testBlocks[i] << " ";
        }
        std::cout << "\n";
    } else {
        std::cout << "Insufficient disk space available!\n";
    }

    /* Test consecutive search */
    unsigned int consecutiveBlocks[numBlocks];
    unsigned int *blockAddress = consecutiveBlocks;
    if (map.searchConsecutive(numBlocks, 1, blockAddress)) {
        std::cout << "List of " << numBlocks << " consecutive blocks: ";
        for (int i = 0; i < numBlocks; i++) {
            std::cout << consecutiveBlocks[i] << " ";
        }
        std::cout << "\n";
    } else {
        std::cout << "Insufficient disk space available!\n";
    }

    /* Test FreeList */
    FreeList freelist = FreeList();
    unsigned int listBlocks[numBlocks];
    freelist.writeBlocks(numBlocks, listBlocks);
    freelist.deleteBlocks(numBlocks, listBlocks);
    if (freelist.writeBlocks(numBlocks, listBlocks)) {
        std::cout << "List of " << numBlocks << " list blocks: ";
        for (int i = 0; i < numBlocks; i++) {
            std::cout << listBlocks[i] << " ";
        }
        std::cout << "\n";
    } else {
        std::cout << "Insufficient disk space available!\n";
    }

    return 0;
}
<commit_msg>Made main() function of test drivers presentable. No more spaghetti code!<commit_after>//
//  main.cpp
//  lab2
//
//  Created by Dylan Brown on 2/5/14.
//  Copyright (c) 2014 Dylan Brown. All rights reserved.
//

#include <iostream>
#include "BitMap.h"
#include "FreeList.h"

/* Below is a collection of test output functions.
 * The arguments 'BitMap& map' and 'FreeList& freelist' are
 * class instances passed into the functions by reference.
 */

void testSearch(BitMap& map, int numBlocks, unsigned int blocks[]) {
    if (map.search(numBlocks, blocks)) {
        for (int i = 0; i < numBlocks; i++) {
            std::cout << blocks[i] << " ";
        }
        std::cout << "\n";
    } else {
        std::cout << "Insufficient disk space available!\n";
    }
}

void testSearch(FreeList& freelist, int numBlocks, unsigned int listBlocks[]) {
    if (freelist.writeBlocks(numBlocks, listBlocks)) {
        for (int i = 0; i < numBlocks; i++) {
            std::cout << listBlocks[i] << " ";
        }
        std::cout << "\n";
    } else {
        std::cout << "Insufficient disk space available!\n";
    }
}

void testConsecutiveSearch(BitMap& map, int numBlocks, unsigned int blocks[]) {
    if (map.searchConsecutive(numBlocks, 1, blocks)) {
        for (int i = 0; i < numBlocks; i++) {
            std::cout << blocks[i] << " ";
        }
        std::cout << "\n";
    } else {
        std::cout << "Insufficient disk space available!\n";
    }
}

int main(int argc, const char * argv[])
{

// (1) TEST the BitMap class
    std::cout << "-- PART 1: BitMap --\n\n";

    /* Create a BitMap object and blocks array with numBlocks elements initialized to zero */
    BitMap map = BitMap();
    const int numBlocks = 10;
    unsigned int blocks[numBlocks] = {0};

    /* Search in the BitMap to fill the blocks array, or error if search failed */
    std::cout << "List of first " << numBlocks << " free blocks in BitMap: ";
    testSearch(map, numBlocks, blocks);

    /* Test writeBlocks and search again for numBlocks free blocks */
    map.writeBlocks(numBlocks, blocks);
    std::cout << "\nBlocks WRITTEN to BitMap.\n\n";
    unsigned int nextBlocks[numBlocks];
    std::cout << "List of next " << numBlocks << " free blocks in BitMap: ";
    testSearch(map, numBlocks, nextBlocks);

    /* Test deleteBlocks and search again for numBlocks free blocks */
    map.deleteBlocks(numBlocks, blocks);
    std::cout << "\nFirst group of blocks DELETED from BitMap.\n\n";
    std::cout << "List of next " << numBlocks << " free blocks in BitMap: ";
    testSearch(map, numBlocks, blocks);

    /* Test consecutive search */
    unsigned int consecutiveBlocks[numBlocks];
    std::cout << "\nList of " << numBlocks << " consecutive free blocks: ";
    testConsecutiveSearch(map, numBlocks, consecutiveBlocks);

// (2) TEST the FreeList class
    std::cout << "\n\n-- PART 2: FreeList --\n\n";

    /* Create an instance of FreeList and another array of numBlocks blocks */
    FreeList freelist = FreeList();
    unsigned int listBlocks[numBlocks];

    /* Test searching for the first numBlocks blocks in the FreeList */
    std::cout << "Writing to first " << numBlocks << " free blocks in FreeList: ";
    testSearch(freelist, numBlocks, listBlocks);

    /* Test the freeing of blocks to the FreeList */
    freelist.deleteBlocks(numBlocks, listBlocks);
    std::cout << "\nFirst " << numBlocks << " blocks DELETED and appended to FreeList.\n\n";

    /* Test searching for the next numBlocks available blocks */
    std::cout << "List of next " << numBlocks << " free blocks in FreeList: ";
    testSearch(freelist, numBlocks, listBlocks);
    std::cout << "\n";

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Sketcher: [skip ci] fix bad static_cast<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <qt/askpassphrasedialog.h>
#include <qt/forms/ui_askpassphrasedialog.h>

#include <qt/guiconstants.h>
#include <qt/walletmodel.h>

#include <support/allocators/secure.h>

#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>

AskPassphraseDialog::AskPassphraseDialog(Mode _mode, QWidget *parent, SecureString* passphrase_out) :
    QDialog(parent),
    ui(new Ui::AskPassphraseDialog),
    mode(_mode),
    model(nullptr),
    fCapsLock(false),
    m_passphrase_out(passphrase_out)
{
    ui->setupUi(this);

    ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
    ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
    ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());

    ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
    ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
    ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);

    // Setup Caps Lock detection.
    ui->passEdit1->installEventFilter(this);
    ui->passEdit2->installEventFilter(this);
    ui->passEdit3->installEventFilter(this);

    switch(mode)
    {
        case Encrypt: // Ask passphrase x2
            ui->warningLabel->setText(tr("Enter the new passphrase for the wallet.
Please use a passphrase of ten or more random characters, or eight or more words."));
            ui->passLabel1->hide();
            ui->passEdit1->hide();
            setWindowTitle(tr("Encrypt wallet"));
            break;
        case Unlock: // Ask passphrase
            ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
            ui->passLabel2->hide();
            ui->passEdit2->hide();
            ui->passLabel3->hide();
            ui->passEdit3->hide();
            setWindowTitle(tr("Unlock wallet"));
            break;
        case Decrypt:   // Ask passphrase
            ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
            ui->passLabel2->hide();
            ui->passEdit2->hide();
            ui->passLabel3->hide();
            ui->passEdit3->hide();
            setWindowTitle(tr("Decrypt wallet"));
            break;
        case ChangePass: // Ask old passphrase + new passphrase x2
            setWindowTitle(tr("Change passphrase"));
            ui->warningLabel->setText(tr("Enter the old passphrase and new passphrase for the wallet."));
            break;
    }
    textChanged();
    connect(ui->toggleShowPasswordButton, &QPushButton::toggled, this, &AskPassphraseDialog::toggleShowPassword);
    connect(ui->passEdit1, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);
    connect(ui->passEdit2, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);
    connect(ui->passEdit3, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);
}

AskPassphraseDialog::~AskPassphraseDialog()
{
    secureClearPassFields();
    delete ui;
}

void AskPassphraseDialog::setModel(WalletModel *_model)
{
    this->model = _model;
}

void AskPassphraseDialog::accept()
{
    SecureString oldpass, newpass1, newpass2;
    if (!model && mode != Encrypt)
        return;
    oldpass.reserve(MAX_PASSPHRASE_SIZE);
    newpass1.reserve(MAX_PASSPHRASE_SIZE);
    newpass2.reserve(MAX_PASSPHRASE_SIZE);
    // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
    // Alternately, find a way to make this input mlock()'d to begin with.
    oldpass.assign(ui->passEdit1->text().toStdString().c_str());
    newpass1.assign(ui->passEdit2->text().toStdString().c_str());
    newpass2.assign(ui->passEdit3->text().toStdString().c_str());

    secureClearPassFields();

    switch(mode)
    {
    case Encrypt: {
        if(newpass1.empty() || newpass2.empty())
        {
            // Cannot encrypt with empty passphrase
            break;
        }
        QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
                 tr("Warning: If you encrypt your wallet and lose your passphrase, you will LOSE ALL OF YOUR VERTCOIN!") + "

" + tr("Are you sure you wish to encrypt your wallet?"),
                 QMessageBox::Yes|QMessageBox::Cancel,
                 QMessageBox::Cancel);
        if(retval == QMessageBox::Yes)
        {
            if(newpass1 == newpass2)
            {
                QString encryption_reminder = tr("Remember that encrypting your wallet cannot fully protect "
                "your bitcoins from being stolen by malware infecting your computer.");
                if (m_passphrase_out) {
                    m_passphrase_out->assign(newpass1);
                    QMessageBox::warning(this, tr("Wallet to be encrypted"),
                                         "<qt>" +
                                         tr("Your wallet is about to be encrypted. ") + encryption_reminder +
                                         "</qt>");
                } else {
                    assert(model != nullptr);
                    if(model->setWalletEncrypted(true, newpass1))
                    {
                        QMessageBox::warning(this, tr("Wallet encrypted"),
                                             "<qt>" +
                                             tr("Your wallet is now encrypted. ") + encryption_reminder +
                                             "

" +
                                             tr("IMPORTANT: Any previous backups you have made of your wallet file "
                                             "should be replaced with the newly generated, encrypted wallet file. "
                                             "For security reasons, previous backups of the unencrypted wallet file "
                                             "will become useless as soon as you start using the new, encrypted wallet.") +
                                             "</qt>");
                    }
                    else
                    {
                        QMessageBox::critical(this, tr("Wallet encryption failed"),
                                             tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
                    }
                }
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The supplied passphrases do not match."));
            }
        }
        else
        {
            QDialog::reject(); // Cancelled
        }
        } break;
    case Unlock:
        try {
            if (!model->setWalletLocked(false, oldpass)) {
                QMessageBox::critical(this, tr("Wallet unlock failed"),
                                      tr("The passphrase entered for the wallet decryption was incorrect."));
            } else {
                QDialog::accept(); // Success
            }
        } catch (const std::runtime_error& e) {
            QMessageBox::critical(this, tr("Wallet unlock failed"), e.what());
        }
        break;
    case Decrypt:
        if(!model->setWalletEncrypted(false, oldpass))
        {
            QMessageBox::critical(this, tr("Wallet decryption failed"),
                                  tr("The passphrase entered for the wallet decryption was incorrect."));
        }
        else
        {
            QDialog::accept(); // Success
        }
        break;
    case ChangePass:
        if(newpass1 == newpass2)
        {
            if(model->changePassphrase(oldpass, newpass1))
            {
                QMessageBox::information(this, tr("Wallet encrypted"),
                                     tr("Wallet passphrase was successfully changed."));
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The passphrase entered for the wallet decryption was incorrect."));
            }
        }
        else
        {
            QMessageBox::critical(this, tr("Wallet encryption failed"),
                                 tr("The supplied passphrases do not match."));
        }
        break;
    }
}

void AskPassphraseDialog::textChanged()
{
    // Validate input, set Ok button to enabled when acceptable
    bool acceptable = false;
    switch(mode)
    {
    case Encrypt: // New passphrase x2
        acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
        break;
    case Unlock: // Old passphrase x1
    case Decrypt:
        acceptable = !ui->passEdit1->text().isEmpty();
        break;
    case ChangePass: // Old passphrase x1, new passphrase x2
        acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
        break;
    }
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}

bool AskPassphraseDialog::event(QEvent *event)
{
    // Detect Caps Lock key press.
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        if (ke->key() == Qt::Key_CapsLock) {
            fCapsLock = !fCapsLock;
        }
        if (fCapsLock) {
            ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
        } else {
            ui->capsLabel->clear();
        }
    }
    return QWidget::event(event);
}

void AskPassphraseDialog::toggleShowPassword(bool show)
{
    ui->toggleShowPasswordButton->setDown(show);
    const auto mode = show ? QLineEdit::Normal : QLineEdit::Password;
    ui->passEdit1->setEchoMode(mode);
    ui->passEdit2->setEchoMode(mode);
    ui->passEdit3->setEchoMode(mode);
}

bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
    /* Detect Caps Lock.
     * There is no good OS-independent way to check a key state in Qt, but we
     * can detect Caps Lock by checking for the following condition:
     * Shift key is down and the result is a lower case character, or
     * Shift key is not down and the result is an upper case character.
     */
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        QString str = ke->text();
        if (str.length() != 0) {
            const QChar *psz = str.unicode();
            bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
            if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
                fCapsLock = true;
                ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
            } else if (psz->isLetter()) {
                fCapsLock = false;
                ui->capsLabel->clear();
            }
        }
    }
    return QDialog::eventFilter(object, event);
}

static void SecureClearQLineEdit(QLineEdit* edit)
{
    // Attempt to overwrite text so that they do not linger around in memory
    edit->setText(QString(" ").repeated(edit->text().size()));
    edit->clear();
}

void AskPassphraseDialog::secureClearPassFields()
{
    SecureClearQLineEdit(ui->passEdit1);
    SecureClearQLineEdit(ui->passEdit2);
    SecureClearQLineEdit(ui->passEdit3);
}
<commit_msg>Update askpassphrasedialog.cpp<commit_after>// Copyright (c) 2011-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <qt/askpassphrasedialog.h>
#include <qt/forms/ui_askpassphrasedialog.h>

#include <qt/guiconstants.h>
#include <qt/walletmodel.h>

#include <support/allocators/secure.h>

#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>

AskPassphraseDialog::AskPassphraseDialog(Mode _mode, QWidget *parent, SecureString* passphrase_out) :
    QDialog(parent),
    ui(new Ui::AskPassphraseDialog),
    mode(_mode),
    model(nullptr),
    fCapsLock(false),
    m_passphrase_out(passphrase_out)
{
    ui->setupUi(this);

    ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
    ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
    ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());

    ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
    ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
    ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);

    // Setup Caps Lock detection.
    ui->passEdit1->installEventFilter(this);
    ui->passEdit2->installEventFilter(this);
    ui->passEdit3->installEventFilter(this);

    switch(mode)
    {
        case Encrypt: // Ask passphrase x2
            ui->warningLabel->setText(tr("Enter the new passphrase for the wallet.
Please use a passphrase of ten or more random characters, or eight or more words."));
            ui->passLabel1->hide();
            ui->passEdit1->hide();
            setWindowTitle(tr("Encrypt wallet"));
            break;
        case Unlock: // Ask passphrase
            ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
            ui->passLabel2->hide();
            ui->passEdit2->hide();
            ui->passLabel3->hide();
            ui->passEdit3->hide();
            setWindowTitle(tr("Unlock wallet"));
            break;
        case Decrypt:   // Ask passphrase
            ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
            ui->passLabel2->hide();
            ui->passEdit2->hide();
            ui->passLabel3->hide();
            ui->passEdit3->hide();
            setWindowTitle(tr("Decrypt wallet"));
            break;
        case ChangePass: // Ask old passphrase + new passphrase x2
            setWindowTitle(tr("Change passphrase"));
            ui->warningLabel->setText(tr("Enter the old passphrase and new passphrase for the wallet."));
            break;
    }
    textChanged();
    connect(ui->toggleShowPasswordButton, &QPushButton::toggled, this, &AskPassphraseDialog::toggleShowPassword);
    connect(ui->passEdit1, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);
    connect(ui->passEdit2, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);
    connect(ui->passEdit3, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);
}

AskPassphraseDialog::~AskPassphraseDialog()
{
    secureClearPassFields();
    delete ui;
}

void AskPassphraseDialog::setModel(WalletModel *_model)
{
    this->model = _model;
}

void AskPassphraseDialog::accept()
{
    SecureString oldpass, newpass1, newpass2;
    if (!model && mode != Encrypt)
        return;
    oldpass.reserve(MAX_PASSPHRASE_SIZE);
    newpass1.reserve(MAX_PASSPHRASE_SIZE);
    newpass2.reserve(MAX_PASSPHRASE_SIZE);
    // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
    // Alternately, find a way to make this input mlock()'d to begin with.
    oldpass.assign(ui->passEdit1->text().toStdString().c_str());
    newpass1.assign(ui->passEdit2->text().toStdString().c_str());
    newpass2.assign(ui->passEdit3->text().toStdString().c_str());

    secureClearPassFields();

    switch(mode)
    {
    case Encrypt: {
        if(newpass1.empty() || newpass2.empty())
        {
            // Cannot encrypt with empty passphrase
            break;
        }
        QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
                 tr("Warning: If you encrypt your wallet and lose your passphrase, you will LOSE ALL OF YOUR VERTCOIN!") + "

" + tr("Are you sure you wish to encrypt your wallet?"),
                 QMessageBox::Yes|QMessageBox::Cancel,
                 QMessageBox::Cancel);
        if(retval == QMessageBox::Yes)
        {
            if(newpass1 == newpass2)
            {
                QString encryption_reminder = tr("Remember that encrypting your wallet cannot fully protect "
                "your vertcoin from being stolen by malware infecting your computer.");
                if (m_passphrase_out) {
                    m_passphrase_out->assign(newpass1);
                    QMessageBox::warning(this, tr("Wallet to be encrypted"),
                                         "<qt>" +
                                         tr("Your wallet is about to be encrypted. ") + encryption_reminder +
                                         "</qt>");
                } else {
                    assert(model != nullptr);
                    if(model->setWalletEncrypted(true, newpass1))
                    {
                        QMessageBox::warning(this, tr("Wallet encrypted"),
                                             "<qt>" +
                                             tr("Your wallet is now encrypted. ") + encryption_reminder +
                                             "

" +
                                             tr("IMPORTANT: Any previous backups you have made of your wallet file "
                                             "should be replaced with the newly generated, encrypted wallet file. "
                                             "For security reasons, previous backups of the unencrypted wallet file "
                                             "will become useless as soon as you start using the new, encrypted wallet.") +
                                             "</qt>");
                    }
                    else
                    {
                        QMessageBox::critical(this, tr("Wallet encryption failed"),
                                             tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
                    }
                }
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The supplied passphrases do not match."));
            }
        }
        else
        {
            QDialog::reject(); // Cancelled
        }
        } break;
    case Unlock:
        try {
            if (!model->setWalletLocked(false, oldpass)) {
                QMessageBox::critical(this, tr("Wallet unlock failed"),
                                      tr("The passphrase entered for the wallet decryption was incorrect."));
            } else {
                QDialog::accept(); // Success
            }
        } catch (const std::runtime_error& e) {
            QMessageBox::critical(this, tr("Wallet unlock failed"), e.what());
        }
        break;
    case Decrypt:
        if(!model->setWalletEncrypted(false, oldpass))
        {
            QMessageBox::critical(this, tr("Wallet decryption failed"),
                                  tr("The passphrase entered for the wallet decryption was incorrect."));
        }
        else
        {
            QDialog::accept(); // Success
        }
        break;
    case ChangePass:
        if(newpass1 == newpass2)
        {
            if(model->changePassphrase(oldpass, newpass1))
            {
                QMessageBox::information(this, tr("Wallet encrypted"),
                                     tr("Wallet passphrase was successfully changed."));
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The passphrase entered for the wallet decryption was incorrect."));
            }
        }
        else
        {
            QMessageBox::critical(this, tr("Wallet encryption failed"),
                                 tr("The supplied passphrases do not match."));
        }
        break;
    }
}

void AskPassphraseDialog::textChanged()
{
    // Validate input, set Ok button to enabled when acceptable
    bool acceptable = false;
    switch(mode)
    {
    case Encrypt: // New passphrase x2
        acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
        break;
    case Unlock: // Old passphrase x1
    case Decrypt:
        acceptable = !ui->passEdit1->text().isEmpty();
        break;
    case ChangePass: // Old passphrase x1, new passphrase x2
        acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
        break;
    }
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}

bool AskPassphraseDialog::event(QEvent *event)
{
    // Detect Caps Lock key press.
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        if (ke->key() == Qt::Key_CapsLock) {
            fCapsLock = !fCapsLock;
        }
        if (fCapsLock) {
            ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
        } else {
            ui->capsLabel->clear();
        }
    }
    return QWidget::event(event);
}

void AskPassphraseDialog::toggleShowPassword(bool show)
{
    ui->toggleShowPasswordButton->setDown(show);
    const auto mode = show ? QLineEdit::Normal : QLineEdit::Password;
    ui->passEdit1->setEchoMode(mode);
    ui->passEdit2->setEchoMode(mode);
    ui->passEdit3->setEchoMode(mode);
}

bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
    /* Detect Caps Lock.
     * There is no good OS-independent way to check a key state in Qt, but we
     * can detect Caps Lock by checking for the following condition:
     * Shift key is down and the result is a lower case character, or
     * Shift key is not down and the result is an upper case character.
     */
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        QString str = ke->text();
        if (str.length() != 0) {
            const QChar *psz = str.unicode();
            bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
            if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
                fCapsLock = true;
                ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
            } else if (psz->isLetter()) {
                fCapsLock = false;
                ui->capsLabel->clear();
            }
        }
    }
    return QDialog::eventFilter(object, event);
}

static void SecureClearQLineEdit(QLineEdit* edit)
{
    // Attempt to overwrite text so that they do not linger around in memory
    edit->setText(QString(" ").repeated(edit->text().size()));
    edit->clear();
}

void AskPassphraseDialog::secureClearPassFields()
{
    SecureClearQLineEdit(ui->passEdit1);
    SecureClearQLineEdit(ui->passEdit2);
    SecureClearQLineEdit(ui->passEdit3);
}
<|endoftext|>


<commit_before>/*!
  @file XYZReader.hpp
  @brief definition of a class that reads xyz file.

  @author Toru Niina (niina.toru.68u@gmail.com)
  @date 2017-01-05 17:00
  @copyright Toru Niina 2016 on MIT License
*/

#ifndef COFFEE_MILL_XYZ_READER
#define COFFEE_MILL_XYZ_READER
#include <mill/data/XYZData.hpp>
#include <memory>
#include <utility>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <vector>

namespace mill
{

//! read XYZfile and return the data as std::vector<std::vector<position>>.
/*!
 *  @tparam vectorT type of position
 */
template<typename vectorT>
class XYZReader
{
  public:
    using vector_type     = vectorT;
    using position_type   = vector_type;
    using frame_type      = XYZFrame<position_type>;
    using trajectory_type = std::vector<frame_type>;

  public:

    XYZReader(const std::string& fname): xyz_(fname)
    {
        if(!xyz_.good())
        {
            throw std::runtime_error("XYZReader: file open error: " + fname);
        }
    }
    ~XYZReader() = default;

    trajectory_type read();
    snapshot_type   read_frame();

    bool is_eof() const noexcept {return xyz_.eof();}

  private:
    std::ifstream xyz_;
};

template<typename vecT>
typename XYZReader<vecT>::trajectory_type XYZReader<vecT>::read()
{
    trajectory_type traj;
    while(!this->xyz_.eof())
    {
        traj.push_back(this->read_frame());
    }
    return traj;
}

template<typename vecT>
typename XYZReader<vecT>::frame_type XYZReader<vecT>::read_frame()
{
    std::string line;
    std::getline(this->xyz_, line);
    std::size_t N = 0;
    try
    {
        N = std::stoull(line);
    }
    catch(...)
    {
        throw std::runtime_error("XYZReader::read_frame: expected number, "
                "but get " + line);
    }
    frame_type frame;
    std::getline(this->xyz_, frame.comment);
    frame.particles.reserve(N);

    for(std::size_t i=0; i<N; ++i)
    {
        std::getline(this->xyz_, line);
        std::istringstream iss(line);
        std::string atom;
        double x, y, z;
        iss >> atom >> x >> y >> z;
        frame.particles.emplace_back(atom, vector_type(x, y, z));
    }
    return frame;
}

}// mill
#endif //COFFEE_MILL_XYZ_READER
<commit_msg>fix: peek before checking eof flag<commit_after>/*!
  @file XYZReader.hpp
  @brief definition of a class that reads xyz file.

  @author Toru Niina (niina.toru.68u@gmail.com)
  @date 2017-01-05 17:00
  @copyright Toru Niina 2016 on MIT License
*/

#ifndef COFFEE_MILL_XYZ_READER
#define COFFEE_MILL_XYZ_READER
#include <mill/data/XYZData.hpp>
#include <memory>
#include <utility>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <vector>

namespace mill
{

//! read XYZfile and return the data as std::vector<std::vector<position>>.
/*!
 *  @tparam vectorT type of position
 */
template<typename vectorT>
class XYZReader
{
  public:
    using vector_type     = vectorT;
    using position_type   = vector_type;
    using frame_type      = XYZFrame<position_type>;
    using snapshot_type   = frame_type;
    using trajectory_type = std::vector<frame_type>;

  public:

    XYZReader(const std::string& fname): xyz_(fname)
    {
        if(!xyz_.good())
        {
            throw std::runtime_error("XYZReader: file open error: " + fname);
        }
    }
    ~XYZReader() = default;

    trajectory_type read();
    snapshot_type   read_frame();

    bool is_eof() const noexcept {return xyz_.eof();}

  private:
    std::ifstream xyz_;
};

template<typename vecT>
typename XYZReader<vecT>::trajectory_type XYZReader<vecT>::read()
{
    trajectory_type traj;
    while(!this->xyz_.eof())
    {
        traj.push_back(this->read_frame());
        this->xyz_.peek();
    }
    return traj;
}

template<typename vecT>
typename XYZReader<vecT>::frame_type XYZReader<vecT>::read_frame()
{
    std::string line;
    std::getline(this->xyz_, line);
    std::size_t N = 0;
    try
    {
        N = std::stoull(line);
    }
    catch(...)
    {
        throw std::runtime_error("XYZReader::read_frame: expected number, "
                "but get " + line);
    }
    frame_type frame;
    std::getline(this->xyz_, frame.comment);
    frame.particles.reserve(N);

    for(std::size_t i=0; i<N; ++i)
    {
        std::getline(this->xyz_, line);
        std::istringstream iss(line);
        std::string atom;
        double x, y, z;
        iss >> atom >> x >> y >> z;
        frame.particles.emplace_back(atom, vector_type(x, y, z));
    }
    return frame;
}

}// mill
#endif //COFFEE_MILL_XYZ_READER
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * TIGHTDB CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2014] TightDB Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of TightDB Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to TightDB Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from TightDB Incorporated.
 *
 **************************************************************************/

#ifndef TIGHTDB_OBJC_UTIL_HPP
#define TIGHTDB_OBJC_UTIL_HPP

#include <cstddef>
#include <stdexcept>

#include <tightdb/util/safe_int_ops.hpp>
#include <tightdb/util/file.hpp>
#include <tightdb/string_data.hpp>
#include <tightdb/mixed.hpp>
#include <tightdb/descriptor.hpp>
#include <tightdb/table.hpp>
#include <tightdb/table_ref.hpp>

struct ObjcStringAccessor {
    ObjcStringAccessor(const NSString* s)
    {
        using namespace std;
        using namespace tightdb;
        NSUInteger size = [s length];
        if (size == 0) {
            m_data = 0;
            m_size = 0;
        }
        else {
            size_t max_size;
            if (util::int_cast_with_overflow_detect([s maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding], max_size))
                throw runtime_error("String size overflow");
            char* data = new char[max_size];
            NSUInteger used;
            NSRange range = NSMakeRange(0, size);
            NSRange remaining_range;
            BOOL at_leat_one = [s getBytes:data maxLength:max_size usedLength:&used encoding:NSUTF8StringEncoding options:0 range:range remainingRange:&remaining_range];
            if (!at_leat_one || remaining_range.length != 0) {
                delete[] data;
                throw runtime_error("String transcoding failed");
            }
            m_data = data;
            m_size = used;
        }
    }

    ~ObjcStringAccessor()
    {
        delete[] m_data;
    }

    operator tightdb::StringData() const TIGHTDB_NOEXCEPT { return tightdb::StringData(m_data, m_size); }

private:
    const char* m_data;
    std::size_t m_size;
};

inline NSString* to_objc_string(tightdb::StringData s)
{
    using namespace std;
    using namespace tightdb;
    const char* data = s.data();
    NSUInteger size;
    if (util::int_cast_with_overflow_detect(s.size(), size))
        throw runtime_error("String size overflow");
    return [[NSString alloc] initWithBytes:data length:size encoding:NSUTF8StringEncoding];
}

inline NSObject* to_objc_object(tightdb::Mixed m)
{
    switch (m.get_type()) {
        case tightdb::type_Bool:
            return [NSNumber numberWithBool:m.get_bool()];
        case tightdb::type_Int:
            return [NSNumber numberWithLongLong:m.get_int()];
        case tightdb::type_Float:
            return [NSNumber numberWithFloat:m.get_float()];
        case tightdb::type_Double:
            return [NSNumber numberWithDouble:m.get_double()];
        case tightdb::type_DateTime:
            return [NSDate dateWithTimeIntervalSince1970:m.get_datetime().get_datetime()];
        case tightdb::type_String:
            return to_objc_string(m.get_string());
        case tightdb::type_Binary: {
            tightdb::BinaryData bd = m.get_binary();
            return [NSData dataWithBytes:bd.data() length:bd.size()];
        }
        case tightdb::type_Mixed:
            TIGHTDB_ASSERT(false); /* we should never get here */
        case tightdb::type_Table:
            TIGHTDB_ASSERT(false);
    }
    return nil;
}

inline NSUInteger was_not_found(size_t n)
{
    if (n == tightdb::not_found)
        return (NSUInteger)NSNotFound;
    return (NSUInteger)n;
}

inline bool nsnumber_is_like_bool(NSObject *obj)
{
    const char* data_type = [(NSNumber *)obj objCType];
    /* @encode(BOOL) is 'B' on iOS 64 and 'c'
     objcType is always 'c'. Therefore compare to "c".
     */
    return data_type[0] == 'c';
}

inline bool nsnumber_is_like_integer(NSObject *obj)
{
    const char* data_type = [(NSNumber *)obj objCType];
    return (strcmp(data_type, @encode(int)) == 0 ||
            strcmp(data_type, @encode(long)) ==  0 ||
            strcmp(data_type, @encode(long long)) == 0 ||
            strcmp(data_type, @encode(unsigned int)) == 0 ||
            strcmp(data_type, @encode(unsigned long)) == 0 ||
            strcmp(data_type, @encode(unsigned long long)) == 0);
}

inline bool nsnumber_is_like_float(NSObject *obj)
{
    const char* data_type = [(NSNumber *)obj objCType];
    return (strcmp(data_type, @encode(float)) == 0 ||
            strcmp(data_type, @encode(int)) == 0 ||
            strcmp(data_type, @encode(long)) ==  0 ||
            strcmp(data_type, @encode(long long)) == 0 ||
            strcmp(data_type, @encode(unsigned int)) == 0 ||
            strcmp(data_type, @encode(unsigned long)) == 0 ||
            strcmp(data_type, @encode(unsigned long long)) == 0);
}

inline bool nsnumber_is_like_double(NSObject *obj)
{
    const char* data_type = [(NSNumber *)obj objCType];
    return (strcmp(data_type, @encode(double)) == 0 ||
            strcmp(data_type, @encode(float)) == 0 ||
            strcmp(data_type, @encode(int)) == 0 ||
            strcmp(data_type, @encode(long)) ==  0 ||
            strcmp(data_type, @encode(long long)) == 0 ||
            strcmp(data_type, @encode(unsigned int)) == 0 ||
            strcmp(data_type, @encode(unsigned long)) == 0 ||
            strcmp(data_type, @encode(unsigned long long)) == 0);
}

void to_mixed(id value, tightdb::Mixed& m);

BOOL set_cell(size_t col_ndx, size_t row_ndx, tightdb::Table& table, NSObject *obj);
BOOL verify_object_is_type(id obj, tightdb::DataType type);
BOOL verify_cell(const tightdb::Descriptor& descr, size_t col_ndx, NSObject *obj);
NSObject* get_cell(size_t col_ndx, size_t row_ndx, tightdb::Table& table);

void verify_row(const tightdb::Descriptor& descr, NSArray * data);
void insert_row(size_t ndx, tightdb::Table& table, NSArray * data);
void set_row(size_t ndx, tightdb::Table& table, NSArray *data);

void verify_row_with_labels(const tightdb::Descriptor& descr, NSDictionary* data);
void insert_row_with_labels(size_t row_ndx, tightdb::Table& table, NSDictionary *data);
void set_row_with_labels(size_t row_ndx, tightdb::Table& table, NSDictionary *data);

void verify_row_from_object(const tightdb::Descriptor& descr, NSObject* data);
void insert_row_from_object(size_t row_ndx, tightdb::Table& table, NSObject *data);
void set_row_from_object(size_t row_ndx, tightdb::Table& table, NSObject *data);

BOOL set_columns(tightdb::TableRef& parent, NSArray *schema);

// Still used in the new error strategy. Perhaps it should be public?
enum TightdbErr {
    tdb_err_Ok                    = 0,
    tdb_err_Fail                  = 1,
    tdb_err_FailRdOnly            = 2,
    tdb_err_File_AccessError      = 3,
    tdb_err_File_PermissionDenied = 4,
    tdb_err_File_Exists           = 5,
    tdb_err_File_NotFound         = 6,
    tdb_err_Rollback              = 7,
    tdb_err_InvalidDatabase       = 8,
    tdb_err_TableNotFound         = 9
};

inline NSError* make_realm_error(TightdbErr code, NSString* desc)
{
    NSMutableDictionary* details = [NSMutableDictionary dictionary];
    [details setValue:desc forKey:NSLocalizedDescriptionKey];
    return [NSError errorWithDomain:@"com.realm" code:code userInfo:details];
}

#define REALM_OBJC_SIZE_T_NUMBER_IN numberWithUnsignedLong
#define REALM_OBJC_SIZE_T_NUMBER_OUT unsignedLongValue

#define REALM_EXCEPTION_ERRHANDLER(action, fail_return_value) \
REALM_EXCEPTION_ERRHANDLER_EX(action, fail_return_value, error)

// This is the old macro, which should be phased out.
#define REALM_EXCEPTION_ERRHANDLER_EX(action, fail_return_value, err_var) \
try { action } \
catch (tightdb::util::File::AccessError& ex) { \
    if (err_var) \
        *err_var = make_realm_error(tdb_err_File_AccessError, [NSString stringWithUTF8String:ex.what()]); \
        return fail_return_value; \
} \
catch (std::exception& ex) { \
    if (err_var) \
        *err_var = make_realm_error(tdb_err_Fail, [NSString stringWithUTF8String:ex.what()]); \
        return fail_return_value; \
}

// This macro is part of the new error strategy, specifically for table value setters.
#define REALM_EXCEPTION_HANDLER_SETTERS(action, datatype) \
if (m_read_only) { \
    NSException* exception = [NSException exceptionWithName:@"tightdb:table_is_read_only" \
                                          reason:@"You tried to modify an immutable table" \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
} \
if (col_ndx >= self.columnCount) { \
    NSException* exception = [NSException exceptionWithName:@"tightdb:column_index_out_of_bounds" \
                                          reason:@"The specified column index is not within the table bounds" \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
} \
if ([self columnTypeOfColumnWithIndex:col_ndx] != datatype) { \
    NSException* exception = [NSException exceptionWithName:@"tightdb:illegal_type" \
                                          reason:@"The supplied type is not compatible with the column type" \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
} \
if (row_ndx >= self.rowCount) { \
    NSException* exception = [NSException exceptionWithName:@"tightdb:row_index_out_of_bounds" \
                                          reason:@"The specified row index is not within the table bounds" \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
} \
try { action } \
catch(std::exception& ex) { \
    NSException* exception = [NSException exceptionWithName:@"tightdb:core_exception" \
                                          reason:[NSString stringWithUTF8String:ex.what()] \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
}

#define REALM_EXCEPTION_HANDLER_COLUMN_INDEX_VALID(columnIndex) \
if (columnIndex >= self.columnCount) { \
                        NSException* exception = [NSException exceptionWithName:@"tightdb:column_index_out_of_bounds" \
                                reason:@"The specified column index is not within the table bounds" \
                                userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
} \

#define REALM_EXCEPTION_HANDLER_CORE_EXCEPTION(action) \
try { action } \
catch(std::exception& ex) { \
    NSException* exception = [NSException exceptionWithName:@"tightdb:core_exception" \
                                          reason:[NSString stringWithUTF8String:ex.what()] \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
}

#endif // TIGHTDB_OBJC_UTIL_HPP
<commit_msg>Updated exception messages<commit_after>/*************************************************************************
 *
 * TIGHTDB CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2014] TightDB Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of TightDB Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to TightDB Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from TightDB Incorporated.
 *
 **************************************************************************/

#ifndef TIGHTDB_OBJC_UTIL_HPP
#define TIGHTDB_OBJC_UTIL_HPP

#include <cstddef>
#include <stdexcept>

#include <tightdb/util/safe_int_ops.hpp>
#include <tightdb/util/file.hpp>
#include <tightdb/string_data.hpp>
#include <tightdb/mixed.hpp>
#include <tightdb/descriptor.hpp>
#include <tightdb/table.hpp>
#include <tightdb/table_ref.hpp>

struct ObjcStringAccessor {
    ObjcStringAccessor(const NSString* s)
    {
        using namespace std;
        using namespace tightdb;
        NSUInteger size = [s length];
        if (size == 0) {
            m_data = 0;
            m_size = 0;
        }
        else {
            size_t max_size;
            if (util::int_cast_with_overflow_detect([s maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding], max_size))
                throw runtime_error("String size overflow");
            char* data = new char[max_size];
            NSUInteger used;
            NSRange range = NSMakeRange(0, size);
            NSRange remaining_range;
            BOOL at_leat_one = [s getBytes:data maxLength:max_size usedLength:&used encoding:NSUTF8StringEncoding options:0 range:range remainingRange:&remaining_range];
            if (!at_leat_one || remaining_range.length != 0) {
                delete[] data;
                throw runtime_error("String transcoding failed");
            }
            m_data = data;
            m_size = used;
        }
    }

    ~ObjcStringAccessor()
    {
        delete[] m_data;
    }

    operator tightdb::StringData() const TIGHTDB_NOEXCEPT { return tightdb::StringData(m_data, m_size); }

private:
    const char* m_data;
    std::size_t m_size;
};

inline NSString* to_objc_string(tightdb::StringData s)
{
    using namespace std;
    using namespace tightdb;
    const char* data = s.data();
    NSUInteger size;
    if (util::int_cast_with_overflow_detect(s.size(), size))
        throw runtime_error("String size overflow");
    return [[NSString alloc] initWithBytes:data length:size encoding:NSUTF8StringEncoding];
}

inline NSObject* to_objc_object(tightdb::Mixed m)
{
    switch (m.get_type()) {
        case tightdb::type_Bool:
            return [NSNumber numberWithBool:m.get_bool()];
        case tightdb::type_Int:
            return [NSNumber numberWithLongLong:m.get_int()];
        case tightdb::type_Float:
            return [NSNumber numberWithFloat:m.get_float()];
        case tightdb::type_Double:
            return [NSNumber numberWithDouble:m.get_double()];
        case tightdb::type_DateTime:
            return [NSDate dateWithTimeIntervalSince1970:m.get_datetime().get_datetime()];
        case tightdb::type_String:
            return to_objc_string(m.get_string());
        case tightdb::type_Binary: {
            tightdb::BinaryData bd = m.get_binary();
            return [NSData dataWithBytes:bd.data() length:bd.size()];
        }
        case tightdb::type_Mixed:
            TIGHTDB_ASSERT(false); /* we should never get here */
        case tightdb::type_Table:
            TIGHTDB_ASSERT(false);
    }
    return nil;
}

inline NSUInteger was_not_found(size_t n)
{
    if (n == tightdb::not_found)
        return (NSUInteger)NSNotFound;
    return (NSUInteger)n;
}

inline bool nsnumber_is_like_bool(NSObject *obj)
{
    const char* data_type = [(NSNumber *)obj objCType];
    /* @encode(BOOL) is 'B' on iOS 64 and 'c'
     objcType is always 'c'. Therefore compare to "c".
     */
    return data_type[0] == 'c';
}

inline bool nsnumber_is_like_integer(NSObject *obj)
{
    const char* data_type = [(NSNumber *)obj objCType];
    return (strcmp(data_type, @encode(int)) == 0 ||
            strcmp(data_type, @encode(long)) ==  0 ||
            strcmp(data_type, @encode(long long)) == 0 ||
            strcmp(data_type, @encode(unsigned int)) == 0 ||
            strcmp(data_type, @encode(unsigned long)) == 0 ||
            strcmp(data_type, @encode(unsigned long long)) == 0);
}

inline bool nsnumber_is_like_float(NSObject *obj)
{
    const char* data_type = [(NSNumber *)obj objCType];
    return (strcmp(data_type, @encode(float)) == 0 ||
            strcmp(data_type, @encode(int)) == 0 ||
            strcmp(data_type, @encode(long)) ==  0 ||
            strcmp(data_type, @encode(long long)) == 0 ||
            strcmp(data_type, @encode(unsigned int)) == 0 ||
            strcmp(data_type, @encode(unsigned long)) == 0 ||
            strcmp(data_type, @encode(unsigned long long)) == 0);
}

inline bool nsnumber_is_like_double(NSObject *obj)
{
    const char* data_type = [(NSNumber *)obj objCType];
    return (strcmp(data_type, @encode(double)) == 0 ||
            strcmp(data_type, @encode(float)) == 0 ||
            strcmp(data_type, @encode(int)) == 0 ||
            strcmp(data_type, @encode(long)) ==  0 ||
            strcmp(data_type, @encode(long long)) == 0 ||
            strcmp(data_type, @encode(unsigned int)) == 0 ||
            strcmp(data_type, @encode(unsigned long)) == 0 ||
            strcmp(data_type, @encode(unsigned long long)) == 0);
}

void to_mixed(id value, tightdb::Mixed& m);

BOOL set_cell(size_t col_ndx, size_t row_ndx, tightdb::Table& table, NSObject *obj);
BOOL verify_object_is_type(id obj, tightdb::DataType type);
BOOL verify_cell(const tightdb::Descriptor& descr, size_t col_ndx, NSObject *obj);
NSObject* get_cell(size_t col_ndx, size_t row_ndx, tightdb::Table& table);

void verify_row(const tightdb::Descriptor& descr, NSArray * data);
void insert_row(size_t ndx, tightdb::Table& table, NSArray * data);
void set_row(size_t ndx, tightdb::Table& table, NSArray *data);

void verify_row_with_labels(const tightdb::Descriptor& descr, NSDictionary* data);
void insert_row_with_labels(size_t row_ndx, tightdb::Table& table, NSDictionary *data);
void set_row_with_labels(size_t row_ndx, tightdb::Table& table, NSDictionary *data);

void verify_row_from_object(const tightdb::Descriptor& descr, NSObject* data);
void insert_row_from_object(size_t row_ndx, tightdb::Table& table, NSObject *data);
void set_row_from_object(size_t row_ndx, tightdb::Table& table, NSObject *data);

BOOL set_columns(tightdb::TableRef& parent, NSArray *schema);

// Still used in the new error strategy. Perhaps it should be public?
enum TightdbErr {
    tdb_err_Ok                    = 0,
    tdb_err_Fail                  = 1,
    tdb_err_FailRdOnly            = 2,
    tdb_err_File_AccessError      = 3,
    tdb_err_File_PermissionDenied = 4,
    tdb_err_File_Exists           = 5,
    tdb_err_File_NotFound         = 6,
    tdb_err_Rollback              = 7,
    tdb_err_InvalidDatabase       = 8,
    tdb_err_TableNotFound         = 9
};

inline NSError* make_realm_error(TightdbErr code, NSString* desc)
{
    NSMutableDictionary* details = [NSMutableDictionary dictionary];
    [details setValue:desc forKey:NSLocalizedDescriptionKey];
    return [NSError errorWithDomain:@"com.realm" code:code userInfo:details];
}

#define REALM_OBJC_SIZE_T_NUMBER_IN numberWithUnsignedLong
#define REALM_OBJC_SIZE_T_NUMBER_OUT unsignedLongValue

#define REALM_EXCEPTION_ERRHANDLER(action, fail_return_value) \
REALM_EXCEPTION_ERRHANDLER_EX(action, fail_return_value, error)

// This is the old macro, which should be phased out.
#define REALM_EXCEPTION_ERRHANDLER_EX(action, fail_return_value, err_var) \
try { action } \
catch (tightdb::util::File::AccessError& ex) { \
    if (err_var) \
        *err_var = make_realm_error(tdb_err_File_AccessError, [NSString stringWithUTF8String:ex.what()]); \
        return fail_return_value; \
} \
catch (std::exception& ex) { \
    if (err_var) \
        *err_var = make_realm_error(tdb_err_Fail, [NSString stringWithUTF8String:ex.what()]); \
        return fail_return_value; \
}

// This macro is part of the new error strategy, specifically for table value setters.
#define REALM_EXCEPTION_HANDLER_SETTERS(action, datatype) \
if (m_read_only) { \
    NSException* exception = [NSException exceptionWithName:@"realm:table_is_read_only" \
                                          reason:@"You tried to modify an immutable table" \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
} \
if (col_ndx >= self.columnCount) { \
    NSException* exception = [NSException exceptionWithName:@"realm:column_index_out_of_bounds" \
                                          reason:@"The specified column index is not within the table bounds" \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
} \
if ([self columnTypeOfColumnWithIndex:col_ndx] != datatype) { \
    NSException* exception = [NSException exceptionWithName:@"realm:illegal_type" \
                                          reason:@"The supplied type is not compatible with the column type" \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
} \
if (row_ndx >= self.rowCount) { \
    NSException* exception = [NSException exceptionWithName:@"realm:row_index_out_of_bounds" \
                                          reason:@"The specified row index is not within the table bounds" \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
} \
try { action } \
catch(std::exception& ex) { \
    NSException* exception = [NSException exceptionWithName:@"realm:core_exception" \
                                          reason:[NSString stringWithUTF8String:ex.what()] \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
}

#define REALM_EXCEPTION_HANDLER_COLUMN_INDEX_VALID(columnIndex) \
if (columnIndex >= self.columnCount) { \
                        NSException* exception = [NSException exceptionWithName:@"realm:column_index_out_of_bounds" \
                                reason:@"The specified column index is not within the table bounds" \
                                userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
} \

#define REALM_EXCEPTION_HANDLER_CORE_EXCEPTION(action) \
try { action } \
catch(std::exception& ex) { \
    NSException* exception = [NSException exceptionWithName:@"realm:core_exception" \
                                          reason:[NSString stringWithUTF8String:ex.what()] \
                                          userInfo:[NSMutableDictionary dictionary]]; \
    [exception raise]; \
}

#endif // TIGHTDB_OBJC_UTIL_HPP
<|endoftext|>


<commit_before>#ifndef MJOLNIR_SYSTEM
#define MJOLNIR_SYSTEM
#include "Particle.hpp"
#include <vector>

namespace mjolnir
{

template<typename traitsT>
class System
{
  public:
    typedef traitsT  traits_type;
    typedef typename traits_type::coordinate_type   coordinate_type;
    typedef Particle<coordinate_type>               particle_type;
    typedef std::vector<particle_type>              container_type;
    typedef typename container_type::iterator       iterator;
    typedef typename container_type::const_iterator const_iterator;
    typedef typename traits_type::boundary_type     boundary_type;

    System()  = default;
    System(std::size_t num_particle) : particles_(num_particle){}
    ~System() = default;

    std::size_t size() const noexcept {return particles_.size();}

    real_type& pressure()             noexcept {return pressure_;}
    real_type  pressure()       const noexcept {return pressure_;}
    real_type& temperature()          noexcept {return temperature_;}
    real_type  temperature()    const noexcept {return temperature_;}
    real_type& ionic_strength()       noexcept {return ionic_strength_;}
    real_type  ionic_strength() const noexcept {return ionic_strength_;}

    coordinate_type adjust_direction(coordiate_type dr) const noexcept
    {return boundary_.adjust_direction(dr);}
    coordinate_type  adjust_position(coordiate_type dr) const noexcept
    {return boundary_.adjust_position(dr);}

    particle_type &      operator[](std::size_t i)       noexcept
    {return particles_[i];}
    particle_type const& operator[](std::size_t i) const noexcept
    {return particles_[i];}
    particle_type &      at(std::size_t i)       noexcept
    {return particles_.at(i);}
    particle_type const& at(std::size_t i) const noexcept
    {return particles_.at(i);}

    iterator       begin()        noexcept {return particles_.begin();}
    iterator       end()          noexcept {return particles_.end();}
    const_iterator cbegin() const noexcept {return particles_.cbegin();}
    const_iterator cend()   const noexcept {return particles_.cend();}

    boundary_type const& boundary() const noexcept {return boundary_;}

  private:

    real_type      temperature_;
    real_type      pressure_;
    real_type      ionic_strength_;
    boundary_type  boundary_;
    container_type particles_;
};

} // mjolnir
#endif// MJOLNIR_SYSTEM
<commit_msg>add ctor from particles and boundary to System<commit_after>#ifndef MJOLNIR_SYSTEM
#define MJOLNIR_SYSTEM
#include "Particle.hpp"
#include <vector>

namespace mjolnir
{

template<typename traitsT>
class System
{
  public:
    typedef traitsT  traits_type;
    typedef typename traits_type::coordinate_type   coordinate_type;
    typedef Particle<coordinate_type>               particle_type;
    typedef std::vector<particle_type>              container_type;
    typedef typename container_type::iterator       iterator;
    typedef typename container_type::const_iterator const_iterator;
    typedef typename traits_type::boundary_type     boundary_type;

    System()  = default;
    ~System() = default;

    System(container_type&& pcon, boundary_type&& bound)
        : boundary_(bound), particles(pcon), temperature_(0.), pressure_(0.),
          ionic_strength_(0.)
    {}

    std::size_t size() const noexcept {return particles_.size();}

    real_type& pressure()             noexcept {return pressure_;}
    real_type  pressure()       const noexcept {return pressure_;}
    real_type& temperature()          noexcept {return temperature_;}
    real_type  temperature()    const noexcept {return temperature_;}
    real_type& ionic_strength()       noexcept {return ionic_strength_;}
    real_type  ionic_strength() const noexcept {return ionic_strength_;}

    coordinate_type adjust_direction(coordiate_type dr) const noexcept
    {return boundary_.adjust_direction(dr);}
    coordinate_type  adjust_position(coordiate_type dr) const noexcept
    {return boundary_.adjust_position(dr);}

    particle_type &      operator[](std::size_t i)       noexcept
    {return particles_[i];}
    particle_type const& operator[](std::size_t i) const noexcept
    {return particles_[i];}
    particle_type &      at(std::size_t i)       noexcept
    {return particles_.at(i);}
    particle_type const& at(std::size_t i) const noexcept
    {return particles_.at(i);}

    iterator       begin()        noexcept {return particles_.begin();}
    iterator       end()          noexcept {return particles_.end();}
    const_iterator cbegin() const noexcept {return particles_.cbegin();}
    const_iterator cend()   const noexcept {return particles_.cend();}

    boundary_type const& boundary() const noexcept {return boundary_;}

  private:

    real_type      temperature_;
    real_type      pressure_;
    real_type      ionic_strength_;
    boundary_type  boundary_;
    container_type particles_;
};

} // mjolnir
#endif// MJOLNIR_SYSTEM
<|endoftext|>