<commit_before>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

#include <kuniqueapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <dcopclient.h>
#include <kcrash.h>

#include "kmkernel.h" //control center

#undef Status // stupid X headers
#include "kmailIface_stub.h" // to call control center of master kmail

#include <kaboutdata.h>

#include "kmversion.h"

// OLD about text.  This is horrbly outdated.
/*const char* aboutText =
    "KMail [" KMAIL_VERSION "] by\n\n"
    "Stefan Taferner <taferner@kde.org>,\n"
    "Markus Wbben <markus.wuebben@kde.org>\n\n"
    "based on the work of:\n"
    "Lynx <lynx@topaz.hknet.com>,\n"
    "Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
    "and the above authors.\n\n"
    "This program is covered by the GPL.\n\n"
    "Please send bugreports to taferner@kde.org";
*/

static KCmdLineOptions kmoptions[] =
{
  { "s", 0 , 0 },
  { "subject <subject>",	I18N_NOOP("Set subject of msg."), 0 },
  { "c", 0 , 0 },
  { "cc <address>",		I18N_NOOP("Send CC: to 'address'."), 0 },
  { "b", 0 , 0 },
  { "bcc <address>",		I18N_NOOP("Send BCC: to 'addres'."), 0 },
  { "h", 0 , 0 },
  { "header <header>",		I18N_NOOP("Add 'header' to msg."), 0 },
  { "msg <file>",		I18N_NOOP("Read msg-body from 'file'."), 0 },
  { "body <text>",              I18N_NOOP("Set body of msg."), 0 },
  { "attach <url>",             I18N_NOOP("Add an attachment to the mail, this can be repeated"), 0 },
  { "check",			I18N_NOOP("Check for new mail only."), 0 },
  { "composer",			I18N_NOOP("Open only composer window."), 0 },
  { "+[address]",		I18N_NOOP("Send msg to 'address'."), 0 },
//  { "+[file]",                  I18N_NOOP("Show message from file 'file'."), 0 },
  { 0, 0, 0}
};

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

extern "C" {

static void setSignalHandler(void (*handler)(int));

// Crash recovery signal handler
static void signalHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  ::exit(-1); //
}

// Crash recovery signal handler
static void crashHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  // Return to DrKonqi.
}
//-----------------------------------------------------------------------------

static void setSignalHandler(void (*handler)(int))
{
  signal(SIGKILL, handler);
  signal(SIGTERM, handler);
  signal(SIGHUP,  handler);
  KCrash::setEmergencySaveFunction(crashHandler);
}

}
//-----------------------------------------------------------------------------

class KMailApplication : public KUniqueApplication
{
public:
  KMailApplication() : KUniqueApplication() { };

  virtual int newInstance();

  void commitData(QSessionManager& sm) {
    kernel->notClosedByUser();
    KApplication::commitData( sm );
  }
};

int KMailApplication::newInstance()
{
  QString to, cc, bcc, subj, body;
  KURL messageFile = QString::null;
  KURL::List attachURLs;
  bool mailto = false;
  bool checkMail = false;
  //bool viewOnly = false;

  // process args:
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if (args->getOption("subject"))
  {
     mailto = true;
     subj = QString::fromLocal8Bit(args->getOption("subject"));
  }

  if (args->getOption("cc"))
  {
     mailto = true;
     cc = QString::fromLocal8Bit(args->getOption("cc"));
  }

  if (args->getOption("bcc"))
  {
     mailto = true;
     bcc = QString::fromLocal8Bit(args->getOption("bcc"));
  }

  if (args->getOption("msg"))
  {
     mailto = true;
     messageFile = QString::fromLocal8Bit(args->getOption("msg"));
  }

  if (args->getOption("body"))
  {
     mailto = true;
     body = QString::fromLocal8Bit(args->getOption("body"));
  }

  QCStringList attachList = args->getOptionList("attach");
  if (!attachList.isEmpty())
  {
     mailto = true;
     for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )
         attachURLs += KURL( QString::fromLocal8Bit( *it ) );
  }

  if (args->isSet("composer"))
    mailto = true;

  if (args->isSet("check"))
    checkMail = true;

  for(int i= 0; i < args->count(); i++)
  {
    if (!to.isEmpty())
      to += ", ";
     if (strncasecmp(args->arg(i),"mailto:",7)==0)
       to += args->arg(i);
     else
       to += args->arg(i);
     mailto = true;
  }

  args->clear();

  kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);
  return 0;
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".

  KAboutData about("kmail", I18N_NOOP("KMail"),
                   KMAIL_VERSION,
		   I18N_NOOP("The KDE E-Mail client."),
		   KAboutData::License_GPL,
                   I18N_NOOP("(c) 1997-2001, The KMail developers"),
		   0,
		   "http://kmail.kde.org");
  about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "michael@haeckel.net" );
  about.addAuthor( "Don Sanders", I18N_NOOP("Current maintainer"), "sanders@kde.org" );
  about.addAuthor( "Stefan Taferner ", 0, "taferner@kde.org" );
  about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "daniel.naber@t-online.de" );
  about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "a.gungl@gmx.de" );
  about.addAuthor( "Toyohiro Asukai", 0, "toyohiro@ksmplus.com" );
  about.addAuthor( "Waldo Bastian", 0, "bastian@kde.org" );
  about.addAuthor( "Steven Brown", 0, "swbrown@ucsd.edu" );
  about.addAuthor( "Cristi Dumitrescu", 0, "cristid@chip.ro" );
  about.addAuthor( "Philippe Fremy", 0, "pfremy@chez.com" );
  about.addAuthor( "Kurt Granroth", 0, "granroth@kde.org" );
  about.addAuthor( "Igor Janssen", 0, "rm@linux.ru.net" );
  about.addAuthor( "Matt Johnston", 0, "matt@caifex.org" );
  about.addAuthor( "Christer Kaivo-oja", 0, "whizkid@telia.com" );
  about.addAuthor( "Ingo Kl\303\266cker", 0, "ingo.kloecker@epost.de" );
  about.addAuthor( "Lars Knoll", 0, "knoll@kde.org" );
  about.addAuthor( "J. Nick Koston", 0, "bdraco@darkorb.net" );
  about.addAuthor( "Stephan Kulow", 0, "coolo@kde.org" );
  about.addAuthor( "Guillaume Laurent", 0, "glaurent@telegraph-road.org" );
  about.addAuthor( "Sam Magnuson", 0, "sam@trolltech.com" );
  about.addAuthor( "Laurent Montel", 0, "lmontel@mandrakesoft.com" );
  about.addAuthor( "Marc Mutz", 0, "mutz@kde.org" );
  about.addAuthor( "Matt Newell", 0, "newellm@proaxis.com" );
  about.addAuthor( "Denis Perchine", 0, "dyp@perchine.com" );
  about.addAuthor( "Carsten Pfeiffer", 0, "pfeiffer@kde.org" );
  about.addAuthor( "Sven Radej", 0, "radej@kde.org" );
  about.addAuthor( "Mark Roberts", 0, "mark@taurine.demon.co.uk" );
  about.addAuthor( "Wolfgang Rohdewald", 0, "WRohdewald@dplanet.ch" );
  about.addAuthor( "Espen Sand", 0, "espen@kde.org" );
  about.addAuthor( "George Staikos", 0, "staikos@kde.org" );
  about.addAuthor( "Jason Stephenson", 0, "panda@mis.net" );
  about.addAuthor( "Jacek Stolarczyk", 0, "jacek@mer.chemia.polsl.gliwice.pl" );
  about.addAuthor( "Roberto S. Teixeira", 0, "maragato@kde.org" );
  about.addAuthor( "Mario Weilguni", 0, "mweilguni@sime.com" );
  about.addAuthor( "Wynn Wilkes", 0, "wynnw@calderasystems.com" );
  about.addAuthor( "Robert D. Williams", 0, "rwilliams@kde.org" );
  about.addAuthor( "Markus Wuebben", 0, "markus.wuebben@kde.org" );
  about.addAuthor( "Karl-Heinz Zimmer", 0, "khz@kde.org" );

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options

  if (!KMailApplication::start())
     return 0;

  KMailApplication app;
  KGlobal::locale()->insertCatalogue("libkdenetwork");

  kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();
  kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  setSignalHandler(signalHandler);

  kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
  // Go!
  int ret = kapp->exec();

  // clean up
  kmailKernel.cleanup();
  return ret;
}

<commit_msg>"Corrected typographical errors"<commit_after>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

#include <kuniqueapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <dcopclient.h>
#include <kcrash.h>

#include "kmkernel.h" //control center

#undef Status // stupid X headers
#include "kmailIface_stub.h" // to call control center of master kmail

#include <kaboutdata.h>

#include "kmversion.h"

// OLD about text.  This is horrbly outdated.
/*const char* aboutText =
    "KMail [" KMAIL_VERSION "] by\n\n"
    "Stefan Taferner <taferner@kde.org>,\n"
    "Markus Wbben <markus.wuebben@kde.org>\n\n"
    "based on the work of:\n"
    "Lynx <lynx@topaz.hknet.com>,\n"
    "Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
    "and the above authors.\n\n"
    "This program is covered by the GPL.\n\n"
    "Please send bugreports to taferner@kde.org";
*/

static KCmdLineOptions kmoptions[] =
{
  { "s", 0 , 0 },
  { "subject <subject>",	I18N_NOOP("Set subject of msg."), 0 },
  { "c", 0 , 0 },
  { "cc <address>",		I18N_NOOP("Send CC: to 'address'."), 0 },
  { "b", 0 , 0 },
  { "bcc <address>",		I18N_NOOP("Send BCC: to 'addres'."), 0 },
  { "h", 0 , 0 },
  { "header <header>",		I18N_NOOP("Add 'header' to msg."), 0 },
  { "msg <file>",		I18N_NOOP("Read msg-body from 'file'."), 0 },
  { "body <text>",              I18N_NOOP("Set body of msg."), 0 },
  { "attach <url>",             I18N_NOOP("Add an attachment to the mail, this can be repeated"), 0 },
  { "check",			I18N_NOOP("Check for new mail only."), 0 },
  { "composer",			I18N_NOOP("Open only composer window."), 0 },
  { "+[address]",		I18N_NOOP("Send msg to 'address'."), 0 },
//  { "+[file]",                  I18N_NOOP("Show message from file 'file'."), 0 },
  { 0, 0, 0}
};

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

extern "C" {

static void setSignalHandler(void (*handler)(int));

// Crash recovery signal handler
static void signalHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  ::exit(-1); //
}

// Crash recovery signal handler
static void crashHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  // Return to DrKonqi.
}
//-----------------------------------------------------------------------------

static void setSignalHandler(void (*handler)(int))
{
  signal(SIGKILL, handler);
  signal(SIGTERM, handler);
  signal(SIGHUP,  handler);
  KCrash::setEmergencySaveFunction(crashHandler);
}

}
//-----------------------------------------------------------------------------

class KMailApplication : public KUniqueApplication
{
public:
  KMailApplication() : KUniqueApplication() { };

  virtual int newInstance();

  void commitData(QSessionManager& sm) {
    kernel->notClosedByUser();
    KApplication::commitData( sm );
  }
};

int KMailApplication::newInstance()
{
  QString to, cc, bcc, subj, body;
  KURL messageFile = QString::null;
  KURL::List attachURLs;
  bool mailto = false;
  bool checkMail = false;
  //bool viewOnly = false;

  // process args:
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if (args->getOption("subject"))
  {
     mailto = true;
     subj = QString::fromLocal8Bit(args->getOption("subject"));
  }

  if (args->getOption("cc"))
  {
     mailto = true;
     cc = QString::fromLocal8Bit(args->getOption("cc"));
  }

  if (args->getOption("bcc"))
  {
     mailto = true;
     bcc = QString::fromLocal8Bit(args->getOption("bcc"));
  }

  if (args->getOption("msg"))
  {
     mailto = true;
     messageFile = QString::fromLocal8Bit(args->getOption("msg"));
  }

  if (args->getOption("body"))
  {
     mailto = true;
     body = QString::fromLocal8Bit(args->getOption("body"));
  }

  QCStringList attachList = args->getOptionList("attach");
  if (!attachList.isEmpty())
  {
     mailto = true;
     for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )
         attachURLs += KURL( QString::fromLocal8Bit( *it ) );
  }

  if (args->isSet("composer"))
    mailto = true;

  if (args->isSet("check"))
    checkMail = true;

  for(int i= 0; i < args->count(); i++)
  {
    if (!to.isEmpty())
      to += ", ";
     if (strncasecmp(args->arg(i),"mailto:",7)==0)
       to += args->arg(i);
     else
       to += args->arg(i);
     mailto = true;
  }

  args->clear();

  kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);
  return 0;
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".

  KAboutData about("kmail", I18N_NOOP("KMail"),
                   KMAIL_VERSION,
		   I18N_NOOP("The KDE Email client."),
		   KAboutData::License_GPL,
                   I18N_NOOP("(c) 1997-2001, The KMail developers"),
		   0,
		   "http://kmail.kde.org");
  about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "michael@haeckel.net" );
  about.addAuthor( "Don Sanders", I18N_NOOP("Current maintainer"), "sanders@kde.org" );
  about.addAuthor( "Stefan Taferner ", 0, "taferner@kde.org" );
  about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "daniel.naber@t-online.de" );
  about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "a.gungl@gmx.de" );
  about.addAuthor( "Toyohiro Asukai", 0, "toyohiro@ksmplus.com" );
  about.addAuthor( "Waldo Bastian", 0, "bastian@kde.org" );
  about.addAuthor( "Steven Brown", 0, "swbrown@ucsd.edu" );
  about.addAuthor( "Cristi Dumitrescu", 0, "cristid@chip.ro" );
  about.addAuthor( "Philippe Fremy", 0, "pfremy@chez.com" );
  about.addAuthor( "Kurt Granroth", 0, "granroth@kde.org" );
  about.addAuthor( "Igor Janssen", 0, "rm@linux.ru.net" );
  about.addAuthor( "Matt Johnston", 0, "matt@caifex.org" );
  about.addAuthor( "Christer Kaivo-oja", 0, "whizkid@telia.com" );
  about.addAuthor( "Ingo Kl\303\266cker", 0, "ingo.kloecker@epost.de" );
  about.addAuthor( "Lars Knoll", 0, "knoll@kde.org" );
  about.addAuthor( "J. Nick Koston", 0, "bdraco@darkorb.net" );
  about.addAuthor( "Stephan Kulow", 0, "coolo@kde.org" );
  about.addAuthor( "Guillaume Laurent", 0, "glaurent@telegraph-road.org" );
  about.addAuthor( "Sam Magnuson", 0, "sam@trolltech.com" );
  about.addAuthor( "Laurent Montel", 0, "lmontel@mandrakesoft.com" );
  about.addAuthor( "Marc Mutz", 0, "mutz@kde.org" );
  about.addAuthor( "Matt Newell", 0, "newellm@proaxis.com" );
  about.addAuthor( "Denis Perchine", 0, "dyp@perchine.com" );
  about.addAuthor( "Carsten Pfeiffer", 0, "pfeiffer@kde.org" );
  about.addAuthor( "Sven Radej", 0, "radej@kde.org" );
  about.addAuthor( "Mark Roberts", 0, "mark@taurine.demon.co.uk" );
  about.addAuthor( "Wolfgang Rohdewald", 0, "WRohdewald@dplanet.ch" );
  about.addAuthor( "Espen Sand", 0, "espen@kde.org" );
  about.addAuthor( "George Staikos", 0, "staikos@kde.org" );
  about.addAuthor( "Jason Stephenson", 0, "panda@mis.net" );
  about.addAuthor( "Jacek Stolarczyk", 0, "jacek@mer.chemia.polsl.gliwice.pl" );
  about.addAuthor( "Roberto S. Teixeira", 0, "maragato@kde.org" );
  about.addAuthor( "Mario Weilguni", 0, "mweilguni@sime.com" );
  about.addAuthor( "Wynn Wilkes", 0, "wynnw@calderasystems.com" );
  about.addAuthor( "Robert D. Williams", 0, "rwilliams@kde.org" );
  about.addAuthor( "Markus Wuebben", 0, "markus.wuebben@kde.org" );
  about.addAuthor( "Karl-Heinz Zimmer", 0, "khz@kde.org" );

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options

  if (!KMailApplication::start())
     return 0;

  KMailApplication app;
  KGlobal::locale()->insertCatalogue("libkdenetwork");

  kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();
  kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  setSignalHandler(signalHandler);

  kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
  // Go!
  int ret = kapp->exec();

  // clean up
  kmailKernel.cleanup();
  return ret;
}

<|endoftext|>


<commit_before>/***************************************************************************
 *  The Kernel-Machine Library                                             *
 *  Copyright (C) 2004, 2005 by Rutger W. ter Borg                         *
 *                                                                         *
 *  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 2         *
 *  of the License, or (at your option) 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 General Public License for more details.                           *
 *                                                                         *
 *  You should have received a copy of the GNU General Public License      *
 *  along with this program; if not, write to the Free Software            *
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307  *
 ***************************************************************************/

#ifndef LINEAR_HPP
#define LINEAR_HPP

#include <boost/mpl/arithmetic.hpp>
#include <boost/mpl/divides.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/math/is_even.hpp>
#include <boost/numeric/bindings/atlas/cblas.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/value_type.hpp>
#include <boost/range/size.hpp>
#include <boost/type_traits/is_scalar.hpp>

#include <kml/power_value.hpp>
#include <numeric>

namespace atlas = boost::numeric::bindings::atlas;
namespace mpl = boost::mpl;

/*!
Linear kernel

Template metaprogramming is used to make one generic function work on both scalar and
vector types.

\todo
- ensure the atlas-specific implementation is not deployed on non-supported types

*/

namespace kml { namespace detail {

class scalar_inner_prod {
public:
    template<typename T>
    static T compute( T const &x, T const &y ) {
        return (x * y);
    }
};

class vector_inner_prod {
public:
    template<typename T>
    static typename boost::range_value<T>::type compute( T const &u, T const &v ) {
#ifdef NO_ATLAS
        typedef typename boost::range_value<T>::type value_type;
        return std::inner_product( boost::begin(u), boost::end(u), boost::begin(v),
                                   static_cast<value_type>(0) );
#else
        return atlas::dot( u, v );
#endif
    }
};

template<int N>
class power_even {
public:
	template<typename T>
	static typename boost::range_value<T>::type compute( T const &x ) {
		return std::pow( inner_product(x,x), N>>1 );
	}
};

template<int N>
class power_uneven {
public:
	template<typename T>
	static T compute( T const &x ) {
		return power_even<N>::compute(x) * x;
	}
};

} // namespace detail

/*!
\brief Linear kernel
\param T defines the underlying data type

The linear kernel is the basic Eucledian inner product.

\todo Remove the second template parameter

*/

template<typename T>
struct linear: public std::binary_function<T,T,typename input_value<T>::type> {
    typedef linear<T> type;
    typedef typename input_value<T>::type scalar_type;

    /*! Construct an uninitialised linear kernel */
    linear() {}

    inline
    scalar_type operator()( T const &u, T const &v ) const {
    		    return mpl::if_<boost::is_scalar<T>,
             				detail::scalar_inner_prod,
           				detail::vector_inner_prod >::type::compute( u, v );
    }

    friend std::ostream& operator<<(std::ostream &os, type const &) {
	os << "Linear kernel" << std::endl;
	return os;
    }

};

template<class T, int N>
struct power_return_type: mpl::eval_if<
   mpl::is_even< mpl::int_<N> >,
   boost::range_value<T>,
   mpl::identity<T> > {};

template<typename Vector, int N>
typename power_return_type<Vector,N>::type power( Vector const &x ) {
	return mpl::if_<
		mpl::is_even< mpl::int_<N> >,
		detail::power_even<N>,
		detail::power_uneven<N> >::type::compute( x );
}

} // namespace kml

#endif

<commit_msg>Improved the linear kernel; it is now CopyConstructable and Assignable<commit_after>/***************************************************************************
 *  The Kernel-Machine Library                                             *
 *  Copyright (C) 2004, 2005 by Rutger W. ter Borg                         *
 *                                                                         *
 *  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 2         *
 *  of the License, or (at your option) 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 General Public License for more details.                           *
 *                                                                         *
 *  You should have received a copy of the GNU General Public License      *
 *  along with this program; if not, write to the Free Software            *
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307  *
 ***************************************************************************/

#ifndef LINEAR_HPP
#define LINEAR_HPP

#include <boost/mpl/arithmetic.hpp>
#include <boost/mpl/divides.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/math/is_even.hpp>
#include <boost/numeric/bindings/atlas/cblas.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/value_type.hpp>
#include <boost/range/size.hpp>
#include <boost/type_traits/is_scalar.hpp>

#include <kml/power_value.hpp>
#include <numeric>

namespace atlas = boost::numeric::bindings::atlas;
namespace mpl = boost::mpl;

/*!
Linear kernel

Template metaprogramming is used to make one generic function work on both scalar and
vector types.

\todo
- ensure the atlas-specific implementation is not deployed on non-supported types

*/

namespace kml { namespace detail {

class scalar_inner_prod {
public:
    template<typename T>
    static T compute( T const &x, T const &y ) {
        return (x * y);
    }
};

class vector_inner_prod {
public:
    template<typename T>
    static typename boost::range_value<T>::type compute( T const &u, T const &v ) {
#ifdef NO_ATLAS
        typedef typename boost::range_value<T>::type value_type;
        return std::inner_product( boost::begin(u), boost::end(u), boost::begin(v),
                                   static_cast<value_type>(0) );
#else
        return atlas::dot( u, v );
#endif
    }
};

template<int N>
class power_even {
public:
	template<typename T>
	static typename boost::range_value<T>::type compute( T const &x ) {
		return std::pow( inner_product(x,x), N>>1 );
	}
};

template<int N>
class power_uneven {
public:
	template<typename T>
	static T compute( T const &x ) {
		return power_even<N>::compute(x) * x;
	}
};

} // namespace detail

/*!
\brief Linear kernel
\param T defines the underlying data type

The linear kernel is the basic Eucledian inner product.

\todo Remove the second template parameter

*/

template<typename T>
struct linear: public std::binary_function<T,T,typename input_value<T>::type> {
    typedef linear<T> type;
    typedef typename input_value<T>::type scalar_type;

    /*! Construct an uninitialised linear kernel */
    linear() {}

    /*! Refinement of CopyConstructable */
    linear( type const &other ) {}

    /*! Refinement of Assignable */
    type &operator=( type const &other ) {
	return *this;
    }

    /*! Kernel constructor by providing TokenIterators */
   template<typename TokenIterator>
   linear( TokenIterator const begin, TokenIterator const end ) {}

    inline
    scalar_type operator()( T const &u, T const &v ) const {
    		    return mpl::if_<boost::is_scalar<T>,
             				detail::scalar_inner_prod,
           				detail::vector_inner_prod >::type::compute( u, v );
    }

    friend std::ostream& operator<<(std::ostream &os, type const &) {
	os << "Linear kernel (u^T * v)" << std::endl;
	return os;
    }

};

template<class T, int N>
struct power_return_type: mpl::eval_if<
   mpl::is_even< mpl::int_<N> >,
   boost::range_value<T>,
   mpl::identity<T> > {};

template<typename Vector, int N>
typename power_return_type<Vector,N>::type power( Vector const &x ) {
	return mpl::if_<
		mpl::is_even< mpl::int_<N> >,
		detail::power_even<N>,
		detail::power_uneven<N> >::type::compute( x );
}

} // namespace kml

#endif

<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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 "libtorrent/pch.hpp"

#include <vector>
#include <cctype>

#include <boost/bind.hpp>

#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#include "libtorrent/aux_/session_impl.hpp"

using boost::tuples::make_tuple;
using boost::tuples::tuple;

namespace
{
	enum
	{
		minimum_tracker_response_length = 3,
		http_buffer_size = 2048
	};

}

namespace libtorrent
{
	timeout_handler::timeout_handler(io_service& ios)
		: m_start_time(time_now_hires())
		, m_read_time(m_start_time)
		, m_timeout(ios)
		, m_completion_timeout(0)
		, m_read_timeout(0)
		, m_abort(false)
	{}

	void timeout_handler::set_timeout(int completion_timeout, int read_timeout)
	{
		m_completion_timeout = completion_timeout;
		m_read_timeout = read_timeout;
		m_start_time = m_read_time = time_now_hires();

		if (m_abort) return;

		int timeout = (std::min)(
			m_read_timeout, (std::min)(m_completion_timeout, m_read_timeout));
		error_code ec;
		m_timeout.expires_at(m_read_time + seconds(timeout), ec);
		m_timeout.async_wait(boost::bind(
			&timeout_handler::timeout_callback, self(), _1));
	}

	void timeout_handler::restart_read_timeout()
	{
		m_read_time = time_now_hires();
	}

	void timeout_handler::cancel()
	{
		m_abort = true;
		m_completion_timeout = 0;
		error_code ec;
		m_timeout.cancel(ec);
	}

	void timeout_handler::timeout_callback(error_code const& error)
	{
		if (error) return;
		if (m_completion_timeout == 0) return;

		ptime now = time_now_hires();
		time_duration receive_timeout = now - m_read_time;
		time_duration completion_timeout = now - m_start_time;

		if (m_read_timeout
			<= total_seconds(receive_timeout)
			|| m_completion_timeout
			<= total_seconds(completion_timeout))
		{
			on_timeout();
			return;
		}

		if (m_abort) return;

		int timeout = (std::min)(
			m_read_timeout, (std::min)(m_completion_timeout, m_read_timeout));
		error_code ec;
		m_timeout.expires_at(m_read_time + seconds(timeout), ec);
		m_timeout.async_wait(
			boost::bind(&timeout_handler::timeout_callback, self(), _1));
	}

	tracker_connection::tracker_connection(
		tracker_manager& man
		, tracker_request const& req
		, io_service& ios
		, boost::weak_ptr<request_callback> r)
		: timeout_handler(ios)
		, m_requester(r)
		, m_man(man)
		, m_req(req)
	{}

	boost::shared_ptr<request_callback> tracker_connection::requester()
	{
		return m_requester.lock();
	}

	void tracker_connection::fail(error_code const& ec, int code
		, char const* msg, int interval, int min_interval)
	{
		boost::shared_ptr<request_callback> cb = requester();
		if (cb) cb->tracker_request_error(m_req, code, ec, msg
			, interval == 0 ? min_interval : interval);
		close();
	}

	void tracker_connection::sent_bytes(int bytes)
	{
		m_man.sent_bytes(bytes);
	}

	void tracker_connection::received_bytes(int bytes)
	{
		m_man.received_bytes(bytes);
	}

	void tracker_connection::close()
	{
		cancel();
		m_man.remove_request(this);
	}

	tracker_manager::~tracker_manager()
	{
		TORRENT_ASSERT(m_abort);
		abort_all_requests(true);
	}

	void tracker_manager::sent_bytes(int bytes)
	{
//		mutex::scoped_lock l(m_ses.m_mutex);
		m_ses.m_stat.sent_tracker_bytes(bytes);
	}

	void tracker_manager::received_bytes(int bytes)
	{
		mutex::scoped_lock l(m_ses.m_mutex);
		m_ses.m_stat.received_tracker_bytes(bytes);
	}

	void tracker_manager::remove_request(tracker_connection const* c)
	{
		mutex_t::scoped_lock l(m_mutex);

		tracker_connections_t::iterator i = std::find(m_connections.begin()
			, m_connections.end(), boost::intrusive_ptr<const tracker_connection>(c));
		if (i == m_connections.end()) return;

		m_connections.erase(i);
	}

	void tracker_manager::queue_request(
		io_service& ios
		, connection_queue& cc
		, tracker_request req
		, std::string const& auth
		, boost::weak_ptr<request_callback> c)
	{
		mutex_t::scoped_lock l(m_mutex);
		TORRENT_ASSERT(req.num_want >= 0);
		TORRENT_ASSERT(!m_abort);
		if (m_abort) return;
		if (req.event == tracker_request::stopped)
			req.num_want = 0;

		TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped);
		if (m_abort && req.event != tracker_request::stopped)
			return;

		std::string protocol = req.url.substr(0, req.url.find(':'));

		boost::intrusive_ptr<tracker_connection> con;

#ifdef TORRENT_USE_OPENSSL
		if (protocol == "http" || protocol == "https")
#else
		if (protocol == "http")
#endif
		{
			con = new http_tracker_connection(
				ios, cc, *this, req, c
				, m_ses, m_proxy, auth
#if TORRENT_USE_I2P
				, &m_ses.m_i2p_conn
#endif
				);
		}
		else if (protocol == "udp")
		{
			con = new udp_tracker_connection(
				ios, cc, *this, req , c, m_ses
				, m_proxy);
		}
		else
		{
			// we need to post the error to avoid deadlock
			if (boost::shared_ptr<request_callback> r = c.lock())
				ios.post(boost::bind(&request_callback::tracker_request_error, r, req
					, -1, error_code(errors::unsupported_url_protocol)
					, "", 0));
			return;
		}

		m_connections.push_back(con);

		boost::shared_ptr<request_callback> cb = con->requester();
		if (cb) cb->m_manager = this;
		con->start();
	}

	bool tracker_manager::incoming_udp(error_code const& e
		, udp::endpoint const& ep, char const* buf, int size)
	{
		for (tracker_connections_t::iterator i = m_connections.begin()
			, end(m_connections.end()); i != end; ++i)
		{
			if ((*i)->on_receive(e, ep, buf, size)) return true;
		}
		return false;
	}

	void tracker_manager::abort_all_requests(bool all)
	{
		// removes all connections from m_connections
		// except 'event=stopped'-requests
		mutex_t::scoped_lock l(m_mutex);

		m_abort = true;
		tracker_connections_t close_connections;

		for (tracker_connections_t::iterator i = m_connections.begin()
			, end(m_connections.end()); i != end; ++i)
		{
			intrusive_ptr<tracker_connection> c = *i;
			tracker_request const& req = c->tracker_req();
			if (req.event == tracker_request::stopped && !all)
				continue;

			close_connections.push_back(c);

#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
			boost::shared_ptr<request_callback> rc = c->requester();
			if (rc) rc->debug_log("aborting: " + req.url);
#endif
		}
		l.unlock();

		for (tracker_connections_t::iterator i = close_connections.begin()
			, end(close_connections.end()); i != end; ++i)
		{
			(*i)->close();
		}
	}

	bool tracker_manager::empty() const
	{
		mutex_t::scoped_lock l(m_mutex);
		return m_connections.empty();
	}

	int tracker_manager::num_requests() const
	{
		mutex_t::scoped_lock l(m_mutex);
		return m_connections.size();
	}
}
<commit_msg>fixed iterator bug introduced when merging the udp trackers over to use the main udp socket<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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 "libtorrent/pch.hpp"

#include <vector>
#include <cctype>

#include <boost/bind.hpp>

#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#include "libtorrent/aux_/session_impl.hpp"

using boost::tuples::make_tuple;
using boost::tuples::tuple;

namespace
{
	enum
	{
		minimum_tracker_response_length = 3,
		http_buffer_size = 2048
	};

}

namespace libtorrent
{
	timeout_handler::timeout_handler(io_service& ios)
		: m_start_time(time_now_hires())
		, m_read_time(m_start_time)
		, m_timeout(ios)
		, m_completion_timeout(0)
		, m_read_timeout(0)
		, m_abort(false)
	{}

	void timeout_handler::set_timeout(int completion_timeout, int read_timeout)
	{
		m_completion_timeout = completion_timeout;
		m_read_timeout = read_timeout;
		m_start_time = m_read_time = time_now_hires();

		if (m_abort) return;

		int timeout = (std::min)(
			m_read_timeout, (std::min)(m_completion_timeout, m_read_timeout));
		error_code ec;
		m_timeout.expires_at(m_read_time + seconds(timeout), ec);
		m_timeout.async_wait(boost::bind(
			&timeout_handler::timeout_callback, self(), _1));
	}

	void timeout_handler::restart_read_timeout()
	{
		m_read_time = time_now_hires();
	}

	void timeout_handler::cancel()
	{
		m_abort = true;
		m_completion_timeout = 0;
		error_code ec;
		m_timeout.cancel(ec);
	}

	void timeout_handler::timeout_callback(error_code const& error)
	{
		if (error) return;
		if (m_completion_timeout == 0) return;

		ptime now = time_now_hires();
		time_duration receive_timeout = now - m_read_time;
		time_duration completion_timeout = now - m_start_time;

		if (m_read_timeout
			<= total_seconds(receive_timeout)
			|| m_completion_timeout
			<= total_seconds(completion_timeout))
		{
			on_timeout();
			return;
		}

		if (m_abort) return;

		int timeout = (std::min)(
			m_read_timeout, (std::min)(m_completion_timeout, m_read_timeout));
		error_code ec;
		m_timeout.expires_at(m_read_time + seconds(timeout), ec);
		m_timeout.async_wait(
			boost::bind(&timeout_handler::timeout_callback, self(), _1));
	}

	tracker_connection::tracker_connection(
		tracker_manager& man
		, tracker_request const& req
		, io_service& ios
		, boost::weak_ptr<request_callback> r)
		: timeout_handler(ios)
		, m_requester(r)
		, m_man(man)
		, m_req(req)
	{}

	boost::shared_ptr<request_callback> tracker_connection::requester()
	{
		return m_requester.lock();
	}

	void tracker_connection::fail(error_code const& ec, int code
		, char const* msg, int interval, int min_interval)
	{
		boost::shared_ptr<request_callback> cb = requester();
		if (cb) cb->tracker_request_error(m_req, code, ec, msg
			, interval == 0 ? min_interval : interval);
		close();
	}

	void tracker_connection::sent_bytes(int bytes)
	{
		m_man.sent_bytes(bytes);
	}

	void tracker_connection::received_bytes(int bytes)
	{
		m_man.received_bytes(bytes);
	}

	void tracker_connection::close()
	{
		cancel();
		m_man.remove_request(this);
	}

	tracker_manager::~tracker_manager()
	{
		TORRENT_ASSERT(m_abort);
		abort_all_requests(true);
	}

	void tracker_manager::sent_bytes(int bytes)
	{
//		mutex::scoped_lock l(m_ses.m_mutex);
		m_ses.m_stat.sent_tracker_bytes(bytes);
	}

	void tracker_manager::received_bytes(int bytes)
	{
		mutex::scoped_lock l(m_ses.m_mutex);
		m_ses.m_stat.received_tracker_bytes(bytes);
	}

	void tracker_manager::remove_request(tracker_connection const* c)
	{
		mutex_t::scoped_lock l(m_mutex);

		tracker_connections_t::iterator i = std::find(m_connections.begin()
			, m_connections.end(), boost::intrusive_ptr<const tracker_connection>(c));
		if (i == m_connections.end()) return;

		m_connections.erase(i);
	}

	void tracker_manager::queue_request(
		io_service& ios
		, connection_queue& cc
		, tracker_request req
		, std::string const& auth
		, boost::weak_ptr<request_callback> c)
	{
		mutex_t::scoped_lock l(m_mutex);
		TORRENT_ASSERT(req.num_want >= 0);
		TORRENT_ASSERT(!m_abort);
		if (m_abort) return;
		if (req.event == tracker_request::stopped)
			req.num_want = 0;

		TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped);
		if (m_abort && req.event != tracker_request::stopped)
			return;

		std::string protocol = req.url.substr(0, req.url.find(':'));

		boost::intrusive_ptr<tracker_connection> con;

#ifdef TORRENT_USE_OPENSSL
		if (protocol == "http" || protocol == "https")
#else
		if (protocol == "http")
#endif
		{
			con = new http_tracker_connection(
				ios, cc, *this, req, c
				, m_ses, m_proxy, auth
#if TORRENT_USE_I2P
				, &m_ses.m_i2p_conn
#endif
				);
		}
		else if (protocol == "udp")
		{
			con = new udp_tracker_connection(
				ios, cc, *this, req , c, m_ses
				, m_proxy);
		}
		else
		{
			// we need to post the error to avoid deadlock
			if (boost::shared_ptr<request_callback> r = c.lock())
				ios.post(boost::bind(&request_callback::tracker_request_error, r, req
					, -1, error_code(errors::unsupported_url_protocol)
					, "", 0));
			return;
		}

		m_connections.push_back(con);

		boost::shared_ptr<request_callback> cb = con->requester();
		if (cb) cb->m_manager = this;
		con->start();
	}

	bool tracker_manager::incoming_udp(error_code const& e
		, udp::endpoint const& ep, char const* buf, int size)
	{
		for (tracker_connections_t::iterator i = m_connections.begin();
			i != m_connections.end();)
		{
			boost::intrusive_ptr<tracker_connection> p = *i;
			++i;
			// on_receive() may remove the tracker connection from the list
			if (p->on_receive(e, ep, buf, size)) return true;
		}
		return false;
	}

	void tracker_manager::abort_all_requests(bool all)
	{
		// removes all connections from m_connections
		// except 'event=stopped'-requests
		mutex_t::scoped_lock l(m_mutex);

		m_abort = true;
		tracker_connections_t close_connections;

		for (tracker_connections_t::iterator i = m_connections.begin()
			, end(m_connections.end()); i != end; ++i)
		{
			intrusive_ptr<tracker_connection> c = *i;
			tracker_request const& req = c->tracker_req();
			if (req.event == tracker_request::stopped && !all)
				continue;

			close_connections.push_back(c);

#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
			boost::shared_ptr<request_callback> rc = c->requester();
			if (rc) rc->debug_log("aborting: " + req.url);
#endif
		}
		l.unlock();

		for (tracker_connections_t::iterator i = close_connections.begin()
			, end(close_connections.end()); i != end; ++i)
		{
			(*i)->close();
		}
	}

	bool tracker_manager::empty() const
	{
		mutex_t::scoped_lock l(m_mutex);
		return m_connections.empty();
	}

	int tracker_manager::num_requests() const
	{
		mutex_t::scoped_lock l(m_mutex);
		return m_connections.size();
	}
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 1998 by Jorrit Tyberghein
    Camera code written by Ivan Avramovic <ivan@avramovic.com>

    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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "sysdef.h"
#include "qint.h"
#include "csengine/camera.h"
#include "csengine/sector.h"
#include "csengine/world.h"

IMPLEMENT_IBASE (csCamera)
  IMPLEMENTS_INTERFACE (iCamera)
IMPLEMENT_IBASE_END

int csCamera::default_aspect = 0;
float csCamera::default_inv_aspect = 0;

csCamera::csCamera () : csOrthoTransform()
{
  CONSTRUCT_IBASE (NULL);
  mirror = false;
  sector = NULL;
  aspect = default_aspect;
  inv_aspect = default_inv_aspect;
  shift_x = csWorld::frame_width / 2;
  shift_y = csWorld::frame_height / 2;
}

csCamera::csCamera (csCamera* c) : csOrthoTransform (*c)
{
  mirror = c->mirror;
  sector = c->sector;
  aspect = c->aspect;
  inv_aspect = c->inv_aspect;
  shift_x = c->shift_x;
  shift_y = c->shift_y;
}

csCamera::~csCamera ()
{
}

csPolygon3D* csCamera::GetHit (csVector3& v)
{
  return sector->HitBeam (v_o2t, v);
}

void csCamera::MoveWorld (const csVector3& v)
{
  csVector3 new_position = GetOrigin () + v;
  if (sector)
    sector = sector->FollowSegment (*this, new_position, mirror);
  SetOrigin (new_position);
}

void csCamera::RotateWorld (const csVector3& v, float angle)
{
  csVector3 u = v;
  float ca, sa;
  u = csVector3::Unit (u);
  ca = cos (angle);
  sa = sin (angle);

  SetT2O (

   csMatrix3(
         ca+(1-ca)*u.x*u.x, u.x*u.y*(1-ca)-u.z*sa, u.x*u.z*(1-ca)+u.y*sa,
     u.x*u.y*(1-ca)+u.z*sa,     ca+(1-ca)*u.y*u.y, u.y*u.z*(1-ca)-u.x*sa,
     u.x*u.z*(1-ca)-u.y*sa, u.y*u.z*(1-ca)+u.x*sa,     ca+(1-ca)*u.z*u.z)

   * GetT2O () );
}

void csCamera::Rotate (const csVector3& v, float angle)
{
  csVector3 u = v;
  float ca, sa;
  u = csVector3::Unit (u);
  ca = cos (angle);
  sa = sin (angle);

  SetT2O (GetT2O () *

   csMatrix3(
         ca+(1-ca)*u.x*u.x, u.x*u.y*(1-ca)-u.z*sa, u.x*u.z*(1-ca)+u.y*sa,
     u.x*u.y*(1-ca)+u.z*sa,     ca+(1-ca)*u.y*u.y, u.y*u.z*(1-ca)-u.x*sa,
     u.x*u.z*(1-ca)-u.y*sa, u.y*u.z*(1-ca)+u.x*sa,     ca+(1-ca)*u.z*u.z)

   );
}

void csCamera::LookAt (const csVector3& v, const csVector3& up)
{
  csMatrix3 m; /* initialized to be the identity matrix */
  csVector3 w1, w2, w3 = v;
  float r;

  if ( (r=sqrt(v*v)) > SMALL_EPSILON )
  {
   w3 /= r;
   w1 = w3 % up;
   if ( (r=sqrt(w1*w1)) < SMALL_EPSILON )
   {
     w1 = w3 % csVector3(0,0,-1);
     if ( (r=sqrt(w1*w1)) < SMALL_EPSILON )
     {
      w1 = w3 % csVector3(0,-1,0);
      r = sqrt(w1*w1);
     }
   }
   w1 /= r;
   w2 = w3 % w1;

   m.m11 = w1.x;  m.m12 = w2.x;  m.m13 = w3.x;
   m.m21 = w1.y;  m.m22 = w2.y;  m.m23 = w3.y;
   m.m31 = w1.z;  m.m32 = w2.z;  m.m33 = w3.z;
  }

  SetT2O (m);
}

void csCamera::Correct (int n)
{
  csVector3 w1, w2, w3;
  float* vals[4];
  if (n==0) return;

  w3 = m_t2o.Col3();
  vals[0] = &w3.x;  vals[1] = &w3.y;  vals[2] = &w3.z;  vals[4] = NULL;
  Correct (n, vals);  /* perform the snap-to operation on the forward vector */

/* Maybe w3 should be normalized.  Only necessary if there is
   significant roundoff error: */
//  w3 = csVector3::unit(w3);

/* perhaps a snap-to should be performed on one of the other vectors as well */

  w1 = m_t2o.Col2();
  w2 = csVector3::Unit(w3 % w1);
  w1 = w2 % w3;

  SetT2O ( csMatrix3 ( w1.x, w2.x, w3.x,
                             w1.y, w2.y, w3.y,
                             w1.z, w2.z, w3.z ) );
}

void csCamera::Correct (int n, float* vals[])
{
  float r, angle;

  if (vals==NULL) return;
  if (vals[0]==NULL) return;
  if (vals[1]==NULL) return;
  if (vals[2]!=NULL)
  {
   if (*vals[0] < *vals[1])
    { r = *vals[2];  *vals[2] = *vals[0];  *vals[0] = r; }
   else { r = *vals[2];  *vals[2] = *vals[1];  *vals[1] = r; }
  }

  angle = atan2 (*vals[1], *vals[0]);
  angle = (2.*M_PI/n) * QRound(n * angle / (2*M_PI) );
  *vals[1] = sqrt( (*vals[0])*(*vals[0]) + (*vals[1])*(*vals[1]) );
  Correct(n, vals+1);
  r = *vals[1];
  *vals[0] = r*cos(angle);  *vals[1] = r*sin(angle);
}

float csCamera::GetAspect ()
{
  return inv_aspect;
}

float csCamera::GetInvAspect ()
{
  return aspect;
}
<commit_msg>Insure++ Fix<commit_after>/*
    Copyright (C) 1998 by Jorrit Tyberghein
    Camera code written by Ivan Avramovic <ivan@avramovic.com>

    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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "sysdef.h"
#include "qint.h"
#include "csengine/camera.h"
#include "csengine/sector.h"
#include "csengine/world.h"

IMPLEMENT_IBASE (csCamera)
  IMPLEMENTS_INTERFACE (iCamera)
IMPLEMENT_IBASE_END

int csCamera::default_aspect = 0;
float csCamera::default_inv_aspect = 0;

csCamera::csCamera () : csOrthoTransform()
{
  CONSTRUCT_IBASE (NULL);
  mirror = false;
  sector = NULL;
  aspect = default_aspect;
  inv_aspect = default_inv_aspect;
  shift_x = csWorld::frame_width / 2;
  shift_y = csWorld::frame_height / 2;
}

csCamera::csCamera (csCamera* c) : csOrthoTransform (*c)
{
  mirror = c->mirror;
  sector = c->sector;
  aspect = c->aspect;
  inv_aspect = c->inv_aspect;
  shift_x = c->shift_x;
  shift_y = c->shift_y;
}

csCamera::~csCamera ()
{
}

csPolygon3D* csCamera::GetHit (csVector3& v)
{
  return sector->HitBeam (v_o2t, v);
}

void csCamera::MoveWorld (const csVector3& v)
{
  csVector3 new_position = GetOrigin () + v;
  if (sector)
    sector = sector->FollowSegment (*this, new_position, mirror);
  SetOrigin (new_position);
}

void csCamera::RotateWorld (const csVector3& v, float angle)
{
  csVector3 u = v;
  float ca, sa;
  u = csVector3::Unit (u);
  ca = cos (angle);
  sa = sin (angle);

  SetT2O (

   csMatrix3(
         ca+(1-ca)*u.x*u.x, u.x*u.y*(1-ca)-u.z*sa, u.x*u.z*(1-ca)+u.y*sa,
     u.x*u.y*(1-ca)+u.z*sa,     ca+(1-ca)*u.y*u.y, u.y*u.z*(1-ca)-u.x*sa,
     u.x*u.z*(1-ca)-u.y*sa, u.y*u.z*(1-ca)+u.x*sa,     ca+(1-ca)*u.z*u.z)

   * GetT2O () );
}

void csCamera::Rotate (const csVector3& v, float angle)
{
  csVector3 u = v;
  float ca, sa;
  u = csVector3::Unit (u);
  ca = cos (angle);
  sa = sin (angle);

  SetT2O (GetT2O () *

   csMatrix3(
         ca+(1-ca)*u.x*u.x, u.x*u.y*(1-ca)-u.z*sa, u.x*u.z*(1-ca)+u.y*sa,
     u.x*u.y*(1-ca)+u.z*sa,     ca+(1-ca)*u.y*u.y, u.y*u.z*(1-ca)-u.x*sa,
     u.x*u.z*(1-ca)-u.y*sa, u.y*u.z*(1-ca)+u.x*sa,     ca+(1-ca)*u.z*u.z)

   );
}

void csCamera::LookAt (const csVector3& v, const csVector3& up)
{
  csMatrix3 m; /* initialized to be the identity matrix */
  csVector3 w1, w2, w3 = v;
  float r;

  if ( (r=sqrt(v*v)) > SMALL_EPSILON )
  {
   w3 /= r;
   w1 = w3 % up;
   if ( (r=sqrt(w1*w1)) < SMALL_EPSILON )
   {
     w1 = w3 % csVector3(0,0,-1);
     if ( (r=sqrt(w1*w1)) < SMALL_EPSILON )
     {
      w1 = w3 % csVector3(0,-1,0);
      r = sqrt(w1*w1);
     }
   }
   w1 /= r;
   w2 = w3 % w1;

   m.m11 = w1.x;  m.m12 = w2.x;  m.m13 = w3.x;
   m.m21 = w1.y;  m.m22 = w2.y;  m.m23 = w3.y;
   m.m31 = w1.z;  m.m32 = w2.z;  m.m33 = w3.z;
  }

  SetT2O (m);
}

void csCamera::Correct (int n)
{
  csVector3 w1, w2, w3;
  float* vals[5];
  if (n==0) return;

  w3 = m_t2o.Col3();
  vals[0] = &w3.x;  vals[1] = &w3.y;  vals[2] = &w3.z;  vals[4] = NULL;
  Correct (n, vals);  /* perform the snap-to operation on the forward vector */

/* Maybe w3 should be normalized.  Only necessary if there is
   significant roundoff error: */
//  w3 = csVector3::unit(w3);

/* perhaps a snap-to should be performed on one of the other vectors as well */

  w1 = m_t2o.Col2();
  w2 = csVector3::Unit(w3 % w1);
  w1 = w2 % w3;

  SetT2O ( csMatrix3 ( w1.x, w2.x, w3.x,
                             w1.y, w2.y, w3.y,
                             w1.z, w2.z, w3.z ) );
}

void csCamera::Correct (int n, float* vals[])
{
  float r, angle;

  if (vals==NULL) return;
  if (vals[0]==NULL) return;
  if (vals[1]==NULL) return;
  if (vals[2]!=NULL)
  {
   if (*vals[0] < *vals[1])
    { r = *vals[2];  *vals[2] = *vals[0];  *vals[0] = r; }
   else { r = *vals[2];  *vals[2] = *vals[1];  *vals[1] = r; }
  }

  angle = atan2 (*vals[1], *vals[0]);
  angle = (2.*M_PI/n) * QRound(n * angle / (2*M_PI) );
  *vals[1] = sqrt( (*vals[0])*(*vals[0]) + (*vals[1])*(*vals[1]) );
  Correct(n, vals+1);
  r = *vals[1];
  *vals[0] = r*cos(angle);  *vals[1] = r*sin(angle);
}

float csCamera::GetAspect ()
{
  return inv_aspect;
}

float csCamera::GetInvAspect ()
{
  return aspect;
}
<|endoftext|>


<commit_before>#include <cstdint>

#define SIMD_ALIGN __attribute__((aligned(16)))

#define packed_byte(b) {uint8_t(b), uint8_t(b), uint8_t(b), uint8_t(b), \
                        uint8_t(b), uint8_t(b), uint8_t(b), uint8_t(b), \
                        uint8_t(b), uint8_t(b), uint8_t(b), uint8_t(b), \
                        uint8_t(b), uint8_t(b), uint8_t(b), uint8_t(b)}

#define packed_word(w) {uint16_t(w), uint16_t(w), uint16_t(w), uint16_t(w), \
                        uint16_t(w), uint16_t(w), uint16_t(w), uint16_t(w)}

uint16_t mul_1_100[8]   SIMD_ALIGN = {  100,      1,    100,      1,
                                        100,      1,    100,      1};

uint16_t mul_10_1000[8] SIMD_ALIGN = { 1000,     10,   1000,     10,
                                       1000,     10,   1000,     10};

uint16_t mul_1_10000[8] SIMD_ALIGN = {10000,      1,      0,      0,
                                      10000,      1,      0,      0};

uint8_t ascii0[16] SIMD_ALIGN = {'0', '0', '0', '0', '0', '0', '0', '0',
                                 '0', '0', '0', '0', '0', '0', '0', '0'};

uint32_t result[4] SIMD_ALIGN;

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

// #define INLINE_ASM # 32-bit code
#if defined(INLINE_ASM)
uint64_t parse_sse(char* s) {
    //assert(strlen(s) >= 16);

    __asm__ __volatile__(
        "movdqu (%%eax), %%xmm0         \n"
        "psubb  ascii0,  %%xmm0         \n"
        "movdqa %%xmm0, %%xmm1          \n"

        // t2_odd  = xmm1
        "psrlw $8, %%xmm1               \n"

        // t2_even = xmm0
        "psllw $8, %%xmm0               \n"
        "psrlw $8, %%xmm0               \n"

        // t3_even = xmm0
        "pmaddwd mul_10_1000, %%xmm0    \n"
        // t4_odd  = xmm1
        "pmaddwd mul_1_100, %%xmm1      \n"

        // t5 = xmm0
        "paddd %%xmm1, %%xmm0           \n"

        // t6 = xmm0
        "movdqa %%xmm0, %%xmm1          \n"
        "psrlq  $16,    %%xmm1          \n"
        "por    %%xmm1, %%xmm0          \n"
        "pmaddwd mul_1_10000, %%xmm0    \n"

        // save result
        "movdqa %%xmm0, result          \n"
        :
        : "a" (s)
        : "memory"
    );

    return uint64_t(result[0]) * 100000000 + result[2];
}
#else

#include <immintrin.h>

uint64_t parse_sse(const char* s) {
    //assert(strlen(s) >= 16);

    const __m128i ascii0 = _mm_set1_epi8('0');
    const __m128i mul_1_100   = _mm_setr_epi16(  100,  1,  100,  1,
                                                 100,  1,  100,  1);
    const __m128i mul_10_1000 = _mm_setr_epi16( 1000, 10, 1000, 10,
                                                1000, 10, 1000, 10);
    const __m128i mul_1_10000 = _mm_setr_epi16(10000,  1,    0,  0,
                                               10000,  1,    0,  0);

    // =--------------

    const __m128i input   = _mm_sub_epi8(_mm_loadu_si128((__m128i*)s), ascii0);

    const __m128i t2_even = _mm_srli_epi16(_mm_slli_epi16(input, 8), 8);
    const __m128i t3_even = _mm_madd_epi16(t2_even, mul_10_1000);

    const __m128i t2_odd  = _mm_srli_epi16(input, 8);
    const __m128i t4_odd  = _mm_madd_epi16(t2_odd, mul_1_100);

    const __m128i t5      = _mm_add_epi32(t3_even, t4_odd);
    const __m128i t6      = _mm_or_si128(t5, _mm_srli_epi64(t5, 16));
    const __m128i t7      = _mm_madd_epi16(t6, mul_1_10000);

    union packed_dword {
        __m128i  vector;
        uint32_t element[4];
    } p;

    p.vector = t7;

    return uint64_t(p.element[0]) * uint64_t(100000000) + p.element[2];
}

#endif //defined(INLINE_ASM)

<commit_msg>Replace two shifts with single bit-and<commit_after>#include <cstdint>

#define SIMD_ALIGN __attribute__((aligned(16)))

#define packed_byte(b) {uint8_t(b), uint8_t(b), uint8_t(b), uint8_t(b), \
                        uint8_t(b), uint8_t(b), uint8_t(b), uint8_t(b), \
                        uint8_t(b), uint8_t(b), uint8_t(b), uint8_t(b), \
                        uint8_t(b), uint8_t(b), uint8_t(b), uint8_t(b)}

#define packed_word(w) {uint16_t(w), uint16_t(w), uint16_t(w), uint16_t(w), \
                        uint16_t(w), uint16_t(w), uint16_t(w), uint16_t(w)}

uint16_t mul_1_100[8]   SIMD_ALIGN = {  100,      1,    100,      1,
                                        100,      1,    100,      1};

uint16_t mul_10_1000[8] SIMD_ALIGN = { 1000,     10,   1000,     10,
                                       1000,     10,   1000,     10};

uint16_t mul_1_10000[8] SIMD_ALIGN = {10000,      1,      0,      0,
                                      10000,      1,      0,      0};

uint8_t ascii0[16] SIMD_ALIGN = {'0', '0', '0', '0', '0', '0', '0', '0',
                                 '0', '0', '0', '0', '0', '0', '0', '0'};

uint32_t result[4] SIMD_ALIGN;

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

// #define INLINE_ASM # 32-bit code
#if defined(INLINE_ASM)
uint64_t parse_sse(char* s) {
    //assert(strlen(s) >= 16);

    __asm__ __volatile__(
        "movdqu (%%eax), %%xmm0         \n"
        "psubb  ascii0,  %%xmm0         \n"
        "movdqa %%xmm0, %%xmm1          \n"

        // t2_odd  = xmm1
        "psrlw $8, %%xmm1               \n"

        // t2_even = xmm0
        "psllw $8, %%xmm0               \n"
        "psrlw $8, %%xmm0               \n"

        // t3_even = xmm0
        "pmaddwd mul_10_1000, %%xmm0    \n"
        // t4_odd  = xmm1
        "pmaddwd mul_1_100, %%xmm1      \n"

        // t5 = xmm0
        "paddd %%xmm1, %%xmm0           \n"

        // t6 = xmm0
        "movdqa %%xmm0, %%xmm1          \n"
        "psrlq  $16,    %%xmm1          \n"
        "por    %%xmm1, %%xmm0          \n"
        "pmaddwd mul_1_10000, %%xmm0    \n"

        // save result
        "movdqa %%xmm0, result          \n"
        :
        : "a" (s)
        : "memory"
    );

    return uint64_t(result[0]) * 100000000 + result[2];
}
#else

#include <immintrin.h>

uint64_t parse_sse(const char* s) {
    //assert(strlen(s) >= 16);

    const __m128i ascii0 = _mm_set1_epi8('0');
    const __m128i mul_1_100   = _mm_setr_epi16(  100,  1,  100,  1,
                                                 100,  1,  100,  1);
    const __m128i mul_10_1000 = _mm_setr_epi16( 1000, 10, 1000, 10,
                                                1000, 10, 1000, 10);
    const __m128i mul_1_10000 = _mm_setr_epi16(10000,  1,    0,  0,
                                               10000,  1,    0,  0);
    const __m128i mask = _mm_set1_epi16(0xff);

    // =--------------

    const __m128i input   = _mm_sub_epi8(_mm_loadu_si128((__m128i*)s), ascii0);

    const __m128i t2_even = _mm_and_si128(input, mask);
    const __m128i t3_even = _mm_madd_epi16(t2_even, mul_10_1000);

    const __m128i t2_odd  = _mm_srli_epi16(input, 8);
    const __m128i t4_odd  = _mm_madd_epi16(t2_odd, mul_1_100);

    const __m128i t5      = _mm_add_epi32(t3_even, t4_odd);
    const __m128i t6      = _mm_or_si128(t5, _mm_srli_epi64(t5, 16));
    const __m128i t7      = _mm_madd_epi16(t6, mul_1_10000);

    union packed_dword {
        __m128i  vector;
        uint32_t element[4];
    } p;

    p.vector = t7;

    return uint64_t(p.element[0]) * uint64_t(100000000) + p.element[2];
}

#endif //defined(INLINE_ASM)

<|endoftext|>


<commit_before>/*
    Copyright (C) 1997, 1998, 1999 by Alex Pfaffe
	(Digital Dawn Graphics Inc)

    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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// ----------------------------------------------------------------------
// General includes
#include <stdio.h>
#include <string.h>

#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#endif

#include "sysdef.h"
// DDG includes
#include "csterr/ddghemap.h"
#include "csterr/ddgvec.h"
//#include "csterr/ddgnoise.h"
#include "csterr/ddgerror.h"
// ----------------------------------------------------------------------

ddgHeightMap::~ddgHeightMap(void)
{
	delete _pixbuffer;
}

void ddgHeightMap::allocate( unsigned short r, unsigned short  c )
{
	_cols = c;
	_rows = r;
	delete _pixbuffer;
	assert(sizeof(short) == 2);
	_pixbuffer = new short[_cols*_rows];
}

// ----------------------------------------------------------------------
// load:
bool ddgHeightMap::readMemory( unsigned short *buf )
{
	int i;
	for (i=0; i < _cols*_rows; i++)
		_pixbuffer[i] = buf[i];
	return false;
}

// ----------------------------------------------------------------------
// load:

bool ddgHeightMap::writeTGN(char *filename, unsigned int base, unsigned int scale)
{
	FILE *fptr = filename && filename[0] ? fopen(filename,"w") : 0;
	if (!fptr) {
		ddgErrorSet(FileWrite,(char *) (filename ? filename : "(null)"));
		goto error;
	}

#ifdef WIN32
	_setmode(_fileno(fptr),_O_BINARY);
#endif

	// Header
	if (fwrite("TERRAGENTERRAIN SIZE",1,20,fptr) < 20)
	{
		ddgErrorSet(FileWrite,"Couldn't write header.");
		goto error;
	}

	// SIZE.
	unsigned char ch1, ch2;
	ch1 = _cols % 256;
	ch2 = _cols - ch1 * 256;
	fputc(ch1,fptr);
	fputc(ch2,fptr);
	// Padding 2 bytes.
	fputc(0,fptr);
	fputc(0,fptr);

	// XPTS.
	if (fwrite("XPTS",1,4,fptr) < 4)
	{
		ddgErrorSet(FileWrite,"Couldn't write XPTS.");
		goto error;
	}

	ch1 = _cols % 256;
	ch2 = _cols - ch1 * 256;
	fputc(ch1,fptr);
	fputc(ch2,fptr);
	// Padding 2 bytes.
	fputc(0,fptr);
	fputc(0,fptr);

	// YPTS.
	if (fwrite("YPTS",1,4,fptr) < 4)
	{
		ddgErrorSet(FileWrite,"Couldn't write YPTS.");
		goto error;
	}

	ch1 = _rows % 256;
	ch2 = _rows - ch1 * 256;
	fputc(ch1,fptr);
	fputc(ch2,fptr);
	// Padding 2 bytes.
	fputc(0,fptr);
	fputc(0,fptr);

	// ALTW.
	if (fwrite("ALTW",1,4,fptr) < 4)
	{
		ddgErrorSet(FileWrite,"Couldn't write ALTW.");
		goto error;
	}

	ch1 = scale % 256;
	ch2 = scale - ch1 * 256;
	fputc(ch1,fptr);
	fputc(ch2,fptr);

	ch1 = base % 256;
	ch2 = base - ch1 * 256;
	fputc(ch1,fptr);
	fputc(ch2,fptr);

	// Write data
	int r, c;
	r = 0;
	while (r < _rows)
	{
		for (c = 0; c < _cols; c++)
		{
			ch1 = _pixbuffer[c + r * _cols] % 256;
			ch2 = _pixbuffer[c + r * _cols] - ch1 * 256;
			fputc(ch1,fptr);
			fputc(ch2,fptr);
		}
		r++;
	}
	// File termination segment.
	fputc(0,fptr);
	fputc(0,fptr);
	fputc(0,fptr);
	fputc(0,fptr);

	fclose(fptr);
	return true;

error:
	fclose(fptr);
	ddgError::report();
	return false;
}

bool ddgHeightMap::readTGN(char *file)
{
	FILE *fptr = file && file[0] ? fopen(file,"r") : 0;
	if (!fptr)
	{
		ddgErrorSet(FileRead,(char *) (file ? file : "(null)"));
		ddgError::report();
		return true;
	}
	unsigned char ch1, ch2;

	#ifdef WIN32
	_setmode(_fileno(fptr),_O_BINARY);
	#endif
	char name[9],type[9], segment[5], pad[2];

	// Name 8 bytes.
	fread(name,8,1,fptr);
	name[8] = '\0';
	fread(type,8,1,fptr);
	type[8] = '\0';
	if (!ddgStr::equal(name,"TERRAGEN") || !ddgStr::equal(type,"TERRAIN "))
	{
		ddgErrorSet(FileRead,(char *) "File is not a TERRAGEN TERRAIN file");
		ddgError::report();
		return true;
	}

	// Segment 4 bytes.
	segment[4] = '\0';

	fread(segment,4,1,fptr);

	if (ddgStr::equal(segment,"SIZE"))
	{
		// SIZE 2 bytes.
		ch1 = fgetc(fptr);
		ch2 = fgetc(fptr);
		_rows = _cols = ch2*256+ch1 +1;
		// Padding 2 bytes.
		fread(pad,2,1,fptr);
		fread(segment,4,1,fptr);
	}

	if (ddgStr::equal(segment,"XPTS"))
	{
		// XPTS.
		ch1 = fgetc(fptr);
		ch2 = fgetc(fptr);
		_cols = ch2*256+ch1;
		// Padding 2 bytes.
		fread(pad,2,1,fptr);

		fread(segment,4,1,fptr);
		// YPTS.
		if (ddgStr::equal(segment,"YPTS"))
		{
			ch1 = fgetc(fptr);
			ch2 = fgetc(fptr);
			_rows = ch2*256+ch1;
			// Padding 2 bytes.
			fread(pad,2,1,fptr);
			fread(segment,4,1,fptr);
		}
		else
		{
			ddgErrorSet(FileRead,(char *) "Expected YPTS segment, but it was not found.");
			ddgError::report();
			return true;
		}
	}

	// ALTW.
	// Absolute elevation for a given point is
	// BaseHeight + elevation* Scale / 65536.
	if (ddgStr::equal(segment,"ALTW"))
	{
		ch1 = fgetc(fptr);
		ch2 = fgetc(fptr);
		_scale = (ch2*256+ch1)/ 65536.0;

		ch1 = fgetc(fptr);
		ch2 = fgetc(fptr);
		_base = ch2*256+ch1;
	}
	else
	{
		ddgErrorSet(FileRead,(char *) "Expected ALTW segment, but it was not found.");
		ddgError::report();
		return true;
	}

	// Read height data
	// The absolute altitude of a particular point (in the same scale as x and y)
	// is equal to BaseHeight + Elevation * HeightScale / 65536
	allocate(_cols,_rows);
	int r = 0;
	int cnt;
	while (r < _rows)
	{
		if ((cnt = fread(&(_pixbuffer[r*_cols]),2,_cols,fptr)) <
		(int)_cols)
		{
			ddgErrorSet(FileRead,(char *) (file ? file : "(null)"));
			ddgError::report();
			if (feof(fptr))
			{
				ddgErrorSet(FileAccess,"Reached end of file!");
				ddgError::report();
			}
			fclose(fptr);
			return true;
		}
		r++;
	}

	fclose(fptr);
	return false;
}

bool ddgHeightMap::generateHeights(unsigned int r, unsigned int c, float /*o*/ )
{
	// Read data
    allocate(r,c);
	unsigned int ci, ri;
	short cc;
	double n;
	ddgVector3 v(0,0,0);
//	double min = 999999, max = -999999;
	for (ri = 0; ri < r; ri++)
	{
		v.v[1] = 0.0f;
		for (ci = 0; ci < c; ci++)
		{
			n = 0; //ddgNoise::four_noise(v,100);	// Returns 0 to 1.
//			if (n < min) min = n;
//			if (n > max) max = n;
			n = (n*0xFFFF) - 0x7FFF;		// Scale to fill range.
			assert(n >=-0x7FFF && n <= 0x7FFF);
			cc = (short) n;
			set(ri,ci, cc);
			v.v[1]+= 100.0f/c;
		}
	v.v[0]+= 100.0f/r;
	}

	return true;
}

void ddgHeightMap::canyonize(float f )
{
	f += 1;
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			unsigned int d = get(r,c);
            unsigned int d2 = (unsigned int)ddgUtil::clamp(pow(d,f),0,0xFFFF);
			set(r,c,d2);
		}
}

void ddgHeightMap::glaciate(float f )
{
	f *= 0xFFFF;
	for (unsigned r = 1; r+1 < _rows; r++)
		for (unsigned c = 1; c+1 < _cols; c++ )
		{
			unsigned int d = get(r,c),
                        dn = (get(r-1,c)+ get(r+1,c)+ get(r,c-1)+ get(r,c+1))/4;
            if (fabs(d-dn) < f)
            {
//                unsigned int d2 = Util::clamp(pow(d,f),0,0xFFFF);
	    		set(r,c,dn);
            }
		}
}

void ddgHeightMap::scale(float s )
{
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
            unsigned int d = (unsigned int)ddgUtil::clamp(s * get(r,c),0,0xFFFF);
			set(r,c,d);
		}
}

void ddgHeightMap::translate(float t )
{
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
            unsigned int d = (unsigned int)ddgUtil::clamp(t + get(r,c),0,0xFFFF);
			set(r,c,d);
		}
}

int ddgHeightMap::mini(void )
{
	int m = get(0,0);
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			int d = get(r,c);
			if (d < m) m = d;
		}
	return m;
}

int ddgHeightMap::maxi(void )
{
	int m = get(0,0);
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			int d = get(r,c);
			if (d > m) m = d;
		}
	return m;
}

void ddgHeightMap::setmin( int m)
{
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			if (get(r,c) < m) set(r,c,m);
		}
}

void ddgHeightMap::setmax( int m)
{
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			if (get(r,c) > m) set(r,c,m);
		}
}

void ddgHeightMap::closeEdge(void)
{
	for (unsigned r = 0; r < _rows; r++)
	{
		set(r,0,0);
		set(r,_cols-1,0);
	}
	for (unsigned c = 0; c < _cols; c++ )
	{
		set(0,c,0);
		set(_rows-1,c,0);
	}
}

void ddgHeightMap::sin(void)
{
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			set(r,c,(short)(10000*(ddgAngle::sin(180.0*(float)r/(float)_rows)
				         +ddgAngle::sin(180.0*(float)c/(float)_cols))));
		}
}
<commit_msg>Endian correction<commit_after>/*
    Copyright (C) 1997, 1998, 1999 by Alex Pfaffe
	(Digital Dawn Graphics Inc)

    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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// ----------------------------------------------------------------------
// General includes
#include <stdio.h>
#include <string.h>

#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#endif

#include "sysdef.h"
// DDG includes
#include "csterr/ddghemap.h"
#include "csterr/ddgvec.h"
//#include "csterr/ddgnoise.h"
#include "csterr/ddgerror.h"
// ----------------------------------------------------------------------

ddgHeightMap::~ddgHeightMap(void)
{
	delete _pixbuffer;
}

void ddgHeightMap::allocate( unsigned short r, unsigned short  c )
{
	_cols = c;
	_rows = r;
	delete _pixbuffer;
	assert(sizeof(short) == 2);
	_pixbuffer = new short[_cols*_rows];
}

// ----------------------------------------------------------------------
// load:
bool ddgHeightMap::readMemory( unsigned short *buf )
{
	int i;
	for (i=0; i < _cols*_rows; i++)
		_pixbuffer[i] = buf[i];
	return false;
}

// ----------------------------------------------------------------------
// load:

bool ddgHeightMap::writeTGN(char *filename, unsigned int base, unsigned int scale)
{
	FILE *fptr = filename && filename[0] ? fopen(filename,"w") : 0;
	if (!fptr) {
		ddgErrorSet(FileWrite,(char *) (filename ? filename : "(null)"));
		goto error;
	}

#ifdef WIN32
	_setmode(_fileno(fptr),_O_BINARY);
#endif

	// Header
	if (fwrite("TERRAGENTERRAIN SIZE",1,20,fptr) < 20)
	{
		ddgErrorSet(FileWrite,"Couldn't write header.");
		goto error;
	}

	// SIZE.
	unsigned char ch1, ch2;
	ch1 = _cols % 256;
	ch2 = _cols - ch1 * 256;
	fputc(ch1,fptr);
	fputc(ch2,fptr);
	// Padding 2 bytes.
	fputc(0,fptr);
	fputc(0,fptr);

	// XPTS.
	if (fwrite("XPTS",1,4,fptr) < 4)
	{
		ddgErrorSet(FileWrite,"Couldn't write XPTS.");
		goto error;
	}

	ch1 = _cols % 256;
	ch2 = _cols - ch1 * 256;
	fputc(ch1,fptr);
	fputc(ch2,fptr);
	// Padding 2 bytes.
	fputc(0,fptr);
	fputc(0,fptr);

	// YPTS.
	if (fwrite("YPTS",1,4,fptr) < 4)
	{
		ddgErrorSet(FileWrite,"Couldn't write YPTS.");
		goto error;
	}

	ch1 = _rows % 256;
	ch2 = _rows - ch1 * 256;
	fputc(ch1,fptr);
	fputc(ch2,fptr);
	// Padding 2 bytes.
	fputc(0,fptr);
	fputc(0,fptr);

	// ALTW.
	if (fwrite("ALTW",1,4,fptr) < 4)
	{
		ddgErrorSet(FileWrite,"Couldn't write ALTW.");
		goto error;
	}

	ch1 = scale % 256;
	ch2 = scale - ch1 * 256;
	fputc(ch1,fptr);
	fputc(ch2,fptr);

	ch1 = base % 256;
	ch2 = base - ch1 * 256;
	fputc(ch1,fptr);
	fputc(ch2,fptr);

	// Write data
	int r, c;
	r = 0;
	while (r < _rows)
	{
		for (c = 0; c < _cols; c++)
		{
			ch1 = _pixbuffer[c + r * _cols] % 256;
			ch2 = _pixbuffer[c + r * _cols] - ch1 * 256;
			fputc(ch1,fptr);
			fputc(ch2,fptr);
		}
		r++;
	}
	// File termination segment.
	fputc(0,fptr);
	fputc(0,fptr);
	fputc(0,fptr);
	fputc(0,fptr);

	fclose(fptr);
	return true;

error:
	fclose(fptr);
	ddgError::report();
	return false;
}

bool ddgHeightMap::readTGN(char *file)
{
	FILE *fptr = file && file[0] ? fopen(file,"rb") : 0;
	if (!fptr)
	{
		ddgErrorSet(FileRead,(char *) (file ? file : "(null)"));
		ddgError::report();
		return true;
	}
	unsigned char ch1, ch2;

	char name[9],type[9], segment[5], pad[2];

	// Name 8 bytes.
	fread(name,8,1,fptr);
	name[8] = '\0';
	fread(type,8,1,fptr);
	type[8] = '\0';
	if (!ddgStr::equal(name,"TERRAGEN") || !ddgStr::equal(type,"TERRAIN "))
	{
		ddgErrorSet(FileRead,(char *) "File is not a TERRAGEN TERRAIN file");
		ddgError::report();
		return true;
	}

	// Segment 4 bytes.
	segment[4] = '\0';

	fread(segment,4,1,fptr);

	if (ddgStr::equal(segment,"SIZE"))
	{
		// SIZE 2 bytes.
		ch1 = fgetc(fptr);
		ch2 = fgetc(fptr);
		_rows = _cols = ch2*256+ch1 +1;
		// Padding 2 bytes.
		fread(pad,2,1,fptr);
		fread(segment,4,1,fptr);
	}

	if (ddgStr::equal(segment,"XPTS"))
	{
		// XPTS.
		ch1 = fgetc(fptr);
		ch2 = fgetc(fptr);
		_cols = ch2*256+ch1;
		// Padding 2 bytes.
		fread(pad,2,1,fptr);

		fread(segment,4,1,fptr);
		// YPTS.
		if (ddgStr::equal(segment,"YPTS"))
		{
			ch1 = fgetc(fptr);
			ch2 = fgetc(fptr);
			_rows = ch2*256+ch1;
			// Padding 2 bytes.
			fread(pad,2,1,fptr);
			fread(segment,4,1,fptr);
		}
		else
		{
			ddgErrorSet(FileRead,(char *) "Expected YPTS segment, but it was not found.");
			ddgError::report();
			return true;
		}
	}

	// ALTW.
	// Absolute elevation for a given point is
	// BaseHeight + elevation* Scale / 65536.
	if (ddgStr::equal(segment,"ALTW"))
	{
		ch1 = fgetc(fptr);
		ch2 = fgetc(fptr);
		_scale = (ch2*256+ch1)/ 65536.0;

		ch1 = fgetc(fptr);
		ch2 = fgetc(fptr);
		_base = ch2*256+ch1;
	}
	else
	{
		ddgErrorSet(FileRead,(char *) "Expected ALTW segment, but it was not found.");
		ddgError::report();
		return true;
	}

	// Read height data
	// The absolute altitude of a particular point (in the same scale as x and y)
	// is equal to BaseHeight + Elevation * HeightScale / 65536
	allocate(_cols,_rows);
	int r = 0;
	int cnt;
	while (r < _rows)
	{
		if ((cnt = fread(&(_pixbuffer[r*_cols]),2,_cols,fptr)) <
		(int)_cols)
		{
			ddgErrorSet(FileRead,(char *) (file ? file : "(null)"));
			ddgError::report();
			if (feof(fptr))
			{
				ddgErrorSet(FileAccess,"Reached end of file!");
				ddgError::report();
			}
			fclose(fptr);
			return true;
		}
		r++;
	}
	// Swap byte order for machines with different endian.
	unsigned long test_value = 0x12345678L;
	if  (*((unsigned char*)&test_value) == 0x12)
	{
		char s;
		int i;

		for (i = 0; i < 2 * _rows * _cols; i=i+2)
		{
			s = _pixbuffer[i];
			_pixbuffer[i] = _pixbuffer[i+1];
			_pixbuffer[i+1] = s;
		}
	}

	fclose(fptr);
	return false;
}

bool ddgHeightMap::generateHeights(unsigned int r, unsigned int c, float /*o*/ )
{
	// Read data
    allocate(r,c);
	unsigned int ci, ri;
	short cc;
	double n;
	ddgVector3 v(0,0,0);
//	double min = 999999, max = -999999;
	for (ri = 0; ri < r; ri++)
	{
		v.v[1] = 0.0f;
		for (ci = 0; ci < c; ci++)
		{
			n = 0; //ddgNoise::four_noise(v,100);	// Returns 0 to 1.
//			if (n < min) min = n;
//			if (n > max) max = n;
			n = (n*0xFFFF) - 0x7FFF;		// Scale to fill range.
			assert(n >=-0x7FFF && n <= 0x7FFF);
			cc = (short) n;
			set(ri,ci, cc);
			v.v[1]+= 100.0f/c;
		}
	v.v[0]+= 100.0f/r;
	}

	return true;
}

void ddgHeightMap::canyonize(float f )
{
	f += 1;
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			unsigned int d = get(r,c);
            unsigned int d2 = (unsigned int)ddgUtil::clamp(pow(d,f),0,0xFFFF);
			set(r,c,d2);
		}
}

void ddgHeightMap::glaciate(float f )
{
	f *= 0xFFFF;
	for (unsigned r = 1; r+1 < _rows; r++)
		for (unsigned c = 1; c+1 < _cols; c++ )
		{
			unsigned int d = get(r,c),
                        dn = (get(r-1,c)+ get(r+1,c)+ get(r,c-1)+ get(r,c+1))/4;
            if (fabs(d-dn) < f)
            {
//                unsigned int d2 = Util::clamp(pow(d,f),0,0xFFFF);
	    		set(r,c,dn);
            }
		}
}

void ddgHeightMap::scale(float s )
{
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
            unsigned int d = (unsigned int)ddgUtil::clamp(s * get(r,c),0,0xFFFF);
			set(r,c,d);
		}
}

void ddgHeightMap::translate(float t )
{
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
            unsigned int d = (unsigned int)ddgUtil::clamp(t + get(r,c),0,0xFFFF);
			set(r,c,d);
		}
}

int ddgHeightMap::mini(void )
{
	int m = get(0,0);
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			int d = get(r,c);
			if (d < m) m = d;
		}
	return m;
}

int ddgHeightMap::maxi(void )
{
	int m = get(0,0);
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			int d = get(r,c);
			if (d > m) m = d;
		}
	return m;
}

void ddgHeightMap::setmin( int m)
{
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			if (get(r,c) < m) set(r,c,m);
		}
}

void ddgHeightMap::setmax( int m)
{
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			if (get(r,c) > m) set(r,c,m);
		}
}

void ddgHeightMap::closeEdge(void)
{
	for (unsigned r = 0; r < _rows; r++)
	{
		set(r,0,0);
		set(r,_cols-1,0);
	}
	for (unsigned c = 0; c < _cols; c++ )
	{
		set(0,c,0);
		set(_rows-1,c,0);
	}
}

void ddgHeightMap::sin(void)
{
	for (unsigned r = 0; r < _rows; r++)
		for (unsigned c = 0; c < _cols; c++ )
		{
			set(r,c,(short)(10000*(ddgAngle::sin(180.0*(float)r/(float)_rows)
				         +ddgAngle::sin(180.0*(float)c/(float)_cols))));
		}
}
<|endoftext|>


<commit_before>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Created by bmuller <bmuller@butterfat.net>
*/

#include "mod_auth_openid.h"

namespace modauthopenid {
  using namespace std;

  void debug(string s) {
#ifdef DEBUG
    string time_s = "";
    time_t rawtime = time(NULL);
    tm *tm_t = localtime(&rawtime);
    char rv[40];
    if(strftime(rv, sizeof(rv)-1, "%a %b %d %H:%M:%S %Y", tm_t))
      time_s = "[" + string(rv) + "] ";
    s = time_s + "[" + string(PACKAGE_NAME) + "] " + s + "\n";
    // escape %'s
    string cleaned_s = "";
    vector<string> parts = explode(s, "%");
    for(unsigned int i=0; i<parts.size()-1; i++)
      cleaned_s += parts[i] + "%%";
    cleaned_s += parts[parts.size()-1];
    // stderr is redirected by apache to apache's error log
    fputs(cleaned_s.c_str(), stderr);
    fflush(stderr);
#endif
  };

  // get a descriptive string for an error; a short string is used as a GET param
  // value in the style of OpenID get params - short, no space, ...
  string error_to_string(error_result_t e, bool use_short_string) {
    string short_string, long_string;
    switch(e) {
    case no_idp_found:
      short_string = "no_idp_found";
      long_string = "There was either no identity provider found for the identity given"
	" or there was trouble connecting to it.";
      break;
    case invalid_id:
      short_string = "invalid_id";
      long_string = "The identity given is not a valid identity.";
      break;
    case idp_not_trusted:
      short_string = "idp_not_trusted";
      long_string = "The identity provider for the identity given is not trusted.";
      break;
    case invalid_nonce:
      short_string = "invalid_nonce";
      long_string = "Invalid nonce; error while authenticating.";
      break;
    case canceled:
      short_string = "canceled";
      long_string = "Identification process has been canceled.";
      break;
    case unauthorized:
      short_string = "unauthorized";
      long_string = "User is not authorized to access this location.";
      break;
    default: // unspecified
      short_string = "unspecified";
      long_string = "There has been an error while attempting to authenticate.";
      break;
    }
    return (use_short_string) ? short_string : long_string;
  };

  string str_replace(string needle, string replacement, string haystack) {
    vector<string> v = explode(haystack, needle);
    string r = "";
    for(vector<string>::size_type i=0; i < v.size()-1; i++)
      r += v[i] + replacement;
    r += v[v.size()-1];
    return r;
  };

  vector<string> explode(string s, string e) {
    vector<string> ret;
    int iPos = s.find(e, 0);
    int iPit = e.length();
    while(iPos>-1) {
      if(iPos!=0)
        ret.push_back(s.substr(0,iPos));
      s.erase(0,iPos+iPit);
      iPos = s.find(e, 0);
    }
    if(s!="")
      ret.push_back(s);
    return ret;
  };

  pcre * make_regex(string pattern) {
    const char * error;
    int erroffset;
    return pcre_compile(pattern.c_str(), 0, &error, &erroffset, NULL);
  }

  bool regex_match(string subject, pcre * re) {
    return (pcre_exec(re, NULL, subject.c_str(), subject.size(), 0, 0, NULL, 0) >= 0);
  };

  void strip(string& s) {
    while(!s.empty() && s.substr(0,1) == " ") s.erase(0,1);
    while(!s.empty() && s.substr(s.size()-1, 1) == " ") s.erase(s.size()-1,1);
  };

  // make a random alpha-numeric string size characters long
  void make_rstring(int size, string& s) {
    s = "";
    const char *cs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for(int index=0; index<size; index++)
      s += cs[true_random()%62];
  }

  void print_sqlite_table(sqlite3 *db, string tablename) {
    fprintf(stdout, "Printing table: %s.  ", tablename.c_str());
    string sql = "SELECT * FROM " + tablename;
    int rc, nr, nc, size;
    char **table;
    rc = sqlite3_get_table(db, sql.c_str(), &table, &nr, &nc, 0);
    fprintf(stdout, "There are %d rows.\n", nr);
    size = (nr * nc) + nc;
    for(int i=0; i<size; i++) {
      fprintf(stdout, "%s\t", table[i]);
      if(((i+1) % nc) == 0)
	fprintf(stdout, "\n");
    }
    fprintf(stdout, "\n");
    sqlite3_free_table(table);
  };

  bool test_sqlite_return(sqlite3 *db, int result, const string& context) {
    if(result != SQLITE_OK){
      string msg = "SQLite Error - " + context + ": %s\n";
      fprintf(stderr, msg.c_str(), sqlite3_errmsg(db));
      return false;
    }
    return true;
  };

  string exec_error_to_string(exec_result_t e, string exec_location, string id) {
    string error;
    switch(e) {
    case fork_failed:
      error = "Could not fork to exec program: " + exec_location + "when attempting to auth " + id;
      break;
    case child_no_return:
      error = "Problem waiting for child " + exec_location + " to return when authenticating " + id;
      break;
    case id_refused:
      error = id + " deemed authenticated by " + exec_location;
      break;
    default: // unspecified
      error = "Error while attempting to authenticate " + id + " using the program " + exec_location;
      break;
    }
    return error;
  }

  exec_result_t exec_auth(string exec_location, string username) {
    if(exec_location.size() > 255)
      exec_location.resize(255);
    if(username.size() > 255)
      username.resize(255);

    char *const argv[] = { (char *) exec_location.c_str(), (char *) username.c_str(), NULL };
    exec_result_t result = id_refused;
    int rvalue = 0;

    pid_t pid = fork();
    switch(pid) {
    case -1:
      // Fork failed
      result = fork_failed;
      break;
    case 0:
      // congrats, you're a kid
      execv(exec_location.c_str(), argv);
      // if we make it here, exec failed, exit from kid with rvalue 1
      exit(1);
    default:
      // you're an adult parent, act responsibly
      if(waitpid(pid, &rvalue, 0) == -1)
	result = child_no_return;
      else
	result = (rvalue == 0) ? id_accepted : id_refused;
      break;
    }
    return result;
  };

  /* true_random -- generate a crypto-quality random number. Taken from apr-util's getuuid.c file */
  int true_random() {
#if APR_HAS_RANDOM
    unsigned char buf[2];
    if (apr_generate_random_bytes(buf, 2) == APR_SUCCESS)
      return (buf[0] << 8) | buf[1];
#endif
    apr_uint64_t time_now = apr_time_now();
    srand((unsigned int)(((time_now >> 32) ^ time_now) & 0xffffffff));
    return rand() & 0x0FFFF;
  };

} // end namespace

<commit_msg>fixed error message when a user is not authenticated by external program<commit_after>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Created by bmuller <bmuller@butterfat.net>
*/

#include "mod_auth_openid.h"

namespace modauthopenid {
  using namespace std;

  void debug(string s) {
#ifdef DEBUG
    string time_s = "";
    time_t rawtime = time(NULL);
    tm *tm_t = localtime(&rawtime);
    char rv[40];
    if(strftime(rv, sizeof(rv)-1, "%a %b %d %H:%M:%S %Y", tm_t))
      time_s = "[" + string(rv) + "] ";
    s = time_s + "[" + string(PACKAGE_NAME) + "] " + s + "\n";
    // escape %'s
    string cleaned_s = "";
    vector<string> parts = explode(s, "%");
    for(unsigned int i=0; i<parts.size()-1; i++)
      cleaned_s += parts[i] + "%%";
    cleaned_s += parts[parts.size()-1];
    // stderr is redirected by apache to apache's error log
    fputs(cleaned_s.c_str(), stderr);
    fflush(stderr);
#endif
  };

  // get a descriptive string for an error; a short string is used as a GET param
  // value in the style of OpenID get params - short, no space, ...
  string error_to_string(error_result_t e, bool use_short_string) {
    string short_string, long_string;
    switch(e) {
    case no_idp_found:
      short_string = "no_idp_found";
      long_string = "There was either no identity provider found for the identity given"
	" or there was trouble connecting to it.";
      break;
    case invalid_id:
      short_string = "invalid_id";
      long_string = "The identity given is not a valid identity.";
      break;
    case idp_not_trusted:
      short_string = "idp_not_trusted";
      long_string = "The identity provider for the identity given is not trusted.";
      break;
    case invalid_nonce:
      short_string = "invalid_nonce";
      long_string = "Invalid nonce; error while authenticating.";
      break;
    case canceled:
      short_string = "canceled";
      long_string = "Identification process has been canceled.";
      break;
    case unauthorized:
      short_string = "unauthorized";
      long_string = "User is not authorized to access this location.";
      break;
    default: // unspecified
      short_string = "unspecified";
      long_string = "There has been an error while attempting to authenticate.";
      break;
    }
    return (use_short_string) ? short_string : long_string;
  };

  string str_replace(string needle, string replacement, string haystack) {
    vector<string> v = explode(haystack, needle);
    string r = "";
    for(vector<string>::size_type i=0; i < v.size()-1; i++)
      r += v[i] + replacement;
    r += v[v.size()-1];
    return r;
  };

  vector<string> explode(string s, string e) {
    vector<string> ret;
    int iPos = s.find(e, 0);
    int iPit = e.length();
    while(iPos>-1) {
      if(iPos!=0)
        ret.push_back(s.substr(0,iPos));
      s.erase(0,iPos+iPit);
      iPos = s.find(e, 0);
    }
    if(s!="")
      ret.push_back(s);
    return ret;
  };

  pcre * make_regex(string pattern) {
    const char * error;
    int erroffset;
    return pcre_compile(pattern.c_str(), 0, &error, &erroffset, NULL);
  }

  bool regex_match(string subject, pcre * re) {
    return (pcre_exec(re, NULL, subject.c_str(), subject.size(), 0, 0, NULL, 0) >= 0);
  };

  void strip(string& s) {
    while(!s.empty() && s.substr(0,1) == " ") s.erase(0,1);
    while(!s.empty() && s.substr(s.size()-1, 1) == " ") s.erase(s.size()-1,1);
  };

  // make a random alpha-numeric string size characters long
  void make_rstring(int size, string& s) {
    s = "";
    const char *cs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for(int index=0; index<size; index++)
      s += cs[true_random()%62];
  }

  void print_sqlite_table(sqlite3 *db, string tablename) {
    fprintf(stdout, "Printing table: %s.  ", tablename.c_str());
    string sql = "SELECT * FROM " + tablename;
    int rc, nr, nc, size;
    char **table;
    rc = sqlite3_get_table(db, sql.c_str(), &table, &nr, &nc, 0);
    fprintf(stdout, "There are %d rows.\n", nr);
    size = (nr * nc) + nc;
    for(int i=0; i<size; i++) {
      fprintf(stdout, "%s\t", table[i]);
      if(((i+1) % nc) == 0)
	fprintf(stdout, "\n");
    }
    fprintf(stdout, "\n");
    sqlite3_free_table(table);
  };

  bool test_sqlite_return(sqlite3 *db, int result, const string& context) {
    if(result != SQLITE_OK){
      string msg = "SQLite Error - " + context + ": %s\n";
      fprintf(stderr, msg.c_str(), sqlite3_errmsg(db));
      return false;
    }
    return true;
  };

  string exec_error_to_string(exec_result_t e, string exec_location, string id) {
    string error;
    switch(e) {
    case fork_failed:
      error = "Could not fork to exec program: " + exec_location + "when attempting to auth " + id;
      break;
    case child_no_return:
      error = "Problem waiting for child " + exec_location + " to return when authenticating " + id;
      break;
    case id_refused:
      error = id + " not authenticated by " + exec_location;
      break;
    default: // unspecified
      error = "Error while attempting to authenticate " + id + " using the program " + exec_location;
      break;
    }
    return error;
  }

  exec_result_t exec_auth(string exec_location, string username) {
    if(exec_location.size() > 255)
      exec_location.resize(255);
    if(username.size() > 255)
      username.resize(255);

    char *const argv[] = { (char *) exec_location.c_str(), (char *) username.c_str(), NULL };
    exec_result_t result = id_refused;
    int rvalue = 0;

    pid_t pid = fork();
    switch(pid) {
    case -1:
      // Fork failed
      result = fork_failed;
      break;
    case 0:
      // congrats, you're a kid
      execv(exec_location.c_str(), argv);
      // if we make it here, exec failed, exit from kid with rvalue 1
      exit(1);
    default:
      // you're an adult parent, act responsibly
      if(waitpid(pid, &rvalue, 0) == -1)
	result = child_no_return;
      else
	result = (rvalue == 0) ? id_accepted : id_refused;
      break;
    }
    return result;
  };

  /* true_random -- generate a crypto-quality random number. Taken from apr-util's getuuid.c file */
  int true_random() {
#if APR_HAS_RANDOM
    unsigned char buf[2];
    if (apr_generate_random_bytes(buf, 2) == APR_SUCCESS)
      return (buf[0] << 8) | buf[1];
#endif
    apr_uint64_t time_now = apr_time_now();
    srand((unsigned int)(((time_now >> 32) ^ time_now) & 0xffffffff));
    return rand() & 0x0FFFF;
  };

} // end namespace

<|endoftext|>


<commit_before>// Copyright (C) 2011 - 2014 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#include "CQBrowserPane.h"

#include "listviews.h"

CQBrowserPane::CQBrowserPane(QWidget* parent) :
  QTreeView(parent)
{
  QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
  sizePolicy.setHorizontalStretch(0);
  sizePolicy.setVerticalStretch(0);
  sizePolicy.setHeightForWidth(this->sizePolicy().hasHeightForWidth());
  setSizePolicy(sizePolicy);
  setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
  setAutoScroll(true);
  setEditTriggers(QAbstractItemView::NoEditTriggers);
  setTextElideMode(Qt::ElideNone);
  setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
  setUniformRowHeights(true);
  setSortingEnabled(true);
  setHeaderHidden(true);

  connect(this, SIGNAL(expanded(const QModelIndex &)), this, SLOT(slotUpdateScrollBar(const QModelIndex &)));
  connect(this, SIGNAL(collapsed(const QModelIndex &)), this, SLOT(slotUpdateScrollBar(const QModelIndex &)));
}

// virtual
CQBrowserPane::~CQBrowserPane()
{}

// virtual
void CQBrowserPane::currentChanged(const QModelIndex & current, const QModelIndex & /* previous */)
{
  static_cast< ListViews * >(parent())->slotFolderChanged(current);
}

void CQBrowserPane::slotUpdateScrollBar(const QModelIndex & index)
{
  resizeColumnToContents(index.column());
}
<commit_msg>- set object name of browser pane to track it more easily<commit_after>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.

// Copyright (C) 2011 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#include "CQBrowserPane.h"

#include "listviews.h"

CQBrowserPane::CQBrowserPane(QWidget* parent) :
  QTreeView(parent)
{
  QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
  sizePolicy.setHorizontalStretch(0);
  sizePolicy.setVerticalStretch(0);
  sizePolicy.setHeightForWidth(this->sizePolicy().hasHeightForWidth());
  setSizePolicy(sizePolicy);
  setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
  setAutoScroll(true);
  setEditTriggers(QAbstractItemView::NoEditTriggers);
  setTextElideMode(Qt::ElideNone);
  setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
  setUniformRowHeights(true);
  setSortingEnabled(true);
  setHeaderHidden(true);
  setObjectName("CQBrowserPane");

  connect(this, SIGNAL(expanded(const QModelIndex &)), this, SLOT(slotUpdateScrollBar(const QModelIndex &)));
  connect(this, SIGNAL(collapsed(const QModelIndex &)), this, SLOT(slotUpdateScrollBar(const QModelIndex &)));
}

// virtual
CQBrowserPane::~CQBrowserPane()
{}

// virtual
void CQBrowserPane::currentChanged(const QModelIndex & current, const QModelIndex & /* previous */)
{
  static_cast< ListViews * >(parent())->slotFolderChanged(current);
}

void CQBrowserPane::slotUpdateScrollBar(const QModelIndex & index)
{
  resizeColumnToContents(index.column());
}
<|endoftext|>


<commit_before>#include <string>
#include <sstream>
#include <fstream>

#include "memory.h"
#include "../luts.h"

std::string mem_string( bool use_colors = false ) {
   std::ostringstream oss;

   unsigned int total_mem;
   unsigned int used_mem;
   unsigned int unused_mem;

   size_t substrStart;
   size_t substrLen;

   std::ifstream meminfo_file( "/proc/meminfo" );

   std::string mem_line;

   getline( meminfo_file, mem_line );
   substrStart = mem_line.find_first_of( ':' ) + 1;
   substrLen   = mem_line.find_first_of( 'k' );
   total_mem = stoi(mem_line.substr(substrStart, substrLen));

   used_mem = total_mem;

   for( unsigned int i = 0; i < 3; i++ ) {
      getline( meminfo_file, mem_line );
      substrStart = mem_line.find_first_of( ':' ) + 1;
      substrLen   = mem_line.find_first_of( 'k' );
      unused_mem = stoi(mem_line.substr(substrStart, substrLen));
      used_mem -= unused_mem;
   }

   meminfo_file.close();

   if( use_colors ) {
      oss << mem_lut[(100 * used_mem) / total_mem];
   }

   oss << used_mem / 1024 << '/' << total_mem / 1024 << "MB";

   if( use_colors ) {
      oss << "#[fg=default,bg=default]";
   }

   return oss.str();
}

<commit_msg>pulled Joe136 solution to MemAvailable being present in /proc/meminfo on some systems<commit_after>#include <string>
#include <sstream>
#include <fstream>

#include "memory.h"
#include "../luts.h"

std::string mem_string( bool use_colors = false ) {
   std::ostringstream oss;

   unsigned int total_mem;
   unsigned int used_mem;
   unsigned int unused_mem;

   size_t substrStart;
   size_t substrLen;

   std::ifstream meminfo_file( "/proc/meminfo" );

   std::string mem_line;

   getline( meminfo_file, mem_line );
   substrStart = mem_line.find_first_of( ':' ) + 1;
   substrLen   = mem_line.find_first_of( 'k' );
   total_mem = stoi(mem_line.substr(substrStart, substrLen));

   used_mem = total_mem;

   for( unsigned int i = 0; i < 3; i++ ) {
      getline( meminfo_file, mem_line );
	  // accomodate MemAvailable potentially being in lines 2-4 of
	  // /proc/meminfo. do this in a way to not break the original logic of the
	  // loop
	  if( mem_line.find("MemAvailable") == 0 )
        i--;
	  else {
		substrStart = mem_line.find_first_of( ':' ) + 1;
		substrLen   = mem_line.find_first_of( 'k' );
		unused_mem = stoi(mem_line.substr(substrStart, substrLen));
		used_mem -= unused_mem;
      }
   }

   meminfo_file.close();

   if( use_colors ) {
      oss << mem_lut[(100 * used_mem) / total_mem];
   }

   oss << used_mem / 1024 << '/' << total_mem / 1024 << "MB";

   if( use_colors ) {
      oss << "#[fg=default,bg=default]";
   }

   return oss.str();
}

<|endoftext|>