<commit_before>#include "wx/dc.h"
#include "wx/dcclient.h"

#include "RoboStruct_GUI_style.hpp"
#include "MainFrame.hpp"

wxAuiToolBarArt* wxAuiSolidToolBarArt::Clone()
{
    return new wxAuiSolidToolBarArt{};
}

void wxAuiSolidToolBarArt::DrawBackground(wxDC& dc, wxWindow* wnd, const wxRect& rect)
{
    wxUnusedVar(wnd);
    dc.GradientFillLinear(rect, wxColour{238, 238, 242}, wxColour{238, 238, 242});
}

wxAuiSolidTabArt::wxAuiSolidTabArt()
    : wxAuiGenericTabArt()
{
    m_normalFont    = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
    m_selectedFont  = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
    m_selectedFont.SetWeight(wxNORMAL);
    m_measuringFont = m_selectedFont;
}

wxAuiSolidTabArt* wxAuiSolidTabArt::Clone()
{
    return new wxAuiSolidTabArt{};
}

void wxAuiSolidTabArt::DrawBackground(wxDC& dc, wxWindow* wnd, const wxRect& rect)
{
    wxUnusedVar(wnd);
    dc.GradientFillLinear(rect, wxColour{238, 238, 242}, wxColour{238, 238, 242});
}

void wxAuiSolidTabArt::DrawTab(wxDC& dc, wxWindow* wnd, const wxAuiNotebookPage& page, const wxRect& in_rect,
                int close_button_state, wxRect* out_tab_rect, wxRect* out_button_rect, int* x_extent)
{
    wxCoord normal_textx, normal_texty;

    // If the caption is empty, measure some temporary text
    wxString caption{page.caption};
    if (caption.empty()) caption = "Xj";

    dc.SetFont(m_normalFont);
    dc.GetTextExtent(caption, &normal_textx, &normal_texty);

    // Figure out the size of the tab
    wxSize  tab_size   = GetTabSize(dc, wnd, page.caption, page.bitmap, page.active, close_button_state, x_extent);
    wxCoord tab_height = m_tabCtrlHeight;
    wxCoord tab_width  = tab_size.x;
    wxCoord tab_x      = in_rect.x;
    wxCoord tab_y      = in_rect.y + in_rect.height - tab_height;

    caption = page.caption;

    dc.SetFont(m_normalFont);

    int drawn_tab_height = tab_height - 2;

    if (page.active)
    {
        // draw base background color
        wxRect r{tab_x, tab_y, tab_width, tab_height};
        dc.GradientFillLinear(r, wxColour{51, 153, 255}, wxColour{51, 153, 255});
    } else
    {
        wxRect r{tab_x, tab_y, tab_width, tab_height};
        dc.GradientFillLinear(r, wxColour{204, 206, 219}, wxColour{204, 206, 219});
    }

    int text_offset = tab_x + 8;

    // Draw tab text
    wxString draw_text = wxAuiChopText(dc, caption, tab_width - (text_offset-tab_x));
    if (page.active)
    {
        dc.SetTextForeground(wxColour{255, 255, 255});
        dc.DrawText(draw_text, text_offset, tab_y + 2 + (drawn_tab_height) / 2 - (normal_texty / 2) - 1);
    } else
    {
        dc.SetTextForeground(wxColour{0, 0, 0});
        dc.DrawText(draw_text, text_offset, tab_y + 2 + (drawn_tab_height) / 2 - (normal_texty / 2) - 1);
    }

    *out_tab_rect = wxRect{tab_x, tab_y, tab_width, tab_height};
}

int wxAuiSolidTabArt::GetBestTabCtrlSize(wxWindow* wnd, const wxAuiNotebookPageArray& pages, const wxSize& requiredBmp_size)
{
    return 22;
}

wxAuiMyNotebook::wxAuiMyNotebook(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
    : wxAuiNotebook(parent, id, pos, size, style)
{
    SetArtProvider(new wxAuiSolidTabArt{});

    m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE,0);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BORDER_COLOUR, wxColour{238, 238, 242});
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, wxColour{238, 238, 242});
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, wxColour{238, 238, 242});
}

void MainFrame::InitializeGuiStyle()
{
    m_toolbar->SetArtProvider(new wxAuiSolidToolBarArt{});
    m_toolbar_log->SetArtProvider(new wxAuiSolidToolBarArt{});
    m_toolbar_options->SetArtProvider(new wxAuiSolidToolBarArt{});

    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BORDER_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE, 0);

    m_mgr.GetArtProvider()->SetFont(wxAUI_DOCKART_CAPTION_FONT, wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
    m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_CAPTION_SIZE, 19);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_COLOUR, wxColour{0, 122, 204});
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR, wxColour{0, 122, 204});
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR, wxColour{255, 255, 255});
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR, wxColour{20, 20, 20});
    m_mgr.Update();
}
<commit_msg>removed call to wxAuiManager::Update()<commit_after>#include "wx/dc.h"
#include "wx/dcclient.h"

#include "RoboStruct_GUI_style.hpp"
#include "MainFrame.hpp"

wxAuiToolBarArt* wxAuiSolidToolBarArt::Clone()
{
    return new wxAuiSolidToolBarArt{};
}

void wxAuiSolidToolBarArt::DrawBackground(wxDC& dc, wxWindow* wnd, const wxRect& rect)
{
    wxUnusedVar(wnd);
    dc.GradientFillLinear(rect, wxColour{238, 238, 242}, wxColour{238, 238, 242});
}

wxAuiSolidTabArt::wxAuiSolidTabArt()
    : wxAuiGenericTabArt()
{
    m_normalFont    = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
    m_selectedFont  = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
    m_selectedFont.SetWeight(wxNORMAL);
    m_measuringFont = m_selectedFont;
}

wxAuiSolidTabArt* wxAuiSolidTabArt::Clone()
{
    return new wxAuiSolidTabArt{};
}

void wxAuiSolidTabArt::DrawBackground(wxDC& dc, wxWindow* wnd, const wxRect& rect)
{
    wxUnusedVar(wnd);
    dc.GradientFillLinear(rect, wxColour{238, 238, 242}, wxColour{238, 238, 242});
}

void wxAuiSolidTabArt::DrawTab(wxDC& dc, wxWindow* wnd, const wxAuiNotebookPage& page, const wxRect& in_rect,
                int close_button_state, wxRect* out_tab_rect, wxRect* out_button_rect, int* x_extent)
{
    wxCoord normal_textx, normal_texty;

    // If the caption is empty, measure some temporary text
    wxString caption{page.caption};
    if (caption.empty()) caption = "Xj";

    dc.SetFont(m_normalFont);
    dc.GetTextExtent(caption, &normal_textx, &normal_texty);

    // Figure out the size of the tab
    wxSize  tab_size   = GetTabSize(dc, wnd, page.caption, page.bitmap, page.active, close_button_state, x_extent);
    wxCoord tab_height = m_tabCtrlHeight;
    wxCoord tab_width  = tab_size.x;
    wxCoord tab_x      = in_rect.x;
    wxCoord tab_y      = in_rect.y + in_rect.height - tab_height;

    caption = page.caption;

    dc.SetFont(m_normalFont);

    int drawn_tab_height = tab_height - 2;

    if (page.active)
    {
        // draw base background color
        wxRect r{tab_x, tab_y, tab_width, tab_height};
        dc.GradientFillLinear(r, wxColour{51, 153, 255}, wxColour{51, 153, 255});
    } else
    {
        wxRect r{tab_x, tab_y, tab_width, tab_height};
        dc.GradientFillLinear(r, wxColour{204, 206, 219}, wxColour{204, 206, 219});
    }

    int text_offset = tab_x + 8;

    // Draw tab text
    wxString draw_text = wxAuiChopText(dc, caption, tab_width - (text_offset-tab_x));
    if (page.active)
    {
        dc.SetTextForeground(wxColour{255, 255, 255});
        dc.DrawText(draw_text, text_offset, tab_y + 2 + (drawn_tab_height) / 2 - (normal_texty / 2) - 1);
    } else
    {
        dc.SetTextForeground(wxColour{0, 0, 0});
        dc.DrawText(draw_text, text_offset, tab_y + 2 + (drawn_tab_height) / 2 - (normal_texty / 2) - 1);
    }

    *out_tab_rect = wxRect{tab_x, tab_y, tab_width, tab_height};
}

int wxAuiSolidTabArt::GetBestTabCtrlSize(wxWindow* wnd, const wxAuiNotebookPageArray& pages, const wxSize& requiredBmp_size)
{
    return 22;
}

wxAuiMyNotebook::wxAuiMyNotebook(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
    : wxAuiNotebook(parent, id, pos, size, style)
{
    SetArtProvider(new wxAuiSolidTabArt{});

    m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE,0);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BORDER_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, light_theme_main_color);
}

void MainFrame::InitializeGuiStyle()
{
    m_toolbar->SetArtProvider(new wxAuiSolidToolBarArt{});
    m_toolbar_log->SetArtProvider(new wxAuiSolidToolBarArt{});
    m_toolbar_options->SetArtProvider(new wxAuiSolidToolBarArt{});

    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BORDER_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE, 0);

    m_mgr.GetArtProvider()->SetFont(wxAUI_DOCKART_CAPTION_FONT, wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
    m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_CAPTION_SIZE, 19);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_COLOUR, wxColour{0, 122, 204});
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR, wxColour{0, 122, 204});
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR, wxColour{255, 255, 255});
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR, light_theme_main_color);
    m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR, wxColour{20, 20, 20});
}
<|endoftext|>


<commit_before>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//

//  SMESH SMDS : implementaion of Salome mesh data structure
//  File   : SMDS_MeshElement.hxx
//  Module : SMESH
//
#ifndef _SMDS_MeshElement_HeaderFile
#define _SMDS_MeshElement_HeaderFile

#include "SMESH_SMDS.hxx"

#include "SMDSAbs_ElementType.hxx"
#include "SMDS_MeshObject.hxx"
#include "SMDS_ElemIterator.hxx"
#include "SMDS_MeshElementIDFactory.hxx"
#include "SMDS_StdIterator.hxx"

#include <vector>
#include <iostream>

#include <vtkType.h>
#include <vtkCellType.h>

//typedef unsigned short UShortType;
typedef short ShortType;
typedef int   LongType;

class SMDS_MeshNode;
class SMDS_MeshEdge;
class SMDS_MeshFace;
class SMDS_Mesh;

// ============================================================
/*!
 * \brief Base class for elements
 */
// ============================================================

class SMDS_EXPORT SMDS_MeshElement:public SMDS_MeshObject
{
public:

  SMDS_ElemIteratorPtr nodesIterator() const;
  SMDS_ElemIteratorPtr edgesIterator() const;
  SMDS_ElemIteratorPtr facesIterator() const;
  virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const;
  virtual SMDS_ElemIteratorPtr nodesIteratorToUNV() const;
  virtual SMDS_ElemIteratorPtr interlacedNodesElemIterator() const;

  // std-like iteration on nodes
  typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_ElemIteratorPtr > iterator;
  iterator begin_nodes() const { return iterator( nodesIterator() ); }
  iterator end_nodes()   const { return iterator(); }

  virtual int NbNodes() const;
  virtual int NbEdges() const;
  virtual int NbFaces() const;
  inline int GetID() const { return myID; };

  ///Return the type of the current element
  virtual SMDSAbs_ElementType GetType() const = 0;
  virtual SMDSAbs_EntityType GetEntityType() const = 0;
  virtual SMDSAbs_GeometryType GetGeomType() const = 0;
  virtual vtkIdType GetVtkType() const = 0;
  virtual bool IsPoly() const { return false; }
  virtual bool IsQuadratic() const;

  virtual bool IsMediumNode(const SMDS_MeshNode* node) const;
  virtual int  NbCornerNodes() const;

  friend SMDS_EXPORT std::ostream & operator <<(std::ostream & OS, const SMDS_MeshElement *);
  friend SMDS_EXPORT bool SMDS_MeshElementIDFactory::BindID(int ID,SMDS_MeshElement* elem);
  friend class SMDS_Mesh;
  friend class SMESHDS_Mesh;
  friend class SMESHDS_SubMesh;
  friend class SMDS_MeshElementIDFactory;

  // ===========================
  //  Access to nodes by index
  // ===========================
  /*!
   * \brief Return node by its index
    * \param ind - node index
    * \retval const SMDS_MeshNode* - the node
   */
  virtual const SMDS_MeshNode* GetNode(const int ind) const;

  /*!
   * \brief Return node by its index
    * \param ind - node index
    * \retval const SMDS_MeshNode* - the node
   *
   * Index is wrapped if it is out of a valid range
   */
  const SMDS_MeshNode* GetNodeWrap(const int ind) const { return GetNode( WrappedIndex( ind )); }

  /*!
   * \brief Return true if index of node is valid (0 <= ind < NbNodes())
    * \param ind - node index
    * \retval bool - index check result
   */
  virtual bool IsValidIndex(const int ind) const;

  /*!
   * \brief Return a valid node index, fixing the given one if necessary
    * \param ind - node index
    * \retval int - valid node index
   */
  int WrappedIndex(const int ind) const {
    if ( ind < 0 ) return NbNodes() + ind % NbNodes();
    if ( ind >= NbNodes() ) return ind % NbNodes();
    return ind;
  }

  /*!
   * \brief Check if a node belongs to the element
    * \param node - the node to check
    * \retval int - node index within the element, -1 if not found
   */
  int GetNodeIndex( const SMDS_MeshNode* node ) const;

  inline ShortType getMeshId()  const { return myMeshId; }
  inline LongType  getshapeId() const { return myShapeId; }
  inline int getIdInShape()     const { return myIdInShape; }
  inline int getVtkId()         const { return myVtkID; }

  /*!
   * \brief Filters of elements, to be used with SMDS_SetIterator
   */
  struct TypeFilter
  {
    SMDSAbs_ElementType _type;
    TypeFilter( SMDSAbs_ElementType t = SMDSAbs_NbElementTypes ):_type(t) {}
    bool operator()(const SMDS_MeshElement* e) const { return e && e->GetType() == _type; }
  };
  struct EntityFilter
  {
    SMDSAbs_EntityType _type;
    EntityFilter( SMDSAbs_EntityType t = SMDSEntity_Last ):_type(t) {}
    bool operator()(const SMDS_MeshElement* e) const { return e && e->GetEntityType() == _type; }
  };
  struct GeomFilter
  {
    SMDSAbs_GeometryType _type;
    GeomFilter( SMDSAbs_GeometryType t = SMDSGeom_NONE ):_type(t) {}
    bool operator()(const SMDS_MeshElement* e) const { return e && e->GetGeomType() == _type; }
  };

protected:
  inline void setId(int id) {myID = id; }
  inline void setShapeId(LongType shapeId) {myShapeId = shapeId; }
  inline void setIdInShape(int id) { myIdInShape = id; }
  inline void setVtkId(int vtkId) { myVtkID = vtkId; }
  SMDS_MeshElement(int ID=-1);
  SMDS_MeshElement(int id, ShortType meshId, LongType shapeId = 0);
  virtual void init(int id = -1, ShortType meshId = -1, LongType shapeId = 0);
  virtual void Print(std::ostream & OS) const;

  //! Element index in vector SMDS_Mesh::myNodes or SMDS_Mesh::myCells
  int myID;
  //! index in vtkUnstructuredGrid
  int myVtkID;
  //! SMDS_Mesh identification in SMESH
  ShortType myMeshId;
  //! SubShape and SubMesh identification in SMESHDS
  LongType myShapeId;
  //! Element index in SMESHDS_SubMesh vector
  int myIdInShape;
};

// ============================================================
/*!
 * \brief Comparator of elements by ID for usage in std containers
 */
// ============================================================

struct TIDCompare {
  bool operator () (const SMDS_MeshElement* e1, const SMDS_MeshElement* e2) const
  { return e1->GetID() < e2->GetID(); }
};

#endif
<commit_msg>Regression of XSMESH_TEST/SMESHCOMMON/SMESH_TEST/Grids/smesh/bugs12/M6<commit_after>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//

//  SMESH SMDS : implementaion of Salome mesh data structure
//  File   : SMDS_MeshElement.hxx
//  Module : SMESH
//
#ifndef _SMDS_MeshElement_HeaderFile
#define _SMDS_MeshElement_HeaderFile

#include "SMESH_SMDS.hxx"

#include "SMDSAbs_ElementType.hxx"
#include "SMDS_MeshObject.hxx"
#include "SMDS_ElemIterator.hxx"
#include "SMDS_MeshElementIDFactory.hxx"
#include "SMDS_StdIterator.hxx"

#include <vector>
#include <iostream>

#include <vtkType.h>
#include <vtkCellType.h>

//typedef unsigned short UShortType;
typedef short ShortType;
typedef int   LongType;

class SMDS_MeshNode;
class SMDS_MeshEdge;
class SMDS_MeshFace;
class SMDS_Mesh;

// ============================================================
/*!
 * \brief Base class for elements
 */
// ============================================================

class SMDS_EXPORT SMDS_MeshElement:public SMDS_MeshObject
{
public:

  SMDS_ElemIteratorPtr nodesIterator() const;
  SMDS_ElemIteratorPtr edgesIterator() const;
  SMDS_ElemIteratorPtr facesIterator() const;
  virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const;
  virtual SMDS_ElemIteratorPtr nodesIteratorToUNV() const;
  virtual SMDS_ElemIteratorPtr interlacedNodesElemIterator() const;

  // std-like iteration on nodes
  typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_ElemIteratorPtr > iterator;
  iterator begin_nodes() const { return iterator( nodesIterator() ); }
  iterator end_nodes()   const { return iterator(); }

  virtual int NbNodes() const;
  virtual int NbEdges() const;
  virtual int NbFaces() const;
  inline int GetID() const { return myID; };

  ///Return the type of the current element
  virtual SMDSAbs_ElementType GetType() const = 0;
  virtual SMDSAbs_EntityType GetEntityType() const = 0;
  virtual SMDSAbs_GeometryType GetGeomType() const = 0;
  virtual vtkIdType GetVtkType() const = 0;
  virtual bool IsPoly() const { return false; }
  virtual bool IsQuadratic() const;

  virtual bool IsMediumNode(const SMDS_MeshNode* node) const;
  virtual int  NbCornerNodes() const;

  friend SMDS_EXPORT std::ostream & operator <<(std::ostream & OS, const SMDS_MeshElement *);
  friend SMDS_EXPORT bool SMDS_MeshElementIDFactory::BindID(int ID,SMDS_MeshElement* elem);
  friend class SMDS_Mesh;
  friend class SMESHDS_Mesh;
  friend class SMESHDS_SubMesh;
  friend class SMDS_MeshElementIDFactory;

  // ===========================
  //  Access to nodes by index
  // ===========================
  /*!
   * \brief Return node by its index
    * \param ind - node index
    * \retval const SMDS_MeshNode* - the node
   */
  virtual const SMDS_MeshNode* GetNode(const int ind) const;

  /*!
   * \brief Return node by its index
    * \param ind - node index
    * \retval const SMDS_MeshNode* - the node
   *
   * Index is wrapped if it is out of a valid range
   */
  const SMDS_MeshNode* GetNodeWrap(const int ind) const { return GetNode( WrappedIndex( ind )); }

  /*!
   * \brief Return true if index of node is valid (0 <= ind < NbNodes())
    * \param ind - node index
    * \retval bool - index check result
   */
  virtual bool IsValidIndex(const int ind) const;

  /*!
   * \brief Return a valid node index, fixing the given one if necessary
    * \param ind - node index
    * \retval int - valid node index
   */
  int WrappedIndex(const int ind) const {
    if ( ind < 0 ) return NbNodes() + ind % NbNodes();
    if ( ind >= NbNodes() ) return ind % NbNodes();
    return ind;
  }

  /*!
   * \brief Check if a node belongs to the element
    * \param node - the node to check
    * \retval int - node index within the element, -1 if not found
   */
  int GetNodeIndex( const SMDS_MeshNode* node ) const;

  inline ShortType getMeshId()  const { return myMeshId; }
  inline LongType  getshapeId() const { return myShapeId; }
  inline int getIdInShape()     const { return myIdInShape; }
  inline int getVtkId()         const { return myVtkID; }

  /*!
   * \brief Filters of elements, to be used with SMDS_SetIterator
   */
  struct TypeFilter
  {
    SMDSAbs_ElementType _type;
    TypeFilter( SMDSAbs_ElementType t = SMDSAbs_NbElementTypes ):_type(t) {}
    bool operator()(const SMDS_MeshElement* e) const { return e && e->GetType() == _type; }
  };
  struct EntityFilter
  {
    SMDSAbs_EntityType _type;
    EntityFilter( SMDSAbs_EntityType t = SMDSEntity_Last ):_type(t) {}
    bool operator()(const SMDS_MeshElement* e) const { return e && e->GetEntityType() == _type; }
  };
  struct GeomFilter
  {
    SMDSAbs_GeometryType _type;
    GeomFilter( SMDSAbs_GeometryType t = SMDSGeom_NONE ):_type(t) {}
    bool operator()(const SMDS_MeshElement* e) const { return e && e->GetGeomType() == _type; }
  };

protected:
  inline void setId(int id) {myID = id; }
  inline void setShapeId(LongType shapeId) {myShapeId = shapeId; }
  inline void setIdInShape(int id) { myIdInShape = id; }
  inline void setVtkId(int vtkId) { myVtkID = vtkId; }
  SMDS_MeshElement(int ID=-1);
  SMDS_MeshElement(int id, ShortType meshId, LongType shapeId = 0);
  virtual void init(int id = -1, ShortType meshId = -1, LongType shapeId = 0);
  virtual void Print(std::ostream & OS) const;

  //! Element index in vector SMDS_Mesh::myNodes or SMDS_Mesh::myCells
  int myID;
  //! index in vtkUnstructuredGrid
  int myVtkID;
  //! SMDS_Mesh identification in SMESH
  ShortType myMeshId;
  //! SubShape and SubMesh identification in SMESHDS
  LongType myShapeId;
  //! Element index in SMESHDS_SubMesh vector
  int myIdInShape;
};

// ============================================================
/*!
 * \brief Comparator of elements by ID for usage in std containers
 */
// ============================================================

struct TIDCompare {
  bool operator () (const SMDS_MeshElement* e1, const SMDS_MeshElement* e2) const
  { return e1->GetType() == e2->GetType() ? e1->GetID() < e2->GetID() : e1->GetType() < e2->GetType(); }
};

#endif
<|endoftext|>


<commit_before>/* Copyright 2018 Carnegie Mellon University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "scanner/api/source.h"
#include "scanner/api/enumerator.h"
#include "stdlib/stdlib.pb.h"

#include "scanner/util/tinyformat.h"
#include "scanner/util/serialize.h"
#include "scanner/util/json.hpp"
#include "stdlib/misc/sql.h"

#include <glog/logging.h>
#include <vector>
#include <pqxx/pqxx>

using nlohmann::json;

namespace scanner {

// NOTE: SQLSource/Enumerator currently only supports Postgres.

class SQLEnumerator : public Enumerator {
 public:
  SQLEnumerator(const EnumeratorConfig& config) : Enumerator(config) {
    bool parsed = args_.ParseFromArray(config.args.data(), config.args.size());
    if (!parsed) {
      RESULT_ERROR(&valid_, "Could not parse SQLEnumeratorArgs");
      return;
    }
  }

  i64 total_elements() override {
    try {
      std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());
      pqxx::work txn{*conn};
      // Count the number the number of groups
      auto query = args_.query();
      pqxx::row r = txn.exec1(tfm::format(
          "SELECT COUNT(DISTINCT(%s)) FROM %s WHERE %s", query.group(),
          query.table(), args_.filter()));
      return r[0].as<i32>();
    } catch (pqxx::pqxx_exception& e) {
      LOG(FATAL) << e.base().what();
    }
  }

  ElementArgs element_args_at(i64 element_idx) override {
    proto::SQLElementArgs args;
    args.set_filter(args_.filter());
    size_t size = args.ByteSizeLong();

    ElementArgs element_args;
    element_args.args.resize(size);
    args.SerializeToArray(element_args.args.data(), size);
    element_args.row_id = element_idx;

    return element_args;
  }

 private:
  Result valid_;
  scanner::proto::SQLEnumeratorArgs args_;

};

class SQLSource : public Source {
 public:
  SQLSource(const SourceConfig& config) : Source(config) {
    bool parsed = args_.ParseFromArray(config.args.data(), config.args.size());
    if (!parsed) {
      RESULT_ERROR(&valid_, "Could not parse SQLSourceArgs");
      return;
    }

    // Query database for mapping from type IDs to type names
    std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());
    pqxx::work txn{*conn};
    pqxx::result types = txn.exec("SELECT oid, typname FROM pg_type");
    for (auto row : types) {
      pq_types_[row["oid"].as<pqxx::oid>()] = row["typname"].as<std::string>();
    }
  }

  void read(const std::vector<ElementArgs>& element_args,
            std::vector<Elements>& output_columns) override {
    LOG_IF(FATAL, element_args.size() == 0) << "Asked to read zero elements";

    // Deserialize all ElementArgs
    std::string filter;
    std::vector<i64> row_ids;
    for (size_t i = 0; i < element_args.size(); ++i) {
      proto::SQLElementArgs a;
      bool parsed = a.ParseFromArray(element_args[i].args.data(),
                                     element_args[i].args.size());
      LOG_IF(FATAL, !parsed) << "Could not parse element args in SQL";

      row_ids.push_back(element_args[i].row_id);
      filter = a.filter();
    }

    auto query = args_.query();

    // If we received elements from a new job, then flush our cached results and run a new query
    if (last_filter_ != filter) {
      last_filter_ = filter;

      // Execute SELECT to fetch all the rows
      std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());
      pqxx::work txn{*conn};
      std::string query_str = tfm::format(
          "SELECT %s, %s AS _scanner_id, %s AS _scanner_number FROM %s "
          "WHERE %s ORDER BY _scanner_number, _scanner_id",
          query.fields(), query.id(), query.group(), query.table(),
          filter);

      pqxx::result result = txn.exec(query_str);
      LOG_IF(FATAL, result.size() == 0) << "Query returned zero rows. Executed query was:\n" << query_str;

      // Group the rows based on the provided key
      cached_rows_.clear();
      std::vector<pqxx::row> cur_group;
      i32 last_group = result[0]["_scanner_number"].as<i32>();
      for (auto row : result) {
        i32 num = row["_scanner_number"].as<i32>();
        if (num != last_group) {
          last_group = num;
          cached_rows_.push_back(cur_group);
          cur_group = std::vector<pqxx::row>();
        }
        cur_group.push_back(row);
      }

      cached_rows_.push_back(cur_group);
    }

    size_t total_size = 0;
    std::vector<size_t> sizes;

    // Collect requested outputs and serialize to JSON
    std::vector<std::string> rows_serialized;
    for (auto row_id : row_ids) {
      json jrows = json::array();
      auto& row_group = cached_rows_[row_id];
      for (auto row : row_group) {
        jrows.push_back(row_to_json(row));
      }
      std::string serialized = jrows.dump();
      rows_serialized.push_back(serialized);
      sizes.push_back(serialized.size());
      total_size += serialized.size();
    }

    // Pack serialized results into a single block buffer;
    u8* block_buffer = new_block_buffer(CPU_DEVICE, total_size, sizes.size());
    u8* cursor = block_buffer;
    for (i32 i = 0; i < sizes.size(); ++i) {
      memcpy_buffer(cursor, CPU_DEVICE, (u8*) rows_serialized[i].c_str(), CPU_DEVICE, sizes[i]);
      insert_element(output_columns[0], cursor, sizes[i]);
      cursor += sizes[i];
    }
  }

 private:
  json row_to_json(pqxx::row row) {
    json jrow;

    for (pqxx::field field : row) {
      std::string name(field.name());
      if (name == "_scanner_id" || name == "_scanner_number") {
        continue;
      }

      pqxx::oid type = field.type();
      std::string& typname = pq_types_[type];
      bool assigned = false;

      #define ASSIGN_IF(NAME, TYPE) \
        if (typname == NAME) { jrow[name] = field.as<TYPE>(); assigned = true; }

      // Left argument is the Postgres type name, right argument is the corresponding C++ type
      ASSIGN_IF("int4", i32);
      ASSIGN_IF("float8", f32);
      ASSIGN_IF("bool", bool);
      ASSIGN_IF("text", std::string);
      ASSIGN_IF("varchar", std::string);

      LOG_IF(FATAL, !assigned)
          << "Requested row has field " << name
          << " with a type we can't serialize yet: " << typname;
    }

    return std::move(jrow);
  }

  Result valid_;
  scanner::proto::SQLSourceArgs args_;
  std::string last_filter_;
  std::vector<std::vector<pqxx::row>> cached_rows_;
  std::map<pqxx::oid, std::string> pq_types_;
};

REGISTER_ENUMERATOR(SQL, SQLEnumerator)
    .protobuf_name("SQLEnumeratorArgs");

REGISTER_SOURCE(SQL, SQLSource)
    .output("output")
    .protobuf_name("SQLSourceArgs");

}  // namespace scanner
<commit_msg>Cache total_elements in SQL source<commit_after>/* Copyright 2018 Carnegie Mellon University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "scanner/api/source.h"
#include "scanner/api/enumerator.h"
#include "stdlib/stdlib.pb.h"

#include "scanner/util/tinyformat.h"
#include "scanner/util/serialize.h"
#include "scanner/util/json.hpp"
#include "stdlib/misc/sql.h"

#include <glog/logging.h>
#include <vector>
#include <pqxx/pqxx>

using nlohmann::json;

namespace scanner {

// NOTE: SQLSource/Enumerator currently only supports Postgres.

class SQLEnumerator : public Enumerator {
 public:
  SQLEnumerator(const EnumeratorConfig& config) : Enumerator(config) {
    bool parsed = args_.ParseFromArray(config.args.data(), config.args.size());
    if (!parsed) {
      RESULT_ERROR(&valid_, "Could not parse SQLEnumeratorArgs");
      return;
    }
  }

  i64 total_elements() override {
    if (total_elements_cached_ == -1) {
      try {
        std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());
        pqxx::work txn{*conn};
        // Count the number the number of groups
        auto query = args_.query();
        pqxx::row r = txn.exec1(tfm::format(
            "SELECT COUNT(DISTINCT(%s)) FROM %s WHERE %s", query.group(),
            query.table(), args_.filter()));
        total_elements_cached_ = r[0].as<i32>();
      } catch (pqxx::pqxx_exception& e) {
        LOG(FATAL) << e.base().what();
      }
    }

    return total_elements_cached_;
  }

  ElementArgs element_args_at(i64 element_idx) override {
    proto::SQLElementArgs args;
    args.set_filter(args_.filter());
    size_t size = args.ByteSizeLong();

    ElementArgs element_args;
    element_args.args.resize(size);
    args.SerializeToArray(element_args.args.data(), size);
    element_args.row_id = element_idx;

    return element_args;
  }

 private:
  Result valid_;
  scanner::proto::SQLEnumeratorArgs args_;
  i64 total_elements_cached_ = -1;
};

class SQLSource : public Source {
 public:
  SQLSource(const SourceConfig& config) : Source(config) {
    bool parsed = args_.ParseFromArray(config.args.data(), config.args.size());
    if (!parsed) {
      RESULT_ERROR(&valid_, "Could not parse SQLSourceArgs");
      return;
    }

    // Query database for mapping from type IDs to type names
    std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());
    pqxx::work txn{*conn};
    pqxx::result types = txn.exec("SELECT oid, typname FROM pg_type");
    for (auto row : types) {
      pq_types_[row["oid"].as<pqxx::oid>()] = row["typname"].as<std::string>();
    }
  }

  void read(const std::vector<ElementArgs>& element_args,
            std::vector<Elements>& output_columns) override {
    LOG_IF(FATAL, element_args.size() == 0) << "Asked to read zero elements";

    // Deserialize all ElementArgs
    std::string filter;
    std::vector<i64> row_ids;
    for (size_t i = 0; i < element_args.size(); ++i) {
      proto::SQLElementArgs a;
      bool parsed = a.ParseFromArray(element_args[i].args.data(),
                                     element_args[i].args.size());
      LOG_IF(FATAL, !parsed) << "Could not parse element args in SQL";

      row_ids.push_back(element_args[i].row_id);
      filter = a.filter();
    }

    auto query = args_.query();

    // If we received elements from a new job, then flush our cached results and run a new query
    if (last_filter_ != filter) {
      last_filter_ = filter;

      // Execute SELECT to fetch all the rows
      std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());
      pqxx::work txn{*conn};
      std::string query_str = tfm::format(
          "SELECT %s, %s AS _scanner_id, %s AS _scanner_number FROM %s "
          "WHERE %s ORDER BY _scanner_number, _scanner_id",
          query.fields(), query.id(), query.group(), query.table(),
          filter);

      pqxx::result result = txn.exec(query_str);
      LOG_IF(FATAL, result.size() == 0) << "Query returned zero rows. Executed query was:\n" << query_str;

      // Group the rows based on the provided key
      cached_rows_.clear();
      std::vector<pqxx::row> cur_group;
      i32 last_group = result[0]["_scanner_number"].as<i32>();
      for (auto row : result) {
        i32 num = row["_scanner_number"].as<i32>();
        if (num != last_group) {
          last_group = num;
          cached_rows_.push_back(cur_group);
          cur_group = std::vector<pqxx::row>();
        }
        cur_group.push_back(row);
      }

      cached_rows_.push_back(cur_group);
    }

    size_t total_size = 0;
    std::vector<size_t> sizes;

    // Collect requested outputs and serialize to JSON
    std::vector<std::string> rows_serialized;
    for (auto row_id : row_ids) {
      json jrows = json::array();
      auto& row_group = cached_rows_[row_id];
      for (auto row : row_group) {
        jrows.push_back(row_to_json(row));
      }
      std::string serialized = jrows.dump();
      rows_serialized.push_back(serialized);
      sizes.push_back(serialized.size());
      total_size += serialized.size();
    }

    // Pack serialized results into a single block buffer;
    u8* block_buffer = new_block_buffer(CPU_DEVICE, total_size, sizes.size());
    u8* cursor = block_buffer;
    for (i32 i = 0; i < sizes.size(); ++i) {
      memcpy_buffer(cursor, CPU_DEVICE, (u8*) rows_serialized[i].c_str(), CPU_DEVICE, sizes[i]);
      insert_element(output_columns[0], cursor, sizes[i]);
      cursor += sizes[i];
    }
  }

 private:
  json row_to_json(pqxx::row row) {
    json jrow;

    for (pqxx::field field : row) {
      std::string name(field.name());
      if (name == "_scanner_id" || name == "_scanner_number") {
        continue;
      }

      pqxx::oid type = field.type();
      std::string& typname = pq_types_[type];
      bool assigned = false;

      #define ASSIGN_IF(NAME, TYPE) \
        if (typname == NAME) { jrow[name] = field.as<TYPE>(); assigned = true; }

      // Left argument is the Postgres type name, right argument is the corresponding C++ type
      ASSIGN_IF("int4", i32);
      ASSIGN_IF("float8", f32);
      ASSIGN_IF("bool", bool);
      ASSIGN_IF("text", std::string);
      ASSIGN_IF("varchar", std::string);

      LOG_IF(FATAL, !assigned)
          << "Requested row has field " << name
          << " with a type we can't serialize yet: " << typname;
    }

    return std::move(jrow);
  }

  Result valid_;
  scanner::proto::SQLSourceArgs args_;
  std::string last_filter_;
  std::vector<std::vector<pqxx::row>> cached_rows_;
  std::map<pqxx::oid, std::string> pq_types_;
};

REGISTER_ENUMERATOR(SQL, SQLEnumerator)
    .protobuf_name("SQLEnumeratorArgs");

REGISTER_SOURCE(SQL, SQLSource)
    .output("output")
    .protobuf_name("SQLSourceArgs");

}  // namespace scanner
<|endoftext|>


<commit_before>#include "fabo-ble113.h"
#include <SoftwareSerial.h>

BeaconParam beaconParam;

SoftwareSerial bleShield(12, 13);
bool DEBUG = false;

void ble113::setDebug(){
  DEBUG = true;
}

void ble113::initBLE113()
{
  // BLEとの通信用
  bleShield.begin(9600);

  if(DEBUG){
    Serial.begin(9600);
  }
}

void ble113::setBeaconUuid(byte uuid[]){

  memcpy(beaconParam.uuid, uuid, 16);
}

void ble113::setBeaconMajor(byte major[]){

  memcpy(beaconParam.major, major, 2);
}

void ble113::setBeaconMinor(byte minor[]){

  memcpy(beaconParam.minor, minor, 2);
}

bool ble113::sendBeacon(){

    byte command[6] = {0x00,  // message type  ->0x00:command
                      0x20,     // Minimum payload length
                      0x06,     // Message class -> 0x06:Generic Access Profile
                      0x09,     // Message ID
                      0x00,     // Advertisement data type -> 0x00: sets advertisement data e
                      0x1e};    // Advertisement data to send

    byte beaconHeader[9] = {0x02,
                          0x01,
                          0x06,
                          0x1A,
                          0xFF,
                          0x4C,
                          0x00,
                          0x02,
                          0x15};
    byte txPower = 0xC9;

    for(int i = 0; i < 6; i++){
      bleShield.write((byte)command[i]);
    }
    for(int i = 0; i < 9; i++){
      bleShield.write((byte)beaconHeader[i]);
    }
    for(int i = 0; i < 16; i++){
      bleShield.write((byte)beaconParam.uuid[i]);
    }
    for(int i = 0; i < 2; i++){
      bleShield.write((byte)beaconParam.major[i]);
    }
    for(int i = 0; i < 2; i++){
      bleShield.write((byte)beaconParam.minor[i]);
    }

    bleShield.write((byte)0xC9);

    delay(1000);

    byte buffer[10];
    int i = 0;
    while (bleShield.available()) {
      buffer[i] = bleShield.read();
      i++;
    }

    if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x09){
      if(buffer[4] == 0x00 && buffer[5] == 0x00){
        return true;
      }
      else {
        if(DEBUG){
          Serial.println("(sendBeacon)Error Code");
          Serial.println(buffer[5],HEX);
          Serial.println(buffer[4],HEX);
        }
        return false;
      }
    } else {
      if(DEBUG){
          Serial.println("(sendBeacon)Unknow Error");
          Serial.println(buffer[0],HEX);
          Serial.println(buffer[1],HEX);
          Serial.println(buffer[2],HEX);
          Serial.println(buffer[3],HEX);
          Serial.println(buffer[4],HEX);
          Serial.println(buffer[5],HEX);
        }
      return false;
    }
}

bool ble113::setMode()
{

  byte command[6] = {0x00,  // message type  ->0x00:command
                  0x02,     // Minimum payload length
                  0x06,     // Message class -> 0x06:Generic Access Profile
                  0x01,     // Message ID
                  0x04,     // GAP Discoverable Mode
                  0x00};    // GAP Connectable Mode

    for(int i = 0; i < 6; i++){
      bleShield.write((byte)command[i]);
    }
    delay(1000);

    byte buffer[10];
    int i = 0;
    while (bleShield.available()) {
      buffer[i] = bleShield.read();
      i++;
    }

    if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x01){
      if(buffer[4] == 0x00 && buffer[5] == 0x00){
        return true;
      }
      else {
        if(DEBUG){
          Serial.println("Error Code");
          Serial.println(buffer[5],HEX);
          Serial.println(buffer[4],HEX);
        }
        return false;
      }
    } else {
      if(DEBUG){
          Serial.println("Unknow Error");
          Serial.println(buffer[0],HEX);
          Serial.println(buffer[1],HEX);
          Serial.println(buffer[2],HEX);
          Serial.println(buffer[3],HEX);
          Serial.println(buffer[4],HEX);
          Serial.println(buffer[5],HEX);
        }
      return false;
    }
}

bool ble113::setAdvParams()
{
    byte command[9] = {0x00,
                  0x05,
                  0x06,
                  0x08,
                  0x00,
                  0x02,
                  0x00,
                  0x02,
                  0x07};

    for(int i = 0; i < 9; i++){
      bleShield.write((byte)command[i]);
    }
    delay(1000);

    byte buffer[10];
    int i = 0;
    while (bleShield.available()) {
      buffer[i] = bleShield.read();
      i++;
    }

    if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x08){
      if(buffer[4] == 0x00 && buffer[5] == 0x00){
        return true;
      }
      else {
        if(DEBUG){
          Serial.println("Error Code");
          Serial.println(buffer[5],HEX);
          Serial.println(buffer[4],HEX);
        }
        return false;
      }
    } else {
      if(DEBUG){
          Serial.println("Unknow Error");
          Serial.println(buffer[0],HEX);
          Serial.println(buffer[1],HEX);
          Serial.println(buffer[2],HEX);
          Serial.println(buffer[3],HEX);
          Serial.println(buffer[4],HEX);
          Serial.println(buffer[5],HEX);
        }
      return false;
    }

ble113 faboBLE;

<commit_msg>fixture addend{<commit_after>#include "fabo-ble113.h"
#include <SoftwareSerial.h>

BeaconParam beaconParam;

SoftwareSerial bleShield(12, 13);
bool DEBUG = false;

void ble113::setDebug(){
    DEBUG = true;
}

void ble113::initBLE113()
{
    // BLEとの通信用
    bleShield.begin(9600);

    if(DEBUG){
        Serial.begin(9600);
    }
}

void ble113::setBeaconUuid(byte uuid[]){

    memcpy(beaconParam.uuid, uuid, 16);
}

void ble113::setBeaconMajor(byte major[]){

    memcpy(beaconParam.major, major, 2);
}

void ble113::setBeaconMinor(byte minor[]){

    memcpy(beaconParam.minor, minor, 2);
}

bool ble113::sendBeacon(){

    byte command[6] = {0x00,  // message type  ->0x00:command
        0x20,     // Minimum payload length
        0x06,     // Message class -> 0x06:Generic Access Profile
        0x09,     // Message ID
        0x00,     // Advertisement data type -> 0x00: sets advertisement data e
        0x1e};    // Advertisement data to send

    byte beaconHeader[9] = {0x02,
        0x01,
        0x06,
        0x1A,
        0xFF,
        0x4C,
        0x00,
        0x02,
        0x15};
    byte txPower = 0xC9;

    for(int i = 0; i < 6; i++){
        bleShield.write((byte)command[i]);
    }
    for(int i = 0; i < 9; i++){
        bleShield.write((byte)beaconHeader[i]);
    }
    for(int i = 0; i < 16; i++){
        bleShield.write((byte)beaconParam.uuid[i]);
    }
    for(int i = 0; i < 2; i++){
        bleShield.write((byte)beaconParam.major[i]);
    }
    for(int i = 0; i < 2; i++){
        bleShield.write((byte)beaconParam.minor[i]);
    }

    bleShield.write((byte)0xC9);

    delay(1000);

    byte buffer[10];
    int i = 0;
    while (bleShield.available()) {
        buffer[i] = bleShield.read();
        i++;
    }

    if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x09){
        if(buffer[4] == 0x00 && buffer[5] == 0x00){
            return true;
        }
        else {
            if(DEBUG){
                Serial.println("(sendBeacon)Error Code");
                Serial.println(buffer[5],HEX);
                Serial.println(buffer[4],HEX);
            }
            return false;
        }
    } else {
        if(DEBUG){
            Serial.println("(sendBeacon)Unknow Error");
            Serial.println(buffer[0],HEX);
            Serial.println(buffer[1],HEX);
            Serial.println(buffer[2],HEX);
            Serial.println(buffer[3],HEX);
            Serial.println(buffer[4],HEX);
            Serial.println(buffer[5],HEX);
        }
        return false;
    }
}

bool ble113::setMode()
{

    byte command[6] = {0x00,  // message type  ->0x00:command
        0x02,     // Minimum payload length
        0x06,     // Message class -> 0x06:Generic Access Profile
        0x01,     // Message ID
        0x04,     // GAP Discoverable Mode
        0x00};    // GAP Connectable Mode

    for(int i = 0; i < 6; i++){
        bleShield.write((byte)command[i]);
    }
    delay(1000);

    byte buffer[10];
    int i = 0;
    while (bleShield.available()) {
        buffer[i] = bleShield.read();
        i++;
    }

    if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x01){
        if(buffer[4] == 0x00 && buffer[5] == 0x00){
            return true;
        }
        else {
            if(DEBUG){
                Serial.println("Error Code");
                Serial.println(buffer[5],HEX);
                Serial.println(buffer[4],HEX);
            }
            return false;
        }
    } else {
        if(DEBUG){
            Serial.println("Unknow Error");
            Serial.println(buffer[0],HEX);
            Serial.println(buffer[1],HEX);
            Serial.println(buffer[2],HEX);
            Serial.println(buffer[3],HEX);
            Serial.println(buffer[4],HEX);
            Serial.println(buffer[5],HEX);
        }
        return false;
    }
}

bool ble113::setAdvParams()
{
    byte command[9] = {0x00,
        0x05,
        0x06,
        0x08,
        0x00,
        0x02,
        0x00,
        0x02,
        0x07};

    for(int i = 0; i < 9; i++){
        bleShield.write((byte)command[i]);
    }
    delay(1000);

    byte buffer[10];
    int i = 0;
    while (bleShield.available()) {
        buffer[i] = bleShield.read();
        i++;
    }

    if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x08){
        if(buffer[4] == 0x00 && buffer[5] == 0x00){
            return true;
        }
        else {
            if(DEBUG){
                Serial.println("Error Code");
                Serial.println(buffer[5],HEX);
                Serial.println(buffer[4],HEX);
            }
            return false;
        }
    } else {
        if(DEBUG){
            Serial.println("Unknow Error");
            Serial.println(buffer[0],HEX);
            Serial.println(buffer[1],HEX);
            Serial.println(buffer[2],HEX);
            Serial.println(buffer[3],HEX);
            Serial.println(buffer[4],HEX);
            Serial.println(buffer[5],HEX);
        }
        return false;
    }
}
    ble113 faboBLE;<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkToolGUI.h"

#include <iostream>

QmitkToolGUI::~QmitkToolGUI()
{
  m_ReferenceCountLock.Lock();
  m_ReferenceCount = 0; // otherwise ITK will complain in LightObject's destructor
  m_ReferenceCountLock.Unlock();
}

void QmitkToolGUI::Register() const
{
  // empty on purpose, just don't let ITK handle calls to Register()
}

void QmitkToolGUI::UnRegister() const
{
  // empty on purpose, just don't let ITK handle calls to UnRegister()
}

void QmitkToolGUI::SetReferenceCount(int)
{
  // empty on purpose, just don't let ITK handle calls to SetReferenceCount()
}

void QmitkToolGUI::SetTool( mitk::Tool* tool )
{
  m_Tool = tool;

  emit( NewToolAssociated(tool) );
}

<commit_msg>Add missing keyword to UnRegister definition<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkToolGUI.h"

#include <iostream>

QmitkToolGUI::~QmitkToolGUI()
{
  m_ReferenceCountLock.Lock();
  m_ReferenceCount = 0; // otherwise ITK will complain in LightObject's destructor
  m_ReferenceCountLock.Unlock();
}

void QmitkToolGUI::Register() const
{
  // empty on purpose, just don't let ITK handle calls to Register()
}

void QmitkToolGUI::UnRegister() const ITK_NOEXCEPT
{
  // empty on purpose, just don't let ITK handle calls to UnRegister()
}

void QmitkToolGUI::SetReferenceCount(int)
{
  // empty on purpose, just don't let ITK handle calls to SetReferenceCount()
}

void QmitkToolGUI::SetTool( mitk::Tool* tool )
{
  m_Tool = tool;

  emit( NewToolAssociated(tool) );
}

<|endoftext|>


<commit_before>//
// Created by mpolovyi on 22/01/16.
//

#include <iostream>
#include <stdlib.h>

#include <cereal/archives/json.hpp>
#include <cereal/types/polymorphic.hpp>

#include <SCOLSS/SimulationController/MonteCarloSimCtrl/CMonteCarloSimParams.h>
#include <SCOLSS/SimulationController/MonteCarloSimCtrl/CMonteCarloSimCtrl.h>
#include <SCOLSS/SimulationController/LangevinSimCtrl/CLangevinSimParams.h>
#include <SCOLSS/SimulationController/LangevinSimCtrl/CLangevinSimCtrl.h>

#include <SCOLSS/ParticlePhysics/CYukawaDipolePt.h>

void InitializeSimulations(int argc, char **argv);
void RunSimulations(std::shared_ptr<CBaseSimCtrl> sim,
                    std::string &fullSaveFileName,
                    std::string &miniSaveFileName,
                    std::string &savePictureFile,
                    std::string& fullSaveTarName,
                    std::string& miniSaveTarName,
                    std::string& pictSaveTarName);

void SaveToFile(std::shared_ptr<CBaseSimCtrl> &contr, std::string &fullSaveFileName, std::string &miniSaveFileName, uint64_t cycle,
                std::string& fullSaveTarName,
                std::string& miniSaveTarName);

int main(int argc, char **argv) {
    InitializeSimulations(argc, argv);
}

void InitializeSimulations(int argc, char **argv) {
    std::string simType = argv[2];
    ESimulationType simT;
    if(simType == "MC"){
        simT = ESimulationType::MonteCarlo;
    } else if (simType == "LD"){
        simT = ESimulationType::LangevinDynamics;
    } else {
        std::cout << "Unknown simulation type. Exiting." << std::endl;
        return;
    }

    std::string simDataFileName = argv[1];
    std::string fullSaveTarName = "FullData_" + simDataFileName + "_" + ".tar";
    std::string miniSaveTarName = "MiniData_" + simDataFileName + "_" + ".tar";
    std::string pictSaveTarName = "PictData_" + simDataFileName + "_" + ".tar";

    std::string createFullTarCommand = "tar -cf " + fullSaveTarName + " -T /dev/null";
    std::string createMiniTarCommand = "tar -cf " + miniSaveTarName + " -T /dev/null";
    std::string createPictTarCommand = "tar -cf " + pictSaveTarName + " -T /dev/null";

    system(createFullTarCommand.c_str());
    system(createMiniTarCommand.c_str());
    system(createPictTarCommand.c_str());

    std::string samples = argv[3];
    for(int i = 1; i <= std::stoi(samples); i++) {
        std::ifstream simDataFileStream(simDataFileName);

        cereal::JSONInputArchive simDataArchieve(simDataFileStream);

        std::shared_ptr<CBaseSimCtrl> sim;

        switch (simT){
            case MonteCarlo: {
                CMonteCarloSimParams data;
                data.load(simDataArchieve);
                sim = std::make_shared<CMonteCarloSimCtrl>(CMonteCarloSimCtrl(data));
                break;
            };
            case LangevinDynamics: {
                CLangevinSimParams data;
                data.load(simDataArchieve);
                sim = std::make_shared<CLangevinSimCtrl>(CLangevinSimCtrl(data));
                break;
            };
        }

        std::string fullSaveFileName = "FullData_" + std::to_string(i) + "_" + simDataFileName;
        std::string miniSaveFileName = "MiniData_" + std::to_string(i) + "_" + simDataFileName;
        std::string pictSaveFileName = "PictData_" + std::to_string(i) + "_" + simDataFileName;

        SaveToFile(sim, fullSaveFileName, miniSaveFileName, 0,
                   fullSaveTarName, miniSaveTarName);

        RunSimulations(sim, fullSaveFileName, miniSaveFileName, pictSaveFileName,
                       fullSaveTarName,
                       miniSaveTarName,
                       pictSaveTarName);

        std::cout << i << std::endl;
    }
}

void RunSimulations(std::shared_ptr<CBaseSimCtrl> sim, std::string &fullSaveFileName, std::string &miniSaveFileName, std::string &pictSaveFileName,
                    std::string& fullSaveTarName,
                    std::string& miniSaveTarName,
                    std::string& pictSaveTarName) {
    {

        EPSPlot savePictureFile(pictSaveFileName.c_str(),
                                0,
                                0,
                                sim->SimulationParameters.GetEpsDimensionX(),
                                sim->SimulationParameters.GetEpsDimensionY());

        savePictureFile.initParticleSavings(sim->SimulationParameters.ParticleDiameter);

        sim->SaveIntoEps(savePictureFile);

        std::chrono::time_point<std::chrono::system_clock> start_time, step_time;
        start_time = std::chrono::system_clock::now();
        uint64_t prev_measure = 0;

        uint64_t totalCycles = sim->SimulationParameters.CyclesBetweenSaves * sim->SimulationParameters.NumberOfSavePoints;
        sim->SimulationParameters.NumberOfImageLines = std::min(totalCycles, sim->SimulationParameters.NumberOfImageLines);

        for (uint64_t cycle = 1; cycle <= totalCycles; ++cycle) {
            sim->DoCycle();

            if (0 == cycle % (sim->SimulationParameters.CyclesBetweenSaves)) {
                SaveToFile(sim, fullSaveFileName, miniSaveFileName, cycle,
                           fullSaveTarName, miniSaveTarName);
            }

            if (sim->SimulationParameters.SaveEpsPicture && 0 == cycle % (totalCycles / sim->SimulationParameters.NumberOfImageLines)) {
                sim->SaveIntoEps(savePictureFile);
            }

            auto doFinish = sim->PrintTimeExtrapolation(start_time, prev_measure, totalCycles, cycle);
            if (doFinish) {
                SaveToFile(sim, fullSaveFileName, miniSaveFileName, cycle,
                           fullSaveTarName, miniSaveTarName);

                sim->SaveIntoEps(savePictureFile);
                break;
            }
        }

    }
    if(sim->SimulationParameters.SaveEpsPicture) {
        std::string pictSaveAppendCommand = "tar -rpf" + pictSaveTarName + " " + pictSaveFileName + " && rm " + pictSaveFileName;
        system(pictSaveAppendCommand.c_str());
    }
}

void SaveToFile(std::shared_ptr<CBaseSimCtrl> &contr, std::string &fullSaveFileName, std::string &miniSaveFileName, uint64_t cycle,
                std::string& fullSaveTarName,
                std::string& miniSaveTarName) {
    {
        std::fstream mainFileStream((fullSaveFileName + std::to_string(cycle)).c_str(), std::ios_base::out);
        cereal::JSONOutputArchive mainFileArchieve(mainFileStream);

        std::fstream minimalFileStream((miniSaveFileName + std::to_string(cycle)).c_str(), std::ios_base::out);
        cereal::JSONOutputArchive minimalFileArchieve(minimalFileStream);

        switch (contr->SimulationParameters.SaveParticlesInfo) {
            case true:
                contr->save(mainFileArchieve);
                contr->SaveMinimal(minimalFileArchieve);
                break;

            case false:
                contr->save(minimalFileArchieve);
                break;
        }
    }

    std::string fullSaveAppendCommand =
            "tar -rpf" + fullSaveTarName + " " + fullSaveFileName + std::to_string(cycle) + " && rm " + fullSaveFileName + std::to_string(cycle);
    std::string miniSaveAppendCommand =
            "tar -rpf" + miniSaveTarName + " " + miniSaveFileName + std::to_string(cycle) + " && rm " + miniSaveFileName + std::to_string(cycle);

    switch (contr->SimulationParameters.SaveParticlesInfo) {
        case true:
            system(fullSaveAppendCommand.c_str());
            system(miniSaveAppendCommand.c_str());
            break;

        case false:
            system(miniSaveAppendCommand.c_str());
            break;
    }
}
<commit_msg>typo in tar file names<commit_after>//
// Created by mpolovyi on 22/01/16.
//

#include <iostream>
#include <stdlib.h>

#include <cereal/archives/json.hpp>
#include <cereal/types/polymorphic.hpp>

#include <SCOLSS/SimulationController/MonteCarloSimCtrl/CMonteCarloSimParams.h>
#include <SCOLSS/SimulationController/MonteCarloSimCtrl/CMonteCarloSimCtrl.h>
#include <SCOLSS/SimulationController/LangevinSimCtrl/CLangevinSimParams.h>
#include <SCOLSS/SimulationController/LangevinSimCtrl/CLangevinSimCtrl.h>

#include <SCOLSS/ParticlePhysics/CYukawaDipolePt.h>

void InitializeSimulations(int argc, char **argv);
void RunSimulations(std::shared_ptr<CBaseSimCtrl> sim,
                    std::string &fullSaveFileName,
                    std::string &miniSaveFileName,
                    std::string &savePictureFile,
                    std::string& fullSaveTarName,
                    std::string& miniSaveTarName,
                    std::string& pictSaveTarName);

void SaveToFile(std::shared_ptr<CBaseSimCtrl> &contr, std::string &fullSaveFileName, std::string &miniSaveFileName, uint64_t cycle,
                std::string& fullSaveTarName,
                std::string& miniSaveTarName);

int main(int argc, char **argv) {
    InitializeSimulations(argc, argv);
}

void InitializeSimulations(int argc, char **argv) {
    std::string simType = argv[2];
    ESimulationType simT;
    if(simType == "MC"){
        simT = ESimulationType::MonteCarlo;
    } else if (simType == "LD"){
        simT = ESimulationType::LangevinDynamics;
    } else {
        std::cout << "Unknown simulation type. Exiting." << std::endl;
        return;
    }

    std::string simDataFileName = argv[1];
    std::string fullSaveTarName = "FullData_" + simDataFileName + ".tar";
    std::string miniSaveTarName = "MiniData_" + simDataFileName + ".tar";
    std::string pictSaveTarName = "PictData_" + simDataFileName + ".tar";

    std::string createFullTarCommand = "tar -cf " + fullSaveTarName + " -T /dev/null";
    std::string createMiniTarCommand = "tar -cf " + miniSaveTarName + " -T /dev/null";
    std::string createPictTarCommand = "tar -cf " + pictSaveTarName + " -T /dev/null";

    system(createFullTarCommand.c_str());
    system(createMiniTarCommand.c_str());
    system(createPictTarCommand.c_str());

    std::string samples = argv[3];
    for(int i = 1; i <= std::stoi(samples); i++) {
        std::ifstream simDataFileStream(simDataFileName);

        cereal::JSONInputArchive simDataArchieve(simDataFileStream);

        std::shared_ptr<CBaseSimCtrl> sim;

        switch (simT){
            case MonteCarlo: {
                CMonteCarloSimParams data;
                data.load(simDataArchieve);
                sim = std::make_shared<CMonteCarloSimCtrl>(CMonteCarloSimCtrl(data));
                break;
            };
            case LangevinDynamics: {
                CLangevinSimParams data;
                data.load(simDataArchieve);
                sim = std::make_shared<CLangevinSimCtrl>(CLangevinSimCtrl(data));
                break;
            };
        }

        std::string fullSaveFileName = "FullData_" + std::to_string(i) + "_" + simDataFileName;
        std::string miniSaveFileName = "MiniData_" + std::to_string(i) + "_" + simDataFileName;
        std::string pictSaveFileName = "PictData_" + std::to_string(i) + "_" + simDataFileName;

        SaveToFile(sim, fullSaveFileName, miniSaveFileName, 0,
                   fullSaveTarName, miniSaveTarName);

        RunSimulations(sim, fullSaveFileName, miniSaveFileName, pictSaveFileName,
                       fullSaveTarName,
                       miniSaveTarName,
                       pictSaveTarName);

        std::cout << i << std::endl;
    }
}

void RunSimulations(std::shared_ptr<CBaseSimCtrl> sim, std::string &fullSaveFileName, std::string &miniSaveFileName, std::string &pictSaveFileName,
                    std::string& fullSaveTarName,
                    std::string& miniSaveTarName,
                    std::string& pictSaveTarName) {
    {

        EPSPlot savePictureFile(pictSaveFileName.c_str(),
                                0,
                                0,
                                sim->SimulationParameters.GetEpsDimensionX(),
                                sim->SimulationParameters.GetEpsDimensionY());

        savePictureFile.initParticleSavings(sim->SimulationParameters.ParticleDiameter);

        sim->SaveIntoEps(savePictureFile);

        std::chrono::time_point<std::chrono::system_clock> start_time, step_time;
        start_time = std::chrono::system_clock::now();
        uint64_t prev_measure = 0;

        uint64_t totalCycles = sim->SimulationParameters.CyclesBetweenSaves * sim->SimulationParameters.NumberOfSavePoints;
        sim->SimulationParameters.NumberOfImageLines = std::min(totalCycles, sim->SimulationParameters.NumberOfImageLines);

        for (uint64_t cycle = 1; cycle <= totalCycles; ++cycle) {
            sim->DoCycle();

            if (0 == cycle % (sim->SimulationParameters.CyclesBetweenSaves)) {
                SaveToFile(sim, fullSaveFileName, miniSaveFileName, cycle,
                           fullSaveTarName, miniSaveTarName);
            }

            if (sim->SimulationParameters.SaveEpsPicture && 0 == cycle % (totalCycles / sim->SimulationParameters.NumberOfImageLines)) {
                sim->SaveIntoEps(savePictureFile);
            }

            auto doFinish = sim->PrintTimeExtrapolation(start_time, prev_measure, totalCycles, cycle);
            if (doFinish) {
                SaveToFile(sim, fullSaveFileName, miniSaveFileName, cycle,
                           fullSaveTarName, miniSaveTarName);

                sim->SaveIntoEps(savePictureFile);
                break;
            }
        }

    }
    if(sim->SimulationParameters.SaveEpsPicture) {
        std::string pictSaveAppendCommand = "tar -rpf" + pictSaveTarName + " " + pictSaveFileName + " && rm " + pictSaveFileName;
        system(pictSaveAppendCommand.c_str());
    }
}

void SaveToFile(std::shared_ptr<CBaseSimCtrl> &contr, std::string &fullSaveFileName, std::string &miniSaveFileName, uint64_t cycle,
                std::string& fullSaveTarName,
                std::string& miniSaveTarName) {
    {
        std::fstream mainFileStream((fullSaveFileName + std::to_string(cycle)).c_str(), std::ios_base::out);
        cereal::JSONOutputArchive mainFileArchieve(mainFileStream);

        std::fstream minimalFileStream((miniSaveFileName + std::to_string(cycle)).c_str(), std::ios_base::out);
        cereal::JSONOutputArchive minimalFileArchieve(minimalFileStream);

        switch (contr->SimulationParameters.SaveParticlesInfo) {
            case true:
                contr->save(mainFileArchieve);
                contr->SaveMinimal(minimalFileArchieve);
                break;

            case false:
                contr->save(minimalFileArchieve);
                break;
        }
    }

    std::string fullSaveAppendCommand =
            "tar -rpf" + fullSaveTarName + " " + fullSaveFileName + std::to_string(cycle) + " && rm " + fullSaveFileName + std::to_string(cycle);
    std::string miniSaveAppendCommand =
            "tar -rpf" + miniSaveTarName + " " + miniSaveFileName + std::to_string(cycle) + " && rm " + miniSaveFileName + std::to_string(cycle);

    switch (contr->SimulationParameters.SaveParticlesInfo) {
        case true:
            system(fullSaveAppendCommand.c_str());
            system(miniSaveAppendCommand.c_str());
            break;

        case false:
            system(miniSaveAppendCommand.c_str());
            break;
    }
}
<|endoftext|>


<commit_before>
#include "fastareader.h"
#include "util.h"
#include <sstream>

FastaReader::FastaReader(string faFile, bool forceUpperCase)
{
    // Set locale and disable stdio synchronization to improve iostream performance
    // http://www.drdobbs.com/the-standard-librarian-iostreams-and-std/184401305
    // http://stackoverflow.com/questions/5166263/how-to-get-iostream-to-perform-better
    setlocale(LC_ALL,"C");
    ios_base::sync_with_stdio(false);

    mFastaFile = faFile;
    mForceUpperCase = forceUpperCase;
    if (is_directory(mFastaFile)) {
        string error_msg = "There is a problem with the provided fasta file: \'";
        error_msg.append(mFastaFile);
        error_msg.append("\' is a directory NOT a file...\n");
        throw invalid_argument(error_msg);
    }
    mFastaFileStream.open( mFastaFile.c_str(),ios::in);
    // verify that the file can be read
    if (!mFastaFileStream.is_open()) {
        string msg = "There is a problem with the provided fasta file: could NOT read ";
        msg.append(mFastaFile.c_str());
        msg.append("...\n");
        throw invalid_argument(msg);
    }

    char c;
    // seek to first contig
    while (mFastaFileStream.get(c) && c != '>') {
        if (mFastaFileStream.eof()) {
            break;
        }
    }
}

FastaReader::~FastaReader()
{
    if (mFastaFileStream.is_open()) {
        mFastaFileStream.close();
    }
}

void FastaReader::readNext()
{
    mCurrentID = "";
    mCurrentDescription = "";
    mCurrentSequence = "";
    bool foundHeader = false;

    char c;
    stringstream ssSeq;
    stringstream ssHeader;
    while(true){
        mFastaFileStream.get(c);
        if(c == '>' || mFastaFileStream.eof())
            break;
        else {
            if (foundHeader)
                ssSeq << c;
            else
                ssHeader << c;
        }

        string line = "";
        getline(mFastaFileStream,line,'\n');

        if(foundHeader == false) {
            ssHeader << line;
            foundHeader = true;
        }
        else {
            str_keep_valid_sequence(line, mForceUpperCase);
            ssSeq << line;
        }
    }
    mCurrentSequence = ssSeq.str();
    string header = ssHeader.str();

    int space = header.find(" ");
    mCurrentID = header.substr(0, space);
}

bool FastaReader::hasNext() {
    return !mFastaFileStream.eof();
}

void FastaReader::readAll() {
    while(!mFastaFileStream.eof()){
        readNext();
        mAllContigs[mCurrentID] = mCurrentSequence;
    }
}

bool FastaReader::test(){
    FastaReader reader("testdata/tinyref.fa");
    reader.readAll();

    string contig1 = "GATCACAGGTCTATCACCCTATTAATTGGTATTTTCGTCTGGGGGGTGTGGAGCCGGAGCACCCTATGTCGCAGT";
    string contig2 = "GTCTGCACAGCCGCTTTCCACACAGAACCCCCCCCTCCCCCCGCTTCTGGCAAACCCCAAAAACAAAGAACCCTA";

    if(reader.mAllContigs.count("contig1") == 0 || reader.mAllContigs.count("contig2") == 0 )
        return false;

    if(reader.mAllContigs["contig1"] != contig1 || reader.mAllContigs["contig2"] != contig2 )
        return false;

    return true;

}

<commit_msg>fix FastaReader lower case bug<commit_after>
#include "fastareader.h"
#include "util.h"
#include <sstream>

FastaReader::FastaReader(string faFile, bool forceUpperCase)
{
    // Set locale and disable stdio synchronization to improve iostream performance
    // http://www.drdobbs.com/the-standard-librarian-iostreams-and-std/184401305
    // http://stackoverflow.com/questions/5166263/how-to-get-iostream-to-perform-better
    setlocale(LC_ALL,"C");
    ios_base::sync_with_stdio(false);

    mFastaFile = faFile;
    mForceUpperCase = forceUpperCase;
    if (is_directory(mFastaFile)) {
        string error_msg = "There is a problem with the provided fasta file: \'";
        error_msg.append(mFastaFile);
        error_msg.append("\' is a directory NOT a file...\n");
        throw invalid_argument(error_msg);
    }
    mFastaFileStream.open( mFastaFile.c_str(),ios::in);
    // verify that the file can be read
    if (!mFastaFileStream.is_open()) {
        string msg = "There is a problem with the provided fasta file: could NOT read ";
        msg.append(mFastaFile.c_str());
        msg.append("...\n");
        throw invalid_argument(msg);
    }

    char c;
    // seek to first contig
    while (mFastaFileStream.get(c) && c != '>') {
        if (mFastaFileStream.eof()) {
            break;
        }
    }
}

FastaReader::~FastaReader()
{
    if (mFastaFileStream.is_open()) {
        mFastaFileStream.close();
    }
}

void FastaReader::readNext()
{
    mCurrentID = "";
    mCurrentDescription = "";
    mCurrentSequence = "";
    bool foundHeader = false;

    char c;
    stringstream ssSeq;
    stringstream ssHeader;
    while(true){
        mFastaFileStream.get(c);
        if(c == '>' || mFastaFileStream.eof())
            break;
        else {
            if (foundHeader){
                if(mForceUpperCase && c>='a' && c<='z') {
                    c -= ('a' - 'A');
                }
                ssSeq << c;
            }
            else
                ssHeader << c;
        }

        string line = "";
        getline(mFastaFileStream,line,'\n');

        if(foundHeader == false) {
            ssHeader << line;
            foundHeader = true;
        }
        else {
            str_keep_valid_sequence(line, mForceUpperCase);
            ssSeq << line;
        }
    }
    mCurrentSequence = ssSeq.str();
    string header = ssHeader.str();

    int space = header.find(" ");
    mCurrentID = header.substr(0, space);
}

bool FastaReader::hasNext() {
    return !mFastaFileStream.eof();
}

void FastaReader::readAll() {
    while(!mFastaFileStream.eof()){
        readNext();
        mAllContigs[mCurrentID] = mCurrentSequence;
    }
}

bool FastaReader::test(){
    FastaReader reader("testdata/tinyref.fa");
    reader.readAll();

    string contig1 = "GATCACAGGTCTATCACCCTATTAATTGGTATTTTCGTCTGGGGGGTGTGGAGCCGGAGCACCCTATGTCGCAGT";
    string contig2 = "GTCTGCACAGCCGCTTTCCACACAGAACCCCCCCCTCCCCCCGCTTCTGGCAAACCCCAAAAACAAAGAACCCTA";

    if(reader.mAllContigs.count("contig1") == 0 || reader.mAllContigs.count("contig2") == 0 )
        return false;

    if(reader.mAllContigs["contig1"] != contig1 || reader.mAllContigs["contig2"] != contig2 )
        return false;

    return true;

}

<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////
//
// webcam.cpp --a part of libdecodeqr
//
// Copyright (c) 2006 NISHI Takao <zophos@koka-in.org>
//
// This is free software with ABSOLUTELY NO WARRANTY.
// You can redistribute and/or modify it under the terms of GPLv2.
//
// $Id$
//
#include <stdio.h>
#include <highgui.h>
#include "../../libdecodeqr/decodeqr.h"

int main(int argc,char *argv[])
{
    //
    // start camera
    //
    CvCapture *capture=cvCaptureFromCAM(0);
    if(!capture)
        return(-1);

    //
    // initialize qr decoder
    //
    QrDecoderHandle decoder=qr_decoder_open();
    printf("libdecodeqr version %s\n",qr_decoder_version());

    cvNamedWindow("src",1);
    cvNamedWindow("bin",1);

    puts("Hit [SPACE] key to grab, or any key to end.");
    puts("");

    //
    // 1 shot grabing
    //
    //
    // allocate grabed buffer to decoder
    //
    int key=-1;

    IplImage *src=cvQueryFrame(capture);
    if(src)
        qr_decoder_set_image_buffer(decoder,src);
    else
        key=1;

    unsigned char *text=NULL;
    int text_size=0;

    while(key<=0){
        cvShowImage("src",src);
        key=cvWaitKey(150);

        //
        // when [SPACE] key pressed, do decode.
        //
        if(key==0x20){
            key=-1;

            //
            // if left-bottom origin (MS-Windows style) format,
            // it must be converted to left-top origin.
            //
            if(src->origin)
                cvConvertImage(src,src,CV_CVTIMG_FLIP);

            //
            // While decoding is a failure, decrease the
            // adaptive_th_size parameter.
            // Note that the adaptive_th_size must be odd.
            //
            for(short sz=25,stat=0;
                (sz>=3)&&((stat&QR_IMAGEREADER_DECODED)==0);
                sz-=2)
                stat=qr_decoder_decode(decoder,sz);

            //
            // for debug, show binarized image.
            //
            cvShowImage("bin",
                        qr_decoder_get_binarized_image_buffer(decoder));
            printf("adaptive_th_size=%d, status=%04x\n",sz,stat);

            //
            // on suceed decoding, print decoded text.
            //
            if(stat&=QR_IMAGEREADER_DECODED){
                QrCodeHeader header;
                qr_decoder_get_header(decoder,&header);
                if(text_sz<header.byte_size+1){
                    if(text)
                        delete text;

                    text_sz=header.byte_size+1;
                    text=new unsigned char[text_sz];
                }
                qr_decoder_get_body(decoder,text,text_sz);
                printf("%s\n\n",text);

                key=cvWaitKey(1000);
            }
        }

        src=cvQueryFrame(capture);
        if(!src)
            break;
    }

    if(text)
        delete text;

    qr_decoder_close(decoder);
    cvReleaseCapture(&capture);

    return(0);
}
<commit_msg> * fixed for gcc<commit_after>/////////////////////////////////////////////////////////////////////////
//
// webcam.cpp --a part of libdecodeqr
//
// Copyright (c) 2006 NISHI Takao <zophos@koka-in.org>
//
// This is free software with ABSOLUTELY NO WARRANTY.
// You can redistribute and/or modify it under the terms of GPLv2.
//
// $Id$
//
#include <stdio.h>
#include <highgui.h>
#include "../../libdecodeqr/decodeqr.h"

int main(int argc,char *argv[])
{
    //
    // start camera
    //
    CvCapture *capture=cvCaptureFromCAM(0);
    if(!capture)
        return(-1);

    //
    // initialize qr decoder
    //
    QrDecoderHandle decoder=qr_decoder_open();
    printf("libdecodeqr version %s\n",qr_decoder_version());

    cvNamedWindow("src",1);
    cvNamedWindow("bin",1);

    puts("Hit [SPACE] key to grab, or any key to end.");
    puts("");

    //
    // 1 shot grabing
    //
    //
    // allocate grabed buffer to decoder
    //
    int key=-1;

    IplImage *src=cvQueryFrame(capture);
    if(src)
        qr_decoder_set_image_buffer(decoder,src);
    else
        key=1;

    unsigned char *text=NULL;
    int text_size=0;

    while(key<=0){
        cvShowImage("src",src);
        key=cvWaitKey(150);

        //
        // when [SPACE] key pressed, do decode.
        //
        if(key==0x20){
            key=-1;

            //
            // if left-bottom origin (MS-Windows style) format,
            // it must be converted to left-top origin.
            //
            if(src->origin)
                cvConvertImage(src,src,CV_CVTIMG_FLIP);

            //
            // While decoding is a failure, decrease the
            // adaptive_th_size parameter.
            // Note that the adaptive_th_size must be odd.
            //
            short sz,stat;
            for(sz=25,stat=0;
                (sz>=3)&&((stat&QR_IMAGEREADER_DECODED)==0);
                sz-=2)
                stat=qr_decoder_decode(decoder,sz);

            //
            // for debug, show binarized image.
            //
            cvShowImage("bin",
                        qr_decoder_get_binarized_image_buffer(decoder));
            printf("adaptive_th_size=%d, status=%04x\n",sz,stat);

            //
            // on suceed decoding, print decoded text.
            //
            if(stat&=QR_IMAGEREADER_DECODED){
                QrCodeHeader header;
                qr_decoder_get_header(decoder,&header);
                if(text_sz<header.byte_size+1){
                    if(text)
                        delete text;

                    text_sz=header.byte_size+1;
                    text=new unsigned char[text_sz];
                }
                qr_decoder_get_body(decoder,text,text_sz);
                printf("%s\n\n",text);

                key=cvWaitKey(1000);
            }
        }

        src=cvQueryFrame(capture);
        if(!src)
            break;
    }

    if(text)
        delete text;

    qr_decoder_close(decoder);
    cvReleaseCapture(&capture);

    return(0);
}
<|endoftext|>


<commit_before>#include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <limits>
#include <sstream>
using namespace std;
using namespace GiNaC;

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        cout << "Usage: " << argv[0] << " <graph-series-filename>\n";
        return 1;
    }

    // Reading in graph series:
    string graph_series_filename(argv[1]);
    ifstream graph_series_file(graph_series_filename);
    parser coefficient_reader;
    KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });
    graph_series.reduce();

    for (size_t n = 0; n <= graph_series.precision(); ++n)
    {
        cout << "h^" << n << ":\n";
        for (auto& term : graph_series[n])
        {
            cout << term.second.encoding() << "    " << term.first << "\n";
        }
    }
}
<commit_msg>Add option --print-differential-orders to reduce<commit_after>#include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <limits>
#include <sstream>
using namespace std;
using namespace GiNaC;

int main(int argc, char* argv[])
{
    if (argc != 2 && argc != 3)
    {
        cout << "Usage: " << argv[0] << " <graph-series-filename> [--print-differential-orders]\n";
        return 1;
    }

    bool print_differential_orders = false;
    if (argc == 3 && string(argv[2]) == "--print-differential-orders")
        print_differential_orders = true;

    // Reading in graph series:
    string graph_series_filename(argv[1]);
    ifstream graph_series_file(graph_series_filename);
    parser coefficient_reader;
    KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });
    graph_series.reduce();

    for (size_t n = 0; n <= graph_series.precision(); ++n)
    {
        if (graph_series[n] != 0 || n == graph_series.precision())
            cout << "h^" << n << ":\n";
        for (auto& indegree : graph_series[n].in_degrees(true))
        {
            if (print_differential_orders)
            {
                cout << "# ";
                for (size_t in : indegree)
                    cout << in << " ";
                cout << "\n";
            }
            for (auto& term : graph_series[n][indegree])
            {
                cout << term.second.encoding() << "    " << term.first << "\n";
            }
        }
    }
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////
//
//   ChContactContainerGPU.cpp
//
// ------------------------------------------------
//       Copyright:Alessandro Tasora / DeltaKnowledge
//             www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////

#include "chrono_parallel/collision/ChContactContainerParallel.h"

#include "physics/ChSystem.h"
#include "physics/ChBody.h"
#include "physics/ChParticlesClones.h"
#include "lcp/ChLcpConstraintTwoContactN.h"
#include "collision/ChCModelBulletBody.h"
#include "collision/ChCModelBulletParticle.h"

#include "core/ChMemory.h" // must be last include (memory leak debugger). In .cpp only.

namespace chrono {

using namespace collision;
using namespace geometry;

// Register into the object factory, to enable run-time
// dynamic creation and persistence
ChClassRegister<ChContactContainerParallel> a_registration_ChContactContainerGPU;

ChContactContainerParallel::ChContactContainerParallel(ChParallelDataManager* dc)
: data_container(dc)
{
  n_added = 0;
}

ChContactContainerParallel::~ChContactContainerParallel() {
  n_added = 0;
}

} // END_OF_NAMESPACE____

<commit_msg>Remove unnecessary code.<commit_after>///////////////////////////////////////////////////
//
//   ChContactContainerGPU.cpp
//
// ------------------------------------------------
//       Copyright:Alessandro Tasora / DeltaKnowledge
//             www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////

#include "chrono_parallel/collision/ChContactContainerParallel.h"

#include "physics/ChSystem.h"
#include "physics/ChBody.h"
#include "physics/ChParticlesClones.h"
#include "lcp/ChLcpConstraintTwoContactN.h"
#include "collision/ChCModelBulletBody.h"
#include "collision/ChCModelBulletParticle.h"

#include "core/ChMemory.h" // must be last include (memory leak debugger). In .cpp only.

namespace chrono {

using namespace collision;
using namespace geometry;

ChContactContainerParallel::ChContactContainerParallel(ChParallelDataManager* dc)
: data_container(dc)
{
  n_added = 0;
}

ChContactContainerParallel::~ChContactContainerParallel() {
  n_added = 0;
}

} // END_OF_NAMESPACE____

<|endoftext|>


<commit_before>#include "core_prop/Solver_prop.h"
#include "MinisatCore_prop.h"
#include "utils/System.h"

namespace BEEV
{

  template <class T>
  MinisatCore_prop<T>::MinisatCore_prop(volatile bool& timeout)
  {
     s = new T(timeout);
  };

  template <class T>
  MinisatCore_prop<T>::~MinisatCore_prop()
  {
    delete s;
  }

  template <class T>
  bool
  MinisatCore_prop<T>::addArray(int array_id, const SATSolver::vec_literals& i, const SATSolver::vec_literals& v, const Minisat::vec<Minisat::lbool> & ki, const Minisat::vec<Minisat::lbool> & kv )
  {
	  s->addArray(array_id, i,v, ki,kv);
   return true;
  }

  template <class T>
  bool
  MinisatCore_prop<T>::addClause(const SATSolver::vec_literals& ps) // Add a clause to the solver.
  {
    s->addClause(ps);
  }

  template <class T>
  bool
  MinisatCore_prop<T>::okay() const // FALSE means solver is in a conflicting state
  {
    return s->okay();
  }

  template <class T>
  bool
  MinisatCore_prop<T>::solve() // Search without assumptions.
  {
    if (!s->simplify())
      return false;

    return s->solve();

  }

  template <class T>
  uint8_t
  MinisatCore_prop<T>::modelValue(Var x) const
  {
    return Minisat::toInt(s->modelValue(x));
  }

  template <class T>
  Minisat::Var
  MinisatCore_prop<T>::newVar()
  {
    return s->newVar();
  }

  template <class T>
  void MinisatCore_prop<T>::setVerbosity(int v)
  {
    s->verbosity = v;
  }

  template <class T>
  int MinisatCore_prop<T>::nVars()
  {return s->nVars();}

  template <class T>
  void MinisatCore_prop<T>::printStats()
    {
      s->printStats();
    }

  template <class T>
  void MinisatCore_prop<T>::setSeed(int i)
  {
    s->random_seed = i;
  }

  template class MinisatCore_prop<Minisat::Solver_prop>;
};
<commit_msg>Forgot to pass on return value, fixing<commit_after>#include "core_prop/Solver_prop.h"
#include "MinisatCore_prop.h"
#include "utils/System.h"

namespace BEEV
{

  template <class T>
  MinisatCore_prop<T>::MinisatCore_prop(volatile bool& timeout)
  {
     s = new T(timeout);
  };

  template <class T>
  MinisatCore_prop<T>::~MinisatCore_prop()
  {
    delete s;
  }

  template <class T>
  bool
  MinisatCore_prop<T>::addArray(int array_id, const SATSolver::vec_literals& i, const SATSolver::vec_literals& v, const Minisat::vec<Minisat::lbool> & ki, const Minisat::vec<Minisat::lbool> & kv )
  {
	  s->addArray(array_id, i,v, ki,kv);
   return true;
  }

  template <class T>
  bool
  MinisatCore_prop<T>::addClause(const SATSolver::vec_literals& ps) // Add a clause to the solver.
  {
    return s->addClause(ps);
  }

  template <class T>
  bool
  MinisatCore_prop<T>::okay() const // FALSE means solver is in a conflicting state
  {
    return s->okay();
  }

  template <class T>
  bool
  MinisatCore_prop<T>::solve() // Search without assumptions.
  {
    if (!s->simplify())
      return false;

    return s->solve();

  }

  template <class T>
  uint8_t
  MinisatCore_prop<T>::modelValue(Var x) const
  {
    return Minisat::toInt(s->modelValue(x));
  }

  template <class T>
  Minisat::Var
  MinisatCore_prop<T>::newVar()
  {
    return s->newVar();
  }

  template <class T>
  void MinisatCore_prop<T>::setVerbosity(int v)
  {
    s->verbosity = v;
  }

  template <class T>
  int MinisatCore_prop<T>::nVars()
  {return s->nVars();}

  template <class T>
  void MinisatCore_prop<T>::printStats()
    {
      s->printStats();
    }

  template <class T>
  void MinisatCore_prop<T>::setSeed(int i)
  {
    s->random_seed = i;
  }

  template class MinisatCore_prop<Minisat::Solver_prop>;
};
<|endoftext|>


<commit_before>// run as
// root -l -b -q  lydia2_print_params_observs.C > lydia2_params_observs.txt

using namespace RooFit ;

void lydia2_print_params_observs()
{

        TFile *_file0 = TFile::Open("/user/pbos/lydia/lydia2.root");
        // TFile *_file0 = TFile::Open("/home/patrick/projects/apcocsm/lydia/lydia2.root");
        RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get("combined"));
        RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj("ModelConfig"));
        RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ;

        RooAbsData * data = w->data("combData");

        RooArgSet* params = pdf->getParameters(data);
        RooAbsCollection* const_params = params->selectByAttrib("Constant",kTRUE);
        RooAbsCollection* var_params = params->selectByAttrib("Constant",kFALSE);
        RooArgSet* observs = pdf->getObservables(data);

        // params->Print()
        // params->Print("v")
        const_params->Print();
        var_params->Print();
        observs->Print();

        // const_params->writeToFile("lydia2_const_params.txt")
        // var_params->writeToFile("lydia2_var_params.txt")
        // observs->writeToFile("lydia2_observs.txt")
}<commit_msg>Modified paths for new laptop<commit_after>// run as
// root -l -b -q  lydia2_print_params_observs.C > lydia2_params_observs.txt

using namespace RooFit ;

void lydia2_print_params_observs()
{

        // TFile *_file0 = TFile::Open("/user/pbos/lydia/lydia2.root");
        TFile *_file0 = TFile::Open("/Users/pbos/projects/apcocsm/lydia/lydia2.root");
        RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get("combined"));
        RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj("ModelConfig"));
        RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ;

        RooAbsData * data = w->data("combData");

        RooArgSet* params = pdf->getParameters(data);
        RooAbsCollection* const_params = params->selectByAttrib("Constant",kTRUE);
        RooAbsCollection* var_params = params->selectByAttrib("Constant",kFALSE);
        RooArgSet* observs = pdf->getObservables(data);

        // params->Print()
        // params->Print("v")
        const_params->Print();
        var_params->Print();
        observs->Print();

        // const_params->writeToFile("lydia2_const_params.txt")
        // var_params->writeToFile("lydia2_var_params.txt")
        // observs->writeToFile("lydia2_observs.txt")
}
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

class NumDays {

	const double HOURS_PER_DAY = 8;

private:
	double hours;
	double days;

public:
	NumDays() {

	}
	NumDays(double hours) {
		this->setHours(hours);
	}

	double getHours() {
		return this->hours;
	}

	double getDays() {
		return this->days;
	}

	void setHours(double hours) {
		this->hours = hours;
		this->days = hours / HOURS_PER_DAY;
	}

	NumDays & operator + (const NumDays & x) {
		return NumDays(this->hours + x.hours);
	}

	NumDays & operator - (const NumDays & x) {
		return NumDays(this->hours - x.hours);
	}

	NumDays & operator ++ () {
		return NumDays(this->hours++);
	}

	NumDays & operator -- () {
		return NumDays(this->hours--);
	}
};

int main() {

	double hours1 = 8;
	double hours2 = 12;

	NumDays days1(hours1);
	NumDays days2(hours2);

	cout << days1.getDays() << endl;
	cout << days2.getDays() << endl;

	cout << endl;

	days1++;

	cout << days1.getDays() << endl;

}
<commit_msg>Update Homework-8.cpp<commit_after>#include <iostream>
#include <stdio.h>

using namespace std;

/**
* Class Definition of NumDays
*/
class NumDays {

	const double HOURS_PER_DAY = 8.0;

private:
	int hours = 0;
	double days = 0.0;

public:
	/**
	* Default Constructor
	*/
	NumDays();

	/**
	* Hours initilizing Constructor.
	*
	* @param int hours;
	*/
	NumDays(int hours);

	/**
	* Getter for hours
	*
	* @return int
	*/
	int getHours();

	/**
	* Getter for days
	*
	* @return double
	*/
	double getDays();

	/**
	* Setter for setting hours and recalculating days.
	*
	* @param int hours
	* @return void
	*/
	void setHours(int hours);

	/**
	* Addition Operator Overload
	*
	* @param NumDays& x
	* @return NumDays
	*/
	NumDays operator+(NumDays& x);

	/**
	* Subtraction Operator Overload
	*
	* @param NumDays& x
	* @return NumDays
	*/
	NumDays operator-(NumDays& x);

	/**
	* Storing Operator Overload
	*
	* @param const NumDays&
	* @return void
	*/
	void operator=(const NumDays&);

	/**
	* Prefix increment operator overload.
	*
	* @return NumDays
	*/
	NumDays& operator++();

	/**
	* Postfix increment operator overload.
	*
	* @return NumDays
	*/
	NumDays operator++(int);

	/**
	* Prefix decrement operator overload.
	*
	* @return NumDays
	*/
	NumDays& operator--();

	/**
	* Postfix decrement operator overload.
	*
	* @return NumDays
	*/
	NumDays operator--(int);

	/**
	* Prints the hours and days. "1 days == 8 hours"
	*
	* @return void
	*/
	void printObject() {
		cout << endl << this->getDays() << " days == " << this->getHours() << " hours" << endl << endl;
	}

};

NumDays::NumDays() {}

NumDays::NumDays(int hours) {
	this->setHours(hours);
}

int NumDays::getHours() {
	return this->hours;
}

double NumDays::getDays() {
	return this->days;
}

void NumDays::setHours(int hours) {
	this->hours = hours;
	this->days = hours / NumDays::HOURS_PER_DAY;
}

NumDays NumDays::operator+(NumDays& x) {
	return NumDays(this->hours + x.hours);
}

NumDays NumDays::operator-(NumDays& x) {
	return NumDays(this->hours - x.hours);
}

void NumDays::operator=(const NumDays& x) {
	this->setHours(x.hours);
}

NumDays& NumDays::operator++() {
	this->hours++;
	this->setHours(this->hours);
	return *this;
}

NumDays NumDays::operator++(int) {
	this->setHours(++this->hours);
	return *this;
}

NumDays& NumDays::operator--() {
	this->hours--;
	this->setHours(this->hours);
	return *this;
}

NumDays NumDays::operator--(int) {
	this->setHours(--this->hours);
	return *this;
}

int main() {

	while (true) {
		int hours;

		cout << "Set hours: ";
		cin >> hours;

		NumDays days1(hours);

		days1.printObject();

		while (true) {
			int selection;

			cout << "Select One: " << endl;
			cout << "1. Prefix Increment Object." << endl;
			cout << "2. Postfix increment Object." << endl;
			cout << "3. Prefix Decrement Object." << endl;
			cout << "4. Postfix Decrement Object." << endl;
			cout << "5. Add another object to this one." << endl;
			cout << "6. Subtract another object from this one" << endl;
			cout << "7. Stop" << endl;
			cout << "Select -> ";
			cin >> selection;

			int newHours;
			NumDays newObject;

			switch (selection) {
			case 1:
				++days1;
				break;
			case 2:
				days1++;
				break;
			case 3:
				--days1;
				break;
			case 4:
				days1--;
				break;
			case 5:
				cout << "Set new object's hours: ";
				cin >> newHours;
				newObject.setHours(newHours);
				days1 = days1 + newObject;
				break;
			case 6:
				cout << "Set new object's hours: ";
				cin >> newHours;
				newObject.setHours(newHours);
				days1 = days1 - newObject;
				break;
			case 7:
				goto end;
			}
			days1.printObject();
			continue;

		end:
			break;
		}

		int choice;

		cout << "Would you like to go again?" << endl;
		cout << "1. Yes" << endl;
		cout << "2. No" << endl;
		cin >> choice;

		if (choice == 2) {
			break;
		}
		else if (choice == 1) {
			continue;
		}
	}

}
<|endoftext|>