<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <gadget/gadgetConfig.h>

#include <vpr/vpr.h>
#include <vpr/Sync/Guard.h>
#include <vpr/Util/Assert.h>

#include <gadget/Type/EventWindow.h>

namespace gadget
{

vpr::ReturnStatus EventWindow::writeObject(vpr::ObjectWriter* writer)
{
   writer->writeUint16(MSG_DATA_KEYBOARD); // Write out the data type so that we can assert if reading in wrong place
   writer->writeUint16(256);

   for ( unsigned i = 0; i < 256; ++i )
   {
      writer->writeUint16(mCurKeys[i]);
   }

   return vpr::ReturnStatus::Succeed;
}

vpr::ReturnStatus EventWindow::readObject(vpr::ObjectReader* reader)
{
   //vprASSERT(reader->attribExists("rim.timestamp.delta"));
   //vpr::Uint64 delta = reader->getAttrib<vpr::Uint64>("rim.timestamp.delta");

   // ASSERT if this data is really not Digital Data
   vpr::Uint16 temp = reader->readUint16();
   vprASSERT(temp==MSG_DATA_KEYBOARD && "[Remote Input Manager]Not Digital Data");
   unsigned numVectors = reader->readUint16();

   for (unsigned i = 0; i < numVectors; ++i )
   {
      mCurKeys[i] = reader->readUint16();
   }

   return vpr::ReturnStatus::Succeed;
}

/**
 * Checks for the given modifier key pressed only.
 * @return true if key pressed exclusively.
 */
//virtual bool modifierOnly(int modKey) =0;
bool EventWindow::modifierOnly(gadget::Keys modKey)
{
   switch (modKey)
   {
      case gadget::KEY_NONE:
         return (!mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);
      case gadget::KEY_SHIFT:
         return (mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);
      case gadget::KEY_CTRL:
         return (!mCurKeys[gadget::KEY_SHIFT] && mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);
      case gadget::KEY_ALT:
         return (!mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && mCurKeys[gadget::KEY_ALT]);
      default:
         vprASSERT(false);
         return 0;
   }
}

std::string EventWindow::getKeyName(gadget::Keys keyId)
{
   switch(keyId)
   {
      case gadget::KEY_NONE: return std::string("VJKEY_NONE");
      case gadget::KEY_UP: return std::string("VJKEY_UP");
      case gadget::KEY_DOWN: return std::string("VJKEY_DOWN");
      case gadget::KEY_LEFT: return std::string("VJKEY_LEFT");
      case gadget::KEY_RIGHT: return std::string("VJKEY_RIGHT");
      case gadget::KEY_SHIFT: return std::string("VJKEY_SHIFT");
      case gadget::KEY_CTRL: return std::string("VJKEY_CTRL");
      case gadget::KEY_ALT: return std::string("VJKEY_ALT");
      case gadget::KEY_1: return std::string("VJKEY_1");
      case gadget::KEY_2: return std::string("VJKEY_2");
      case gadget::KEY_3: return std::string("VJKEY_3");
      case gadget::KEY_4: return std::string("VJKEY_4");
      case gadget::KEY_5: return std::string("VJKEY_5");
      case gadget::KEY_6: return std::string("VJKEY_6");
      case gadget::KEY_7: return std::string("VJKEY_7");
      case gadget::KEY_8: return std::string("VJKEY_8");
      case gadget::KEY_9: return std::string("VJKEY_9");
      case gadget::KEY_0: return std::string("VJKEY_0");
      case gadget::KEY_A: return std::string("VJKEY_A");
      case gadget::KEY_B: return std::string("VJKEY_B");
      case gadget::KEY_C: return std::string("VJKEY_C");
      case gadget::KEY_D: return std::string("VJKEY_D");
      case gadget::KEY_E: return std::string("VJKEY_E");
      case gadget::KEY_F: return std::string("VJKEY_F");
      case gadget::KEY_G: return std::string("VJKEY_G");
      case gadget::KEY_H: return std::string("VJKEY_H");
      case gadget::KEY_I: return std::string("VJKEY_I");
      case gadget::KEY_J: return std::string("VJKEY_J");
      case gadget::KEY_K: return std::string("VJKEY_K");
      case gadget::KEY_L: return std::string("VJKEY_L");
      case gadget::KEY_M: return std::string("VJKEY_M");
      case gadget::KEY_N: return std::string("VJKEY_N");
      case gadget::KEY_O: return std::string("VJKEY_O");
      case gadget::KEY_P: return std::string("VJKEY_P");
      case gadget::KEY_Q: return std::string("VJKEY_Q");
      case gadget::KEY_R: return std::string("VJKEY_R");
      case gadget::KEY_S: return std::string("VJKEY_S");
      case gadget::KEY_T: return std::string("VJKEY_T");
      case gadget::KEY_U: return std::string("VJKEY_U");
      case gadget::KEY_V: return std::string("VJKEY_V");
      case gadget::KEY_W: return std::string("VJKEY_W");
      case gadget::KEY_X: return std::string("VJKEY_X");
      case gadget::KEY_Y: return std::string("VJKEY_Y");
      case gadget::KEY_Z: return std::string("VJKEY_Z");
      case gadget::KEY_ESC: return std::string("VJKEY_ESC");
      case gadget::MOUSE_POSX: return std::string("VJMOUSE_POSX");
      case gadget::MOUSE_NEGX: return std::string("VJMOUSE_NEGX");
      case gadget::MOUSE_POSY: return std::string("VJMOUSE_POSY");
      case gadget::MOUSE_NEGY: return std::string("VJMOUSE_NEGY");
      case gadget::MBUTTON1: return std::string("VJMBUTTON1");
      case gadget::MBUTTON2: return std::string("VJMBUTTON2");
      case gadget::MBUTTON3: return std::string("VJMBUTTON3");
   }

   // If all of the above fell through ...
   return std::string("Unknown key");
}

std::queue<gadget::EventPtr> EventWindow::getEventQueue()
{
   vpr::Guard<vpr::Mutex> guard(mCurEventQueueLock);
   return mCurEventQueue;
}

void EventWindow::addEvent(gadget::EventPtr e)
{
   vpr::Guard<vpr::Mutex> guard(mWorkingEventQueueLock);
   mWorkingEventQueue.push(e);
}

void EventWindow::updateEventQueue()
{
   vpr::Guard<vpr::Mutex> work_guard(mWorkingEventQueueLock);
   {
      vpr::Guard<vpr::Mutex> cur_guard(mCurEventQueueLock);
      mCurEventQueue = mWorkingEventQueue;
   }

   while ( ! mWorkingEventQueue.empty() )
   {
      mWorkingEventQueue.pop();
   }
}

} // End of gadget namespcae
<commit_msg>Removed the "VJ" prefix from the symbolic key names returned by getKeyName().  I sincerely hope that no one was depending on these strings for anything other than debugging output.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <gadget/gadgetConfig.h>

#include <vpr/vpr.h>
#include <vpr/Sync/Guard.h>
#include <vpr/Util/Assert.h>

#include <gadget/Type/EventWindow.h>

namespace gadget
{

vpr::ReturnStatus EventWindow::writeObject(vpr::ObjectWriter* writer)
{
   writer->writeUint16(MSG_DATA_KEYBOARD); // Write out the data type so that we can assert if reading in wrong place
   writer->writeUint16(256);

   for ( unsigned i = 0; i < 256; ++i )
   {
      writer->writeUint16(mCurKeys[i]);
   }

   return vpr::ReturnStatus::Succeed;
}

vpr::ReturnStatus EventWindow::readObject(vpr::ObjectReader* reader)
{
   //vprASSERT(reader->attribExists("rim.timestamp.delta"));
   //vpr::Uint64 delta = reader->getAttrib<vpr::Uint64>("rim.timestamp.delta");

   // ASSERT if this data is really not Digital Data
   vpr::Uint16 temp = reader->readUint16();
   vprASSERT(temp==MSG_DATA_KEYBOARD && "[Remote Input Manager]Not Digital Data");
   unsigned numVectors = reader->readUint16();

   for (unsigned i = 0; i < numVectors; ++i )
   {
      mCurKeys[i] = reader->readUint16();
   }

   return vpr::ReturnStatus::Succeed;
}

/**
 * Checks for the given modifier key pressed only.
 * @return true if key pressed exclusively.
 */
//virtual bool modifierOnly(int modKey) =0;
bool EventWindow::modifierOnly(gadget::Keys modKey)
{
   switch (modKey)
   {
      case gadget::KEY_NONE:
         return (!mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);
      case gadget::KEY_SHIFT:
         return (mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);
      case gadget::KEY_CTRL:
         return (!mCurKeys[gadget::KEY_SHIFT] && mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);
      case gadget::KEY_ALT:
         return (!mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && mCurKeys[gadget::KEY_ALT]);
      default:
         vprASSERT(false);
         return 0;
   }
}

std::string EventWindow::getKeyName(gadget::Keys keyId)
{
   switch(keyId)
   {
      case gadget::KEY_NONE: return std::string("KEY_NONE");
      case gadget::KEY_UP: return std::string("KEY_UP");
      case gadget::KEY_DOWN: return std::string("KEY_DOWN");
      case gadget::KEY_LEFT: return std::string("KEY_LEFT");
      case gadget::KEY_RIGHT: return std::string("KEY_RIGHT");
      case gadget::KEY_SHIFT: return std::string("KEY_SHIFT");
      case gadget::KEY_CTRL: return std::string("KEY_CTRL");
      case gadget::KEY_ALT: return std::string("KEY_ALT");
      case gadget::KEY_1: return std::string("KEY_1");
      case gadget::KEY_2: return std::string("KEY_2");
      case gadget::KEY_3: return std::string("KEY_3");
      case gadget::KEY_4: return std::string("KEY_4");
      case gadget::KEY_5: return std::string("KEY_5");
      case gadget::KEY_6: return std::string("KEY_6");
      case gadget::KEY_7: return std::string("KEY_7");
      case gadget::KEY_8: return std::string("KEY_8");
      case gadget::KEY_9: return std::string("KEY_9");
      case gadget::KEY_0: return std::string("KEY_0");
      case gadget::KEY_A: return std::string("KEY_A");
      case gadget::KEY_B: return std::string("KEY_B");
      case gadget::KEY_C: return std::string("KEY_C");
      case gadget::KEY_D: return std::string("KEY_D");
      case gadget::KEY_E: return std::string("KEY_E");
      case gadget::KEY_F: return std::string("KEY_F");
      case gadget::KEY_G: return std::string("KEY_G");
      case gadget::KEY_H: return std::string("KEY_H");
      case gadget::KEY_I: return std::string("KEY_I");
      case gadget::KEY_J: return std::string("KEY_J");
      case gadget::KEY_K: return std::string("KEY_K");
      case gadget::KEY_L: return std::string("KEY_L");
      case gadget::KEY_M: return std::string("KEY_M");
      case gadget::KEY_N: return std::string("KEY_N");
      case gadget::KEY_O: return std::string("KEY_O");
      case gadget::KEY_P: return std::string("KEY_P");
      case gadget::KEY_Q: return std::string("KEY_Q");
      case gadget::KEY_R: return std::string("KEY_R");
      case gadget::KEY_S: return std::string("KEY_S");
      case gadget::KEY_T: return std::string("KEY_T");
      case gadget::KEY_U: return std::string("KEY_U");
      case gadget::KEY_V: return std::string("KEY_V");
      case gadget::KEY_W: return std::string("KEY_W");
      case gadget::KEY_X: return std::string("KEY_X");
      case gadget::KEY_Y: return std::string("KEY_Y");
      case gadget::KEY_Z: return std::string("KEY_Z");
      case gadget::KEY_ESC: return std::string("KEY_ESC");
      case gadget::MOUSE_POSX: return std::string("MOUSE_POSX");
      case gadget::MOUSE_NEGX: return std::string("MOUSE_NEGX");
      case gadget::MOUSE_POSY: return std::string("MOUSE_POSY");
      case gadget::MOUSE_NEGY: return std::string("MOUSE_NEGY");
      case gadget::MBUTTON1: return std::string("MBUTTON1");
      case gadget::MBUTTON2: return std::string("MBUTTON2");
      case gadget::MBUTTON3: return std::string("MBUTTON3");
   }

   // If all of the above fell through ...
   return std::string("Unknown key");
}

std::queue<gadget::EventPtr> EventWindow::getEventQueue()
{
   vpr::Guard<vpr::Mutex> guard(mCurEventQueueLock);
   return mCurEventQueue;
}

void EventWindow::addEvent(gadget::EventPtr e)
{
   vpr::Guard<vpr::Mutex> guard(mWorkingEventQueueLock);
   mWorkingEventQueue.push(e);
}

void EventWindow::updateEventQueue()
{
   vpr::Guard<vpr::Mutex> work_guard(mWorkingEventQueueLock);
   {
      vpr::Guard<vpr::Mutex> cur_guard(mCurEventQueueLock);
      mCurEventQueue = mWorkingEventQueue;
   }

   while ( ! mWorkingEventQueue.empty() )
   {
      mWorkingEventQueue.pop();
   }
}

} // End of gadget namespcae
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Copyright (C) 2012 Sergey Lisitsyn
 */

#include <shogun/transfer/multitask/MultitaskClusteredLogisticRegression.h>
#include <shogun/lib/malsar/malsar_clustered.h>
#include <shogun/lib/malsar/malsar_options.h>
#include <shogun/lib/SGVector.h>

namespace shogun
{

CMultitaskClusteredLogisticRegression::CMultitaskClusteredLogisticRegression() :
	CMultitaskLogisticRegression(), m_rho1(0.0), m_rho2(0.0)
{
}

CMultitaskClusteredLogisticRegression::CMultitaskClusteredLogisticRegression(
     float64_t rho1, float64_t rho2, CDotFeatures* train_features,
     CBinaryLabels* train_labels, CTaskGroup* task_group, int32_t n_clusters) :
	CMultitaskLogisticRegression(0.0,train_features,train_labels,(CTaskRelation*)task_group)
{
	set_rho1(rho1);
	set_rho2(rho2);
	set_num_clusters(n_clusters);
}

int32_t CMultitaskClusteredLogisticRegression::get_rho1() const
{
	return m_rho1;
}

int32_t CMultitaskClusteredLogisticRegression::get_rho2() const
{
	return m_rho2;
}

void CMultitaskClusteredLogisticRegression::set_rho1(float64_t rho1)
{
	m_rho1 = rho1;
}

void CMultitaskClusteredLogisticRegression::set_rho2(float64_t rho2)
{
	m_rho2 = rho2;
}

int32_t CMultitaskClusteredLogisticRegression::get_num_clusters() const
{
	return m_num_clusters;
}

void CMultitaskClusteredLogisticRegression::set_num_clusters(int32_t num_clusters)
{
	m_num_clusters = num_clusters;
}

CMultitaskClusteredLogisticRegression::~CMultitaskClusteredLogisticRegression()
{
}

bool CMultitaskClusteredLogisticRegression::train_locked_implementation(SGVector<index_t>* tasks)
{
	SGVector<float64_t> y(m_labels->get_num_labels());
	for (int32_t i=0; i<y.vlen; i++)
		y[i] = ((CBinaryLabels*)m_labels)->get_label(i);

	malsar_options options = malsar_options::default_options();
	options.termination = m_termination;
	options.tolerance = m_tolerance;
	options.max_iter = m_max_iter;
	options.n_tasks = ((CTaskGroup*)m_task_relation)->get_num_tasks();
	options.tasks_indices = tasks;
	options.n_clusters = m_num_clusters;

#ifdef HAVE_EIGEN3
#ifndef HAVE_CXX11
	malsar_result_t model = malsar_clustered(
		features, y.vector, m_rho1, m_rho2, options);

	m_tasks_w = model.w;
	m_tasks_c = model.c;
#else
	SG_WARNING("Clustered LR is unstable with C++11\n")
	m_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);
	m_tasks_w.set_const(0);
	m_tasks_c = SGVector<float64_t>(options.n_tasks);
	m_tasks_c.set_const(0);
#endif
#else
	SG_WARNING("Please install Eigen3 to use MultitaskClusteredLogisticRegression\n")
	m_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);
	m_tasks_c = SGVector<float64_t>(options.n_tasks);
#endif
	return true;
}

bool CMultitaskClusteredLogisticRegression::train_machine(CFeatures* data)
{
	if (data && (CDotFeatures*)data)
		set_features((CDotFeatures*)data);

	ASSERT(features)
	ASSERT(m_labels)
	ASSERT(m_task_relation)

	SGVector<float64_t> y(m_labels->get_num_labels());
	for (int32_t i=0; i<y.vlen; i++)
		y[i] = ((CBinaryLabels*)m_labels)->get_label(i);

	malsar_options options = malsar_options::default_options();
	options.termination = m_termination;
	options.tolerance = m_tolerance;
	options.max_iter = m_max_iter;
	options.n_tasks = ((CTaskGroup*)m_task_relation)->get_num_tasks();
	options.tasks_indices = ((CTaskGroup*)m_task_relation)->get_tasks_indices();
	options.n_clusters = m_num_clusters;

#ifdef HAVE_EIGEN3
#ifndef HAVE_CXX11
	malsar_result_t model = malsar_clustered(
		features, y.vector, m_rho1, m_rho2, options);

	m_tasks_w = model.w;
	m_tasks_c = model.c;
#else
	SG_WARNING("Clustered LR is unstable with C++11\n")
	m_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);
	m_tasks_c = SGVector<float64_t>(options.n_tasks);
#endif
#else
	SG_WARNING("Please install Eigen3 to use MultitaskClusteredLogisticRegression\n")
	m_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);
	m_tasks_c = SGVector<float64_t>(options.n_tasks);
#endif

	SG_FREE(options.tasks_indices);

	return true;
}

}
<commit_msg>Fixed MALSAR clustered LR fallback (affects #1360)<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Copyright (C) 2012 Sergey Lisitsyn
 */

#include <shogun/transfer/multitask/MultitaskClusteredLogisticRegression.h>
#include <shogun/lib/malsar/malsar_clustered.h>
#include <shogun/lib/malsar/malsar_options.h>
#include <shogun/lib/SGVector.h>

namespace shogun
{

CMultitaskClusteredLogisticRegression::CMultitaskClusteredLogisticRegression() :
	CMultitaskLogisticRegression(), m_rho1(0.0), m_rho2(0.0)
{
}

CMultitaskClusteredLogisticRegression::CMultitaskClusteredLogisticRegression(
     float64_t rho1, float64_t rho2, CDotFeatures* train_features,
     CBinaryLabels* train_labels, CTaskGroup* task_group, int32_t n_clusters) :
	CMultitaskLogisticRegression(0.0,train_features,train_labels,(CTaskRelation*)task_group)
{
	set_rho1(rho1);
	set_rho2(rho2);
	set_num_clusters(n_clusters);
}

int32_t CMultitaskClusteredLogisticRegression::get_rho1() const
{
	return m_rho1;
}

int32_t CMultitaskClusteredLogisticRegression::get_rho2() const
{
	return m_rho2;
}

void CMultitaskClusteredLogisticRegression::set_rho1(float64_t rho1)
{
	m_rho1 = rho1;
}

void CMultitaskClusteredLogisticRegression::set_rho2(float64_t rho2)
{
	m_rho2 = rho2;
}

int32_t CMultitaskClusteredLogisticRegression::get_num_clusters() const
{
	return m_num_clusters;
}

void CMultitaskClusteredLogisticRegression::set_num_clusters(int32_t num_clusters)
{
	m_num_clusters = num_clusters;
}

CMultitaskClusteredLogisticRegression::~CMultitaskClusteredLogisticRegression()
{
}

bool CMultitaskClusteredLogisticRegression::train_locked_implementation(SGVector<index_t>* tasks)
{
	SGVector<float64_t> y(m_labels->get_num_labels());
	for (int32_t i=0; i<y.vlen; i++)
		y[i] = ((CBinaryLabels*)m_labels)->get_label(i);

	malsar_options options = malsar_options::default_options();
	options.termination = m_termination;
	options.tolerance = m_tolerance;
	options.max_iter = m_max_iter;
	options.n_tasks = ((CTaskGroup*)m_task_relation)->get_num_tasks();
	options.tasks_indices = tasks;
	options.n_clusters = m_num_clusters;

#ifdef HAVE_EIGEN3
#ifndef HAVE_CXX11
	malsar_result_t model = malsar_clustered(
		features, y.vector, m_rho1, m_rho2, options);

	m_tasks_w = model.w;
	m_tasks_c = model.c;
#else
	SG_WARNING("Clustered LR is unstable with C++11\n")
	m_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);
	m_tasks_w.set_const(0);
	m_tasks_c = SGVector<float64_t>(options.n_tasks);
	m_tasks_c.set_const(0);
#endif
#else
	SG_WARNING("Please install Eigen3 to use MultitaskClusteredLogisticRegression\n")
	m_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);
	m_tasks_c = SGVector<float64_t>(options.n_tasks);
#endif
	return true;
}

bool CMultitaskClusteredLogisticRegression::train_machine(CFeatures* data)
{
	if (data && (CDotFeatures*)data)
		set_features((CDotFeatures*)data);

	ASSERT(features)
	ASSERT(m_labels)
	ASSERT(m_task_relation)

	SGVector<float64_t> y(m_labels->get_num_labels());
	for (int32_t i=0; i<y.vlen; i++)
		y[i] = ((CBinaryLabels*)m_labels)->get_label(i);

	malsar_options options = malsar_options::default_options();
	options.termination = m_termination;
	options.tolerance = m_tolerance;
	options.max_iter = m_max_iter;
	options.n_tasks = ((CTaskGroup*)m_task_relation)->get_num_tasks();
	options.tasks_indices = ((CTaskGroup*)m_task_relation)->get_tasks_indices();
	options.n_clusters = m_num_clusters;

#ifdef HAVE_EIGEN3
#ifndef HAVE_CXX11
	malsar_result_t model = malsar_clustered(
		features, y.vector, m_rho1, m_rho2, options);

	m_tasks_w = model.w;
	m_tasks_c = model.c;
#else
	SG_WARNING("Clustered LR is unstable with C++11\n")
	m_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);
	m_tasks_w.set_const(0);
	m_tasks_c = SGVector<float64_t>(options.n_tasks);
	m_tasks_c.set_const(0);
#endif
#else
	SG_WARNING("Please install Eigen3 to use MultitaskClusteredLogisticRegression\n")
	m_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);
	m_tasks_c = SGVector<float64_t>(options.n_tasks);
#endif

	SG_FREE(options.tasks_indices);

	return true;
}

}
<|endoftext|>


<commit_before>/*-
 * Copyright (c) 2008 Michael Marner <michael@20papercups.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

// include system headers
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>

// include openGL headers
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include <wcl/video/VideoDecoder.h>

using namespace std;
using namespace wcl;

VideoDecoder *decoder;

void usage()
{
    printf("Usage: video filename\n");
}

/**
 * Initialise OpenGL
 */
GLvoid init()
{
	unsigned char *data = new unsigned char[decoder->getWidth() * decoder->getHeight() * 3 /* RGB */];
	glShadeModel(GL_SMOOTH);
	glClearColor(0,0,0,0);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);

	// create a texture for the image...
	glTexImage2D(GL_TEXTURE_2D,             //target
				 0,                         //level of detail
				 3,                         //colour components
				 decoder->getWidth(),     //width
				 decoder->getHeight(),    //height
				 0,                         //border
				 GL_RGB,                    //image format
				 GL_UNSIGNED_BYTE,
				 data);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

	glEnable(GL_TEXTURE_2D);

	glMatrixMode(GL_PROJECTION);
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
	delete data;
}

/**
 * Constantly fetch a new image from the camera to display
 */
GLvoid idle()
{
	glutPostRedisplay();
}

/**
 * Display Loop.
 */
GLvoid display()
{
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

	const unsigned char* frame = decoder->getFrame();
	if( frame == NULL ){
	    // No more frames
	    exit(1);
	}

	glTexSubImage2D(GL_TEXTURE_2D,
	                0,
					0,
					0,
					decoder->getWidth(),
					decoder->getHeight(),
					GL_RGB,
					GL_UNSIGNED_BYTE,
					frame);

	glMatrixMode(GL_MODELVIEW);

	glLoadIdentity();
		glBegin(GL_QUADS);

		glTexCoord2f(0,1);
		glVertex2f(0,0);

		glTexCoord2f(1,1);
		glVertex2f(1,0);

		glTexCoord2f(1,0);
		glVertex2f(1,1);

		glTexCoord2f(0,0);
		glVertex2f(0,1);
	glEnd();

	glRasterPos2d( 0, 0);

	glDisable(GL_TEXTURE_2D);
	char buffer[100];
	sprintf(buffer, "[Video Test] Frame: %lld - %2.2f FPS",
		decoder->getCurrentFrame(),
		decoder->getFPS());
	for(char *c=buffer; *c != '\0'; c++)
	    glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,*c);
	glEnable(GL_TEXTURE_2D);

	glFlush();
	glutSwapBuffers();

	// print out any opengl errors to the console
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
	{
		cout << gluErrorString(error) << endl;
	}
}

/**
 * This doesn't do what it is supposed to do!
 */
GLvoid reshape(int width, int height)
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
}

void keyboard(unsigned char key, int w, int h)
{
    if(key==27)
	exit(EXIT_SUCCESS);
}

int main(int argc, char** argv)
{
    if(argc < 2 ){
		usage();
		return 1;
    }

	try {
		cout << "Opening Video... ";

		decoder = new VideoDecoder(argv[1]);

		cout << "Done!" << endl;

		// Create GLUT window
		glutInit(&argc, argv);
		glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
		glutInitWindowSize(decoder->getWidth(), decoder->getHeight());
		glutCreateWindow(argv[0]);

		init();

		// register callbacks
		glutDisplayFunc(display);
		glutReshapeFunc(reshape);
		glutKeyboardFunc(keyboard);
		glutIdleFunc(idle);

		// GO!
		glutMainLoop();

		delete decoder;

	}
	catch (std::string s)
	{
		cout << "Exception Occured: " << s << endl;
	}

	return 0;
}

<commit_msg>examples: Play the video at it intended speed, allow window resizing<commit_after>/*-
 * Copyright (c) 2008 Michael Marner <michael@20papercups.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

// include system headers
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>

// include openGL headers
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include <wcl/video/VideoDecoder.h>

using namespace std;
using namespace wcl;

VideoDecoder *decoder;

void usage()
{
    printf("Usage: video filename\n");
}

/**
 * Initialise OpenGL
 */
GLvoid init()
{
	unsigned char *data = new unsigned char[decoder->getWidth() * decoder->getHeight() * 3 /* RGB */];
	glShadeModel(GL_SMOOTH);
	glClearColor(0,0,0,0);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);

	// create a texture for the image...
	glTexImage2D(GL_TEXTURE_2D,             //target
				 0,                         //level of detail
				 3,                         //colour components
				 decoder->getWidth(),     //width
				 decoder->getHeight(),    //height
				 0,                         //border
				 GL_RGB,                    //image format
				 GL_UNSIGNED_BYTE,
				 data);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

	glEnable(GL_TEXTURE_2D);

	glMatrixMode(GL_PROJECTION);
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
	delete data;
}

/**
 * Constantly fetch a new image from the camera to display
 */
GLvoid idle()
{
	glutPostRedisplay();
}

/**
 * Display Loop.
 */
GLvoid display()
{
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

	const unsigned char* frame = decoder->getFrame();
	if( frame == NULL ){
	    // No more frames
	    exit(1);
	}

	glTexSubImage2D(GL_TEXTURE_2D,
	                0,
					0,
					0,
					decoder->getWidth(),
					decoder->getHeight(),
					GL_RGB,
					GL_UNSIGNED_BYTE,
					frame);

	glMatrixMode(GL_MODELVIEW);

	glLoadIdentity();
		glBegin(GL_QUADS);

		glTexCoord2f(0,1);
		glVertex2f(0,0);

		glTexCoord2f(1,1);
		glVertex2f(1,0);

		glTexCoord2f(1,0);
		glVertex2f(1,1);

		glTexCoord2f(0,0);
		glVertex2f(0,1);
	glEnd();

	glRasterPos2d( 0, 0);

	glDisable(GL_TEXTURE_2D);
	char buffer[100];
	sprintf(buffer, "[Video Test] Frame: %lld - %2.2f FPS",
		decoder->getCurrentFrame(),
		decoder->getFPS());
	for(char *c=buffer; *c != '\0'; c++)
	    glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,*c);
	glEnable(GL_TEXTURE_2D);

	glFlush();
	glutSwapBuffers();

	// print out any opengl errors to the console
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
	{
		cout << gluErrorString(error) << endl;
	}
}

/**
 * This doesn't do what it is supposed to do!
 */
GLvoid reshape(int width, int height)
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
	glViewport(0,0, (GLsizei)width, (GLsizei)height);
}

void keyboard(unsigned char key, int w, int h)
{
    if(key==27)
	exit(EXIT_SUCCESS);
}

int main(int argc, char** argv)
{
    if(argc < 2 ){
		usage();
		return 1;
    }

	try {
		cout << "Opening Video... ";

		decoder = new VideoDecoder(argv[1],true);

		cout << "Done!" << endl;

		// Create GLUT window
		glutInit(&argc, argv);
		glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
		glutInitWindowSize(decoder->getWidth(), decoder->getHeight());
		glutCreateWindow(argv[0]);

		init();

		// register callbacks
		glutDisplayFunc(display);
		glutReshapeFunc(reshape);
		glutKeyboardFunc(keyboard);
		glutIdleFunc(idle);

		// GO!
		glutMainLoop();

		delete decoder;

	}
	catch (std::string s)
	{
		cout << "Exception Occured: " << s << endl;
	}

	return 0;
}

<|endoftext|>


<commit_before>/* exonerate_fastparse.cpp
 *
 * Reads raw exonerate output (from STDIN)
 *
 */

#define BUFFER_SIZE 4096

#include <cstdlib>
#include <stdio.h>
#include <string>
#include <string.h>
#include <sstream>
#include <iostream>
#include <getopt.h>
using namespace std;

string get_sans_introns_header();
string get_with_introns_header();
string get_simple_header();

string parse_simple(string line, int stop, char delim);
string parse_sans_introns(string line, int stop, char delim);
string parse_with_introns(string line, int stop, char delim);
string parse_verbose(string line, int stop, char delim);
int get_first_integer(string line);
int get_stop_position(string line, int offset);

int main(int argc, char **argv)
{

    int format = 0;
    int c;

    while (1) {
        static struct option long_options[] =
        {
            {"simple",       no_argument, &format, 0},
            {"sans-introns", no_argument, &format, 1},
            {"with-introns", no_argument, &format, 2},
            {"verbose",      no_argument, &format, 3},
            {"help",         no_argument, 0, 'h'},
            {0,0,0,0}
        };
        int option_index = 0;
        c = getopt_long (argc, argv, "h", long_options, &option_index);

        /* Detect the end of the options. */
        if (c == -1)
            break;

        switch(c) {
            case 0:
                break;
            case 'h':
                cout << "Usage: exonerate-fastparse [options] filename" << endl
                     << "Format options:" << endl
                     << "   --simple - writes tabular output with the following columns:" << endl
                     << "      1. query_seqid"   << endl
                     << "      2. query_start"   << endl
                     << "      3. query_stop"    << endl
                     << "      4. query_strand"  << endl
                     << "      5. target_seqid"  << endl
                     << "      6. target_start"  << endl
                     << "      7. target_stop"   << endl
                     << "      8. target_strand" << endl
                     << "      9. score"         << endl
                     << "   --sans-introns - adds 5 columns to the simple output" << endl
                     << "      10. first_stop"     << endl
                     << "      11. has_frameshift" << endl
                     << "      12. split_codons"   << endl
                     << "      13. introns"        << endl
                     << "      14. max_introns"    << endl
                     << "   --with-introns - adds 1 column to the sans-introns output" << endl
                     << "      15. intron_lengths - a comma-delimited list of intron lengths" << endl
                     << "   --verbose\tprints simple tabular output and then one line for each gff entry" << endl;
                return 0;
        }
    }

    string (*parse)(string, int, char);

    switch(format) {
        case 0:
            cout << get_simple_header() << endl;
            parse = parse_simple;
            break;
        case 1:
            cout << get_sans_introns_header() << endl;
            parse = parse_sans_introns;
            break;
        case 2:
            cout << get_with_introns_header() << endl;
            parse = parse_with_introns;
            break;
        case 3:
            parse = parse_verbose;
            break;
    }

    // buffer to hold data input
    char buffer[BUFFER_SIZE];

    // string to hold line input
    string line;

    // index for ordering within a record
    int position = 0;

    // flag for being within the alignment region of a record
    bool between = true;

    // query start position for current alignment segment
    int running_position = 0;

    // position of first stop codon, 0 indicates none found
    int stop = 0;

    // temporary storage for output of get_stop_position
    int tmp_stop;

    while(fgets(buffer, BUFFER_SIZE, stdin)){

        // cast the cstring as a string object
        line = buffer;

        if(between){
            if(line.length() > 3 && line.substr(2,6) == "Target"){
                position = 1;
                between = false;
            }
            continue;
        }

        switch(position % 5) {
            case 2: if(line[0] == 'v'){
                        cout << parse(line, stop, '\t') << endl;
                        between = true;
                        stop = 0;
                    } else {
                        running_position = get_first_integer(line);
                    }
                    break;
            case 4: if(stop == 0) {
                        tmp_stop = get_stop_position(line, running_position);
                        if(tmp_stop != 0 && stop == 0){
                            stop = tmp_stop;
                        }
                    }
                    break;
        }

        position++;
    }
}

int get_stop_position(string line, int pos){
    for(unsigned int i = 0; i < line.length(); i++){
        // All capital letters signal a new amino acid
        if(line[i] >= 'A' && line[i] <= 'Z'){
            pos++;
        }
        // I am interested only in the position of the first stop,
        // so return when first '*' is encountered
        else if(line[i] == '*'){
            return(pos);
        }
    }
    // Return 0 if no stop is found
    return 0;
}

int get_first_integer(string line){
    int x;
    std::stringstream ss;
    ss << line;
    ss >> x;
    return x;
}

string get_simple_header(){
    string header = "query_seqid\t"
                    "query_start\t"
                    "query_stop\t"
                    "query_strand\t"
                    "target_contig\t"
                    "target_start\t"
                    "target_stop\t"
                    "target_strand\t"
                    "score\t";
    return header;
}

string get_sans_introns_header(){
    string header = get_simple_header();
    header += "first_stop\t"
              "has_frameshift\t"
              "split_codons\t"
              "introns\t"
              "max_intron";
    return header;
}

string get_with_introns_header(){
    string header = get_sans_introns_header();
    header += "\tintron_lengths";
    return header;
}

string parse_sans_introns(string line, int stop, char delim){
    stringstream s(line);
    stringstream out;
    string word;
    for(int i = 0; i < 10 && s >> word; i++){
        if(i > 0){
            out << word << delim;
        }
    }
    out << stop << delim;
    bool shifted = false;
    int nintrons = 0;
    int splits = 0;
    int longest_intron = 0;
    while(s >> word){
        switch(word[0]){
            case 'F': shifted = true;
                      break;
            case 'I': { nintrons++;
                        s >> word;
                        s >> word;
                        int len = atoi(word.c_str());
                        if(len > longest_intron)
                            longest_intron = len;
                      }
                      break;
            case 'S': splits++;
                      break;
        }
    }
    out << shifted  << delim
        << splits   << delim
        << nintrons << delim
        << longest_intron;
    return out.str();
}

string parse_with_introns(string line, int stop, char delim){
    stringstream out;
    stringstream s(line);
    out << parse_sans_introns(line, stop, delim) << delim;
    string word;
    bool has_intron = false;
    while(s >> word){
        if(word[0] == 'I'){
           s >> word;
           s >> word;
           if(has_intron)
               out << ',';
           out << word;
           has_intron = true;
        }
    }
    if(! has_intron)
        out << '-';
    return out.str();
}

string parse_simple(string line, int stop, char delim){
    stringstream s(line);
    stringstream out;
    string word;
    for(int i = 0; i < 9 && s >> word; i++){
        if(i > 0){
            out << word << delim;
        }
    }
    s >> word;
    out << word;
    return out.str();
}

string parse_verbose(string line, int stop, char delim){
    stringstream s(line);
    stringstream out;
    string word;
    for(int i = 0; i < 10 && s >> word; i++){
        if(i > 0){
            out << word << delim;
        }
    }
    out << stop << endl;
    for(int i = 0; s >> word; i++){
        if(i % 3 == 0)
            out << "> ";
        out << word;
        out << ((i % 3 != 2) ? delim  : '\n');
    }
    return out.str();
}
<commit_msg>abstracted header handling<commit_after>/* exonerate_fastparse.cpp
 *
 * Reads raw exonerate output (from STDIN)
 *
 */

#define BUFFER_SIZE 4096

#include <cstdlib>
#include <stdio.h>
#include <string>
#include <string.h>
#include <sstream>
#include <iostream>
#include <getopt.h>
using namespace std;

string get_sans_introns_header();
string get_with_introns_header();
string get_simple_header();

string parse_simple(string line, int stop, char delim);
string parse_sans_introns(string line, int stop, char delim);
string parse_with_introns(string line, int stop, char delim);
string parse_verbose(string line, int stop, char delim);
int get_first_integer(string line);
int get_stop_position(string line, int offset);

int main(int argc, char **argv)
{

    int format = 0;
    int c;
    bool header = true;

    while (1) {
        static struct option long_options[] =
        {
            {"simple",       no_argument, &format, 0},
            {"sans-introns", no_argument, &format, 1},
            {"with-introns", no_argument, &format, 2},
            {"verbose",      no_argument, &format, 3},
            {"help",         no_argument, 0, 'h'},
            {"no-header",    no_argument, 0, 's'},
            {0,0,0,0}
        };
        int option_index = 0;
        c = getopt_long (argc, argv, "hs", long_options, &option_index);

        /* Detect the end of the options. */
        if (c == -1)
            break;

        switch(c) {
            case 0:
                break;
            case 's':
                header = false;
                break;
            case 'h':
                cout << "Usage: exonerate-fastparse [options] filename"                                    << endl
                     << "Format options:"                                                                  << endl
                     << "   --simple - writes tabular output with the following columns:"                  << endl
                     << "      1. query_seqid"                                                             << endl
                     << "      2. query_start"                                                             << endl
                     << "      3. query_stop"                                                              << endl
                     << "      4. query_strand"                                                            << endl
                     << "      5. target_seqid"                                                            << endl
                     << "      6. target_start"                                                            << endl
                     << "      7. target_stop"                                                             << endl
                     << "      8. target_strand"                                                           << endl
                     << "      9. score"                                                                   << endl
                     << "   --sans-introns - adds 5 columns to the simple output"                          << endl
                     << "      10. first_stop - first stop codon in alignment"                             << endl
                     << "      11. has_frameshift - is there a frameshift? [01]"                           << endl
                     << "      12. split_codons - number of codons split by introns"                       << endl
                     << "      13. introns - total number of introns"                                      << endl
                     << "      14. max_introns - longest single intron"                                    << endl
                     << "   --with-introns - adds 1 column to the sans-introns output"                     << endl
                     << "      15. intron_lengths - a comma-delimited list of intron lengths"              << endl
                     << "   --verbose - prints simple tabular output and then one line for each gff entry" << endl;
                return 0;
        }
    }

    string (*parse)(string, int, char);
    string (*get_header)(void);

    switch(format) {
        case 0:
            get_header = get_simple_header;
            parse = parse_simple;
            break;
        case 1:
            get_header = get_sans_introns_header;
            parse = parse_sans_introns;
            break;
        case 2:
            get_header = get_with_introns_header;
            parse = parse_with_introns;
            break;
        case 3:
            header = false;
            parse = parse_verbose;
            break;
    }

    if(header)
        cout << get_header() << endl;

    // buffer to hold data input
    char buffer[BUFFER_SIZE];

    // string to hold line input
    string line;

    // index for ordering within a record
    int position = 0;

    // flag for being within the alignment region of a record
    bool between = true;

    // query start position for current alignment segment
    int running_position = 0;

    // position of first stop codon, 0 indicates none found
    int stop = 0;

    // temporary storage for output of get_stop_position
    int tmp_stop;

    while(fgets(buffer, BUFFER_SIZE, stdin)){

        // cast the cstring as a string object
        line = buffer;

        if(between){
            if(line.length() > 3 && line.substr(2,6) == "Target"){
                position = 1;
                between = false;
            }
            continue;
        }

        switch(position % 5) {
            case 2: if(line[0] == 'v'){
                        cout << parse(line, stop, '\t') << endl;
                        between = true;
                        stop = 0;
                    } else {
                        running_position = get_first_integer(line);
                    }
                    break;
            case 4: if(stop == 0) {
                        tmp_stop = get_stop_position(line, running_position);
                        if(tmp_stop != 0 && stop == 0){
                            stop = tmp_stop;
                        }
                    }
                    break;
        }

        position++;
    }
}

int get_stop_position(string line, int pos){
    for(unsigned int i = 0; i < line.length(); i++){
        // All capital letters signal a new amino acid
        if(line[i] >= 'A' && line[i] <= 'Z'){
            pos++;
        }
        // I am interested only in the position of the first stop,
        // so return when first '*' is encountered
        else if(line[i] == '*'){
            return(pos);
        }
    }
    // Return 0 if no stop is found
    return 0;
}

int get_first_integer(string line){
    int x;
    std::stringstream ss;
    ss << line;
    ss >> x;
    return x;
}

string get_simple_header(){
    string header = "query_seqid\t"
                    "query_start\t"
                    "query_stop\t"
                    "query_strand\t"
                    "target_contig\t"
                    "target_start\t"
                    "target_stop\t"
                    "target_strand\t"
                    "score\t";
    return header;
}

string get_sans_introns_header(){
    string header = get_simple_header();
    header += "first_stop\t"
              "has_frameshift\t"
              "split_codons\t"
              "introns\t"
              "max_intron";
    return header;
}

string get_with_introns_header(){
    string header = get_sans_introns_header();
    header += "\tintron_lengths";
    return header;
}

string parse_sans_introns(string line, int stop, char delim){
    stringstream s(line);
    stringstream out;
    string word;
    for(int i = 0; i < 10 && s >> word; i++){
        if(i > 0){
            out << word << delim;
        }
    }
    out << stop << delim;
    bool shifted = false;
    int nintrons = 0;
    int splits = 0;
    int longest_intron = 0;
    while(s >> word){
        switch(word[0]){
            case 'F': shifted = true;
                      break;
            case 'I': { nintrons++;
                        s >> word;
                        s >> word;
                        int len = atoi(word.c_str());
                        if(len > longest_intron)
                            longest_intron = len;
                      }
                      break;
            case 'S': splits++;
                      break;
        }
    }
    out << shifted  << delim
        << splits   << delim
        << nintrons << delim
        << longest_intron;
    return out.str();
}

string parse_with_introns(string line, int stop, char delim){
    stringstream out;
    stringstream s(line);
    out << parse_sans_introns(line, stop, delim) << delim;
    string word;
    bool has_intron = false;
    while(s >> word){
        if(word[0] == 'I'){
           s >> word;
           s >> word;
           if(has_intron)
               out << ',';
           out << word;
           has_intron = true;
        }
    }
    if(! has_intron)
        out << '-';
    return out.str();
}

string parse_simple(string line, int stop, char delim){
    stringstream s(line);
    stringstream out;
    string word;
    for(int i = 0; i < 9 && s >> word; i++){
        if(i > 0){
            out << word << delim;
        }
    }
    s >> word;
    out << word;
    return out.str();
}

string parse_verbose(string line, int stop, char delim){
    stringstream s(line);
    stringstream out;
    string word;
    for(int i = 0; i < 10 && s >> word; i++){
        if(i > 0){
            out << word << delim;
        }
    }
    out << stop << endl;
    for(int i = 0; s >> word; i++){
        if(i % 3 == 0)
            out << "> ";
        out << word;
        out << ((i % 3 != 2) ? delim  : '\n');
    }
    return out.str();
}
<|endoftext|>


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

#include "modules/monitor/common/can_checker_factory.h"

#include "modules/monitor/hwmonitor/hw/esdcan/esdcan_checker.h"

/**
 * @file: hw_checker_factory.cc
 */

namespace apollo {
namespace monitor {

using ::apollo::drivers::canbus::CANCardParameter;
using ::apollo::monitor::HwCheckerInterface;
using ::apollo::monitor::hw::EsdCanChecker;

CanCheckerFactory::CanCheckerFactory() {}

void CanCheckerFactory::RegisterCanCheckers() {
  Register(CANCardParameter::FAKE_CAN,
           []() -> HwCheckerInterface* { return new EsdCanChecker(); });
}

std::unique_ptr<HwCheckerInterface> CanCheckerFactory::CreateCanChecker(
    const CANCardParameter& parameter) {
  auto factory = CreateObject(parameter.brand());
  if (!factory) {
    AERROR << "Failed to create CAN checker with parameter: "
           << parameter.DebugString();
  }
  return factory;
}

}  // namespace monitor
}  // namespace apollo

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

#include "modules/monitor/common/can_checker_factory.h"

#include "modules/monitor/hwmonitor/hw/esdcan/esdcan_checker.h"

/**
 * @file: hw_checker_factory.cc
 */

namespace apollo {
namespace monitor {

using ::apollo::drivers::canbus::CANCardParameter;
using ::apollo::monitor::HwCheckerInterface;
using ::apollo::monitor::hw::EsdCanChecker;

CanCheckerFactory::CanCheckerFactory() {}

void CanCheckerFactory::RegisterCanCheckers() {
  Register(CANCardParameter::ESD_CAN,
           []() -> HwCheckerInterface* { return new EsdCanChecker(); });
}

std::unique_ptr<HwCheckerInterface> CanCheckerFactory::CreateCanChecker(
    const CANCardParameter& parameter) {
  auto factory = CreateObject(parameter.brand());
  if (!factory) {
    AERROR << "Failed to create CAN checker with parameter: "
           << parameter.DebugString();
  }
  return factory;
}

}  // namespace monitor
}  // namespace apollo
<|endoftext|>


<commit_before>/*
 * AscEmu Framework based on ArcEmu MMORPG Server
 * Copyright (c) 2014-2021 AscEmu Team <http://www.ascemu.org>
 * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
 * Copyright (C) 2005-2007 Ascent Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <cstdint>
#include <Network/Network.h>
#include <Config/Config.h>

#include "BaseConsole.h"
#include "ConsoleCommands.h"
#include "Server/World.h"

#include "ConsoleSocket.h"
#include "ConsoleAuthMgr.h"

ListenSocket<ConsoleSocket>* g_pListenSocket = nullptr;

void ConsoleAuthCallback(uint32_t request, uint32_t result)
{
    ConsoleSocket* consoleSocket = sConsoleAuthMgr.getSocketByRequestId(request);
    if (consoleSocket == nullptr || consoleSocket->IsConnected() == false)
    {
        return;
    }

    if (result)
    {
        consoleSocket->getConsoleAuthResult(true);
    }
    else
    {
        consoleSocket->getConsoleAuthResult(false);
    }
}

void CloseConsoleListener()
{
    if (g_pListenSocket != nullptr)
    {
        g_pListenSocket->Close();
    }
}

bool StartConsoleListener()
{
    if (worldConfig.remoteConsole.isEnabled == false)
    {
        return false;
    }

    std::string consoleListenHost = worldConfig.remoteConsole.host;
    uint32_t consoleListenPort = worldConfig.remoteConsole.port;

    g_pListenSocket = new ListenSocket<ConsoleSocket>(consoleListenHost.c_str(), consoleListenPort);
    if (g_pListenSocket == nullptr)
    {
        return false;
    }

    if (g_pListenSocket->IsOpen() == false)
    {
        g_pListenSocket->Close();

        delete g_pListenSocket;
        g_pListenSocket = nullptr;

        return false;
    }

    sConsoleAuthMgr.initialize();
    return true;
}

ThreadBase* GetConsoleListener()
{
    //\todo Zyres: cast in redundant on MSVC but gcc needs it.
    return static_cast<ThreadBase*>(g_pListenSocket);
}

RemoteConsole::RemoteConsole(ConsoleSocket* pSocket)
{
    m_pSocket = pSocket;
}

void RemoteConsole::Write(const char* Format, ...)
{
    char obuf[65536];
    va_list ap;

    va_start(ap, Format);
    vsnprintf(obuf, 65536, Format, ap);
    va_end(ap);

    if (*obuf == '\0')
        return;

    m_pSocket->Send((const uint8*)obuf, (uint32)strlen(obuf));
}

struct ConsoleCommand
{
    bool(*CommandPointer)(BaseConsole*, int, std::string, bool);
    std::string consoleCommand;
    int argumentCount;
    std::string argumentFormat;
    std::string commandDescription;
};

static ConsoleCommand Commands[] =
{
    { &handleSendChatAnnounceCommand,   "a",                1,  "<announce>",                           "Send chat announce." },
    { &handleSendChatAnnounceCommand,   "announce",         1,  "<announce>",                           "Send chat announce." },
    { &handleBanAccountCommand,         "ban",              3,  "<account> <time e.g. 3d> [reason]",    "Bans account <account> for time <time> with optional reason [reason]." },
    { &handleBanAccountCommand,         "banaccount",       3,  "<account> <time e.g. 3d> [reason]",    "Bans account <account> for time <time> with optional reason [reason]." },
    { &handleCreateAccountCommand,      "createaccount",    2,  "<accountname> <password>",             "Creates an account X with password y" },
    { &handleCancelShutdownCommand,     "cancel",           0,  "None",                                 "Cancels a pending shutdown." },
    { &handleServerInfoCommand,         "info",             0,  "None",                                 "Return current Server information." },
    { &handleOnlineGmsCommand,          "gms",              0,  "None",                                 "Shows online GMs." },
    { &handleKickPlayerCommand,         "kick",             2,  "<player name> [reason]",               "Kicks player <player name> for optional reason [reason]." },
    { &handleMotdCommand,               "getmotd",          0,  "None",                                 "View the current MOTD" },
    { &handleMotdCommand,               "setmotd",          1,  "<motd>",                               "Sets a new MOTD" },
    { &handleAccountPermission,         "setaccpermission", 2,  "<account> <permission>",               "Aets permission y for account name x" },
    { &handleListOnlinePlayersCommand,  "online",           0,  "None",                                 "Shows online players." },
    { &handlePlayerInfoCommand,         "playerinfo",       1,  "<player name>",                        "Shows information about a player." },
    { &handleShutDownServerCommand,     "exit",             0,  "[delay]",                              "Server shutdown with optional delay in seconds." },
    { &handleShutDownServerCommand,     "shutdown",         0,  "[delay]",                              "Server shutdown with optional delay in seconds." },
    { &handleRehashConfigCommand,       "rehash",           0,  "None",                                 "Reload world-config." },
    { &handleUnbanAccountCommand,       "unban",            1,  "<account>",                            "Unbans account x." },
    { &handleUnbanAccountCommand,       "unbanaccount",     1,  "<account>",                            "Unbans account x." },
    { &handleSendWAnnounceCommand,      "w",                1,  "<wannounce>",                          "Send announce on screen for all." },
    { &handleSendWAnnounceCommand,      "wannounce",        1,  "<wannounce>",                          "Send announce on screen for all." },
    { &handleWhisperCommand,            "whisper",          2,  "<player> <message>",                   "Whispers message to someone." },
    { &handleCreateNameHashCommand,     "getnamehash",      1,  "<text>",                               "Returns the crc32 hash of <text>" },
    { &handleRevivePlayerCommand,       "reviveplr",        1,  "<player name>",                        "Revives a Player <player name>" },
    { &handleClearConsoleCommand,       "clear",            0,  "None",                                 "Clears the console." },
    { &handleReloadScriptEngineCommand, "reloadscripts",    0,  "None",                                 "Reloads all scripting engines currently loaded." },
    { &handlePrintTimeDateCommand,      "datetime",         0,  "None",                                 "Shows time and date according to localtime()" },
    { &handleGetAccountsCommand,        "getaccountdata",   0,  "None",                                 "Prints out all account data" },
    { nullptr,                          "",                 0,  "",                                     "" },
};

void processConsoleInput(BaseConsole* baseConsole, std::string consoleInput, bool isWebClient)
{
    ConsoleCommand commandList;

    std::stringstream consoleInputStream(consoleInput);

    std::string commandName;
    std::string commandVars;

    consoleInputStream >> commandName;
    std::getline(consoleInputStream, commandVars);

    bool commandFound = false;
    bool isHelpCommand = false;
    for (int i = 0; Commands[i].consoleCommand.empty() == false; ++i)
    {
        if (commandName.empty())
            break;

        if (commandName.compare("help") == 0 || commandName.compare("?") == 0)
        {
            isHelpCommand = true;
            break;
        }

        if (Commands[i].consoleCommand.compare(commandName) == 0)
        {
            commandFound = true;
            commandList = Commands[i];
            break;
        }
    }

    if (isHelpCommand)
    {
        if (isWebClient == false)
        {
            baseConsole->Write("Show Command list with ----- :%s\r\n", commandName.c_str());

            baseConsole->Write("===============================================================================\r\n");
            baseConsole->Write("| %15s | %57s |\r\n", "Name", "Arguments");
            baseConsole->Write("===============================================================================\r\n");

            for (int j = 0; Commands[j].consoleCommand.empty() == false; ++j)
            {
                baseConsole->Write("| %15s | %57s |\r\n", Commands[j].consoleCommand.c_str(), Commands[j].argumentFormat.c_str());
            }

            baseConsole->Write("===============================================================================\r\n");
            baseConsole->Write("| type 'quit' to terminate a Remote Console Session                           |\r\n");
            baseConsole->Write("===============================================================================\r\n");
        }
    }
    else
    {
        if (commandFound)
        {
            if (isWebClient == false)
            {
                baseConsole->Write("Received command: %s\r\n", commandName.c_str());
            }

            if (commandList.argumentCount > 0 && commandVars.empty() == false)
            {
                if (isWebClient == false)
                {
                    baseConsole->Write("Received vars: %s\r\n", commandVars.c_str());
                }
            }

            if (!commandList.CommandPointer(baseConsole, commandList.argumentCount, commandVars, isWebClient))
            {
                if (isWebClient == false)
                {
                    baseConsole->Write("[!]Error, '%s' used an incorrect syntax, the correct syntax is: '%s'.\r\n\r\n",
                        commandList.consoleCommand.c_str(), commandList.argumentFormat.c_str());
                }
            }
        }
        else
        {
            if (isWebClient == false)
            {
                baseConsole->Write("[!]Error, Command '%s' doesn't exist. Type '?' or 'help' to get a command overview.\r\n\r\n",
                    commandName.c_str());
            }
        }
    }
}

void LocalConsole::Write(const char* Format, ...)
{
    va_list ap;
    va_start(ap, Format);
    vprintf(Format, ap);
    va_end(ap);
}
<commit_msg>Update ConsoleListener.cpp<commit_after>/*
 * AscEmu Framework based on ArcEmu MMORPG Server
 * Copyright (c) 2014-2021 AscEmu Team <http://www.ascemu.org>
 * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
 * Copyright (C) 2005-2007 Ascent Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <cstdint>
#include <Network/Network.h>
#include <Config/Config.h>

#include "BaseConsole.h"
#include "ConsoleCommands.h"
#include "Server/World.h"

#include "ConsoleSocket.h"
#include "ConsoleAuthMgr.h"

#include "Threading/LegacyThreadBase.h"

ListenSocket<ConsoleSocket>* g_pListenSocket = nullptr;

void ConsoleAuthCallback(uint32_t request, uint32_t result)
{
    ConsoleSocket* consoleSocket = sConsoleAuthMgr.getSocketByRequestId(request);
    if (consoleSocket == nullptr || consoleSocket->IsConnected() == false)
    {
        return;
    }

    if (result)
    {
        consoleSocket->getConsoleAuthResult(true);
    }
    else
    {
        consoleSocket->getConsoleAuthResult(false);
    }
}

void CloseConsoleListener()
{
    if (g_pListenSocket != nullptr)
    {
        g_pListenSocket->Close();
    }
}

bool StartConsoleListener()
{
    if (worldConfig.remoteConsole.isEnabled == false)
    {
        return false;
    }

    std::string consoleListenHost = worldConfig.remoteConsole.host;
    uint32_t consoleListenPort = worldConfig.remoteConsole.port;

    g_pListenSocket = new ListenSocket<ConsoleSocket>(consoleListenHost.c_str(), consoleListenPort);
    if (g_pListenSocket == nullptr)
    {
        return false;
    }

    if (g_pListenSocket->IsOpen() == false)
    {
        g_pListenSocket->Close();

        delete g_pListenSocket;
        g_pListenSocket = nullptr;

        return false;
    }

    sConsoleAuthMgr.initialize();
    return true;
}

ThreadBase* GetConsoleListener()
{
    //\todo Zyres: cast in redundant on MSVC but gcc needs it.
    return static_cast<ThreadBase*>(g_pListenSocket);
}

RemoteConsole::RemoteConsole(ConsoleSocket* pSocket)
{
    m_pSocket = pSocket;
}

void RemoteConsole::Write(const char* Format, ...)
{
    char obuf[65536];
    va_list ap;

    va_start(ap, Format);
    vsnprintf(obuf, 65536, Format, ap);
    va_end(ap);

    if (*obuf == '\0')
        return;

    m_pSocket->Send((const uint8*)obuf, (uint32)strlen(obuf));
}

struct ConsoleCommand
{
    bool(*CommandPointer)(BaseConsole*, int, std::string, bool);
    std::string consoleCommand;
    int argumentCount;
    std::string argumentFormat;
    std::string commandDescription;
};

static ConsoleCommand Commands[] =
{
    { &handleSendChatAnnounceCommand,   "a",                1,  "<announce>",                           "Send chat announce." },
    { &handleSendChatAnnounceCommand,   "announce",         1,  "<announce>",                           "Send chat announce." },
    { &handleBanAccountCommand,         "ban",              3,  "<account> <time e.g. 3d> [reason]",    "Bans account <account> for time <time> with optional reason [reason]." },
    { &handleBanAccountCommand,         "banaccount",       3,  "<account> <time e.g. 3d> [reason]",    "Bans account <account> for time <time> with optional reason [reason]." },
    { &handleCreateAccountCommand,      "createaccount",    2,  "<accountname> <password>",             "Creates an account X with password y" },
    { &handleCancelShutdownCommand,     "cancel",           0,  "None",                                 "Cancels a pending shutdown." },
    { &handleServerInfoCommand,         "info",             0,  "None",                                 "Return current Server information." },
    { &handleOnlineGmsCommand,          "gms",              0,  "None",                                 "Shows online GMs." },
    { &handleKickPlayerCommand,         "kick",             2,  "<player name> [reason]",               "Kicks player <player name> for optional reason [reason]." },
    { &handleMotdCommand,               "getmotd",          0,  "None",                                 "View the current MOTD" },
    { &handleMotdCommand,               "setmotd",          1,  "<motd>",                               "Sets a new MOTD" },
    { &handleAccountPermission,         "setaccpermission", 2,  "<account> <permission>",               "Aets permission y for account name x" },
    { &handleListOnlinePlayersCommand,  "online",           0,  "None",                                 "Shows online players." },
    { &handlePlayerInfoCommand,         "playerinfo",       1,  "<player name>",                        "Shows information about a player." },
    { &handleShutDownServerCommand,     "exit",             0,  "[delay]",                              "Server shutdown with optional delay in seconds." },
    { &handleShutDownServerCommand,     "shutdown",         0,  "[delay]",                              "Server shutdown with optional delay in seconds." },
    { &handleRehashConfigCommand,       "rehash",           0,  "None",                                 "Reload world-config." },
    { &handleUnbanAccountCommand,       "unban",            1,  "<account>",                            "Unbans account x." },
    { &handleUnbanAccountCommand,       "unbanaccount",     1,  "<account>",                            "Unbans account x." },
    { &handleSendWAnnounceCommand,      "w",                1,  "<wannounce>",                          "Send announce on screen for all." },
    { &handleSendWAnnounceCommand,      "wannounce",        1,  "<wannounce>",                          "Send announce on screen for all." },
    { &handleWhisperCommand,            "whisper",          2,  "<player> <message>",                   "Whispers message to someone." },
    { &handleCreateNameHashCommand,     "getnamehash",      1,  "<text>",                               "Returns the crc32 hash of <text>" },
    { &handleRevivePlayerCommand,       "reviveplr",        1,  "<player name>",                        "Revives a Player <player name>" },
    { &handleClearConsoleCommand,       "clear",            0,  "None",                                 "Clears the console." },
    { &handleReloadScriptEngineCommand, "reloadscripts",    0,  "None",                                 "Reloads all scripting engines currently loaded." },
    { &handlePrintTimeDateCommand,      "datetime",         0,  "None",                                 "Shows time and date according to localtime()" },
    { &handleGetAccountsCommand,        "getaccountdata",   0,  "None",                                 "Prints out all account data" },
    { nullptr,                          "",                 0,  "",                                     "" },
};

void processConsoleInput(BaseConsole* baseConsole, std::string consoleInput, bool isWebClient)
{
    ConsoleCommand commandList;

    std::stringstream consoleInputStream(consoleInput);

    std::string commandName;
    std::string commandVars;

    consoleInputStream >> commandName;
    std::getline(consoleInputStream, commandVars);

    bool commandFound = false;
    bool isHelpCommand = false;
    for (int i = 0; Commands[i].consoleCommand.empty() == false; ++i)
    {
        if (commandName.empty())
            break;

        if (commandName.compare("help") == 0 || commandName.compare("?") == 0)
        {
            isHelpCommand = true;
            break;
        }

        if (Commands[i].consoleCommand.compare(commandName) == 0)
        {
            commandFound = true;
            commandList = Commands[i];
            break;
        }
    }

    if (isHelpCommand)
    {
        if (isWebClient == false)
        {
            baseConsole->Write("Show Command list with ----- :%s\r\n", commandName.c_str());

            baseConsole->Write("===============================================================================\r\n");
            baseConsole->Write("| %15s | %57s |\r\n", "Name", "Arguments");
            baseConsole->Write("===============================================================================\r\n");

            for (int j = 0; Commands[j].consoleCommand.empty() == false; ++j)
            {
                baseConsole->Write("| %15s | %57s |\r\n", Commands[j].consoleCommand.c_str(), Commands[j].argumentFormat.c_str());
            }

            baseConsole->Write("===============================================================================\r\n");
            baseConsole->Write("| type 'quit' to terminate a Remote Console Session                           |\r\n");
            baseConsole->Write("===============================================================================\r\n");
        }
    }
    else
    {
        if (commandFound)
        {
            if (isWebClient == false)
            {
                baseConsole->Write("Received command: %s\r\n", commandName.c_str());
            }

            if (commandList.argumentCount > 0 && commandVars.empty() == false)
            {
                if (isWebClient == false)
                {
                    baseConsole->Write("Received vars: %s\r\n", commandVars.c_str());
                }
            }

            if (!commandList.CommandPointer(baseConsole, commandList.argumentCount, commandVars, isWebClient))
            {
                if (isWebClient == false)
                {
                    baseConsole->Write("[!]Error, '%s' used an incorrect syntax, the correct syntax is: '%s'.\r\n\r\n",
                        commandList.consoleCommand.c_str(), commandList.argumentFormat.c_str());
                }
            }
        }
        else
        {
            if (isWebClient == false)
            {
                baseConsole->Write("[!]Error, Command '%s' doesn't exist. Type '?' or 'help' to get a command overview.\r\n\r\n",
                    commandName.c_str());
            }
        }
    }
}

void LocalConsole::Write(const char* Format, ...)
{
    va_list ap;
    va_start(ap, Format);
    vprintf(Format, ap);
    va_end(ap);
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP
#define STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/typedefs.hpp>
#include <stan/math/prim/mat/fun/cholesky_decompose.hpp>
#include <stan/math/rev/scal/fun/value_of_rec.hpp>
#include <stan/math/rev/scal/fun/value_of.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/mat/fun/value_of_rec.hpp>
#include <stan/math/prim/mat/err/check_pos_definite.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#include <stan/math/prim/mat/err/check_symmetric.hpp>
#include <algorithm>

namespace stan {
  namespace math {

    class cholesky_decompose_v_vari : public vari {
    public:
      int M_;  // A.rows() = A.cols()
      int block_size_;
      typedef Eigen::Block<Eigen::MatrixXd> Block_;
      vari** variRefA_;
      vari** variRefL_;

      /**
       * Constructor for cholesky function.
       *
       * Stores varis for A.
       * Instantiates and stores varis for L.
       * Instantiates and stores dummy vari for
       * upper triangular part of var result returned
       * in cholesky_decompose function call
       *
       * variRefL aren't on the chainable
       * autodiff stack, only used for storage
       * and computation. Note that varis for
       * L are constructed externally in
       * cholesky_decompose.
       *
       * block_size_ determined using the same
       * calculation Eigen/LLT.h
       *
       * @param matrix A
       * @param matrix L, cholesky factor of A
       */
      cholesky_decompose_v_vari(const Eigen::Matrix<var, -1, -1>& A,
                                const Eigen::Matrix<double, -1, -1>& L_A)
        : vari(0.0),
          M_(A.rows()),
          variRefA_(ChainableStack::memalloc_.alloc_array<vari*>
                    (A.rows() * (A.rows() + 1) / 2)),
          variRefL_(ChainableStack::memalloc_.alloc_array<vari*>
                    (A.rows() * (A.rows() + 1) / 2)) {
            size_t pos = 0;
            block_size_ = M_/8;
            block_size_ = (block_size_/16)*16;
            block_size_ = (std::min)((std::max)(block_size_, 8), 128);
            for (size_type j = 0; j < M_; ++j) {
              for (size_type i = j; i < M_; ++i) {
                variRefA_[pos] = A.coeffRef(i, j).vi_;
                variRefL_[pos] = new vari(L_A.coeffRef(i, j), false);
                ++pos;
              }
            }
          }

      inline void symbolic_rev(Block_& L,
                               Block_& Lbar,
                               int size) {
        using Eigen::Lower;
        using Eigen::Upper;
        using Eigen::StrictlyUpper;
        L.transposeInPlace();
        Lbar = (L * Lbar.triangularView<Lower>()).eval();
        Lbar.triangularView<StrictlyUpper>()
          = Lbar.adjoint().triangularView<StrictlyUpper>();
        L.triangularView<Upper>().solveInPlace(Lbar);
        L.triangularView<Upper>().solveInPlace(Lbar.transpose());
      }

      /**
       * Reverse mode differentiation
       * algorithm refernce:
       *
       * Iain Murray: Differentiation of
       * the Cholesky decomposition, 2016.
       *
       */
      virtual void chain() {
        using Eigen::MatrixXd;
        using Eigen::Lower;
        using Eigen::Block;
        using Eigen::Upper;
        using Eigen::StrictlyUpper;
        MatrixXd Lbar(M_, M_);
        MatrixXd L(M_, M_);

        Lbar.setZero();
        L.setZero();
        size_t pos = 0;
        for (size_type j = 0; j < M_; ++j) {
          for (size_type i = j; i < M_; ++i) {
            Lbar.coeffRef(i, j) = variRefL_[pos]->adj_;
            L.coeffRef(i, j) = variRefL_[pos]->val_;
            ++pos;
          }
        }

        for (int k = M_; k > 0; k -= block_size_) {
          int j = std::max(0, k - block_size_);
          Block_ R = L.block(j, 0, k - j, j);
          Block_ D = L.block(j, j, k - j, k - j);
          Block_ B = L.block(k, 0, M_ - k, j);
          Block_ C = L.block(k, j, M_ - k, k - j);
          Block_ Rbar = Lbar.block(j, 0, k - j, j);
          Block_ Dbar = Lbar.block(j, j, k - j, k - j);
          Block_ Bbar = Lbar.block(k, 0, M_ - k, j);
          Block_ Cbar = Lbar.block(k, j, M_ - k, k - j);
          if (Cbar.size() > 0) {
            Cbar
              = D.transpose().triangularView<Upper>()
              .solve(Cbar.transpose()).transpose();
            Bbar.noalias() -= Cbar * R;
            Dbar.noalias() -= Cbar.transpose() * C;
          }
          symbolic_rev(D, Dbar, D.rows());
          Rbar.noalias() -= Cbar.transpose() * B;
          Rbar.noalias() -= Dbar.selfadjointView<Lower>() * R;
          Dbar.diagonal().array() *= 0.5;
          Dbar.triangularView<StrictlyUpper>().setZero();
        }
        pos = 0;
        for (size_type j = 0; j < M_; ++j)
          for (size_type i = j; i < M_; ++i)
            variRefA_[pos++]->adj_ += Lbar.coeffRef(i, j);
      }
    };

    /**
     * Reverse mode specialization of
     * cholesky decomposition
     *
     * Internally calls llt rather than using
     * cholesky_decompose in order
     * to use selfadjointView<Lower> optimization.
     *
     * TODO(rtrangucci): Use Eigen 3.3 inplace Cholesky
     * when possible
     *
     * Note chainable stack varis are created
     * below in Matrix<var, -1, -1>
     *
     * @param Matrix A
     * @return L cholesky factor of A
     */
    inline Eigen::Matrix<var, -1, -1>
      cholesky_decompose(const Eigen::Matrix<var, -1, -1> &A) {
      check_square("cholesky_decompose", "A", A);
      check_symmetric("cholesky_decompose", "A", A);

      Eigen::Matrix<double, -1, -1> L_A(value_of_rec(A));
      Eigen::LLT<Eigen::MatrixXd> L_factor
        = L_A.selfadjointView<Eigen::Lower>().llt();
      check_pos_definite("cholesky_decompose", "m", L_factor);
      L_A = L_factor.matrixL();

      // Memory allocated in arena.
      cholesky_decompose_v_vari *baseVari
        = new cholesky_decompose_v_vari(A, L_A);
      vari dummy(0.0, false);
      Eigen::Matrix<var, -1, -1> L(A.rows(), A.cols());
      size_t pos = 0;
      for (size_type j = 0; j < L.cols(); ++j) {
        for (size_type i = j; i < L.cols(); ++i) {
          L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos++];
        }
        for (size_type k = 0; k < j; ++k)
          L.coeffRef(k, j).vi_ = &dummy;
      }
      return L;
    }
  }
}
#endif
<commit_msg>Fixed memory leak<commit_after>#ifndef STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP
#define STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/typedefs.hpp>
#include <stan/math/prim/mat/fun/cholesky_decompose.hpp>
#include <stan/math/rev/scal/fun/value_of_rec.hpp>
#include <stan/math/rev/scal/fun/value_of.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/mat/fun/value_of_rec.hpp>
#include <stan/math/prim/mat/err/check_pos_definite.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#include <stan/math/prim/mat/err/check_symmetric.hpp>
#include <algorithm>

namespace stan {
  namespace math {

    class cholesky_decompose_v_vari : public vari {
    public:
      int M_;  // A.rows() = A.cols()
      int block_size_;
      typedef Eigen::Block<Eigen::MatrixXd> Block_;
      vari** variRefA_;
      vari** variRefL_;

      /**
       * Constructor for cholesky function.
       *
       * Stores varis for A.
       * Instantiates and stores varis for L.
       * Instantiates and stores dummy vari for
       * upper triangular part of var result returned
       * in cholesky_decompose function call
       *
       * variRefL aren't on the chainable
       * autodiff stack, only used for storage
       * and computation. Note that varis for
       * L are constructed externally in
       * cholesky_decompose.
       *
       * block_size_ determined using the same
       * calculation Eigen/LLT.h
       *
       * @param matrix A
       * @param matrix L, cholesky factor of A
       */
      cholesky_decompose_v_vari(const Eigen::Matrix<var, -1, -1>& A,
                                const Eigen::Matrix<double, -1, -1>& L_A)
        : vari(0.0),
          M_(A.rows()),
          variRefA_(ChainableStack::memalloc_.alloc_array<vari*>
                    (A.rows() * (A.rows() + 1) / 2)),
          variRefL_(ChainableStack::memalloc_.alloc_array<vari*>
                    (A.rows() * (A.rows() + 1) / 2)) {
            size_t pos = 0;
            block_size_ = M_/8;
            block_size_ = (block_size_/16)*16;
            block_size_ = (std::min)((std::max)(block_size_, 8), 128);
            for (size_type j = 0; j < M_; ++j) {
              for (size_type i = j; i < M_; ++i) {
                variRefA_[pos] = A.coeffRef(i, j).vi_;
                variRefL_[pos] = new vari(L_A.coeffRef(i, j), false);
                ++pos;
              }
            }
          }

      inline void symbolic_rev(Block_& L,
                               Block_& Lbar,
                               int size) {
        using Eigen::Lower;
        using Eigen::Upper;
        using Eigen::StrictlyUpper;
        L.transposeInPlace();
        Lbar = (L * Lbar.triangularView<Lower>()).eval();
        Lbar.triangularView<StrictlyUpper>()
          = Lbar.adjoint().triangularView<StrictlyUpper>();
        L.triangularView<Upper>().solveInPlace(Lbar);
        L.triangularView<Upper>().solveInPlace(Lbar.transpose());
      }

      /**
       * Reverse mode differentiation
       * algorithm refernce:
       *
       * Iain Murray: Differentiation of
       * the Cholesky decomposition, 2016.
       *
       */
      virtual void chain() {
        using Eigen::MatrixXd;
        using Eigen::Lower;
        using Eigen::Block;
        using Eigen::Upper;
        using Eigen::StrictlyUpper;
        MatrixXd Lbar(M_, M_);
        MatrixXd L(M_, M_);

        Lbar.setZero();
        L.setZero();
        size_t pos = 0;
        for (size_type j = 0; j < M_; ++j) {
          for (size_type i = j; i < M_; ++i) {
            Lbar.coeffRef(i, j) = variRefL_[pos]->adj_;
            L.coeffRef(i, j) = variRefL_[pos]->val_;
            ++pos;
          }
        }

        for (int k = M_; k > 0; k -= block_size_) {
          int j = std::max(0, k - block_size_);
          Block_ R = L.block(j, 0, k - j, j);
          Block_ D = L.block(j, j, k - j, k - j);
          Block_ B = L.block(k, 0, M_ - k, j);
          Block_ C = L.block(k, j, M_ - k, k - j);
          Block_ Rbar = Lbar.block(j, 0, k - j, j);
          Block_ Dbar = Lbar.block(j, j, k - j, k - j);
          Block_ Bbar = Lbar.block(k, 0, M_ - k, j);
          Block_ Cbar = Lbar.block(k, j, M_ - k, k - j);
          if (Cbar.size() > 0) {
            Cbar
              = D.transpose().triangularView<Upper>()
              .solve(Cbar.transpose()).transpose();
            Bbar.noalias() -= Cbar * R;
            Dbar.noalias() -= Cbar.transpose() * C;
          }
          symbolic_rev(D, Dbar, D.rows());
          Rbar.noalias() -= Cbar.transpose() * B;
          Rbar.noalias() -= Dbar.selfadjointView<Lower>() * R;
          Dbar.diagonal().array() *= 0.5;
          Dbar.triangularView<StrictlyUpper>().setZero();
        }
        pos = 0;
        for (size_type j = 0; j < M_; ++j)
          for (size_type i = j; i < M_; ++i)
            variRefA_[pos++]->adj_ += Lbar.coeffRef(i, j);
      }
    };

    /**
     * Reverse mode specialization of
     * cholesky decomposition
     *
     * Internally calls llt rather than using
     * cholesky_decompose in order
     * to use selfadjointView<Lower> optimization.
     *
     * TODO(rtrangucci): Use Eigen 3.3 inplace Cholesky
     * when possible
     *
     * Note chainable stack varis are created
     * below in Matrix<var, -1, -1>
     *
     * @param Matrix A
     * @return L cholesky factor of A
     */
    inline Eigen::Matrix<var, -1, -1>
      cholesky_decompose(const Eigen::Matrix<var, -1, -1> &A) {
      check_square("cholesky_decompose", "A", A);
      check_symmetric("cholesky_decompose", "A", A);

      Eigen::Matrix<double, -1, -1> L_A(value_of_rec(A));
      Eigen::LLT<Eigen::MatrixXd> L_factor
        = L_A.selfadjointView<Eigen::Lower>().llt();
      check_pos_definite("cholesky_decompose", "m", L_factor);
      L_A = L_factor.matrixL();

      // Memory allocated in arena.
      cholesky_decompose_v_vari *baseVari
        = new cholesky_decompose_v_vari(A, L_A);
      vari* dummy = new vari(0.0, false);
      Eigen::Matrix<var, -1, -1> L(A.rows(), A.cols());
      size_t pos = 0;
      for (size_type j = 0; j < L.cols(); ++j) {
        for (size_type i = j; i < L.cols(); ++i) {
          L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos++];
        }
        for (size_type k = 0; k < j; ++k)
          L.coeffRef(k, j).vi_ = dummy;
      }
      return L;
    }
  }
}
#endif
<|endoftext|>