<commit_before>// Copyright 2015 Vladimir Ivan

/*
 - Designer will publish:
 http://docs.ros.org/indigo/api/trajectory_msgs/html/msg/JointTrajectory.html
 - Designer will receive: (with root link as 0,0,0)
 http://docs.ros.org/indigo/api/sensor_msgs/html/msg/JointState.html
 */
#include <cstdlib>
#include <string>
#include <ros/ros.h>
#include <lcm/lcm-cpp.hpp>

#include "lcmtypes/drc/robot_plan_t.hpp"
#include "lcmtypes/drc/plan_control_t.hpp"
#include "lcmtypes/drc/affordance_collection_t.hpp"
#include "lcmtypes/drc/robot_state_t.hpp"
#include "lcmtypes/drc/exotica_planner_request_t.hpp"
#include <trajectory_msgs/JointTrajectory.h>
#include <ipab_msgs/PlannerRequest.h>
#include <std_srvs/Empty.h>
#include <std_msgs/String.h>

class LCM2ROS
{
public:
  LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_in, ros::NodeHandle &nh_in);
  ~LCM2ROS()
  {
  }

private:
  boost::shared_ptr<lcm::LCM> lcm_;
  ros::NodeHandle nh_;

  ros::Publisher planner_request_pub_;
  ros::Publisher ik_request_pub_;

  void plannerRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
                             const drc::exotica_planner_request_t* msg);
  void ikRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
                        const drc::exotica_planner_request_t* msg);
};

LCM2ROS::LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_in, ros::NodeHandle &nh_in) : lcm_(lcm_in), nh_(nh_in)
{
  lcm_->subscribe("PLANNER_REQUEST", &LCM2ROS::plannerRequestHandler, this);
  planner_request_pub_ = nh_.advertise<ipab_msgs::PlannerRequest>("/exotica/planner_request", 10);

  lcm_->subscribe("IK_REQUEST", &LCM2ROS::ikRequestHandler, this);
  ik_request_pub_ = nh_.advertise<ipab_msgs::PlannerRequest>("/exotica/ik_request", 10);
}

void translatePlannerRequest(const drc::exotica_planner_request_t* msg, ipab_msgs::PlannerRequest& m)
{
  m.header.stamp = ros::Time().fromSec(msg->utime * 1E-6);
  m.poses = msg->poses;
  m.constraints = msg->constraints;
  m.affordances = msg->affordances;
  m.seed_pose = msg->seed_pose;
  m.nominal_pose = msg->nominal_pose;
  m.end_pose = msg->end_pose;
  m.joint_names = msg->joint_names;
  m.options = msg->options;
}

void LCM2ROS::plannerRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
                                    const drc::exotica_planner_request_t* msg)
{
  ROS_ERROR("LCM2ROS got PLANNER_REQUEST");
  ipab_msgs::PlannerRequest m;
  translatePlannerRequest(msg, m);
  planner_request_pub_.publish(m);
}

void LCM2ROS::ikRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
                               const drc::exotica_planner_request_t* msg)
{
  ROS_ERROR("LCM2ROS got IK_REQUEST");
  ipab_msgs::PlannerRequest m;
  translatePlannerRequest(msg, m);
  ik_request_pub_.publish(m);
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "lcm2ros", ros::init_options::NoSigintHandler);
  boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);
  if (!lcm->good())
  {
    std::cerr << "ERROR: lcm is not good()" << std::endl;
  }
  ros::NodeHandle nh;

  LCM2ROS handlerObject(lcm, nh);
  ROS_INFO_STREAM("lcm2ros translator ready");
  ROS_ERROR_STREAM("LCM2ROS Translator Ready");

  while (0 == lcm->handle())
  {
  }

  return 0;
}
<commit_msg>republishes Octree to ROS from LCM (including transform)<commit_after>// Copyright 2015 Vladimir Ivan

/*
 - Designer will publish:
 http://docs.ros.org/indigo/api/trajectory_msgs/html/msg/JointTrajectory.html
 - Designer will receive: (with root link as 0,0,0)
 http://docs.ros.org/indigo/api/sensor_msgs/html/msg/JointState.html
 */
#include <cstdlib>
#include <string>
#include <ros/ros.h>
#include <lcm/lcm-cpp.hpp>

#include "lcmtypes/drc/robot_plan_t.hpp"
#include "lcmtypes/drc/plan_control_t.hpp"
#include "lcmtypes/drc/affordance_collection_t.hpp"
#include "lcmtypes/drc/robot_state_t.hpp"
#include "lcmtypes/drc/exotica_planner_request_t.hpp"
#include "lcmtypes/drc/map_octree_t.hpp"
#include <trajectory_msgs/JointTrajectory.h>
#include <ipab_msgs/PlannerRequest.h>
#include <octomap_msgs/OctomapWithPose.h>
#include <octomap_msgs/Octomap.h>
#include <std_srvs/Empty.h>
#include <std_msgs/String.h>
#include <Eigen/Dense>

class LCM2ROS
{
public:
  LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_in, ros::NodeHandle &nh_in);
  ~LCM2ROS()
  {
  }

private:
  boost::shared_ptr<lcm::LCM> lcm_;
  ros::NodeHandle nh_;

  ros::Publisher planner_request_pub_;
  ros::Publisher ik_request_pub_;
  ros::Publisher octomap_pub_;

  void plannerRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
                             const drc::exotica_planner_request_t* msg);
  void ikRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
                        const drc::exotica_planner_request_t* msg);
  void octreeHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
                        const drc::map_octree_t* msg);
};

LCM2ROS::LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_in, ros::NodeHandle &nh_in) : lcm_(lcm_in), nh_(nh_in)
{
  lcm_->subscribe("PLANNER_REQUEST", &LCM2ROS::plannerRequestHandler, this);
  planner_request_pub_ = nh_.advertise<ipab_msgs::PlannerRequest>("/exotica/planner_request", 10);

  lcm_->subscribe("IK_REQUEST", &LCM2ROS::ikRequestHandler, this);
  ik_request_pub_ = nh_.advertise<ipab_msgs::PlannerRequest>("/exotica/ik_request", 10);

  lcm_->subscribe("MAP_OCTREE", &LCM2ROS::octreeHandler, this);
  octomap_pub_ = nh_.advertise<octomap_msgs::OctomapWithPose>("/octomap_binary_with_pose", 10);
}

void translatePlannerRequest(const drc::exotica_planner_request_t* msg, ipab_msgs::PlannerRequest& m)
{
  m.header.stamp = ros::Time().fromSec(msg->utime * 1E-6);
  m.poses = msg->poses;
  m.constraints = msg->constraints;
  m.affordances = msg->affordances;
  m.seed_pose = msg->seed_pose;
  m.nominal_pose = msg->nominal_pose;
  m.end_pose = msg->end_pose;
  m.joint_names = msg->joint_names;
  m.options = msg->options;
}

void LCM2ROS::plannerRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
                                    const drc::exotica_planner_request_t* msg)
{
  ROS_ERROR("LCM2ROS got PLANNER_REQUEST");
  ipab_msgs::PlannerRequest m;
  translatePlannerRequest(msg, m);
  planner_request_pub_.publish(m);
}

void LCM2ROS::ikRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
                               const drc::exotica_planner_request_t* msg)
{
  ROS_ERROR("LCM2ROS got IK_REQUEST");
  ipab_msgs::PlannerRequest m;
  translatePlannerRequest(msg, m);
  ik_request_pub_.publish(m);
}

void LCM2ROS::octreeHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
                               const drc::map_octree_t* msg)
{
  //ROS_ERROR("LCM2ROS got MAP_OCTREE");

  geometry_msgs::Pose p;
  //Eigen::Affine3f msgTransform;
  Eigen::Projective3f msgTransform;
  for (int i = 0; i < 4; ++i) {
    for (int j = 0; j < 4; ++j) {
      msgTransform(i,j) = msg->transform[i][j];
    }
  }
  Eigen::Vector3f msgTrans(msgTransform.translation());
  Eigen::Quaternionf msgQuat(msgTransform.rotation());
  p.position.x = msgTrans.x();
  p.position.y = msgTrans.y();
  p.position.z = msgTrans.z();
  p.orientation.w = msgQuat.w();
  p.orientation.x = msgQuat.x();
  p.orientation.y = msgQuat.y();
  p.orientation.z = msgQuat.z();

  octomap_msgs::Octomap m;
  m.header.stamp = ros::Time().fromSec(msg->utime * 1E-6);

  // hard coded because the incoming message has no resolution
  // A better solution might be to also check the view_id if there are
  // multiple octrees being published
  m.resolution = 0.01;
  m.binary = true;
  m.id = "workspace_octomap";
  m.data.resize( msg->num_bytes );
  memcpy(&m.data[0], msg->data.data(), msg->num_bytes );

  octomap_msgs::OctomapWithPose o;
  o.origin = p;
  o.octomap = m;
  o.header = m.header;
  octomap_pub_.publish(o);
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "lcm2ros", ros::init_options::NoSigintHandler);
  boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);
  if (!lcm->good())
  {
    std::cerr << "ERROR: lcm is not good()" << std::endl;
  }
  ros::NodeHandle nh;

  LCM2ROS handlerObject(lcm, nh);
  ROS_INFO_STREAM("lcm2ros translator ready");
  ROS_ERROR_STREAM("LCM2ROS Translator Ready");

  while (0 == lcm->handle())
  {
  }

  return 0;
}
<|endoftext|>


<commit_before>//===========================================================================
//  CVS Information:
//
//     $RCSfile: ilu_qmr.cpp,v $  $Revision: 1.3 $  $State: Exp $
//     $Author: llee $  $Date: 2001/10/18 14:08:33 $
//     $Locker:  $
//---------------------------------------------------------------------------
//
// DESCRIPTION
//
//---------------------------------------------------------------------------
//
// LICENSE AGREEMENT
// Copyright 1997, University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee
//
// This file is part of the Iterative Template Library
//
// You should have received a copy of the License Agreement for the
// Iterative Template Library along with the software;  see the
// file LICENSE.  If not, contact Office of Research, University of Notre
// Dame, Notre Dame, IN  46556.
//
// Permission to modify the code and to distribute modified code is
// granted, provided the text of this NOTICE is retained, a notice that
// the code was modified is included with the above COPYRIGHT NOTICE and
// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE
// file is distributed with the modified code.
//
// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
// By way of example, but not limitation, Licensor MAKES NO
// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
// OR OTHER RIGHTS.
//---------------------------------------------------------------------------
//
// REVISION HISTORY:
//
// $Log: ilu_qmr.cpp,v $
// Revision 1.3  2001/10/18 14:08:33  llee
// re-organize the directory structures
//
// Revision 1.2  2000/07/27 04:39:21  llee1
// *** empty log message ***
//
// Revision 1.1  2000/07/26 21:50:09  llee1
// change file extension from .cc to .cpp
//
// Revision 1.1  2000/07/18 16:41:01  llee1
// add Harwell-Boeing matrix test
//
// Revision 1.2  2000/07/17 15:44:04  llee1
// *** empty log message ***
//
// Revision 1.1  1999/11/21 20:47:07  lums
// *** empty log message ***
//
//===========================================================================

#include <desolin/Desolin.hpp>
#include <itl/interface/mtl.h>
#include "itl/preconditioner/ilu.h"
#include "itl/krylov/qmr.h"

/*
  In thsi example, we show how to use QMR algorithm
*/
using namespace itl;

typedef double Type;
typedef desolin::Scalar<Type> Scalar;
typedef desolin::Vector<Type> Vector;
typedef desolin::Matrix<Type> Matrix;

int main(int argc, char* argv[])
{
  using std::cout;
  using std::endl;

  if ( argc == 1 ) {
    cout << "Usage: " << argv[0]
	 << " <Unsymmetric matrix in Harwell-Boeing format> "
	 << endl;
    return 0;
  }

  harwell_boeing_stream<Type> hbs(argv[1]);

  int max_iter = 50;
  //begin
  Matrix A(hbs);
  //end

  //begin
  Vector x(A.nrows(), Type(0));
  Vector b(A.ncols(), Type(1.));

  //Identity preconditioner
  identity_preconditioner precond;
  //iteration
  noisy_iteration<Scalar> iter(b, max_iter, 1e-6);
  //qmr algorithm
  qmr(A, x, b, precond.left(), precond.right(), iter);
  //end

  //verify the result
  Vector b1(A.ncols());
  itl::mult(A, x, b1);
  itl::add(b1, itl::scaled(b, -1.), b1);

  cout << "Residual " << itl::two_norm(b1) << endl;

  return 0;
}

<commit_msg>Removed old identity_qmr.cpp source file.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tp_TitleRotation.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: dr $ $Date: 2004-08-04 14:14:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CHART2_TP_TITLEROTATION_HXX
#define _CHART2_TP_TITLEROTATION_HXX
/*
#include "SchSfxItemIds.hxx"
// header for enum SvxChartKindError
#include "SchAllDefinesFor_svx_chrtitem.hxx"
#ifndef _SVX_CHRTITEM_HXX //autogen
#include <svx/chrtitem.hxx>
#endif
*/
// header for SfxTabPage
#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif
// header for SvxWinOrientation
#ifndef SVX_ORIENTHELPER_HXX //autogen
#include <svx/orienthelper.hxx>
#endif
/*
// header for class ValueSet
#ifndef _VALUESET_HXX
#include <svtools/valueset.hxx>
#endif
*/
// header for FixedLine
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
// header for CheckBox
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
/*
// header for MetricField
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
*/
//.............................................................................
namespace chart
{
//.............................................................................

class SchAlignmentTabPage : public SfxTabPage
{
private:

    //Seit 4/1998 koennen Texte frei gedreht werden: SID_ATTR_ALIGN_DEGREES
#if 0 // DR: TODO new control types
    svx::OrientationHelper  aWinOrient;
#endif

//  CheckBox    aCbxTextOverlap;

//  CheckBox    aCbxTextBreak;
//  FixedLine   aFlTextBreak;

//  RadioButton aRbtSideBySide;
//  RadioButton aRbtUpDown;
//  RadioButton aRbtDownUp;
//  RadioButton aRbtAutoOrder;
//  FixedLine   aFlOrder;
//  OrderMode   eOrderMode;

//  DECL_LINK(CheckButtonHdl, Button*);
//  BOOL bTextCanOverlap;
public:
    SchAlignmentTabPage(Window* pParent, const SfxItemSet& rInAttrs);
    virtual ~SchAlignmentTabPage();

    static SfxTabPage* Create(Window* pParent, const SfxItemSet& rInAttrs);
    virtual BOOL FillItemSet(SfxItemSet& rOutAttrs);
    virtual void Reset(const SfxItemSet& rInAttrs);

//  void SetOrderMode(OrderMode eMode);
//  void SetTextCanOverlap(BOOL b){bTextCanOverlap=b;}
};

//.............................................................................
} //namespace chart
//.............................................................................

#endif
<commit_msg>INTEGRATION: CWS sch03 (1.4.2); FILE MERGED 2004/08/17 09:15:47 dr 1.4.2.1: #i32576# new svx controls added in CWS dr14<commit_after>/*************************************************************************
 *
 *  $RCSfile: tp_TitleRotation.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-20 08:46:55 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CHART2_TP_TITLEROTATION_HXX
#define _CHART2_TP_TITLEROTATION_HXX
/*
#include "SchSfxItemIds.hxx"
// header for enum SvxChartKindError
#include "SchAllDefinesFor_svx_chrtitem.hxx"
#ifndef _SVX_CHRTITEM_HXX //autogen
#include <svx/chrtitem.hxx>
#endif
*/
// header for SfxTabPage
#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif

#ifndef SVX_DIALCONTROL_HXX
#include <svx/dialcontrol.hxx>
#endif
#ifndef SVX_WRAPFIELD_HXX
#include <svx/wrapfield.hxx>
#endif
#ifndef SVX_ORIENTHELPER_HXX
#include <svx/orienthelper.hxx>
#endif

/*
// header for class ValueSet
#ifndef _VALUESET_HXX
#include <svtools/valueset.hxx>
#endif
*/
// header for FixedLine
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
// header for CheckBox
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
/*
// header for MetricField
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
*/
//.............................................................................
namespace chart
{
//.............................................................................

class SchAlignmentTabPage : public SfxTabPage
{
private:

    //Seit 4/1998 koennen Texte frei gedreht werden: SID_ATTR_ALIGN_DEGREES
    FixedLine               aFlAlign;
    svx::DialControl        aCtrlDial;
    FixedText               aFtRotate;
    svx::WrapField          aNfRotate;
    TriStateBox             aCbStacked;
    svx::OrientationHelper  aOrientHlp;

//  CheckBox    aCbxTextOverlap;

//  CheckBox    aCbxTextBreak;
//  FixedLine   aFlTextBreak;

//  RadioButton aRbtSideBySide;
//  RadioButton aRbtUpDown;
//  RadioButton aRbtDownUp;
//  RadioButton aRbtAutoOrder;
//  FixedLine   aFlOrder;
//  OrderMode   eOrderMode;

//  DECL_LINK(CheckButtonHdl, Button*);
//  BOOL bTextCanOverlap;
public:
    SchAlignmentTabPage(Window* pParent, const SfxItemSet& rInAttrs);
    virtual ~SchAlignmentTabPage();

    static SfxTabPage* Create(Window* pParent, const SfxItemSet& rInAttrs);
    virtual BOOL FillItemSet(SfxItemSet& rOutAttrs);
    virtual void Reset(const SfxItemSet& rInAttrs);

//  void SetOrderMode(OrderMode eMode);
//  void SetTextCanOverlap(BOOL b){bTextCanOverlap=b;}
};

//.............................................................................
} //namespace chart
//.............................................................................

#endif
<|endoftext|>


<commit_before><commit_msg>fix windows build break.<commit_after><|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//
//    Copyright (C) Streamlet. All rights reserved.
//
//    File Name:   Main.cpp
//    Author:      Streamlet
//    Create Time: 2010-08-10
//    Description:
//
//    Version history:
//
//
//
//------------------------------------------------------------------------------

#include <xl/Containers/xlList.h>
#include "../UnitTestFrame.h"

using namespace xl;

TEST_CASE(ctor)
{
    List<int> a;
    TEST_ASSERT(a.Size() == 0);
}

TEST_CASE(ctor_copy)
{
    List<int> a;

    a.PushBack(1);
    a.PushBack(2);

    List<int> b(a);

    TEST_ASSERT(b == a);

    List<int>::Iterator it = b.Begin();
    TEST_ASSERT(*it == 1);
    ++it;
    TEST_ASSERT(*it == 2);
}

TEST_CASE(operator_set)
{
    List<int> a;

    a.PushBack(10);
    a.PushBack(9);

    List<int> b;

    b = a;

    TEST_ASSERT(b == a);

    List<int>::Iterator it = b.Begin();
    TEST_ASSERT(*it == 10);
    ++it;
    TEST_ASSERT(*it == 9);
}

TEST_CASE(operator_equal)
{
    List<int> a, b;

    a.PushBack(11);
    a.PushBack(22);

    b = a;
    TEST_ASSERT(b == a);

    ++*b.Begin();
    TEST_ASSERT(b != a);

    --*b.Begin();
    TEST_ASSERT(b == a);

    a.PushBack(100);
    TEST_ASSERT(b != a);

    a.PopBack();
    TEST_ASSERT(b == a);
}

TEST_CASE(method_size)
{
    List<int> a;
    TEST_ASSERT(a.Empty() == true);

    a.PushBack(0);
    TEST_ASSERT(a.Empty() == false);

    a.PopBack();
    TEST_ASSERT(a.Empty() == true);

    a.PushFront(1);
    a.PushFront(0);
    TEST_ASSERT(a.Size() == 2);

    a.Clear();
    TEST_ASSERT(a.Size() == 0);
}

TEST_CASE(method_insert_delete)
{
    List<int> a;
    TEST_ASSERT(a.Empty() == true);

//     int data[4] = { 1, 3, 2, 4 };
//     a.Insert(0, data, 4);
//     TEST_ASSERT(a.Size() == 4);
//     TEST_ASSERT(a[0] == 1);
//     TEST_ASSERT(a[1] == 3);
//     TEST_ASSERT(a[2] == 2);
//     TEST_ASSERT(a[3] == 4);
//
//     a.Insert(2, 10);
//     TEST_ASSERT(a.Size() == 5);
//     TEST_ASSERT(a[0] == 1);
//     TEST_ASSERT(a[1] == 3);
//     TEST_ASSERT(a[2] == 10);
//     TEST_ASSERT(a[3] == 2);
//     TEST_ASSERT(a[4] == 4);
//
//     a.PushBack(15);
//     TEST_ASSERT(a.Size() == 6);
//     TEST_ASSERT(a[0] == 1);
//     TEST_ASSERT(a[1] == 3);
//     TEST_ASSERT(a[2] == 10);
//     TEST_ASSERT(a[3] == 2);
//     TEST_ASSERT(a[4] == 4);
//     TEST_ASSERT(a[5] == 15);
//
//     a.PushFront(20);
//     TEST_ASSERT(a.Size() == 7);
//     TEST_ASSERT(a[0] == 20);
//     TEST_ASSERT(a[1] == 1);
//     TEST_ASSERT(a[2] == 3);
//     TEST_ASSERT(a[3] == 10);
//     TEST_ASSERT(a[4] == 2);
//     TEST_ASSERT(a[5] == 4);
//     TEST_ASSERT(a[6] == 15);
//
//     a.Delete(2, 3);
//     TEST_ASSERT(a.Size() == 4);
//     TEST_ASSERT(a[0] == 20);
//     TEST_ASSERT(a[1] == 1);
//     TEST_ASSERT(a[2] == 4);
//     TEST_ASSERT(a[3] == 15);
//
//     a.Delete(1);
//     TEST_ASSERT(a.Size() == 3);
//     TEST_ASSERT(a[0] == 20);
//     TEST_ASSERT(a[1] == 4);
//     TEST_ASSERT(a[2] == 15);
//
//     a.PopFront();
//     TEST_ASSERT(a.Size() == 2);
//     TEST_ASSERT(a[0] == 4);
//     TEST_ASSERT(a[1] == 15);
//
//     a.PopBack();
//     TEST_ASSERT(a.Size() == 1);
//     TEST_ASSERT(a[0] == 4);
//
//     a.Resize(100);
//     a[99] = 1001;
//     TEST_ASSERT(a.Size() == 100);
//     TEST_ASSERT(a[0] == 4);
//     TEST_ASSERT(a[99] == 1001);

    a.Clear();
    TEST_ASSERT(a.Size() == 0);
}

int main()
{
    return 0;
}
<commit_msg>add unit test and performance test for xl::List<commit_after>//------------------------------------------------------------------------------
//
//    Copyright (C) Streamlet. All rights reserved.
//
//    File Name:   Main.cpp
//    Author:      Streamlet
//    Create Time: 2010-08-10
//    Description:
//
//    Version history:
//
//
//
//------------------------------------------------------------------------------

#include <xl/Containers/xlList.h>
#include "../UnitTestFrame.h"

using namespace xl;

TEST_CASE(ctor)
{
    List<int> a;
    TEST_ASSERT(a.Size() == 0);
}

TEST_CASE(ctor_copy)
{
    List<int> a;

    a.PushBack(1);
    a.PushBack(2);

    List<int> b(a);

    TEST_ASSERT(b == a);

    List<int>::Iterator it = b.Begin();
    TEST_ASSERT(*it == 1);
    ++it;
    TEST_ASSERT(*it == 2);
}

TEST_CASE(operator_set)
{
    List<int> a;

    a.PushBack(10);
    a.PushBack(9);

    List<int> b;

    b = a;

    TEST_ASSERT(b == a);

    List<int>::Iterator it = b.Begin();
    TEST_ASSERT(*it == 10);
    ++it;
    TEST_ASSERT(*it == 9);
}

TEST_CASE(operator_equal)
{
    List<int> a, b;

    a.PushBack(11);
    a.PushBack(22);

    b = a;
    TEST_ASSERT(b == a);

    ++*b.Begin();
    TEST_ASSERT(b != a);

    --*b.Begin();
    TEST_ASSERT(b == a);

    a.PushBack(100);
    TEST_ASSERT(b != a);

    a.PopBack();
    TEST_ASSERT(b == a);
}

TEST_CASE(method_size)
{
    List<int> a;
    TEST_ASSERT(a.Empty() == true);

    a.PushBack(0);
    TEST_ASSERT(a.Empty() == false);

    a.PopBack();
    TEST_ASSERT(a.Empty() == true);

    a.PushFront(1);
    a.PushFront(0);
    TEST_ASSERT(a.Size() == 2);

    a.Clear();
    TEST_ASSERT(a.Size() == 0);
}

TEST_CASE(method_insert_delete)
{
    List<int> a;
    TEST_ASSERT(a.Empty() == true);

    a.Insert(a.Begin(), -1);
    TEST_ASSERT(a.Size() == 1);
    TEST_ASSERT(*a.Begin() == -1);

    a.PushBack(15);
    TEST_ASSERT(a.Size() == 2);
    TEST_ASSERT(*a.ReverseBegin() == 15);

    a.PushFront(20);
    TEST_ASSERT(a.Size() == 3);
    TEST_ASSERT(*a.Begin() == 20);

    a.Delete(a.Begin());
    TEST_ASSERT(a.Size() == 2);
    TEST_ASSERT(*a.Begin() == -1);
    TEST_ASSERT(*(++a.Begin()) == 15);

    a.PopBack();
    TEST_ASSERT(a.Size() == 1);
    TEST_ASSERT(*a.Begin() == -1);

    a.Clear();
    TEST_ASSERT(a.Size() == 0);
    TEST_ASSERT(a.Empty() == true);
}

// Performance Test

#include <stdio.h>
#include <time.h>

#define SECTION_BEGIN(name) \
    printf("Testing \"" #name "\"...\n")
#define SECTION_END()   \
    printf("\n")
#define PERFORMANCE_TEST_BEGIN(name)    \
    printf("Test begins.\n");   \
    clock_t begin_##name = clock()
#define PERFORMANCE_TEST_END(name)  \
    clock_t end_##name = clock();   \
    printf("Test ends. Time elasped: %lfs.\n", (double)(end_##name - begin_##name) / CLK_TCK)

#include <list>
using namespace std;

int main()
{
    SECTION_BEGIN(StdListPushBack100000);
    list<int> l1;
    PERFORMANCE_TEST_BEGIN(StdListPushBack100000);
    for (int i = 0; i < 100000; ++i)
    {
        l1.push_back(i);
    }
    PERFORMANCE_TEST_END(StdListPushBack100000);
    SECTION_END();

    SECTION_BEGIN(xlListPushBack100000);
    List<int> a1;
    PERFORMANCE_TEST_BEGIN(xlListPushBack100000);
    for (int i = 0; i < 100000; ++i)
    {
        a1.PushBack(i);
    }
    PERFORMANCE_TEST_END(xlListPushBack100000);
    SECTION_END();

    SECTION_BEGIN(StdListPushFront100000);
    list<int> l2;
    PERFORMANCE_TEST_BEGIN(StdListPushFront100000);
    for (int i = 0; i < 100000; ++i)
    {
        l2.push_back(i);
    }
    PERFORMANCE_TEST_END(StdListPushFront100000);
    SECTION_END();

    SECTION_BEGIN(xlListPushFront100000);
    List<int> a2;
    PERFORMANCE_TEST_BEGIN(xlListPushFront100000);
    for (int i = 0; i < 100000; ++i)
    {
        a2.PushFront(i);
    }
    PERFORMANCE_TEST_END(xlListPushFront100000);
    SECTION_END();

    SECTION_BEGIN(StdListPushBack1000000);
    list<int> l3;
    PERFORMANCE_TEST_BEGIN(StdListPushBack1000000);
    for (int i = 0; i < 1000000; ++i)
    {
        l3.push_back(i);
    }
    PERFORMANCE_TEST_END(StdListPushBack1000000);
    SECTION_END();

    SECTION_BEGIN(xlListPushBack1000000);
    List<int> a3;
    PERFORMANCE_TEST_BEGIN(xlListPushBack1000000);
    for (int i = 0; i < 1000000; ++i)
    {
        a3.PushBack(i);
    }
    PERFORMANCE_TEST_END(xlListPushBack1000000);
    SECTION_END();

    SECTION_BEGIN(StdListPushFront1000000);
    list<int> l4;
    PERFORMANCE_TEST_BEGIN(StdListPushFront1000000);
    for (int i = 0; i < 1000000; ++i)
    {
        l4.push_back(i);
    }
    PERFORMANCE_TEST_END(StdListPushFront1000000);
    SECTION_END();

    SECTION_BEGIN(xlListPushFront1000000);
    List<int> a4;
    PERFORMANCE_TEST_BEGIN(xlListPushFront1000000);
    for (int i = 0; i < 1000000; ++i)
    {
        a4.PushFront(i);
    }
    PERFORMANCE_TEST_END(xlListPushFront1000000);
    SECTION_END();

    SECTION_BEGIN(StdListPushBack10000000);
    list<int> l5;
    PERFORMANCE_TEST_BEGIN(StdListPushBack10000000);
    for (int i = 0; i < 10000000; ++i)
    {
        l5.push_back(i);
    }
    PERFORMANCE_TEST_END(StdListPushBack10000000);
    SECTION_END();

    SECTION_BEGIN(xlListPushBack10000000);
    List<int> a5;
    PERFORMANCE_TEST_BEGIN(xlListPushBack10000000);
    for (int i = 0; i < 10000000; ++i)
    {
        a5.PushBack(i);
    }
    PERFORMANCE_TEST_END(xlListPushBack10000000);
    SECTION_END();

    SECTION_BEGIN(StdListPushFront10000000);
    list<int> l6;
    PERFORMANCE_TEST_BEGIN(StdListPushFront10000000);
    for (int i = 0; i < 10000000; ++i)
    {
        l6.push_back(i);
    }
    PERFORMANCE_TEST_END(StdListPushFront10000000);
    SECTION_END();

    SECTION_BEGIN(xlListPushFront10000000);
    List<int> a6;
    PERFORMANCE_TEST_BEGIN(xlListPushFront10000000);
    for (int i = 0; i < 10000000; ++i)
    {
        a6.PushFront(i);
    }
    PERFORMANCE_TEST_END(xlListPushFront10000000);
    SECTION_END();

    return 0;
}
<|endoftext|>


<commit_before>#pragma once
#include "stdafx.h"
#include <myo/myo.hpp>

class MyoConnection : public myo::DeviceListener {
public:
	MyoConnection()
		: onArm(false), currentPose()
	{

	}
	// onUnpair() is called whenever the Myo is disconnected from Myo Connect by the user.
	void onUnpair(myo::Myo* myo, uint64_t timestamp)
	{
		onArm = false;
	}
	// onPose() is called whenever the Myo detects that the person wearing it has changed their pose, for example,
	// making a fist, or not making a fist anymore.
	void onPose(myo::Myo* myo, uint64_t timestamp, myo::Pose pose)
	{
		currentPose = pose;

		if (pose != myo::Pose::unknown && pose != myo::Pose::rest) {
			// Tell the Myo to stay unlocked until told otherwise. We do that here so you can hold the poses without the
			// Myo becoming locked.
			//myo->unlock(myo::Myo::unlockHold);

			// Notify the Myo that the pose has resulted in an action, in this case changing
			// the text on the screen. The Myo will vibrate.
			myo->notifyUserAction();
			lastActivePose = currentPose;
		}
		else {
			// Tell the Myo to stay unlocked only for a short period. This allows the Myo to stay unlocked while poses
			// are being performed, but lock after inactivity.
			//myo->unlock(myo::Myo::unlockTimed);
		}
	}
	// onArmSync() is called whenever Myo has recognized a Sync Gesture after someone has put it on their
	// arm. This lets Myo know which arm it's on and which way it's facing.
	void onArmSync(myo::Myo* myo, uint64_t timestamp, myo::Arm arm, myo::XDirection xDirection, float rotation,
		myo::WarmupState warmupState)
	{
		onArm = true;
		whichArm = arm;
	}

	// onArmUnsync() is called whenever Myo has detected that it was moved from a stable position on a person's arm after
	// it recognized the arm. Typically this happens when someone takes Myo off of their arm, but it can also happen
	// when Myo is moved around on the arm.
	void onArmUnsync(myo::Myo* myo, uint64_t timestamp)
	{
		onArm = false;
	}
	// These values are set by onArmSync() and onArmUnsync() above.
	bool onArm;
	myo::Arm whichArm;

	// These values are set  onPose() above.

	myo::Pose currentPose = myo::Pose::rest;
	myo::Pose lastActivePose = myo::Pose::rest;
};
//Casually commenting this out, leaving it here until we can implement.
int main(int argc, char** argv)
{
	// We catch any exceptions that might occur below -- see the catch statement for more details.
	try {

		// First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when
		// publishing your application. The Hub provides access to one or more Myos.
		myo::Hub hub("com.darkworld.darkworld");
		hub.setLockingPolicy(myo::Hub::lockingPolicyNone);

		std::cout << "Attempting to find a Myo..." << std::endl;

		// Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo
		// immediately.
		// waitForMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and
		// if that fails, the function will return a null pointer.
		myo::Myo* myo = hub.waitForMyo(10000);

		// If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message.
		if (!myo) {
			throw std::runtime_error("Unable to find a Myo!");
		}

		// We've found a Myo.
		std::cout << "Connected to a Myo armband!" << std::endl << std::endl;

		// Next we construct an instance of our DeviceListener, so that we can register it with the Hub.
		MyoConnection collector;

		// Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause
		// Hub::run() to send events to all registered device listeners.
		hub.addListener(&collector);

		// Finally we enter our main loop.
		while (1) {
			// In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds.
			// In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds.
			hub.run(1000 / 20);

			if (collector.currentPose != myo::Pose::rest){
				std::cout << collector.lastActivePose << " - " << collector.currentPose << std::endl << std::endl;
			}
		}

		// If a standard exception occurred, we print out its message and exit.
	}
	catch (const std::exception& e) {
		std::cerr << "Error: " << e.what() << std::endl;
		std::cerr << "Press enter to continue.";
		std::cin.ignore();
		return 1;
	}
}
<commit_msg>Fixed bad logic that was bad<commit_after>#pragma once
#include "stdafx.h"
#include <myo/myo.hpp>

class MyoConnection : public myo::DeviceListener {
public:
	MyoConnection()
		: onArm(false), currentPose()
	{

	}
	// onUnpair() is called whenever the Myo is disconnected from Myo Connect by the user.
	void onUnpair(myo::Myo* myo, uint64_t timestamp)
	{
		onArm = false;
	}
	// onPose() is called whenever the Myo detects that the person wearing it has changed their pose, for example,
	// making a fist, or not making a fist anymore.
	void onPose(myo::Myo* myo, uint64_t timestamp, myo::Pose pose)
	{
		currentPose = pose;

		if (pose != myo::Pose::unknown && pose != myo::Pose::rest) {
			// Tell the Myo to stay unlocked until told otherwise. We do that here so you can hold the poses without the
			// Myo becoming locked.
			//myo->unlock(myo::Myo::unlockHold);

			// Notify the Myo that the pose has resulted in an action, in this case changing
			// the text on the screen. The Myo will vibrate.
			myo->notifyUserAction();
			lastActivePose = currentPose;
		}
		else {
			// Tell the Myo to stay unlocked only for a short period. This allows the Myo to stay unlocked while poses
			// are being performed, but lock after inactivity.
			//myo->unlock(myo::Myo::unlockTimed);
		}
	}
	// onArmSync() is called whenever Myo has recognized a Sync Gesture after someone has put it on their
	// arm. This lets Myo know which arm it's on and which way it's facing.
	void onArmSync(myo::Myo* myo, uint64_t timestamp, myo::Arm arm, myo::XDirection xDirection, float rotation,
		myo::WarmupState warmupState)
	{
		onArm = true;
		whichArm = arm;
	}

	// onArmUnsync() is called whenever Myo has detected that it was moved from a stable position on a person's arm after
	// it recognized the arm. Typically this happens when someone takes Myo off of their arm, but it can also happen
	// when Myo is moved around on the arm.
	void onArmUnsync(myo::Myo* myo, uint64_t timestamp)
	{
		onArm = false;
	}
	// These values are set by onArmSync() and onArmUnsync() above.
	bool onArm;
	myo::Arm whichArm;

	// These values are set  onPose() above.

	myo::Pose currentPose = myo::Pose::rest;
	myo::Pose lastActivePose = myo::Pose::rest;
};
//Casually commenting this out, leaving it here until we can implement.
int main(int argc, char** argv)
{
	// We catch any exceptions that might occur below -- see the catch statement for more details.
	try {

		// First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when
		// publishing your application. The Hub provides access to one or more Myos.
		myo::Hub hub("com.darkworld.darkworld");
		hub.setLockingPolicy(myo::Hub::lockingPolicyNone);

		std::cout << "Attempting to find a Myo..." << std::endl;

		// Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo
		// immediately.
		// waitForMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and
		// if that fails, the function will return a null pointer.
		myo::Myo* myo = hub.waitForMyo(10000);

		// If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message.
		if (!myo) {
			throw std::runtime_error("Unable to find a Myo!");
		}

		// We've found a Myo.
		std::cout << "Connected to a Myo armband!" << std::endl << std::endl;

		// Next we construct an instance of our DeviceListener, so that we can register it with the Hub.
		MyoConnection collector;

		// Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause
		// Hub::run() to send events to all registered device listeners.
		hub.addListener(&collector);

		// Finally we enter our main loop.
		while (1) {
			// In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds.
			// In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds.
			hub.run(1000 / 20);

			if (collector.currentPose != myo::Pose::rest && collector.currentPose != myo::Pose::unknown){
				std::cout << collector.lastActivePose << " - " << collector.currentPose << std::endl << std::endl;
			}
		}

		// If a standard exception occurred, we print out its message and exit.
	}
	catch (const std::exception& e) {
		std::cerr << "Error: " << e.what() << std::endl;
		std::cerr << "Press enter to continue.";
		std::cin.ignore();
		return 1;
	}
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <windows.h>
#include <tchar.h>

#define TARGET_WIN_NAME1 _T("VOICEROID{ 䂩 EX")
#define TARGET_WIN_NAME2 _T("VOICEROID{ 䂩 EX*")
#define SAVE_DIALOG_NAME _T("t@C̕ۑ")
#define WAIT_TIME 1500

HWND yukari;
HWND saveDialog;
HWND confirmationOverwriteDialog;

// "VOICEROID{ 䂩 EX" EBhET
BOOL CALLBACK SearchYukari(HWND hwnd, LPARAM lp);

// "t@C̕ۑ" _CAOT
BOOL CALLBACK SearchSaveDialog(HWND hwnd, LPARAM lp);

// ㏑mF_CAO
BOOL CALLBACK SearchConfirmationOverwriteDialog(HWND hwnd, LPARAM lp);

// "eLXgGA" T
HWND CALLBACK SearchTextArea(HWND mainWindow);

// "Đ{^" T
HWND CALLBACK SearchPlayButton(HWND mainWindow);

// "~{^" T
HWND CALLBACK SearchStopButton(HWND mainWindow);

// "ۑ{^" T
HWND CALLBACK SearchSaveButton(HWND mainWindow);

// "t@C:" T
HWND CALLBACK SearchSaveFilePath(HWND savaDialog);

// "ۑ(S)" T
HWND CALLBACK SearchSaveButtonInSaveDialog(HWND savaDialog);

// ㏑mF_CAÓu͂v{^T
HWND CALLBACK SearchYesButtonInConfirmationOverwriteDialog(HWND confirmationOverwriteDialog);

// w肵nh text 𑗐M
void sendText(HWND hwnd, TCHAR* text);

int _tmain(int argc, _TCHAR* argv[])
{
	// "VOICEROID{ 䂩 EX" T
	EnumWindows(SearchYukari, 0x0);

	HWND textArea = SearchTextArea(yukari);

	// ȂŃeLXgGA...
	SendMessage(textArea, WM_SETTEXT, (WPARAM)_T(""), NULL);

	sendText(textArea, _T("}CÑeXgB"));

	// "ۑ{^" Tĉ
	HWND save_button = SearchSaveButton(yukari);
	PostMessage(save_button, BM_CLICK, 0, 0);
	Sleep(WAIT_TIME);

	// "t@C̕ۑ" EBhET
	EnumWindows(SearchSaveDialog, 0x0);

	// t@CeLXgGAT
	HWND saveFilePath = SearchSaveFilePath(saveDialog);

	// t@C
	sendText(saveFilePath, _T("C:\\Users\\mikoto\\Music\\TEST.wav"));

	// "ۑ(S)" {^
	HWND save_button_in_save_dialog = SearchSaveButtonInSaveDialog(saveDialog);
	PostMessage(save_button_in_save_dialog, BM_CLICK, 0, 0);

	Sleep(WAIT_TIME);

	// "VOICEROID{ 䂩 EX" T
	EnumWindows(SearchConfirmationOverwriteDialog, 0x0);
	if (confirmationOverwriteDialog != NULL) {
		HWND yes_button_in_confirmation_overwrite_dialog = SearchYesButtonInConfirmationOverwriteDialog(confirmationOverwriteDialog);
		PostMessage(yes_button_in_confirmation_overwrite_dialog, BM_CLICK, 0, 0);
	}

	exit(0);
}

// "VOICEROID{ 䂩 EX" EBhET
BOOL CALLBACK SearchYukari(HWND hwnd, LPARAM lp) {
	TCHAR strWindowText[1024];
	GetWindowText(hwnd, strWindowText, 1024);

	if (_tcscmp(TARGET_WIN_NAME1, strWindowText) == 0
		    || _tcscmp(TARGET_WIN_NAME2, strWindowText) == 0)
	{
		_tprintf(_T("%s ܂B\n"), strWindowText);
		yukari = hwnd;
		return false;
	}

	return true;
}

// "t@C̕ۑ" _CAOT
BOOL CALLBACK SearchSaveDialog(HWND hwnd, LPARAM lp) {
	TCHAR strWindowText[1024];
	GetWindowText(hwnd, strWindowText, 1024);

	if (_tcscmp(SAVE_DIALOG_NAME, strWindowText) == 0)
	{
		_tprintf(_T("%s ܂B\n"), strWindowText);
		saveDialog = hwnd;
		return false;
	}

	return true;
}

// ㏑mF_CAOT
BOOL CALLBACK SearchConfirmationOverwriteDialog(HWND hwnd, LPARAM lp) {
	TCHAR strWindowText[1024];
	GetWindowText(hwnd, strWindowText, 1024);

	if (_tcscmp(SAVE_DIALOG_NAME, strWindowText) == 0
			&& saveDialog != hwnd)
	{
		_tprintf(_T("%s ܂B\n"), strWindowText);
		confirmationOverwriteDialog = hwnd;
		return false;
	}

	return true;
}

// "eLXgGA" T
HWND CALLBACK SearchTextArea(HWND mainWindow) {
	HWND tmp = GetWindow(mainWindow, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);

	return tmp;
}

// "Đ{^" T
HWND CALLBACK SearchPlayButton(HWND mainWindow) {
	HWND tmp = GetWindow(mainWindow, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);

	return tmp;
}

// "~{^" T
HWND CALLBACK SearchStopButton(HWND mainWindow) {
	HWND tmp = GetWindow(mainWindow, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);

	return tmp;
}

// "ۑ{^" T
HWND CALLBACK SearchSaveButton(HWND mainWindow) {
	HWND tmp = GetWindow(mainWindow, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_HWNDNEXT);

	return tmp;
}

// "t@C:" T
HWND CALLBACK SearchSaveFilePath(HWND savaDialog) {
	HWND tmp = GetWindow(saveDialog, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);

	return tmp;
}

// "ۑ(S){^" T
HWND CALLBACK SearchSaveButtonInSaveDialog(HWND savaDialog) {
	HWND tmp = GetWindow(saveDialog, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_HWNDNEXT);

	return tmp;
}

// ㏑mF_CAÓu͂v{^T
HWND CALLBACK SearchYesButtonInConfirmationOverwriteDialog(HWND confirmationOverwriteDialog) {
	return GetWindow(confirmationOverwriteDialog, GW_CHILD);
}

// w肵nh text 𑗐M
void sendText(HWND hwnd, TCHAR* text) {
	for (int i = 0; i < _tcslen(text); i++) {
		SendMessage(hwnd, WM_CHAR, (WPARAM)text[i], 0);
	}
}

<commit_msg>Added parsing command line arguments logic.<commit_after>#include <atlconv.h>
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <boost/program_options.hpp>

using namespace boost::program_options;

#define TARGET_WIN_NAME1 _T("VOICEROID{ 䂩 EX")
#define TARGET_WIN_NAME2 _T("VOICEROID{ 䂩 EX*")
#define SAVE_DIALOG_NAME _T("t@C̕ۑ")
#define WAIT_TIME 1500

HWND yukari;
HWND saveDialog;
HWND confirmationOverwriteDialog;

// "VOICEROID{ 䂩 EX" EBhET
BOOL CALLBACK SearchYukari(HWND hwnd, LPARAM lp);

// "t@C̕ۑ" _CAOT
BOOL CALLBACK SearchSaveDialog(HWND hwnd, LPARAM lp);

// ㏑mF_CAO
BOOL CALLBACK SearchConfirmationOverwriteDialog(HWND hwnd, LPARAM lp);

// "eLXgGA" T
HWND CALLBACK SearchTextArea(HWND mainWindow);

// "Đ{^" T
HWND CALLBACK SearchPlayButton(HWND mainWindow);

// "~{^" T
HWND CALLBACK SearchStopButton(HWND mainWindow);

// "ۑ{^" T
HWND CALLBACK SearchSaveButton(HWND mainWindow);

// "t@C:" T
HWND CALLBACK SearchSaveFilePath(HWND savaDialog);

// "ۑ(S)" T
HWND CALLBACK SearchSaveButtonInSaveDialog(HWND savaDialog);

// ㏑mF_CAÓu͂v{^T
HWND CALLBACK SearchYesButtonInConfirmationOverwriteDialog(HWND confirmationOverwriteDialog);

// w肵nh text 𑗐M
void sendText(HWND hwnd, TCHAR* text);

int _tmain(int argc, _TCHAR* argv[])
{
	setlocale(LC_CTYPE, "");

	options_description opt("IvV");
	// R}hC`
	opt.add_options()
		("help,h", "wv\")
		("output-file,o", value<std::string>()->default_value(""), "o̓t@CpX")
		("input-file,i", value<std::string>()->default_value(""), "̓t@CpX")
		("sync,s", "[h(ĐEۑ܂őҋ@܂)");

	// R}hC
	variables_map argmap;
	auto pr = parse_command_line(argc, argv, opt);
	store(pr, argmap);
	notify(argmap);

	// ͌ʎ擾
	std::string output_file = argmap["output-file"].as<std::string>();
	std::string input_file = argmap["input-file"].as<std::string>();
	bool is_sync_mode = !argmap["sync"].empty();
	std::wstring echo_text = _T("");

	// IvVȊÕR}hC擾
	for (auto const& str : collect_unrecognized(pr.options, include_positional)) {
		echo_text.append(_T(" "));
		echo_text.append(str);
	}

	// wv\w肪邩A
	// echo_text, input_file Ƃ̏ꍇAwv\ďI
	if (argmap.count("help") ||
		(echo_text.compare(_T("")) == 0
			&& input_file.compare("") == 0)) {
		_TCHAR drive[_MAX_DRIVE];
		_TCHAR dir[_MAX_DIR];
		_TCHAR filename[_MAX_FNAME];
		_TCHAR ext[_MAX_EXT];
		_tsplitpath(argv[0], drive, dir, filename, ext);

		std::wcout << "Usage: " << filename << ext << " [options] [TEXT]" << std::endl;
		std::cout << opt << std::endl;
		return 1;
	}

	// "VOICEROID{ 䂩 EX" T
	EnumWindows(SearchYukari, 0x0);

	HWND textArea = SearchTextArea(yukari);

	// ȂŃeLXgGA...
	SendMessage(textArea, WM_SETTEXT, (WPARAM)_T(""), NULL);

	sendText(textArea, W2T((LPWSTR)echo_text.c_str()));

	// "ۑ{^" Tĉ
	HWND save_button = SearchSaveButton(yukari);
	PostMessage(save_button, BM_CLICK, 0, 0);
	Sleep(WAIT_TIME);

	// "t@C̕ۑ" EBhET
	EnumWindows(SearchSaveDialog, 0x0);

	// t@CeLXgGAT
	HWND saveFilePath = SearchSaveFilePath(saveDialog);

	// t@C
	// t@C wstring ɕϊ
	wchar_t *wcs = new wchar_t[output_file.length() + 1];
	mbstowcs(wcs, output_file.c_str(), output_file.length() + 1);

    // t@CeLXgGAɑ}
	sendText(saveFilePath, W2T((LPWSTR)wcs));
	delete [] wcs;

	// "ۑ(S)" {^
	HWND save_button_in_save_dialog = SearchSaveButtonInSaveDialog(saveDialog);
	PostMessage(save_button_in_save_dialog, BM_CLICK, 0, 0);

	Sleep(WAIT_TIME);

	// "VOICEROID{ 䂩 EX" T
	EnumWindows(SearchConfirmationOverwriteDialog, 0x0);
	if (confirmationOverwriteDialog != NULL) {
		HWND yes_button_in_confirmation_overwrite_dialog = SearchYesButtonInConfirmationOverwriteDialog(confirmationOverwriteDialog);
		PostMessage(yes_button_in_confirmation_overwrite_dialog, BM_CLICK, 0, 0);
	}

	exit(0);
}

// "VOICEROID{ 䂩 EX" EBhET
BOOL CALLBACK SearchYukari(HWND hwnd, LPARAM lp) {
	TCHAR strWindowText[1024];
	GetWindowText(hwnd, strWindowText, 1024);

	if (_tcscmp(TARGET_WIN_NAME1, strWindowText) == 0
		    || _tcscmp(TARGET_WIN_NAME2, strWindowText) == 0)
	{
		_tprintf(_T("%s ܂B\n"), strWindowText);
		yukari = hwnd;
		return false;
	}

	return true;
}

// "t@C̕ۑ" _CAOT
BOOL CALLBACK SearchSaveDialog(HWND hwnd, LPARAM lp) {
	TCHAR strWindowText[1024];
	GetWindowText(hwnd, strWindowText, 1024);

	if (_tcscmp(SAVE_DIALOG_NAME, strWindowText) == 0)
	{
		_tprintf(_T("%s ܂B\n"), strWindowText);
		saveDialog = hwnd;
		return false;
	}

	return true;
}

// ㏑mF_CAOT
BOOL CALLBACK SearchConfirmationOverwriteDialog(HWND hwnd, LPARAM lp) {
	TCHAR strWindowText[1024];
	GetWindowText(hwnd, strWindowText, 1024);

	if (_tcscmp(SAVE_DIALOG_NAME, strWindowText) == 0
			&& saveDialog != hwnd)
	{
		_tprintf(_T("%s ܂B\n"), strWindowText);
		confirmationOverwriteDialog = hwnd;
		return false;
	}

	return true;
}

// "eLXgGA" T
HWND CALLBACK SearchTextArea(HWND mainWindow) {
	HWND tmp = GetWindow(mainWindow, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);

	return tmp;
}

// "Đ{^" T
HWND CALLBACK SearchPlayButton(HWND mainWindow) {
	HWND tmp = GetWindow(mainWindow, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);

	return tmp;
}

// "~{^" T
HWND CALLBACK SearchStopButton(HWND mainWindow) {
	HWND tmp = GetWindow(mainWindow, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);

	return tmp;
}

// "ۑ{^" T
HWND CALLBACK SearchSaveButton(HWND mainWindow) {
	HWND tmp = GetWindow(mainWindow, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_HWNDNEXT);

	return tmp;
}

// "t@C:" T
HWND CALLBACK SearchSaveFilePath(HWND savaDialog) {
	HWND tmp = GetWindow(saveDialog, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);
	tmp = GetWindow(tmp, GW_CHILD);

	return tmp;
}

// "ۑ(S){^" T
HWND CALLBACK SearchSaveButtonInSaveDialog(HWND savaDialog) {
	HWND tmp = GetWindow(saveDialog, GW_CHILD);
	tmp = GetWindow(tmp, GW_HWNDNEXT);
	tmp = GetWindow(tmp, GW_HWNDNEXT);

	return tmp;
}

// ㏑mF_CAÓu͂v{^T
HWND CALLBACK SearchYesButtonInConfirmationOverwriteDialog(HWND confirmationOverwriteDialog) {
	return GetWindow(confirmationOverwriteDialog, GW_CHILD);
}

// w肵nh text 𑗐M
void sendText(HWND hwnd, TCHAR* text) {
	for (int i = 0; i < _tcslen(text); i++) {
		SendMessage(hwnd, WM_CHAR, (WPARAM)text[i], 0);
	}
}

<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2004 by Stanislav Karchebny                             *
 *   Stanislav.Karchebny@kdemail.net                                       *
 *                                                                         *
 *   Licensed under GPL.                                                   *
 ***************************************************************************/

#include "app.h"
#include "akregator.h"
#include "trayicon.h"
#include "akregatorconfig.h"

//settings
#include "settings_general.h"
#include "settings_browser.h"

#include <dcopclient.h>
#include <dcopobject.h>
#include <dcopref.h>

#include <ksqueezedtextlabel.h>
#include <kkeydialog.h>
#include <kfiledialog.h>
#include <kprogress.h>
#include <kconfig.h>
#include <kurl.h>
#include <kconfigdialog.h>

#include <kedittoolbar.h>

#include <kaction.h>
#include <kstdaction.h>

#include <klibloader.h>
#include <kmessagebox.h>
#include <kstatusbar.h>
#include <klocale.h>
#include <kdebug.h>

using namespace Akregator;

BrowserInterface::BrowserInterface( aKregator *shell, const char *name )
    : KParts::BrowserInterface( shell, name )
{
    m_shell = shell;
}

void BrowserInterface::updateUnread(int unread)
{
    m_shell->updateUnread(unread);
}

bool BrowserInterface::haveWindowLoaded() const
{
    return akreapp->haveWindowLoaded();
}

aKregator::aKregator()
    : KParts::MainWindow( 0L, "aKregator" )
    , m_quit(false)
{
    // set the shell's ui resource file
    setXMLFile("akregator_shell.rc");

    m_browserIface=new BrowserInterface(this, "browser_interface");
    m_activePart=0;

    // then, setup our actions
    setupActions();

    m_icon = new TrayIcon(this);
    m_icon->show();
    connect(m_icon, SIGNAL(quitSelected()),
            this, SLOT(quitProgram()));

    // and a status bar
    statusBar()->show();

    int statH=fontMetrics().height()+2;
    m_statusLabel = new KSqueezedTextLabel(this);
    m_statusLabel->setTextFormat(Qt::RichText);
    m_statusLabel->setSizePolicy(QSizePolicy( QSizePolicy::Ignored, QSizePolicy::Fixed ));
    m_statusLabel->setMinimumWidth( 0 );
    m_statusLabel->setFixedHeight( statH );
    statusBar()->addWidget (m_statusLabel, 1, false);

    m_progressBar = new KProgress( this );
    // blame the following on KMLittleProgress
    m_progressBar->setMaximumWidth(fontMetrics().width( " 999.9 kB/s 00:00:01 " ) + 14);
    m_progressBar->setFixedHeight(statH);
    m_progressBar->hide();
    statusBar()->addWidget( m_progressBar, 0, true);

    // apply the saved mainwindow settings, if any, and ask the mainwindow
    // to automatically save settings if changed: window size, toolbar
    // position, icon size, etc.
    setAutoSaveSettings();
}

bool aKregator::loadPart()
{
    // this routine will find and load our Part.  it finds the Part by
    // name which is a bad idea usually.. but it's alright in this
    // case since our Part is made for this Shell
    KLibFactory *factory = KLibLoader::self()->factory("libakregatorpart");
    if (factory)
    {
        // now that the Part is loaded, we cast it to a Part to get
        // our hands on it
        m_part = static_cast<KParts::ReadWritePart*>(factory->create(this, "akregator_part", "KParts::ReadWritePart" ));

        if (m_part)
        {
            // tell the KParts::MainWindow that this is indeed the main widget
            setCentralWidget(m_part->widget());

            connect (m_part, SIGNAL(partChanged(KParts::ReadOnlyPart *)), this, SLOT(partChanged(KParts::ReadOnlyPart *)));
            connect( browserExtension(m_part), SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)) );
            m_activePart=m_part;
            // and integrate the part's GUI with the shell's
            createGUI(m_part);
            browserExtension(m_part)->setBrowserInterface(m_browserIface);
        }
        return true;
    }
    else
    {
        KMessageBox::error(this, i18n("Could not find our part. Please check your installation."));
        return false;
    }

}

void aKregator::loadLastOpenFile()
{
   load( Settings::lastOpenFile() );
}

aKregator::~aKregator()
{
   Settings::setLastOpenFile( m_part->url().url() );
   Settings::writeConfig();
}

void aKregator::partChanged(KParts::ReadOnlyPart *p)
{
    KParts::BrowserExtension *ext;
    loadingProgress(-1);
    if (m_activePart)
    {
        ext=browserExtension(m_activePart);
        if (ext)
            disconnect( ext, SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)) );
    }
    ext=browserExtension(p);
    if (ext)
        connect( ext, SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)) );
    m_activePart=p;
    createGUI(p);
}

void aKregator::load(const KURL& url)
{
    m_part->openURL( url );
}

void aKregator::setupActions()
{
    KStdAction::openNew(this, SLOT(fileNew()), actionCollection());
//    KStdAction::open(this, SLOT(fileOpen()), actionCollection());

    KStdAction::quit(this, SLOT(quitProgram()), actionCollection());

    m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection());
    m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection());

    KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());
    KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());
    KStdAction::preferences(this, SLOT(showOptions()), actionCollection());
}

void aKregator::saveProperties(KConfig* /*config*/)
{
    // the 'config' object points to the session managed
    // config file.  anything you write here will be available
    // later when this app is restored
}

void aKregator::readProperties(KConfig* /*config*/)
{
    // the 'config' object points to the session managed
    // config file.  this function is automatically called whenever
    // the app is being restored.  read in here whatever you wrote
    // in 'saveProperties'
}

void aKregator::fileNew()
{
    // this slot is called whenever the File->New menu is selected,
    // the New shortcut is pressed (usually CTRL+N) or the New toolbar
    // button is clicked

    // About this function, the style guide (
    // http://developer.kde.org/documentation/standards/kde/style/basics/index.html )
    // says that it should open a new window if the document is _not_
    // in its initial state.  This is what we do here..
    if ( ! m_part->url().isEmpty() || m_part->isModified() )
    {
        DCOPRef partref(akreapp->dcopClient()->appId(), QString("aKregatorPart#%1").arg((uint)this).latin1());
        partref.call("saveSettings");
        (new aKregator)->show();
    };
}

void aKregator::optionsShowToolbar()
{
    // this is all very cut and paste code for showing/hiding the
    // toolbar
    if (m_toolbarAction->isChecked())
        toolBar()->show();
    else
        toolBar()->hide();
}

void aKregator::optionsShowStatusbar()
{
    // this is all very cut and paste code for showing/hiding the
    // statusbar
    if (m_statusbarAction->isChecked())
        statusBar()->show();
    else
        statusBar()->hide();
}

void aKregator::optionsConfigureKeys()
{
    KKeyDialog dlg( true, this );

    dlg.insert(actionCollection());
    if (m_part)
        dlg.insert(m_part->actionCollection());

    dlg.configure();
}

void aKregator::optionsConfigureToolbars()
{
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
    saveMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
    saveMainWindowSettings(KGlobal::config() );
# endif
#else
    saveMainWindowSettings(KGlobal::config() );
#endif

    // use the standard toolbar editor
    KEditToolbar dlg(factory());
    connect(&dlg, SIGNAL(newToolbarConfig()),
            this, SLOT(applyNewToolbarConfig()));
    dlg.exec();
}

void aKregator::showOptions()
{
    if ( KConfigDialog::showDialog( "settings" ) )
        return;

    KConfigDialog *dialog = new KConfigDialog( this, "settings", Settings::self() );
    dialog->addPage(new settings_general(0, "General"), i18n("General"), "package_settings");
    dialog->addPage(new settings_browser(0, "Browser"), i18n("Browser"), "browser");

    connect( dialog, SIGNAL(settingsChanged()),
             m_part, SLOT(saveSettings()) );

    dialog->show();
}

void aKregator::applyNewToolbarConfig()
{
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
    applyMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
    applyMainWindowSettings(KGlobal::config());
# endif
#else
    applyMainWindowSettings(KGlobal::config());
#endif
}

void aKregator::fileOpen()
{
    // this slot is called whenever the File->Open menu is selected,
    // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar
    // button is clicked
    KURL url =
        KFileDialog::getOpenURL( QString::null, QString::null, this );

    if (url.isEmpty() == false)
    {
        // About this function, the style guide (
        // http://developer.kde.org/documentation/standards/kde/style/basics/index.html )
        // says that it should open a new window if the document is _not_
        // in its initial state.  This is what we do here..
        if ( m_part->url().isEmpty() && ! m_part->isModified() )
        {
            // we open the file in this window...
            load( url );
        }
        else
        {
            // we open the file in a new window...
            aKregator* newWin = new aKregator;
            newWin->load( url );
            newWin->show();
        }
    }
}

KParts::BrowserExtension *aKregator::browserExtension(KParts::ReadOnlyPart *p)
{
    return KParts::BrowserExtension::childObject( p );
}

void aKregator::quitProgram()
{
    // will call queryClose()
    m_quit = true;
    if( Settings::markAllReadOnExit() )
    {
        kdDebug() << "marking all as read.." << endl;
        emit markAllRead();
    }
    close();
}

// from KonqFrameStatusBar
void aKregator::fontChange(const QFont & /* oldFont */)
{
    int h = fontMetrics().height();
    if ( h < 13 ) h = 13;
    m_progressBar->setFixedHeight( h + 2 );

}

void aKregator::updateUnread(int unread)
{
    m_icon->updateUnread(unread);
}

void aKregator::loadingProgress(int percent)
{
    if ( percent > -1 && percent < 100 )
    {
        if ( !m_progressBar->isVisible() )
            m_progressBar->show();
    }
    else
        m_progressBar->hide();

    m_progressBar->setValue( percent );
}

void aKregator::slotSetStatusBarText(const QString & s)
{
    m_statusLabel->setText(s);
}

void aKregator::closeEvent(QCloseEvent* e)
{
    if (!m_quit && !kapp->sessionSaving())
    {
        KMessageBox::information(this, i18n( "<qt>Closing the main window will keep aKregator running in the system tray. Use 'Quit' from the 'File' menu to quit the application.</qt>" ), i18n( "Docking in System Tray" ), "hideOnCloseInfo");
        hide();
        e->ignore();
    }
    else
    {
        if (m_part->queryClose())
            KMainWindow::closeEvent(e);
    }
    m_quit = false;
}

#include "akregator.moc"
<commit_msg>Fix for crash when quitting from system tray icon.  Someone please check this.<commit_after>/***************************************************************************
 *   Copyright (C) 2004 by Stanislav Karchebny                             *
 *   Stanislav.Karchebny@kdemail.net                                       *
 *                                                                         *
 *   Licensed under GPL.                                                   *
 ***************************************************************************/

#include "app.h"
#include "akregator.h"
#include "trayicon.h"
#include "akregatorconfig.h"

//settings
#include "settings_general.h"
#include "settings_browser.h"

#include <dcopclient.h>
#include <dcopobject.h>
#include <dcopref.h>

#include <ksqueezedtextlabel.h>
#include <kkeydialog.h>
#include <kfiledialog.h>
#include <kprogress.h>
#include <kconfig.h>
#include <kurl.h>
#include <kconfigdialog.h>

#include <kedittoolbar.h>

#include <kaction.h>
#include <kstdaction.h>

#include <klibloader.h>
#include <kmessagebox.h>
#include <kstatusbar.h>
#include <klocale.h>
#include <kdebug.h>

using namespace Akregator;

BrowserInterface::BrowserInterface( aKregator *shell, const char *name )
    : KParts::BrowserInterface( shell, name )
{
    m_shell = shell;
}

void BrowserInterface::updateUnread(int unread)
{
    m_shell->updateUnread(unread);
}

bool BrowserInterface::haveWindowLoaded() const
{
    return akreapp->haveWindowLoaded();
}

aKregator::aKregator()
    : KParts::MainWindow( 0L, "aKregator" )
    , m_quit(false)
{
    // set the shell's ui resource file
    setXMLFile("akregator_shell.rc");

    m_browserIface=new BrowserInterface(this, "browser_interface");
    m_activePart=0;

    // then, setup our actions
    setupActions();

    m_icon = new TrayIcon(this);
    m_icon->show();
    connect(m_icon, SIGNAL(quitSelected()),
            this, SLOT(quitProgram()));

    // and a status bar
    statusBar()->show();

    int statH=fontMetrics().height()+2;
    m_statusLabel = new KSqueezedTextLabel(this);
    m_statusLabel->setTextFormat(Qt::RichText);
    m_statusLabel->setSizePolicy(QSizePolicy( QSizePolicy::Ignored, QSizePolicy::Fixed ));
    m_statusLabel->setMinimumWidth( 0 );
    m_statusLabel->setFixedHeight( statH );
    statusBar()->addWidget (m_statusLabel, 1, false);

    m_progressBar = new KProgress( this );
    // blame the following on KMLittleProgress
    m_progressBar->setMaximumWidth(fontMetrics().width( " 999.9 kB/s 00:00:01 " ) + 14);
    m_progressBar->setFixedHeight(statH);
    m_progressBar->hide();
    statusBar()->addWidget( m_progressBar, 0, true);

    // apply the saved mainwindow settings, if any, and ask the mainwindow
    // to automatically save settings if changed: window size, toolbar
    // position, icon size, etc.
    setAutoSaveSettings();
}

bool aKregator::loadPart()
{
    // this routine will find and load our Part.  it finds the Part by
    // name which is a bad idea usually.. but it's alright in this
    // case since our Part is made for this Shell
    KLibFactory *factory = KLibLoader::self()->factory("libakregatorpart");
    if (factory)
    {
        // now that the Part is loaded, we cast it to a Part to get
        // our hands on it
        m_part = static_cast<KParts::ReadWritePart*>(factory->create(this, "akregator_part", "KParts::ReadWritePart" ));

        if (m_part)
        {
            // tell the KParts::MainWindow that this is indeed the main widget
            setCentralWidget(m_part->widget());

            connect (m_part, SIGNAL(partChanged(KParts::ReadOnlyPart *)), this, SLOT(partChanged(KParts::ReadOnlyPart *)));
            connect( browserExtension(m_part), SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)) );
            m_activePart=m_part;
            // and integrate the part's GUI with the shell's
            createGUI(m_part);
            browserExtension(m_part)->setBrowserInterface(m_browserIface);
        }
        return true;
    }
    else
    {
        KMessageBox::error(this, i18n("Could not find our part. Please check your installation."));
        return false;
    }

}

void aKregator::loadLastOpenFile()
{
   load( Settings::lastOpenFile() );
}

aKregator::~aKregator()
{
   Settings::setLastOpenFile( m_part->url().url() );
   Settings::writeConfig();
}

void aKregator::partChanged(KParts::ReadOnlyPart *p)
{
    KParts::BrowserExtension *ext;
    loadingProgress(-1);
    if (m_activePart)
    {
        ext=browserExtension(m_activePart);
        if (ext)
            disconnect( ext, SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)) );
    }
    ext=browserExtension(p);
    if (ext)
        connect( ext, SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)) );
    m_activePart=p;
    createGUI(p);
}

void aKregator::load(const KURL& url)
{
    m_part->openURL( url );
}

void aKregator::setupActions()
{
    KStdAction::openNew(this, SLOT(fileNew()), actionCollection());
//    KStdAction::open(this, SLOT(fileOpen()), actionCollection());

    KStdAction::quit(this, SLOT(quitProgram()), actionCollection());

    m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection());
    m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection());

    KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());
    KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());
    KStdAction::preferences(this, SLOT(showOptions()), actionCollection());
}

void aKregator::saveProperties(KConfig* /*config*/)
{
    // the 'config' object points to the session managed
    // config file.  anything you write here will be available
    // later when this app is restored
}

void aKregator::readProperties(KConfig* /*config*/)
{
    // the 'config' object points to the session managed
    // config file.  this function is automatically called whenever
    // the app is being restored.  read in here whatever you wrote
    // in 'saveProperties'
}

void aKregator::fileNew()
{
    // this slot is called whenever the File->New menu is selected,
    // the New shortcut is pressed (usually CTRL+N) or the New toolbar
    // button is clicked

    // About this function, the style guide (
    // http://developer.kde.org/documentation/standards/kde/style/basics/index.html )
    // says that it should open a new window if the document is _not_
    // in its initial state.  This is what we do here..
    if ( ! m_part->url().isEmpty() || m_part->isModified() )
    {
        DCOPRef partref(akreapp->dcopClient()->appId(), QString("aKregatorPart#%1").arg((uint)this).latin1());
        partref.call("saveSettings");
        (new aKregator)->show();
    };
}

void aKregator::optionsShowToolbar()
{
    // this is all very cut and paste code for showing/hiding the
    // toolbar
    if (m_toolbarAction->isChecked())
        toolBar()->show();
    else
        toolBar()->hide();
}

void aKregator::optionsShowStatusbar()
{
    // this is all very cut and paste code for showing/hiding the
    // statusbar
    if (m_statusbarAction->isChecked())
        statusBar()->show();
    else
        statusBar()->hide();
}

void aKregator::optionsConfigureKeys()
{
    KKeyDialog dlg( true, this );

    dlg.insert(actionCollection());
    if (m_part)
        dlg.insert(m_part->actionCollection());

    dlg.configure();
}

void aKregator::optionsConfigureToolbars()
{
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
    saveMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
    saveMainWindowSettings(KGlobal::config() );
# endif
#else
    saveMainWindowSettings(KGlobal::config() );
#endif

    // use the standard toolbar editor
    KEditToolbar dlg(factory());
    connect(&dlg, SIGNAL(newToolbarConfig()),
            this, SLOT(applyNewToolbarConfig()));
    dlg.exec();
}

void aKregator::showOptions()
{
    if ( KConfigDialog::showDialog( "settings" ) )
        return;

    KConfigDialog *dialog = new KConfigDialog( this, "settings", Settings::self() );
    dialog->addPage(new settings_general(0, "General"), i18n("General"), "package_settings");
    dialog->addPage(new settings_browser(0, "Browser"), i18n("Browser"), "browser");

    connect( dialog, SIGNAL(settingsChanged()),
             m_part, SLOT(saveSettings()) );

    dialog->show();
}

void aKregator::applyNewToolbarConfig()
{
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
    applyMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
    applyMainWindowSettings(KGlobal::config());
# endif
#else
    applyMainWindowSettings(KGlobal::config());
#endif
}

void aKregator::fileOpen()
{
    // this slot is called whenever the File->Open menu is selected,
    // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar
    // button is clicked
    KURL url =
        KFileDialog::getOpenURL( QString::null, QString::null, this );

    if (url.isEmpty() == false)
    {
        // About this function, the style guide (
        // http://developer.kde.org/documentation/standards/kde/style/basics/index.html )
        // says that it should open a new window if the document is _not_
        // in its initial state.  This is what we do here..
        if ( m_part->url().isEmpty() && ! m_part->isModified() )
        {
            // we open the file in this window...
            load( url );
        }
        else
        {
            // we open the file in a new window...
            aKregator* newWin = new aKregator;
            newWin->load( url );
            newWin->show();
        }
    }
}

KParts::BrowserExtension *aKregator::browserExtension(KParts::ReadOnlyPart *p)
{
    return KParts::BrowserExtension::childObject( p );
}

void aKregator::quitProgram()
{
    // will call queryClose()
    m_quit = true;
    if( Settings::markAllReadOnExit() )
    {
        kdDebug() << "marking all as read.." << endl;
        emit markAllRead();
    }
    close();
}

// from KonqFrameStatusBar
void aKregator::fontChange(const QFont & /* oldFont */)
{
    int h = fontMetrics().height();
    if ( h < 13 ) h = 13;
    m_progressBar->setFixedHeight( h + 2 );

}

void aKregator::updateUnread(int unread)
{
    m_icon->updateUnread(unread);
}

void aKregator::loadingProgress(int percent)
{
    if ( percent > -1 && percent < 100 )
    {
        if ( !m_progressBar->isVisible() )
            m_progressBar->show();
    }
    else
        m_progressBar->hide();

    m_progressBar->setValue( percent );
}

void aKregator::slotSetStatusBarText(const QString & s)
{
    m_statusLabel->setText(s);
}

void aKregator::closeEvent(QCloseEvent* e)
{
    if (!m_quit && !kapp->sessionSaving())
    {
        kdDebug() << "aKregator::closeEvent m_quit is false" << endl;
        KMessageBox::information(this, i18n( "<qt>Closing the main window will keep aKregator running in the system tray. Use 'Quit' from the 'File' menu to quit the application.</qt>" ), i18n( "Docking in System Tray" ), "hideOnCloseInfo");
        hide();
        e->ignore();
    }
    else
    {
        kdDebug() << "aKregator::closeEvent m_quit is true" << endl;
        if (m_part->queryClose())
            KMainWindow::closeEvent(e);
    }
    // Commenting this out fixes crash when quitting from system tray icon.  Why was it here? ..cramblitt
    // m_quit = false;
}

#include "akregator.moc"
<|endoftext|>


<commit_before>/*
 * ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have purchased from
 * Numenta, Inc. a separate commercial license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
 * Implementation for SparsePooler
 */

#include <nta/algorithms/SparsePooler.hpp>

using namespace std;

namespace nta {

  //--------------------------------------------------------------------------------
  const std::string SparsePooler::current_sparse_pooler_version_ = "SparsePooler_1.7";

  //--------------------------------------------------------------------------------
  // SPARSE POOLER INPUT MASKS
  //--------------------------------------------------------------------------------
  SparsePoolerInputMasks::SparsePoolerInputMasks()
    : segment_size_(0), min_size_(0), max_size_(0),
      sizes_(), masks_()
  {}

  //--------------------------------------------------------------------------------
  SparsePoolerInputMasks::SparsePoolerInputMasks(size_type ss,
						 const std::vector<Mask>& masks)
    : segment_size_(ss), min_size_(0), max_size_(0),
      sizes_(), masks_(masks)
  {
    compute_cache_();
  }

  //--------------------------------------------------------------------------------
  SparsePoolerInputMasks::SparsePoolerInputMasks(std::istream& inStream)
    : segment_size_(0), min_size_(0), max_size_(0),
      sizes_(), masks_()
  {
    readState(inStream);
  }

  //--------------------------------------------------------------------------------
  SparsePoolerInputMasks&
  SparsePoolerInputMasks::operator=(const SparsePoolerInputMasks& other)
  {
    if (&other != this) {
      segment_size_ = other.segment_size_;
      min_size_ = other.min_size_;
      max_size_ = other.max_size_;
      sizes_ = other.sizes_;
      masks_ = other.masks_;
    }
    return *this;
  }

  //--------------------------------------------------------------------------------
  void SparsePoolerInputMasks::saveState(std::ostream& outStream) const
  {
    outStream << segmentSize() << " " << masks_ << " ";
  }

  //--------------------------------------------------------------------------------
  void SparsePoolerInputMasks::readState(std::istream& inStream)
  {
    inStream >> segment_size_ >> general_vector >> masks_;
    compute_cache_();
  }

  //--------------------------------------------------------------------------------
  void SparsePoolerInputMasks::compute_cache_()
  {
    { // Pre-conditions
      NTA_CHECK(segment_size_ > 0)
	<< "SparsePoolerInputMasks: Invalid segment size: " << segment_size_
	<< " - Should be > 0";

      NTA_CHECK(masks_.size() > 0)
	<< "SparsePoolerInputMasks: No masks passed";

      for (size_type i = 0; i != masks_.size(); ++i) {

	NTA_CHECK(masks_[i].size() > 0)
	  << "SparsePoolerInputMasks: Empty mask";

	for (size_type j = 0; j != masks_[i].size(); ++j)
	  NTA_CHECK(masks_[i][j].second > 0)
	    << "SparsePoolerInputMasks: Empty mask segment";
      }
    } // End pre-conditions

    min_size_ = std::numeric_limits<size_type>::max();
    max_size_ = 0;
    sizes_.resize(masks_.size(), 0);

    for (size_type i = 0; i != masks_.size(); ++i) {
      size_type a_size = 0;
      for (size_type j = 0; j != masks_[i].size(); ++j)
	a_size += masks_[i][j].second;
      sizes_[i] = a_size;
      if (a_size < min_size_)
	min_size_ = a_size;
      if (a_size > max_size_)
	max_size_ = a_size;
    }
  }

  //--------------------------------------------------------------------------------
  std::ostream& operator<<(std::ostream& outStream, const SparsePoolerInputMasks& masks)
  {
    masks.saveState(outStream);
    return outStream;
  }

  //--------------------------------------------------------------------------------
  std::istream& operator>>(std::istream& inStream, SparsePoolerInputMasks& masks)
  {
    masks.readState(inStream);
    return inStream;
  }

  //--------------------------------------------------------------------------------
  // SPARSE POOLER
  //--------------------------------------------------------------------------------
  SparsePooler::SparsePooler()
    : normalize_(false),
      lp_(0),
      sparsification_mode_(none),
      k_winners_(0),
      threshold_(0),
      min_accept_distance_(0),
      min_accept_norm_(0),
      min_proto_sum_(1),
      inference_mode_(product),
      sigma_(0),
      input_masks_(),
      p_(0),
      buf_(),
      prototypes_(),
      rng_(0),
      cachedCM_()
  {}

  //------------------------------------------------------------------------------
  SparsePooler::SparsePooler(const SparsePoolerInputMasks& inputMasks,
			     size_type normalize,
			     value_type norm,
			     size_type sparsification_mode,
			     size_type inference_mode,
			     size_type kWinners,
			     value_type threshold,
			     value_type min_accept_distance,
			     value_type min_accept_norm,
			     value_type min_proto_sum,
			     value_type sigma,
			     UInt32 seed)
    : normalize_(false),
      lp_(0),
      sparsification_mode_(none),
      k_winners_(0),
      threshold_(0),
      min_accept_distance_(0),
      min_accept_norm_(0),
      min_proto_sum_(1),
      inference_mode_(product),
      sigma_(0),
      input_masks_(inputMasks),
      p_(0),
      buf_(inputMasks.maxSize()),
      prototypes_(),
      rng_(seed)
  {
    setDoNormalization(normalize);
    setNorm(norm);
    setSparsificationMode(sparsification_mode);
    setKWinners(kWinners);
    setInferenceMode(inference_mode);
    setThreshold(threshold);
    setMinAcceptDistance(min_accept_distance);
    setMinAcceptNorm(min_accept_norm);
    setMinProtoSum(min_proto_sum);
    setSigma(sigma);

    prototypes_.resize(inputMasks.nMasks());
    for (size_type i = 0; i != inputMasks.nMasks(); ++i)
      prototypes_[i].resize(0, inputMasks.size(i));

    init_invariants_();
  }

  //--------------------------------------------------------------------------------
  SparsePooler::SparsePooler(istream& inStream, UInt32 seed)
    : normalize_(false),
      lp_(0),
      sparsification_mode_(none),
      k_winners_(0),
      threshold_(0),
      min_accept_distance_(0),
      min_accept_norm_(0),
      min_proto_sum_(1),
      inference_mode_(product),
      sigma_(0),
      input_masks_(),
      p_(0),
      buf_(),
      prototypes_(),
      rng_(seed)
  {
    readState(inStream);
  }

  //--------------------------------------------------------------------------------
  SparsePooler::~SparsePooler()
  {}

  //--------------------------------------------------------------------------------
  void SparsePooler::saveState(ostream& outStream) const
  {
    outStream << getCurrentSparsePoolerVersion() << " "
	      << getSparsificationMode() << " "
	      << getInferenceMode() << " "
	      << getInputMasks() << " "
	      << getDoNormalization() << " "
	      << getNorm() << " "
	      << getKWinners() << " "
	      << getThreshold() << " "
	      << getMinAcceptDistance() << " "
	      << getMinAcceptNorm() << " "
	      << getMinProtoSum() << " "
	      << getSigma() << " ";

    for (size_type i = 0; i != prototypes_.size(); ++i)
      getPrototypes(i).toCSR(outStream);
  }

  //--------------------------------------------------------------------------------
  void SparsePooler::readState(istream& inStream)
  {
    const std::string where = "SparsePooler::readState: ";

    string flag("");
    size_type i_val = 0;
    value_type f_val = (value_type) 0;

    inStream >> flag;

    inStream >> i_val;
    setSparsificationMode(i_val);

    inStream >> i_val;
    setInferenceMode(i_val);

    inStream >> input_masks_;

    inStream >> i_val;
    setDoNormalization(i_val);

    inStream >> f_val;
    setNorm(f_val);

    inStream >> i_val;
    setKWinners(i_val);

    inStream >> f_val;
    setThreshold(f_val);

    inStream >> f_val;
    setMinAcceptDistance(f_val);

    inStream >> f_val;
    setMinAcceptNorm(f_val);

    if (flag == "SparsePooler_1.7") {
      inStream >> f_val;
      setMinProtoSum(f_val);
    }

    inStream >> f_val;
    setSigma(f_val);

    size_type n_prototypes = getInputMasks().nMasks();

    prototypes_.resize(n_prototypes);

    for (size_type i = 0; i != n_prototypes; ++i)
      prototypes_[i].fromCSR(inStream, true);

    p_ = 0;
    buf_.resize(getInputMasks().maxSize());

    init_invariants_();
  }

 //--------------------------------------------------------------------------------
  void SparsePooler::init_invariants_() const
  {
  }

  //--------------------------------------------------------------------------------
} // end namespace nta
<commit_msg>use NTA_ASSERT<commit_after>/*
 * ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have purchased from
 * Numenta, Inc. a separate commercial license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
 * Implementation for SparsePooler
 */

#include <nta/algorithms/SparsePooler.hpp>

using namespace std;

namespace nta {

  //--------------------------------------------------------------------------------
  const std::string SparsePooler::current_sparse_pooler_version_ = "SparsePooler_1.7";

  //--------------------------------------------------------------------------------
  // SPARSE POOLER INPUT MASKS
  //--------------------------------------------------------------------------------
  SparsePoolerInputMasks::SparsePoolerInputMasks()
    : segment_size_(0), min_size_(0), max_size_(0),
      sizes_(), masks_()
  {}

  //--------------------------------------------------------------------------------
  SparsePoolerInputMasks::SparsePoolerInputMasks(size_type ss,
						 const std::vector<Mask>& masks)
    : segment_size_(ss), min_size_(0), max_size_(0),
      sizes_(), masks_(masks)
  {
    compute_cache_();
  }

  //--------------------------------------------------------------------------------
  SparsePoolerInputMasks::SparsePoolerInputMasks(std::istream& inStream)
    : segment_size_(0), min_size_(0), max_size_(0),
      sizes_(), masks_()
  {
    readState(inStream);
  }

  //--------------------------------------------------------------------------------
  SparsePoolerInputMasks&
  SparsePoolerInputMasks::operator=(const SparsePoolerInputMasks& other)
  {
    if (&other != this) {
      segment_size_ = other.segment_size_;
      min_size_ = other.min_size_;
      max_size_ = other.max_size_;
      sizes_ = other.sizes_;
      masks_ = other.masks_;
    }
    return *this;
  }

  //--------------------------------------------------------------------------------
  void SparsePoolerInputMasks::saveState(std::ostream& outStream) const
  {
    outStream << segmentSize() << " " << masks_ << " ";
  }

  //--------------------------------------------------------------------------------
  void SparsePoolerInputMasks::readState(std::istream& inStream)
  {
    inStream >> segment_size_ >> general_vector >> masks_;
    compute_cache_();
  }

  //--------------------------------------------------------------------------------
  void SparsePoolerInputMasks::compute_cache_()
  {
    { // Pre-conditions
      NTA_ASSERT(segment_size_ > 0)
	<< "SparsePoolerInputMasks: Invalid segment size: " << segment_size_
	<< " - Should be > 0";

      NTA_ASSERT(masks_.size() > 0)
	<< "SparsePoolerInputMasks: No masks passed";

      for (size_type i = 0; i != masks_.size(); ++i) {

	NTA_ASSERT(masks_[i].size() > 0)
	  << "SparsePoolerInputMasks: Empty mask";

	for (size_type j = 0; j != masks_[i].size(); ++j)
	  NTA_ASSERT(masks_[i][j].second > 0)
	    << "SparsePoolerInputMasks: Empty mask segment";
      }
    } // End pre-conditions

    min_size_ = std::numeric_limits<size_type>::max();
    max_size_ = 0;
    sizes_.resize(masks_.size(), 0);

    for (size_type i = 0; i != masks_.size(); ++i) {
      size_type a_size = 0;
      for (size_type j = 0; j != masks_[i].size(); ++j)
	a_size += masks_[i][j].second;
      sizes_[i] = a_size;
      if (a_size < min_size_)
	min_size_ = a_size;
      if (a_size > max_size_)
	max_size_ = a_size;
    }
  }

  //--------------------------------------------------------------------------------
  std::ostream& operator<<(std::ostream& outStream, const SparsePoolerInputMasks& masks)
  {
    masks.saveState(outStream);
    return outStream;
  }

  //--------------------------------------------------------------------------------
  std::istream& operator>>(std::istream& inStream, SparsePoolerInputMasks& masks)
  {
    masks.readState(inStream);
    return inStream;
  }

  //--------------------------------------------------------------------------------
  // SPARSE POOLER
  //--------------------------------------------------------------------------------
  SparsePooler::SparsePooler()
    : normalize_(false),
      lp_(0),
      sparsification_mode_(none),
      k_winners_(0),
      threshold_(0),
      min_accept_distance_(0),
      min_accept_norm_(0),
      min_proto_sum_(1),
      inference_mode_(product),
      sigma_(0),
      input_masks_(),
      p_(0),
      buf_(),
      prototypes_(),
      rng_(0),
      cachedCM_()
  {}

  //------------------------------------------------------------------------------
  SparsePooler::SparsePooler(const SparsePoolerInputMasks& inputMasks,
			     size_type normalize,
			     value_type norm,
			     size_type sparsification_mode,
			     size_type inference_mode,
			     size_type kWinners,
			     value_type threshold,
			     value_type min_accept_distance,
			     value_type min_accept_norm,
			     value_type min_proto_sum,
			     value_type sigma,
			     UInt32 seed)
    : normalize_(false),
      lp_(0),
      sparsification_mode_(none),
      k_winners_(0),
      threshold_(0),
      min_accept_distance_(0),
      min_accept_norm_(0),
      min_proto_sum_(1),
      inference_mode_(product),
      sigma_(0),
      input_masks_(inputMasks),
      p_(0),
      buf_(inputMasks.maxSize()),
      prototypes_(),
      rng_(seed)
  {
    setDoNormalization(normalize);
    setNorm(norm);
    setSparsificationMode(sparsification_mode);
    setKWinners(kWinners);
    setInferenceMode(inference_mode);
    setThreshold(threshold);
    setMinAcceptDistance(min_accept_distance);
    setMinAcceptNorm(min_accept_norm);
    setMinProtoSum(min_proto_sum);
    setSigma(sigma);

    prototypes_.resize(inputMasks.nMasks());
    for (size_type i = 0; i != inputMasks.nMasks(); ++i)
      prototypes_[i].resize(0, inputMasks.size(i));

    init_invariants_();
  }

  //--------------------------------------------------------------------------------
  SparsePooler::SparsePooler(istream& inStream, UInt32 seed)
    : normalize_(false),
      lp_(0),
      sparsification_mode_(none),
      k_winners_(0),
      threshold_(0),
      min_accept_distance_(0),
      min_accept_norm_(0),
      min_proto_sum_(1),
      inference_mode_(product),
      sigma_(0),
      input_masks_(),
      p_(0),
      buf_(),
      prototypes_(),
      rng_(seed)
  {
    readState(inStream);
  }

  //--------------------------------------------------------------------------------
  SparsePooler::~SparsePooler()
  {}

  //--------------------------------------------------------------------------------
  void SparsePooler::saveState(ostream& outStream) const
  {
    outStream << getCurrentSparsePoolerVersion() << " "
	      << getSparsificationMode() << " "
	      << getInferenceMode() << " "
	      << getInputMasks() << " "
	      << getDoNormalization() << " "
	      << getNorm() << " "
	      << getKWinners() << " "
	      << getThreshold() << " "
	      << getMinAcceptDistance() << " "
	      << getMinAcceptNorm() << " "
	      << getMinProtoSum() << " "
	      << getSigma() << " ";

    for (size_type i = 0; i != prototypes_.size(); ++i)
      getPrototypes(i).toCSR(outStream);
  }

  //--------------------------------------------------------------------------------
  void SparsePooler::readState(istream& inStream)
  {
    const std::string where = "SparsePooler::readState: ";

    string flag("");
    size_type i_val = 0;
    value_type f_val = (value_type) 0;

    inStream >> flag;

    inStream >> i_val;
    setSparsificationMode(i_val);

    inStream >> i_val;
    setInferenceMode(i_val);

    inStream >> input_masks_;

    inStream >> i_val;
    setDoNormalization(i_val);

    inStream >> f_val;
    setNorm(f_val);

    inStream >> i_val;
    setKWinners(i_val);

    inStream >> f_val;
    setThreshold(f_val);

    inStream >> f_val;
    setMinAcceptDistance(f_val);

    inStream >> f_val;
    setMinAcceptNorm(f_val);

    if (flag == "SparsePooler_1.7") {
      inStream >> f_val;
      setMinProtoSum(f_val);
    }

    inStream >> f_val;
    setSigma(f_val);

    size_type n_prototypes = getInputMasks().nMasks();

    prototypes_.resize(n_prototypes);

    for (size_type i = 0; i != n_prototypes; ++i)
      prototypes_[i].fromCSR(inStream, true);

    p_ = 0;
    buf_.resize(getInputMasks().maxSize());

    init_invariants_();
  }

 //--------------------------------------------------------------------------------
  void SparsePooler::init_invariants_() const
  {
  }

  //--------------------------------------------------------------------------------
} // end namespace nta
<|endoftext|>