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

#include "coinbase-payee.h"
#include "util.h"
#include "addrman.h"
#include "masternode.h"
#include "darksend.h"
#include "masternodeman.h"
#include <boost/filesystem.hpp>

CCoinbasePayee coinbasePayee;

//
// CCoinbasePayeeDB
//

CCoinbasePayeeDB::CCoinbasePayeeDB()
{
    pathDB = GetDataDir() / "coinbase-payee.dat";
    strMagicMessage = "CoinbasePayeeDB";
}

bool CCoinbasePayeeDB::Write(const CCoinbasePayee& objToSave)
{
    int64_t nStart = GetTimeMillis();

    // serialize, checksum data up to that point, then append checksum
    CDataStream ssObj(SER_DISK, CLIENT_VERSION);
    ssObj << strMagicMessage; // masternode cache file specific magic message
    ssObj << FLATDATA(Params().MessageStart()); // network specific magic number
    ssObj << objToSave;
    uint256 hash = Hash(ssObj.begin(), ssObj.end());
    ssObj << hash;

    // open output file, and associate with CAutoFile
    FILE *file = fopen(pathDB.string().c_str(), "wb");
    CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
    if (fileout.IsNull())
        return error("%s : Failed to open file %s", __func__, pathDB.string());

    // Write and commit header, data
    try {
        fileout << ssObj;
    }
    catch (std::exception &e) {
        return error("%s : Serialize or I/O error - %s", __func__, e.what());
    }
    fileout.fclose();

    LogPrintf("Written info to coinbase-payee.dat  %dms\n", GetTimeMillis() - nStart);

    return true;
}

CCoinbasePayeeDB::ReadResult CCoinbasePayeeDB::Read(CCoinbasePayee& objToLoad)
{

    int64_t nStart = GetTimeMillis();
    // open input file, and associate with CAutoFile
    FILE *file = fopen(pathDB.string().c_str(), "rb");
    CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
    if (filein.IsNull())
    {
        error("%s : Failed to open file %s", __func__, pathDB.string());
        return FileError;
    }

    // use file size to size memory buffer
    int fileSize = boost::filesystem::file_size(pathDB);
    int dataSize = fileSize - sizeof(uint256);
    // Don't try to resize to a negative number if file is small
    if (dataSize < 0)
        dataSize = 0;
    vector<unsigned char> vchData;
    vchData.resize(dataSize);
    uint256 hashIn;

    // read data and checksum from file
    try {
        filein.read((char *)&vchData[0], dataSize);
        filein >> hashIn;
    }
    catch (std::exception &e) {
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return HashReadError;
    }
    filein.fclose();

    CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);

    // verify stored checksum matches input data
    uint256 hashTmp = Hash(ssObj.begin(), ssObj.end());
    if (hashIn != hashTmp)
    {
        error("%s : Checksum mismatch, data corrupted", __func__);
        return IncorrectHash;
    }

    unsigned char pchMsgTmp[4];
    std::string strMagicMessageTmp;
    try {
        // de-serialize file header (masternode cache file specific magic message) and ..
        ssObj >> strMagicMessageTmp;

        // ... verify the message matches predefined one
        if (strMagicMessage != strMagicMessageTmp)
        {
            error("%s : Invalid masternode cache magic message", __func__);
            return IncorrectMagicMessage;
        }

        // de-serialize file header (network specific magic number) and ..
        ssObj >> FLATDATA(pchMsgTmp);

        // ... verify the network matches ours
        if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
        {
            error("%s : Invalid network magic number", __func__);
            return IncorrectMagicNumber;
        }

        // de-serialize data into CCoinbasePayee object
        ssObj >> objToLoad;
    }
    catch (std::exception &e) {
        objToLoad.Clear();
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return IncorrectFormat;
    }

    objToLoad.CleanUp(); // clean out expired
    LogPrintf("Loaded info from coinbase-payee.dat  %dms\n", GetTimeMillis() - nStart);
    LogPrintf("  %s\n", objToLoad.ToString());

    return Ok;
}

void DumpCoinbasePayees()
{
    int64_t nStart = GetTimeMillis();

    CCoinbasePayeeDB mndb;
    CCoinbasePayee temp;

    LogPrintf("Verifying coinbase-payee.dat format...\n");
    CCoinbasePayeeDB::ReadResult readResult = mndb.Read(temp);
    // there was an error and it was not an error on file openning => do not proceed
    if (readResult == CCoinbasePayeeDB::FileError)
        LogPrintf("Missing payees cache file - coinbase-payee.dat, will try to recreate\n");
    else if (readResult != CCoinbasePayeeDB::Ok)
    {
        LogPrintf("Error reading coinbase-payee.dat: ");
        if(readResult == CCoinbasePayeeDB::IncorrectFormat)
            LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
        else
        {
            LogPrintf("file format is unknown or invalid, please fix it manually\n");
            return;
        }
    }
    LogPrintf("Writting info to coinbase-payee.dat...\n");
    mndb.Write(coinbasePayee);

    LogPrintf("Coinbase payee dump finished  %dms\n", GetTimeMillis() - nStart);
}

void CCoinbasePayee::BuildIndex()
{
    if(mapPaidTime.size() > 0) {
        LogPrintf("CCoinbasePayee::BuildIndex - coinbase cache exists, skipping BuildIndex\n");
        return;
    }

    //scan last 30 days worth of blocks (from oldest to newest in that order), run processBlockCoinbaseTX for each
}

void CCoinbasePayee::ProcessBlockCoinbaseTX(CTransaction& txCoinbase, int64_t nTime)
{
    if (!txCoinbase.IsCoinBase()){
        LogPrintf("ERROR: CCoinbasePayee::ProcessBlockCoinbaseTX - tx is not coinbase\n");
        return;
    }

    BOOST_FOREACH(CTxOut out, txCoinbase.vout){
        uint256 h = GetScriptHash(out.scriptPubKey);
        mapPaidTime[h] = nTime;
    }
}

int64_t CCoinbasePayee::GetLastPaid(CScript& pubkey)
{
    uint256 h = GetScriptHash(pubkey);

    if(mapPaidTime.count(h)){
        return mapPaidTime[h];
    }

    return 0;
}

void CCoinbasePayee::CleanUp()
{
    std::map<uint256, int64_t>::iterator it = mapPaidTime.begin();
    while(it != mapPaidTime.end())
    {
        //keep 30 days of history
        if((*it).second < GetAdjustedTime() - (60*60*24*30)) {
            mapPaidTime.erase(it++);
        } else {
            ++it;
        }
    }
}<commit_msg>Scan blocks if coinpayee cache is not present<commit_after>// Copyright (c) 2014-2015 The Dash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "coinbase-payee.h"
#include "util.h"
#include "addrman.h"
#include "masternode.h"
#include "darksend.h"
#include "masternodeman.h"
#include <boost/filesystem.hpp>

CCoinbasePayee coinbasePayee;

//
// CCoinbasePayeeDB
//

CCoinbasePayeeDB::CCoinbasePayeeDB()
{
    pathDB = GetDataDir() / "coinbase-payee.dat";
    strMagicMessage = "CoinbasePayeeDB";
}

bool CCoinbasePayeeDB::Write(const CCoinbasePayee& objToSave)
{
    int64_t nStart = GetTimeMillis();

    // serialize, checksum data up to that point, then append checksum
    CDataStream ssObj(SER_DISK, CLIENT_VERSION);
    ssObj << strMagicMessage; // masternode cache file specific magic message
    ssObj << FLATDATA(Params().MessageStart()); // network specific magic number
    ssObj << objToSave;
    uint256 hash = Hash(ssObj.begin(), ssObj.end());
    ssObj << hash;

    // open output file, and associate with CAutoFile
    FILE *file = fopen(pathDB.string().c_str(), "wb");
    CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
    if (fileout.IsNull())
        return error("%s : Failed to open file %s", __func__, pathDB.string());

    // Write and commit header, data
    try {
        fileout << ssObj;
    }
    catch (std::exception &e) {
        return error("%s : Serialize or I/O error - %s", __func__, e.what());
    }
    fileout.fclose();

    LogPrintf("Written info to coinbase-payee.dat  %dms\n", GetTimeMillis() - nStart);

    return true;
}

CCoinbasePayeeDB::ReadResult CCoinbasePayeeDB::Read(CCoinbasePayee& objToLoad)
{

    int64_t nStart = GetTimeMillis();
    // open input file, and associate with CAutoFile
    FILE *file = fopen(pathDB.string().c_str(), "rb");
    CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
    if (filein.IsNull())
    {
        error("%s : Failed to open file %s", __func__, pathDB.string());
        return FileError;
    }

    // use file size to size memory buffer
    int fileSize = boost::filesystem::file_size(pathDB);
    int dataSize = fileSize - sizeof(uint256);
    // Don't try to resize to a negative number if file is small
    if (dataSize < 0)
        dataSize = 0;
    vector<unsigned char> vchData;
    vchData.resize(dataSize);
    uint256 hashIn;

    // read data and checksum from file
    try {
        filein.read((char *)&vchData[0], dataSize);
        filein >> hashIn;
    }
    catch (std::exception &e) {
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return HashReadError;
    }
    filein.fclose();

    CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);

    // verify stored checksum matches input data
    uint256 hashTmp = Hash(ssObj.begin(), ssObj.end());
    if (hashIn != hashTmp)
    {
        error("%s : Checksum mismatch, data corrupted", __func__);
        return IncorrectHash;
    }

    unsigned char pchMsgTmp[4];
    std::string strMagicMessageTmp;
    try {
        // de-serialize file header (masternode cache file specific magic message) and ..
        ssObj >> strMagicMessageTmp;

        // ... verify the message matches predefined one
        if (strMagicMessage != strMagicMessageTmp)
        {
            error("%s : Invalid masternode cache magic message", __func__);
            return IncorrectMagicMessage;
        }

        // de-serialize file header (network specific magic number) and ..
        ssObj >> FLATDATA(pchMsgTmp);

        // ... verify the network matches ours
        if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
        {
            error("%s : Invalid network magic number", __func__);
            return IncorrectMagicNumber;
        }

        // de-serialize data into CCoinbasePayee object
        ssObj >> objToLoad;
    }
    catch (std::exception &e) {
        objToLoad.Clear();
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return IncorrectFormat;
    }

    objToLoad.CleanUp(); // clean out expired
    LogPrintf("Loaded info from coinbase-payee.dat  %dms\n", GetTimeMillis() - nStart);
    LogPrintf("  %s\n", objToLoad.ToString());

    return Ok;
}

void DumpCoinbasePayees()
{
    int64_t nStart = GetTimeMillis();

    CCoinbasePayeeDB mndb;
    CCoinbasePayee temp;

    LogPrintf("Verifying coinbase-payee.dat format...\n");
    CCoinbasePayeeDB::ReadResult readResult = mndb.Read(temp);
    // there was an error and it was not an error on file openning => do not proceed
    if (readResult == CCoinbasePayeeDB::FileError)
        LogPrintf("Missing payees cache file - coinbase-payee.dat, will try to recreate\n");
    else if (readResult != CCoinbasePayeeDB::Ok)
    {
        LogPrintf("Error reading coinbase-payee.dat: ");
        if(readResult == CCoinbasePayeeDB::IncorrectFormat)
            LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
        else
        {
            LogPrintf("file format is unknown or invalid, please fix it manually\n");
            return;
        }
    }
    LogPrintf("Writting info to coinbase-payee.dat...\n");
    mndb.Write(coinbasePayee);

    LogPrintf("Coinbase payee dump finished  %dms\n", GetTimeMillis() - nStart);
}

void CCoinbasePayee::BuildIndex()
{
    if(mapPaidTime.size() > 0) {
        LogPrintf("CCoinbasePayee::BuildIndex - coinbase cache exists, skipping BuildIndex\n");
        return;
    }

    //scan last 30 days worth of blocks, run processBlockCoinbaseTX for each

    CBlockIndex* pindexPrev = chainActive.Tip();
    int count = 0;

    for (unsigned int i = 1; pindexPrev && pindexPrev->nHeight > 0; i++) {
        count++;
        if(count > 18000) return;

        CBlock block;
        if (ReadBlockFromDisk(block, pindexPrev)) {
            printf("scan block\n");
            ProcessBlockCoinbaseTX(block.vtx[0], block.nTime);
        }

        if (pindexPrev->pprev == NULL) { assert(pindexPrev); break; }
        pindexPrev = pindexPrev->pprev;
    }

    return;
}

void CCoinbasePayee::ProcessBlockCoinbaseTX(CTransaction& txCoinbase, int64_t nTime)
{
    if (!txCoinbase.IsCoinBase()){
        LogPrintf("ERROR: CCoinbasePayee::ProcessBlockCoinbaseTX - tx is not coinbase\n");
        return;
    }

    BOOST_FOREACH(CTxOut out, txCoinbase.vout){
        uint256 h = GetScriptHash(out.scriptPubKey);
        if(mapPaidTime.count(h)){
            if(mapPaidTime[h] < nTime) {
                mapPaidTime[h] = nTime;
            }
        } else {
            mapPaidTime[h] = nTime;
        }
    }
}

int64_t CCoinbasePayee::GetLastPaid(CScript& pubkey)
{
    uint256 h = GetScriptHash(pubkey);

    if(mapPaidTime.count(h)){
        return mapPaidTime[h];
    }

    return 0;
}

void CCoinbasePayee::CleanUp()
{
    std::map<uint256, int64_t>::iterator it = mapPaidTime.begin();
    while(it != mapPaidTime.end())
    {
        //keep 30 days of history
        if((*it).second < GetAdjustedTime() - (60*60*24*30)) {
            mapPaidTime.erase(it++);
        } else {
            ++it;
        }
    }
}<|endoftext|>


<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.

HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.

Redistribution and use of HOOMD-blue, 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 copyright holder nor the names of HOOMD-blue's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.

Disclaimer

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR
ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/

// $Id$
// $URL$
// Maintainer: ndtrung

#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif

#include <boost/python.hpp>
using namespace boost::python;

#include "FIREEnergyMinimizerRigid.h"
#include "TwoStepNVERigid.h"

/*! \file FIREEnergyMinimizerRigid.h
    \brief Contains code for the FIREEnergyMinimizerRigid class
*/

/*! \param sysdef SystemDefinition this method will act on. Must not be NULL.
    \param group The group of particles this integration method is to work on (group is a placeholder for now)
    \param dt Time step for MD integrator
    \param reset_and_create_integrator Flag to indicate if resetting and creating integrator are needed
    \post The method is constructed with the given particle data and a NULL profiler.
*/
FIREEnergyMinimizerRigid::FIREEnergyMinimizerRigid(boost::shared_ptr<SystemDefinition> sysdef,
                                                    boost::shared_ptr<ParticleGroup> group,
                                                    Scalar dt,
                                                    bool reset_and_create_integrator)
    :   FIREEnergyMinimizer(sysdef, group, dt, false) // using false for the parent class
    {
    const ParticleDataArraysConst& arrays = m_pdata->acquireReadOnly();
    m_nparticles = arrays.nparticles;
    m_pdata->release();

    // Get the system rigid data
    m_rigid_data = sysdef->getRigidData();

    // Create my rigid body group from the particle group
    m_body_group = boost::shared_ptr<RigidBodyGroup>(new RigidBodyGroup(sysdef, m_group));

    // Get the number of rigid bodies for frequent use
    m_n_bodies = m_body_group->getNumMembers();

    if (m_n_bodies == 0)
        {
        cout << "***Warning! Empty group of rigid bodies." << endl;
        }

    // Time steps to run NVE between minimizer moves
    m_nevery = 1;

    // sanity check
    assert(m_sysdef);
    assert(m_pdata);
    if (reset_and_create_integrator)
        {
        reset();
        boost::shared_ptr<TwoStepNVERigid> integrator(new TwoStepNVERigid(sysdef, group));
        addIntegrationMethod(integrator);
        setDeltaT(m_deltaT);
        }
    }

/*! Reset minimizer parameters and zero velocities
*/
void FIREEnergyMinimizerRigid::reset()
    {
    m_converged = false;
    m_n_since_negative = m_nmin+1;
    m_n_since_start++;
    m_alpha = m_alpha_start;
    m_was_reset = true;

    ArrayHandle<Scalar4> vel_handle(m_rigid_data->getVel(), access_location::host, access_mode::readwrite);
    ArrayHandle<Scalar4> angmom_handle(m_rigid_data->getAngMom(), access_location::host, access_mode::readwrite);
    for (unsigned int group_idx = 0; group_idx < m_n_bodies; group_idx++)
        {
        unsigned int body = m_body_group->getMemberIndex(group_idx);

        // scales translational velocity
        vel_handle.data[body].x = 0.0;
        vel_handle.data[body].y = 0.0;
        vel_handle.data[body].z = 0.0;

        angmom_handle.data[body].x = 0.0;
        angmom_handle.data[body].y = 0.0;
        angmom_handle.data[body].z = 0.0;
        }

    setDeltaT(m_deltaT_set);
    }

/*! \param timestep is the current timestep
*/
void FIREEnergyMinimizerRigid::update(unsigned int timestep)
    {
    if (m_converged)
        return;

    IntegratorTwoStep::update(timestep);

    if (timestep % m_nevery != 0)
        return;

    if (m_n_bodies <= 0)
        {
        cerr << endl << "***Error! FIREENergyMinimizerRigid: There is no rigid body for this integrator" << endl << endl;
        throw runtime_error("Error update for FIREEnergyMinimizerRigid (no rigid body)");
        return;
        }

    Scalar Pt(0.0), Pr(0.0);
    Scalar vnorm(0.0), wnorm(0.0);
    Scalar fnorm(0.0), tnorm(0.0);

    // The energy minimized is currently the system potential energy
    Scalar energy = computePotentialEnergy(timestep) / m_nparticles;

    if (m_was_reset)
        {
        m_was_reset = false;
        m_old_energy = energy + Scalar(100000) * m_etol;
        }

    ArrayHandle<Scalar4> vel_handle(m_rigid_data->getVel(), access_location::host, access_mode::readwrite);
    ArrayHandle<Scalar4> angmom_handle(m_rigid_data->getAngMom(), access_location::host, access_mode::readwrite);
    ArrayHandle<Scalar4> angvel_handle(m_rigid_data->getAngVel(), access_location::host, access_mode::read);
    ArrayHandle<Scalar4> force_handle(m_rigid_data->getForce(), access_location::host, access_mode::read);
    ArrayHandle<Scalar4> torque_handle(m_rigid_data->getTorque(), access_location::host, access_mode::read);

    // Calculates the powers
    for (unsigned int group_idx = 0; group_idx < m_n_bodies; group_idx++)
        {
        unsigned int body = m_body_group->getMemberIndex(group_idx);

        // translational power = force * vel
        Pt += force_handle.data[body].x * vel_handle.data[body].x + force_handle.data[body].y * vel_handle.data[body].y
                + force_handle.data[body].z * vel_handle.data[body].z;
        fnorm += force_handle.data[body].x * force_handle.data[body].x + force_handle.data[body].y * force_handle.data[body].y
                + force_handle.data[body].z * force_handle.data[body].z;
        vnorm += vel_handle.data[body].x * vel_handle.data[body].x + vel_handle.data[body].y * vel_handle.data[body].y
                + vel_handle.data[body].z * vel_handle.data[body].z;

        // rotational power = torque * angvel
        Pr += torque_handle.data[body].x * angvel_handle.data[body].x + torque_handle.data[body].y * angvel_handle.data[body].y
                + torque_handle.data[body].z * angvel_handle.data[body].z;
        tnorm += torque_handle.data[body].x * torque_handle.data[body].x + torque_handle.data[body].y * torque_handle.data[body].y
                + torque_handle.data[body].z * torque_handle.data[body].z;
        wnorm += angvel_handle.data[body].x * angvel_handle.data[body].x + angvel_handle.data[body].y * angvel_handle.data[body].y
                + angvel_handle.data[body].z * angvel_handle.data[body].z;
        }

    fnorm = sqrt(fnorm);
    vnorm = sqrt(vnorm);

    tnorm = sqrt(tnorm);
    wnorm = sqrt(wnorm);

//  printf("f = %g (%g); e = %g (%g)\n", fnorm/sqrt(m_sysdef->getNDimensions() * m_n_bodies), m_ftol, fabs(energy-m_old_energy), m_etol);

    if ((fnorm/sqrt(m_sysdef->getNDimensions() * m_n_bodies) < m_ftol || fabs(energy-m_old_energy) < m_etol) && m_n_since_start >= m_run_minsteps)
        {
        printf("Converged: f = %g (ftol = %g); e = %g (etol = %g)\n", fnorm/sqrt(m_sysdef->getNDimensions() * m_n_bodies), m_ftol, fabs(energy-m_old_energy), m_etol);
        m_converged = true;
        return;
        }

    // Scales velocities and angular momenta
    Scalar factor_t, factor_r;
    if (fabs(fnorm) > EPSILON)
        factor_t = m_alpha * vnorm / fnorm;
    else
        factor_t = 1.0;

    if (fabs(tnorm) > EPSILON)
        factor_r = m_alpha * wnorm / tnorm;
    else
        factor_r = 1.0;

    for (unsigned int group_idx = 0; group_idx < m_n_bodies; group_idx++)
        {
        unsigned int body = m_body_group->getMemberIndex(group_idx);

        // scales translational velocity
        vel_handle.data[body].x = vel_handle.data[body].x * (1.0 - m_alpha) + force_handle.data[body].x * factor_t;
        vel_handle.data[body].y = vel_handle.data[body].y * (1.0 - m_alpha) + force_handle.data[body].y * factor_t;
        vel_handle.data[body].z = vel_handle.data[body].z * (1.0 - m_alpha) + force_handle.data[body].z * factor_t;

        // scales angular momenta (now using the same m_alpha as translational)
        angmom_handle.data[body].x = angmom_handle.data[body].x * (1.0 - m_alpha) + torque_handle.data[body].x * factor_r;
        angmom_handle.data[body].y = angmom_handle.data[body].y * (1.0 - m_alpha) + torque_handle.data[body].y * factor_r;
        angmom_handle.data[body].z = angmom_handle.data[body].z * (1.0 - m_alpha) + torque_handle.data[body].z * factor_r;
        }

    // A simply naive measure is to sum up the power coming from translational and rotational motions,
    // more sophisticated measure can be devised later
    Scalar P = Pt + Pr;
    if (P > Scalar(0.0))
        {
        m_n_since_negative++;
        if (m_n_since_negative > m_nmin) // has been positive for a while?
            {
            IntegratorTwoStep::setDeltaT(std::min(m_deltaT * m_finc, m_deltaT_max));
            m_alpha *= m_falpha; // decreases m_alpha to reduce the influence of the power on the velocities in searching for the well
            }
        }
    else if (P <= Scalar(0.0))
        {
        IntegratorTwoStep::setDeltaT(m_deltaT * m_fdec);
        m_alpha = m_alpha_start;
        m_n_since_negative = 0;
        for (unsigned int group_idx = 0; group_idx < m_n_bodies; group_idx++)
            {
            unsigned int body = m_body_group->getMemberIndex(group_idx);

            vel_handle.data[body].x = Scalar(0.0);
            vel_handle.data[body].y = Scalar(0.0);
            vel_handle.data[body].z = Scalar(0.0);

            angmom_handle.data[body].x = Scalar(0.0);
            angmom_handle.data[body].y = Scalar(0.0);
            angmom_handle.data[body].z = Scalar(0.0);
            }
        }

    m_n_since_start++;
    m_old_energy = energy;
    }

void export_FIREEnergyMinimizerRigid()
    {
    class_<FIREEnergyMinimizerRigid, boost::shared_ptr<FIREEnergyMinimizerRigid>, bases<FIREEnergyMinimizer>, boost::noncopyable>
        ("FIREEnergyMinimizerRigid", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<ParticleGroup>, Scalar >())
        .def("getEvery", &FIREEnergyMinimizerRigid::getEvery)
        .def("setEvery", &FIREEnergyMinimizerRigid::setEvery);
    }

#ifdef WIN32
#pragma warning( pop )
#endif

<commit_msg>Commented out offending code that breaks compilation<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.

HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.

Redistribution and use of HOOMD-blue, 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 copyright holder nor the names of HOOMD-blue's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.

Disclaimer

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR
ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/

// $Id$
// $URL$
// Maintainer: ndtrung

#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif

#include <boost/python.hpp>
using namespace boost::python;

#include "FIREEnergyMinimizerRigid.h"
#include "TwoStepNVERigid.h"

/*! \file FIREEnergyMinimizerRigid.h
    \brief Contains code for the FIREEnergyMinimizerRigid class
*/

/*! \param sysdef SystemDefinition this method will act on. Must not be NULL.
    \param group The group of particles this integration method is to work on (group is a placeholder for now)
    \param dt Time step for MD integrator
    \param reset_and_create_integrator Flag to indicate if resetting and creating integrator are needed
    \post The method is constructed with the given particle data and a NULL profiler.
*/
FIREEnergyMinimizerRigid::FIREEnergyMinimizerRigid(boost::shared_ptr<SystemDefinition> sysdef,
                                                    boost::shared_ptr<ParticleGroup> group,
                                                    Scalar dt,
                                                    bool reset_and_create_integrator)
    :   FIREEnergyMinimizer(sysdef, group, dt, false) // using false for the parent class
    {
    const ParticleDataArraysConst& arrays = m_pdata->acquireReadOnly();
    m_nparticles = arrays.nparticles;
    m_pdata->release();

    // Get the system rigid data
    m_rigid_data = sysdef->getRigidData();

    // Create my rigid body group from the particle group
    m_body_group = boost::shared_ptr<RigidBodyGroup>(new RigidBodyGroup(sysdef, m_group));

    // Get the number of rigid bodies for frequent use
    m_n_bodies = m_body_group->getNumMembers();

    if (m_n_bodies == 0)
        {
        cout << "***Warning! Empty group of rigid bodies." << endl;
        }

    // Time steps to run NVE between minimizer moves
    m_nevery = 1;

    // sanity check
    assert(m_sysdef);
    assert(m_pdata);
    if (reset_and_create_integrator)
        {
        reset();
        boost::shared_ptr<TwoStepNVERigid> integrator(new TwoStepNVERigid(sysdef, group));
        addIntegrationMethod(integrator);
        setDeltaT(m_deltaT);
        }
    }

/*! Reset minimizer parameters and zero velocities
*/
void FIREEnergyMinimizerRigid::reset()
    {
    m_converged = false;
    m_n_since_negative = m_nmin+1;
    m_n_since_start++;
    m_alpha = m_alpha_start;
    m_was_reset = true;

    ArrayHandle<Scalar4> vel_handle(m_rigid_data->getVel(), access_location::host, access_mode::readwrite);
    ArrayHandle<Scalar4> angmom_handle(m_rigid_data->getAngMom(), access_location::host, access_mode::readwrite);
    for (unsigned int group_idx = 0; group_idx < m_n_bodies; group_idx++)
        {
        unsigned int body = m_body_group->getMemberIndex(group_idx);

        // scales translational velocity
        vel_handle.data[body].x = 0.0;
        vel_handle.data[body].y = 0.0;
        vel_handle.data[body].z = 0.0;

        angmom_handle.data[body].x = 0.0;
        angmom_handle.data[body].y = 0.0;
        angmom_handle.data[body].z = 0.0;
        }

    setDeltaT(m_deltaT_set);
    }

/*! \param timestep is the current timestep
*/
void FIREEnergyMinimizerRigid::update(unsigned int timestep)
    {
    if (m_converged)
        return;

    IntegratorTwoStep::update(timestep);

    if (timestep % m_nevery != 0)
        return;

    if (m_n_bodies <= 0)
        {
        cerr << endl << "***Error! FIREENergyMinimizerRigid: There is no rigid body for this integrator" << endl << endl;
        throw runtime_error("Error update for FIREEnergyMinimizerRigid (no rigid body)");
        return;
        }

    Scalar Pt(0.0), Pr(0.0);
    Scalar vnorm(0.0), wnorm(0.0);
    Scalar fnorm(0.0), tnorm(0.0);

    // The energy minimized is currently the system potential energy
    throw std::runtime_error("Error: FIRE rigid needs to be fixed");
    //Scalar energy = computePotentialEnergy(timestep) / m_nparticles;
    Scalar energy = 0.0;

    if (m_was_reset)
        {
        m_was_reset = false;
        m_old_energy = energy + Scalar(100000) * m_etol;
        }

    ArrayHandle<Scalar4> vel_handle(m_rigid_data->getVel(), access_location::host, access_mode::readwrite);
    ArrayHandle<Scalar4> angmom_handle(m_rigid_data->getAngMom(), access_location::host, access_mode::readwrite);
    ArrayHandle<Scalar4> angvel_handle(m_rigid_data->getAngVel(), access_location::host, access_mode::read);
    ArrayHandle<Scalar4> force_handle(m_rigid_data->getForce(), access_location::host, access_mode::read);
    ArrayHandle<Scalar4> torque_handle(m_rigid_data->getTorque(), access_location::host, access_mode::read);

    // Calculates the powers
    for (unsigned int group_idx = 0; group_idx < m_n_bodies; group_idx++)
        {
        unsigned int body = m_body_group->getMemberIndex(group_idx);

        // translational power = force * vel
        Pt += force_handle.data[body].x * vel_handle.data[body].x + force_handle.data[body].y * vel_handle.data[body].y
                + force_handle.data[body].z * vel_handle.data[body].z;
        fnorm += force_handle.data[body].x * force_handle.data[body].x + force_handle.data[body].y * force_handle.data[body].y
                + force_handle.data[body].z * force_handle.data[body].z;
        vnorm += vel_handle.data[body].x * vel_handle.data[body].x + vel_handle.data[body].y * vel_handle.data[body].y
                + vel_handle.data[body].z * vel_handle.data[body].z;

        // rotational power = torque * angvel
        Pr += torque_handle.data[body].x * angvel_handle.data[body].x + torque_handle.data[body].y * angvel_handle.data[body].y
                + torque_handle.data[body].z * angvel_handle.data[body].z;
        tnorm += torque_handle.data[body].x * torque_handle.data[body].x + torque_handle.data[body].y * torque_handle.data[body].y
                + torque_handle.data[body].z * torque_handle.data[body].z;
        wnorm += angvel_handle.data[body].x * angvel_handle.data[body].x + angvel_handle.data[body].y * angvel_handle.data[body].y
                + angvel_handle.data[body].z * angvel_handle.data[body].z;
        }

    fnorm = sqrt(fnorm);
    vnorm = sqrt(vnorm);

    tnorm = sqrt(tnorm);
    wnorm = sqrt(wnorm);

//  printf("f = %g (%g); e = %g (%g)\n", fnorm/sqrt(m_sysdef->getNDimensions() * m_n_bodies), m_ftol, fabs(energy-m_old_energy), m_etol);

    if ((fnorm/sqrt(m_sysdef->getNDimensions() * m_n_bodies) < m_ftol || fabs(energy-m_old_energy) < m_etol) && m_n_since_start >= m_run_minsteps)
        {
        printf("Converged: f = %g (ftol = %g); e = %g (etol = %g)\n", fnorm/sqrt(m_sysdef->getNDimensions() * m_n_bodies), m_ftol, fabs(energy-m_old_energy), m_etol);
        m_converged = true;
        return;
        }

    // Scales velocities and angular momenta
    Scalar factor_t, factor_r;
    if (fabs(fnorm) > EPSILON)
        factor_t = m_alpha * vnorm / fnorm;
    else
        factor_t = 1.0;

    if (fabs(tnorm) > EPSILON)
        factor_r = m_alpha * wnorm / tnorm;
    else
        factor_r = 1.0;

    for (unsigned int group_idx = 0; group_idx < m_n_bodies; group_idx++)
        {
        unsigned int body = m_body_group->getMemberIndex(group_idx);

        // scales translational velocity
        vel_handle.data[body].x = vel_handle.data[body].x * (1.0 - m_alpha) + force_handle.data[body].x * factor_t;
        vel_handle.data[body].y = vel_handle.data[body].y * (1.0 - m_alpha) + force_handle.data[body].y * factor_t;
        vel_handle.data[body].z = vel_handle.data[body].z * (1.0 - m_alpha) + force_handle.data[body].z * factor_t;

        // scales angular momenta (now using the same m_alpha as translational)
        angmom_handle.data[body].x = angmom_handle.data[body].x * (1.0 - m_alpha) + torque_handle.data[body].x * factor_r;
        angmom_handle.data[body].y = angmom_handle.data[body].y * (1.0 - m_alpha) + torque_handle.data[body].y * factor_r;
        angmom_handle.data[body].z = angmom_handle.data[body].z * (1.0 - m_alpha) + torque_handle.data[body].z * factor_r;
        }

    // A simply naive measure is to sum up the power coming from translational and rotational motions,
    // more sophisticated measure can be devised later
    Scalar P = Pt + Pr;
    if (P > Scalar(0.0))
        {
        m_n_since_negative++;
        if (m_n_since_negative > m_nmin) // has been positive for a while?
            {
            IntegratorTwoStep::setDeltaT(std::min(m_deltaT * m_finc, m_deltaT_max));
            m_alpha *= m_falpha; // decreases m_alpha to reduce the influence of the power on the velocities in searching for the well
            }
        }
    else if (P <= Scalar(0.0))
        {
        IntegratorTwoStep::setDeltaT(m_deltaT * m_fdec);
        m_alpha = m_alpha_start;
        m_n_since_negative = 0;
        for (unsigned int group_idx = 0; group_idx < m_n_bodies; group_idx++)
            {
            unsigned int body = m_body_group->getMemberIndex(group_idx);

            vel_handle.data[body].x = Scalar(0.0);
            vel_handle.data[body].y = Scalar(0.0);
            vel_handle.data[body].z = Scalar(0.0);

            angmom_handle.data[body].x = Scalar(0.0);
            angmom_handle.data[body].y = Scalar(0.0);
            angmom_handle.data[body].z = Scalar(0.0);
            }
        }

    m_n_since_start++;
    m_old_energy = energy;
    }

void export_FIREEnergyMinimizerRigid()
    {
    class_<FIREEnergyMinimizerRigid, boost::shared_ptr<FIREEnergyMinimizerRigid>, bases<FIREEnergyMinimizer>, boost::noncopyable>
        ("FIREEnergyMinimizerRigid", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<ParticleGroup>, Scalar >())
        .def("getEvery", &FIREEnergyMinimizerRigid::getEvery)
        .def("setEvery", &FIREEnergyMinimizerRigid::setEvery);
    }

#ifdef WIN32
#pragma warning( pop )
#endif

<|endoftext|>


<commit_before>/*
    This file is part of libkpimexchange.
    Copyright (c) 2002 Jan-Pascal van Best <janpascal@vanbest.org>

    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; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
    02111-1307, USA.
*/

#include <stdlib.h>

#include <qdatetime.h>
#include <qstring.h>
#include <qptrlist.h>

#include <kdebug.h>

#include <libkcal/calendarlocal.h>
#include <libkcal/calendar.h>
#include <libkcal/journal.h>

#include "dateset.h"
#include "exchangeaccount.h"
#include "exchangeclient.h"

#include "exchangecalendar.h"

using namespace KCal;
using namespace KPIM;

ExchangeCalendar::ExchangeCalendar( KPIM::ExchangeAccount* account )
  : Calendar()
{
  init( account );
  mCache = new CalendarLocal();
}

ExchangeCalendar::ExchangeCalendar( KPIM::ExchangeAccount* account, const QString &timeZoneId)
  : Calendar(timeZoneId)
{
  init( account );
  mCache = new CalendarLocal( timeZoneId );
}

void ExchangeCalendar::init( KPIM::ExchangeAccount* account )
{
  kdDebug() << "ExchangeCalendar::init()" << endl;
  mAccount = account;
  mClient = new ExchangeClient( account );
  mDates = new DateSet();

  mEventDates = new QMap<Event,QDateTime>();
  mCacheDates = new QMap<QDate, QDateTime>();

  mCachedSeconds = 600; // After 5 minutes, reread from server
  // mOldestDate = 0L;
  // mNewestDate = 0L;
}

ExchangeCalendar::~ExchangeCalendar()
{
  kdDebug() << "Destructing ExchangeCalendar" << endl;
  close();
  // delete mNewestDate;
  // delete mOldestDate;
  delete mDates;
  delete mClient;
  delete mEventDates;
  delete mCacheDates;
  delete mCache;
}

bool ExchangeCalendar::load( const QString &fileName )
{
  // return mCache->load( fileName );
  return true;
}

bool ExchangeCalendar::save( const QString &fileName, CalFormat *format )
{
  return mCache->save( fileName, format );
}

void ExchangeCalendar::close()
{
  mCache->close();
  setModified( false );
}

void ExchangeCalendar::addEvent(Event *anEvent)
{
  kdDebug() << "ExchangeCalendar::addEvent" << endl;
  mCache->addEvent( anEvent );
  insertEvent(anEvent);

  anEvent->registerObserver( this );

  setModified( true );
}

// probably not really efficient, but...it works for now.
void ExchangeCalendar::deleteEvent(Event *event)
{
  kdDebug(5800) << "ExchangeCalendar::deleteEvent" << endl;
  mCache->deleteEvent( event );
  setModified( true );
}

Event *ExchangeCalendar::event( const QString &uid )
{
  kdDebug(5800) << "ExchangeCalendar::event(): " << uid << endl;

  return mCache->event( uid );
}

void ExchangeCalendar::addTodo(Todo *todo)
{
  mCache->addTodo( todo );

  todo->registerObserver( this );

  setModified( true );
}

void ExchangeCalendar::deleteTodo(Todo *todo)
{
  mCache->deleteTodo( todo );

  setModified( true );
}

QPtrList<Todo> ExchangeCalendar::rawTodos() const
{
  return mCache->rawTodos();
}

Todo *ExchangeCalendar::todo( const QString &uid )
{
  return mCache->todo( uid );
}

QPtrList<Todo> ExchangeCalendar::todos( const QDate &date )
{
  return mCache->todos( date );
}

int ExchangeCalendar::numEvents(const QDate &qd)
{
   kdDebug() << "ExchangeCalendar::numEvents" << endl;
  return mCache->numEvents( qd );
}

Alarm::List ExchangeCalendar::alarmsTo( const QDateTime &to )
{
  return mCache->alarmsTo( to );
}

Alarm::List ExchangeCalendar::alarms( const QDateTime &from, const QDateTime &to )
{
  kdDebug(5800) << "ExchangeCalendar::alarms(" << from.toString() << " - " << to.toString() << ")\n";
  return mCache->alarms( from, to );
}

/****************************** PROTECTED METHODS ****************************/

// after changes are made to an event, this should be called.
void ExchangeCalendar::update(IncidenceBase *incidence)
{
  setModified( true );
}

// this function will take a VEvent and insert it into the event
// dictionary for the ExchangeCalendar.  If there is no list of events for that
// particular location in the dictionary, a new one will be created.
void ExchangeCalendar::insertEvent(const Event *anEvent)
{
  kdDebug() << "ExchangeCalendar::insertEvent" << endl;

}

// taking a QDate, this function will look for an eventlist in the dict
// with that date attached -
QPtrList<Event> ExchangeCalendar::rawEventsForDate(const QDate &qd, bool sorted)
{
  kdDebug() << "ExchangeCalendar::rawEventsForDate(" << qd.toString() << "," << sorted << ")" << endl;

  // If the events for this date are not in the cache, or if they are old,
  // get them again
  QDateTime now = QDateTime::currentDateTime();
  // kdDebug() << "Now is " << now.toString() << endl;
  // kdDebug() << "mDates: " << mDates << endl;
  // kdDebug() << "mDates->contains(qd) is " << mDates->contains( qd ) << endl;
  if ( !mDates->contains( qd ) || (*mCacheDates)[qd].secsTo( now ) > mCachedSeconds ) {
    kdDebug() << "Reading events for date " << qd.toString() << endl;
    mClient->downloadSynchronous( mCache, qd, qd );
    mDates->add( qd );
    mCacheDates->insert( qd, now );
  }

  // Events are safely in the cache now, return them from cache
  QPtrList<Event> events = mCache->rawEventsForDate( qd, sorted );
  kdDebug() << "Found " << events.count() << " events." << endl;
  return events;

/*
  if (!sorted) {
    return eventList;
  }

  //  kdDebug(5800) << "Sorting events for date\n" << endl;
  // now, we have to sort it based on getDtStart.time()
  QPtrList<Event> eventListSorted;
  for (anEvent = eventList.first(); anEvent; anEvent = eventList.next()) {
    if (!eventListSorted.isEmpty() &&
	anEvent->dtStart().time() < eventListSorted.at(0)->dtStart().time()) {
      eventListSorted.insert(0,anEvent);
      goto nextToInsert;
    }
    for (i = 0; (uint) i+1 < eventListSorted.count(); i++) {
      if (anEvent->dtStart().time() > eventListSorted.at(i)->dtStart().time() &&
	  anEvent->dtStart().time() <= eventListSorted.at(i+1)->dtStart().time()) {
	eventListSorted.insert(i+1,anEvent);
	goto nextToInsert;
      }
    }
    eventListSorted.append(anEvent);
  nextToInsert:
    continue;
  }
  return eventListSorted;
*/
}

QPtrList<Event> ExchangeCalendar::rawEvents( const QDate &start, const QDate &end,
                                          bool inclusive )
{
   kdDebug() << "ExchangeCalendar::rawEvents(start,end,inclusive)" << endl;
 return mCache->rawEvents( start, end, inclusive );
}

QPtrList<Event> ExchangeCalendar::rawEventsForDate(const QDateTime &qdt)
{
   kdDebug() << "ExchangeCalendar::rawEventsForDate(qdt)" << endl;
 return rawEventsForDate( qdt.date() );
}

QPtrList<Event> ExchangeCalendar::rawEvents()
{
   kdDebug() << "ExchangeCalendar::rawEvents()" << endl;
 return mCache->rawEvents();
}

void ExchangeCalendar::addJournal(Journal *journal)
{
  kdDebug(5800) << "Adding Journal on " << journal->dtStart().toString() << endl;
  mCache->addJournal( journal );

  journal->registerObserver( this );

  setModified( true );
}

Journal *ExchangeCalendar::journal(const QDate &date)
{
//  kdDebug(5800) << "ExchangeCalendar::journal() " << date.toString() << endl;
  return mCache->journal( date );
}

Journal *ExchangeCalendar::journal(const QString &uid)
{
  return mCache->journal( uid );
}

QPtrList<Journal> ExchangeCalendar::journals()
{
  return mCache->journals();
}
<commit_msg>Optimisation: use "cache line size" of a month to limit effect of latency in contacting the exchange server.<commit_after>/*
    This file is part of libkpimexchange.
    Copyright (c) 2002 Jan-Pascal van Best <janpascal@vanbest.org>

    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; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
    02111-1307, USA.
*/

#include <stdlib.h>

#include <qdatetime.h>
#include <qstring.h>
#include <qptrlist.h>

#include <kdebug.h>

#include <libkcal/calendarlocal.h>
#include <libkcal/calendar.h>
#include <libkcal/journal.h>

#include "dateset.h"
#include "exchangeaccount.h"
#include "exchangeclient.h"

#include "exchangecalendar.h"

using namespace KCal;
using namespace KPIM;

ExchangeCalendar::ExchangeCalendar( KPIM::ExchangeAccount* account )
  : Calendar()
{
  init( account );
  mCache = new CalendarLocal();
}

ExchangeCalendar::ExchangeCalendar( KPIM::ExchangeAccount* account, const QString &timeZoneId)
  : Calendar(timeZoneId)
{
  init( account );
  mCache = new CalendarLocal( timeZoneId );
}

void ExchangeCalendar::init( KPIM::ExchangeAccount* account )
{
  kdDebug() << "ExchangeCalendar::init()" << endl;
  mAccount = account;
  mClient = new ExchangeClient( account );
  mDates = new DateSet();

  mEventDates = new QMap<Event,QDateTime>();
  mCacheDates = new QMap<QDate, QDateTime>();

  mCachedSeconds = 600; // After 5 minutes, reread from server
  // mOldestDate = 0L;
  // mNewestDate = 0L;
}

ExchangeCalendar::~ExchangeCalendar()
{
  kdDebug() << "Destructing ExchangeCalendar" << endl;
  close();
  // delete mNewestDate;
  // delete mOldestDate;
  delete mDates;
  delete mClient;
  delete mEventDates;
  delete mCacheDates;
  delete mCache;
}

bool ExchangeCalendar::load( const QString &fileName )
{
  // return mCache->load( fileName );
  return true;
}

bool ExchangeCalendar::save( const QString &fileName, CalFormat *format )
{
  return mCache->save( fileName, format );
}

void ExchangeCalendar::close()
{
  mCache->close();
  setModified( false );
}

void ExchangeCalendar::addEvent(Event *anEvent)
{
  kdDebug() << "ExchangeCalendar::addEvent" << endl;
  mCache->addEvent( anEvent );
  insertEvent(anEvent);

  anEvent->registerObserver( this );

  setModified( true );
}

// probably not really efficient, but...it works for now.
void ExchangeCalendar::deleteEvent(Event *event)
{
  kdDebug(5800) << "ExchangeCalendar::deleteEvent" << endl;
  mCache->deleteEvent( event );
  setModified( true );
}

Event *ExchangeCalendar::event( const QString &uid )
{
  kdDebug(5800) << "ExchangeCalendar::event(): " << uid << endl;

  return mCache->event( uid );
}

void ExchangeCalendar::addTodo(Todo *todo)
{
  mCache->addTodo( todo );

  todo->registerObserver( this );

  setModified( true );
}

void ExchangeCalendar::deleteTodo(Todo *todo)
{
  mCache->deleteTodo( todo );

  setModified( true );
}

QPtrList<Todo> ExchangeCalendar::rawTodos() const
{
  return mCache->rawTodos();
}

Todo *ExchangeCalendar::todo( const QString &uid )
{
  return mCache->todo( uid );
}

QPtrList<Todo> ExchangeCalendar::todos( const QDate &date )
{
  return mCache->todos( date );
}

int ExchangeCalendar::numEvents(const QDate &qd)
{
   kdDebug() << "ExchangeCalendar::numEvents" << endl;
  return mCache->numEvents( qd );
}

Alarm::List ExchangeCalendar::alarmsTo( const QDateTime &to )
{
  return mCache->alarmsTo( to );
}

Alarm::List ExchangeCalendar::alarms( const QDateTime &from, const QDateTime &to )
{
  kdDebug(5800) << "ExchangeCalendar::alarms(" << from.toString() << " - " << to.toString() << ")\n";
  return mCache->alarms( from, to );
}

/****************************** PROTECTED METHODS ****************************/

// after changes are made to an event, this should be called.
void ExchangeCalendar::update(IncidenceBase *incidence)
{
  setModified( true );
}

// this function will take a VEvent and insert it into the event
// dictionary for the ExchangeCalendar.  If there is no list of events for that
// particular location in the dictionary, a new one will be created.
void ExchangeCalendar::insertEvent(const Event *anEvent)
{
  kdDebug() << "ExchangeCalendar::insertEvent" << endl;

}

// taking a QDate, this function will look for an eventlist in the dict
// with that date attached -
QPtrList<Event> ExchangeCalendar::rawEventsForDate(const QDate &qd, bool sorted)
{
  kdDebug() << "ExchangeCalendar::rawEventsForDate(" << qd.toString() << "," << sorted << ")" << endl;

  // If the events for this date are not in the cache, or if they are old,
  // get them again
  QDateTime now = QDateTime::currentDateTime();
  // kdDebug() << "Now is " << now.toString() << endl;
  // kdDebug() << "mDates: " << mDates << endl;
  // kdDebug() << "mDates->contains(qd) is " << mDates->contains( qd ) << endl;
  QDate start = QDate( qd.year(), qd.month(), 1 ); // First day of month
  if ( !mDates->contains( start ) || (*mCacheDates)[start].secsTo( now ) > mCachedSeconds ) {
    kdDebug() << "Reading events for month of " << start.toString() << endl;
    QDate end = start.addMonths( 1 ).addDays( -1 ); // Last day of month
    mClient->downloadSynchronous( mCache, start, end, true ); // Show progress dialog
    mDates->add( start );
    mCacheDates->insert( start, now );
  }

  // Events are safely in the cache now, return them from cache
  QPtrList<Event> events = mCache->rawEventsForDate( qd, sorted );
  kdDebug() << "Found " << events.count() << " events." << endl;
  return events;

/*
  if (!sorted) {
    return eventList;
  }

  //  kdDebug(5800) << "Sorting events for date\n" << endl;
  // now, we have to sort it based on getDtStart.time()
  QPtrList<Event> eventListSorted;
  for (anEvent = eventList.first(); anEvent; anEvent = eventList.next()) {
    if (!eventListSorted.isEmpty() &&
	anEvent->dtStart().time() < eventListSorted.at(0)->dtStart().time()) {
      eventListSorted.insert(0,anEvent);
      goto nextToInsert;
    }
    for (i = 0; (uint) i+1 < eventListSorted.count(); i++) {
      if (anEvent->dtStart().time() > eventListSorted.at(i)->dtStart().time() &&
	  anEvent->dtStart().time() <= eventListSorted.at(i+1)->dtStart().time()) {
	eventListSorted.insert(i+1,anEvent);
	goto nextToInsert;
      }
    }
    eventListSorted.append(anEvent);
  nextToInsert:
    continue;
  }
  return eventListSorted;
*/
}

QPtrList<Event> ExchangeCalendar::rawEvents( const QDate &start, const QDate &end,
                                          bool inclusive )
{
   kdDebug() << "ExchangeCalendar::rawEvents(start,end,inclusive)" << endl;
 return mCache->rawEvents( start, end, inclusive );
}

QPtrList<Event> ExchangeCalendar::rawEventsForDate(const QDateTime &qdt)
{
   kdDebug() << "ExchangeCalendar::rawEventsForDate(qdt)" << endl;
 return rawEventsForDate( qdt.date() );
}

QPtrList<Event> ExchangeCalendar::rawEvents()
{
   kdDebug() << "ExchangeCalendar::rawEvents()" << endl;
 return mCache->rawEvents();
}

void ExchangeCalendar::addJournal(Journal *journal)
{
  kdDebug(5800) << "Adding Journal on " << journal->dtStart().toString() << endl;
  mCache->addJournal( journal );

  journal->registerObserver( this );

  setModified( true );
}

Journal *ExchangeCalendar::journal(const QDate &date)
{
//  kdDebug(5800) << "ExchangeCalendar::journal() " << date.toString() << endl;
  return mCache->journal( date );
}

Journal *ExchangeCalendar::journal(const QString &uid)
{
  return mCache->journal( uid );
}

QPtrList<Journal> ExchangeCalendar::journals()
{
  return mCache->journals();
}
<|endoftext|>


<commit_before>// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// 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.

#ifndef ROCPRIM_INTRINSICS_THREAD_HPP_
#define ROCPRIM_INTRINSICS_THREAD_HPP_

// HC API
#include <hcc/hc.hpp>

#include "../detail/config.hpp"

BEGIN_ROCPRIM_NAMESPACE

// Sizes

/// \brief Returns number of threads in a warp.
constexpr unsigned int warp_size() [[hc]] [[cpu]]
{
    // Using marco allows contexpr, but we may have to
    // change it to hc::__wavesize() for safety
    return __HSA_WAVEFRONT_SIZE__;
    // return hc::__wavesize();
}

inline unsigned int flat_block_size() [[hc]]
{
    return hc_get_group_size(2) * hc_get_group_size(1) * hc_get_group_size(0);
}

inline unsigned int flat_tile_size() [[hc]]
{
    return flat_block_size();
}

// IDs

/// \brief Returns thread id in a warp.
inline unsigned int lane_id() [[hc]]
{
    return hc::__lane_id();
}

/// \brief Returns flat thread id in a block (tile).
inline unsigned int flat_block_thread_id() [[hc]]
{
    return (hc_get_workitem_id(2) * hc_get_group_size(1) * hc_get_group_size(0))
        + (hc_get_workitem_id(1) * hc_get_group_size(0))
        + hc_get_workitem_id(0);
}

/// \brief Returns flat thread id in a tile (block).
inline unsigned int flat_tile_thread_id() [[hc]]
{
    return flat_block_thread_id();
}

/// \brief Returns warp id in the block (tile)
inline unsigned int warp_id() [[hc]]
{
    return flat_block_thread_id()/warp_size();
}

inline unsigned int flat_block_id() [[hc]]
{
    return (hc_get_group_id(2) * hc_get_num_groups(1) * hc_get_num_groups(0))
        + (hc_get_group_id(1) * hc_get_num_groups(0))
        + hc_get_group_id(0);
}

// Sync

/// \bried Synchronize all threads in a block (tile)
inline void sync_all_threads() [[hc]]
{
    hc_barrier(CLK_LOCAL_MEM_FENCE);
}

namespace detail
{
    template<unsigned int LogicalWarpSize>
    unsigned int logical_lane_id() [[hc]]
    {
        return lane_id() & (LogicalWarpSize-1); // same as land_id()%WarpSize
    }

    template<>
    unsigned int logical_lane_id<warp_size()>() [[hc]]
    {
        return lane_id();
    }

    template<unsigned int LogicalWarpSize>
    unsigned int logical_warp_id() [[hc]]
    {
        return lane_id()/LogicalWarpSize;
    }

    template<>
    unsigned int logical_warp_id<warp_size()>() [[hc]]
    {
        return warp_id();
    }
}

END_ROCPRIM_NAMESPACE

#endif // ROCPRIM_INTRINSICS_THREAD_HPP_
<commit_msg>Change sync_all_threads() to syncthreads()<commit_after>// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// 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.

#ifndef ROCPRIM_INTRINSICS_THREAD_HPP_
#define ROCPRIM_INTRINSICS_THREAD_HPP_

// HC API
#include <hcc/hc.hpp>

#include "../detail/config.hpp"

BEGIN_ROCPRIM_NAMESPACE

// Sizes

/// \brief Returns number of threads in a warp.
constexpr unsigned int warp_size() [[hc]] [[cpu]]
{
    // Using marco allows contexpr, but we may have to
    // change it to hc::__wavesize() for safety
    return __HSA_WAVEFRONT_SIZE__;
    // return hc::__wavesize();
}

inline unsigned int flat_block_size() [[hc]]
{
    return hc_get_group_size(2) * hc_get_group_size(1) * hc_get_group_size(0);
}

inline unsigned int flat_tile_size() [[hc]]
{
    return flat_block_size();
}

// IDs

/// \brief Returns thread id in a warp.
inline unsigned int lane_id() [[hc]]
{
    return hc::__lane_id();
}

/// \brief Returns flat thread id in a block (tile).
inline unsigned int flat_block_thread_id() [[hc]]
{
    return (hc_get_workitem_id(2) * hc_get_group_size(1) * hc_get_group_size(0))
        + (hc_get_workitem_id(1) * hc_get_group_size(0))
        + hc_get_workitem_id(0);
}

/// \brief Returns flat thread id in a tile (block).
inline unsigned int flat_tile_thread_id() [[hc]]
{
    return flat_block_thread_id();
}

/// \brief Returns warp id in the block (tile)
inline unsigned int warp_id() [[hc]]
{
    return flat_block_thread_id()/warp_size();
}

inline unsigned int flat_block_id() [[hc]]
{
    return (hc_get_group_id(2) * hc_get_num_groups(1) * hc_get_num_groups(0))
        + (hc_get_group_id(1) * hc_get_num_groups(0))
        + hc_get_group_id(0);
}

// Sync

/// \brief Synchronize all threads in a block (tile)
inline void syncthreads() [[hc]]
{
    hc_barrier(CLK_LOCAL_MEM_FENCE);
}

namespace detail
{
    template<unsigned int LogicalWarpSize>
    unsigned int logical_lane_id() [[hc]]
    {
        return lane_id() & (LogicalWarpSize-1); // same as land_id()%WarpSize
    }

    template<>
    unsigned int logical_lane_id<warp_size()>() [[hc]]
    {
        return lane_id();
    }

    template<unsigned int LogicalWarpSize>
    unsigned int logical_warp_id() [[hc]]
    {
        return lane_id()/LogicalWarpSize;
    }

    template<>
    unsigned int logical_warp_id<warp_size()>() [[hc]]
    {
        return warp_id();
    }
}

END_ROCPRIM_NAMESPACE

#endif // ROCPRIM_INTRINSICS_THREAD_HPP_
<|endoftext|>


<commit_before>/*
 *            kPPP: A pppd front end for the KDE project
 *
 * $Id$
 *
 *            Copyright (C) 1997 Bernd Johannes Wuebben
 *                   wuebben@math.cornell.edu
 *
 * based on EzPPP:
 * Copyright (C) 1997  Jay Painter
 *
 *
 * 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 program; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "pppdargs.h"

PPPdArguments::PPPdArguments(QWidget *parent, const char *name)
  : QDialog(parent, name, TRUE)
{
  setCaption(klocale->translate("Customize pppd Arguments"));

  argument = new QLineEdit(this);
  argument->setGeometry(95, 15, 170, 25);
  connect(argument, SIGNAL(returnPressed()), SLOT(addbutton()));

  argument_label = new QLabel(this);
  argument_label->setGeometry(15,15,65,25);
  argument_label->setText(klocale->translate("Argument:"));

  add = new QPushButton(klocale->translate("Add"), this);
  add->setGeometry(15, 55, 110, 30);
  connect(add, SIGNAL(clicked()), SLOT(addbutton()));

  remove = new QPushButton(klocale->translate("Remove"), this);
  remove->setGeometry(155, 55, 110, 30);
  connect(remove, SIGNAL(clicked()), SLOT(removebutton()));

  arguments = new QListBox(this);
  arguments->setGeometry(15, 105, 250, 100);

  closebtn = new QPushButton(klocale->translate("Close"), this);
  closebtn->setGeometry(15, 225, 110, 30);
  connect(closebtn, SIGNAL(clicked()), SLOT(closebutton()));

  defaults = new QPushButton(klocale->translate("Restore Defaults"), this);
  defaults->setGeometry(155, 225, 110, 30);
  connect(defaults, SIGNAL(clicked()), SLOT(defaultsbutton()));

  setFixedSize(280,270);
  //load info from gpppdata
  init();
}

//
//private slots
//
void PPPdArguments::addbutton() {
  if(strcmp(argument->text(), "") != 0 &&
     arguments->count() < MAX_PPPD_ARGUMENTS) {
    arguments->insertItem(argument->text());
    argument->setText("");
  }
}

void PPPdArguments::removebutton() {
  if(arguments->currentItem() >= 0)
    arguments->removeItem(arguments->currentItem());
}

void PPPdArguments::defaultsbutton() {
  gpppdata.setpppdArgumentDefaults();
  init();
}

void PPPdArguments::closebutton() {
  if(arguments->count() > 0) {
    for(uint i=0; i <= arguments->count()-1; i++)
      gpppdata.setpppdArgument(i, arguments->text(i));
  }
  else {
    gpppdata.setpppdArgument(0, 0L);
  }

  done(0);
}

//
//private funcitons
//

void PPPdArguments::init() {
  arguments->clear();

  for(int i=0; gpppdata.pppdArgument(i) &&
	i <= MAX_PPPD_ARGUMENTS-1; i++) {
    arguments->insertItem(gpppdata.pppdArgument(i));
  }
}

#include "pppdargs.moc"
<commit_msg>Bernd: geometry fixes<commit_after>/*
 *            kPPP: A pppd front end for the KDE project
 *
 * $Id$
 *
 *            Copyright (C) 1997 Bernd Johannes Wuebben
 *                   wuebben@math.cornell.edu
 *
 * based on EzPPP:
 * Copyright (C) 1997  Jay Painter
 *
 *
 * 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 program; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "pppdargs.h"

PPPdArguments::PPPdArguments(QWidget *parent, const char *name)
  : QDialog(parent, name, TRUE)
{
  setCaption(klocale->translate("Customize pppd Arguments"));

  argument = new QLineEdit(this);
  argument->setGeometry(95, 15, 170, 25);
  connect(argument, SIGNAL(returnPressed()), SLOT(addbutton()));

  argument_label = new QLabel(this);
  argument_label->setGeometry(15,15,65,25);
  argument_label->setText(klocale->translate("Argument:"));

  add = new QPushButton(klocale->translate("Add"), this);
  add->setGeometry(15, 55, 110, add->sizeHint().height());
  connect(add, SIGNAL(clicked()), SLOT(addbutton()));

  remove = new QPushButton(klocale->translate("Remove"), this);
  remove->setGeometry(155, 55, 110, remove->sizeHint().height());
  connect(remove, SIGNAL(clicked()), SLOT(removebutton()));

  arguments = new QListBox(this);
  arguments->setGeometry(15, 105, 250, 100);

  closebtn = new QPushButton(klocale->translate("Close"), this);
  closebtn->setGeometry(15, 225, 110, closebtn->sizeHint().height());
  connect(closebtn, SIGNAL(clicked()), SLOT(closebutton()));

  defaults = new QPushButton(klocale->translate("Restore Defaults"), this);
  defaults->setGeometry(155, 225, 110, defaults->sizeHint().height());
  connect(defaults, SIGNAL(clicked()), SLOT(defaultsbutton()));

  setFixedSize(280,270);
  //load info from gpppdata
  init();
}

//
//private slots
//
void PPPdArguments::addbutton() {
  if(strcmp(argument->text(), "") != 0 &&
     arguments->count() < MAX_PPPD_ARGUMENTS) {
    arguments->insertItem(argument->text());
    argument->setText("");
  }
}

void PPPdArguments::removebutton() {
  if(arguments->currentItem() >= 0)
    arguments->removeItem(arguments->currentItem());
}

void PPPdArguments::defaultsbutton() {
  gpppdata.setpppdArgumentDefaults();
  init();
}

void PPPdArguments::closebutton() {
  if(arguments->count() > 0) {
    for(uint i=0; i <= arguments->count()-1; i++)
      gpppdata.setpppdArgument(i, arguments->text(i));
  }
  else {
    gpppdata.setpppdArgument(0, 0L);
  }

  done(0);
}

//
//private funcitons
//

void PPPdArguments::init() {
  arguments->clear();

  for(int i=0; gpppdata.pppdArgument(i) &&
	i <= MAX_PPPD_ARGUMENTS-1; i++) {
    arguments->insertItem(gpppdata.pppdArgument(i));
  }
}

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


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include <date/date.h>

#include "vast/concept/printable/core.hpp"
#include "vast/concept/printable/string/any.hpp"
#include "vast/concept/printable/string/string.hpp"
#include "vast/concept/printable/numeric/integral.hpp"
#include "vast/concept/printable/numeric/real.hpp"
#include "vast/detail/chrono_io.hpp"
#include "vast/time.hpp"

namespace vast {
namespace policy {

struct adaptive {};
struct fixed {};

} // namespace policy

template <class Rep, class Period, class Policy = policy::adaptive>
struct duration_printer : printer<duration_printer<Rep, Period, Policy>> {
  using attribute = std::chrono::duration<Rep, Period>;

  template <class To, class R, class P>
  static auto is_at_least(std::chrono::duration<R, P> d) {
    return std::chrono::duration_cast<To>(date::abs(d)) >= To{1};
  }

  template <class To, class R, class P>
  static auto count(std::chrono::duration<R, P> d) {
    using fractional = std::chrono::duration<double, typename To::period>;
    return std::chrono::duration_cast<fractional>(d).count();
  }

  template <class R, class P>
  static std::string units(std::chrono::duration<R, P>) {
    return date::detail::get_units<char>(Period{}).data();
  }

  template <class R>
  static std::string units(std::chrono::duration<R, std::micro>) {
    return "us";
  }

  template <class Iterator, class P = Policy>
  auto print(Iterator& out, std::chrono::duration<Rep, Period> d) const
  -> std::enable_if_t<std::is_same_v<P, policy::adaptive>, bool> {
    using namespace std::chrono;
    using namespace date;
    auto num = printers::real2;
    if (is_at_least<days>(d))
      return (num << 'd')(out, count<days>(d));
    if (is_at_least<hours>(d))
      return (num << 'h')(out, count<hours>(d));
    if (is_at_least<minutes>(d))
      return (num << 'm')(out, count<minutes>(d));
    if (is_at_least<seconds>(d))
      return (num << 's')(out, count<seconds>(d));
    if (is_at_least<milliseconds>(d))
      return (num << "ms")(out, count<milliseconds>(d));
    if (is_at_least<microseconds>(d))
      return (num << "us")(out, count<microseconds>(d));
    return (num << "ns")(out, count<nanoseconds>(d));
  }

  template <class Iterator, class P = Policy>
  auto print(Iterator& out, std::chrono::duration<Rep, Period> d) const
  -> std::enable_if_t<std::is_same_v<P, policy::fixed>, bool> {
    return (make_printer<Rep>{} << units(d))(out, d.count());
  }
};

template <class Clock, class Duration>
struct time_point_printer : printer<time_point_printer<Clock, Duration>> {
  using attribute = std::chrono::time_point<Clock, Duration>;

  template <class Iterator>
  bool print(Iterator& out, std::chrono::time_point<Clock, Duration> tp) const {
    using namespace std::chrono;
    using namespace date;
    auto num = printers::integral<int>;
    auto num2 = printers::integral<int, policy::plain, 2>;
    auto unum2 = printers::integral<unsigned, policy::plain, 2>;
    auto p = num << '-' << unum2 << '-' << unum2
                 << '+' << num2 << ':' << num2 << ':' << num2
                 << '.' << num;
    auto sd = floor<days>(tp);
    auto ymd = year_month_day{sd};
    auto t = make_time(tp - sd);
    auto sub_secs = duration_cast<milliseconds>(t.subseconds());
    return p(out,
             static_cast<int>(ymd.year()),
             static_cast<unsigned>(ymd.month()),
             static_cast<unsigned>(ymd.day()),
             static_cast<int>(t.hours().count()),
             static_cast<int>(t.minutes().count()),
             static_cast<int>(t.seconds().count()),
             static_cast<int>(sub_secs.count()));
  }
};

template <class Rep, class Period>
struct printer_registry<std::chrono::duration<Rep, Period>> {
  using type = duration_printer<Rep, Period>;
};

template <class Clock, class Duration>
struct printer_registry<std::chrono::time_point<Clock, Duration>> {
  using type = time_point_printer<Clock, Duration>;
};

namespace printers {

template <class Duration, class Policy = policy::adaptive>
const auto duration = duration_printer<
  typename Duration::rep,
  typename Duration::period,
  Policy
>{};

template <class Clock, class Duration = class Clock::duration>
const auto time_point = time_point_printer<Clock, Duration>{};

} // namespace printers
} // namespace vast

<commit_msg>Replace SFINAE with if constexpr<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include <date/date.h>

#include "vast/concept/printable/core.hpp"
#include "vast/concept/printable/string/any.hpp"
#include "vast/concept/printable/string/string.hpp"
#include "vast/concept/printable/numeric/integral.hpp"
#include "vast/concept/printable/numeric/real.hpp"
#include "vast/detail/chrono_io.hpp"
#include "vast/time.hpp"

namespace vast {
namespace policy {

struct adaptive {};
struct fixed {};

} // namespace policy

template <class Rep, class Period, class Policy = policy::adaptive>
struct duration_printer : printer<duration_printer<Rep, Period, Policy>> {
  using attribute = std::chrono::duration<Rep, Period>;

  template <class To, class R, class P>
  static auto is_at_least(std::chrono::duration<R, P> d) {
    return std::chrono::duration_cast<To>(date::abs(d)) >= To{1};
  }

  template <class To, class R, class P>
  static auto count(std::chrono::duration<R, P> d) {
    using fractional = std::chrono::duration<double, typename To::period>;
    return std::chrono::duration_cast<fractional>(d).count();
  }

  template <class R, class P>
  static std::string units(std::chrono::duration<R, P>) {
    return date::detail::get_units<char>(Period{}).data();
  }

  template <class R>
  static std::string units(std::chrono::duration<R, std::micro>) {
    return "us";
  }

  template <class Iterator>
  bool print(Iterator& out, std::chrono::duration<Rep, Period> d) const {
    if constexpr (std::is_same_v<Policy, policy::fixed>) {
      auto p = make_printer<Rep>{} << units(d);
      return p(out, d.count());
    } else if constexpr (std::is_same_v<Policy, policy::adaptive>) {
      using namespace std::chrono;
      using namespace date;
      auto num = printers::real2;
      if (is_at_least<days>(d))
        return (num << 'd')(out, count<days>(d));
      if (is_at_least<hours>(d))
        return (num << 'h')(out, count<hours>(d));
      if (is_at_least<minutes>(d))
        return (num << 'm')(out, count<minutes>(d));
      if (is_at_least<seconds>(d))
        return (num << 's')(out, count<seconds>(d));
      if (is_at_least<milliseconds>(d))
        return (num << "ms")(out, count<milliseconds>(d));
      if (is_at_least<microseconds>(d))
        return (num << "us")(out, count<microseconds>(d));
      return (num << "ns")(out, count<nanoseconds>(d));
    }
  }
};

template <class Clock, class Duration>
struct time_point_printer : printer<time_point_printer<Clock, Duration>> {
  using attribute = std::chrono::time_point<Clock, Duration>;

  template <class Iterator>
  bool print(Iterator& out, std::chrono::time_point<Clock, Duration> tp) const {
    using namespace std::chrono;
    using namespace date;
    auto num = printers::integral<int>;
    auto num2 = printers::integral<int, policy::plain, 2>;
    auto unum2 = printers::integral<unsigned, policy::plain, 2>;
    auto p = num << '-' << unum2 << '-' << unum2
                 << '+' << num2 << ':' << num2 << ':' << num2
                 << '.' << num;
    auto sd = floor<days>(tp);
    auto ymd = year_month_day{sd};
    auto t = make_time(tp - sd);
    auto sub_secs = duration_cast<milliseconds>(t.subseconds());
    return p(out,
             static_cast<int>(ymd.year()),
             static_cast<unsigned>(ymd.month()),
             static_cast<unsigned>(ymd.day()),
             static_cast<int>(t.hours().count()),
             static_cast<int>(t.minutes().count()),
             static_cast<int>(t.seconds().count()),
             static_cast<int>(sub_secs.count()));
  }
};

template <class Rep, class Period>
struct printer_registry<std::chrono::duration<Rep, Period>> {
  using type = duration_printer<Rep, Period>;
};

template <class Clock, class Duration>
struct printer_registry<std::chrono::time_point<Clock, Duration>> {
  using type = time_point_printer<Clock, Duration>;
};

namespace printers {

template <class Duration, class Policy = policy::adaptive>
const auto duration = duration_printer<
  typename Duration::rep,
  typename Duration::period,
  Policy
>{};

template <class Clock, class Duration = class Clock::duration>
const auto time_point = time_point_printer<Clock, Duration>{};

} // namespace printers
} // namespace vast

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/desktop_capture/cropping_window_capturer.h"

#include "webrtc/modules/desktop_capture/cropped_desktop_frame.h"
#include "webrtc/system_wrappers/interface/logging.h"

namespace webrtc {

CroppingWindowCapturer::CroppingWindowCapturer(
    const DesktopCaptureOptions& options)
    : options_(options),
      callback_(NULL),
      window_capturer_(WindowCapturer::Create(options)),
      selected_window_(kNullWindowId),
      excluded_window_(kNullWindowId) {
}

CroppingWindowCapturer::~CroppingWindowCapturer() {}

void CroppingWindowCapturer::Start(DesktopCapturer::Callback* callback) {
  callback_ = callback;
  window_capturer_->Start(callback);
}

void CroppingWindowCapturer::Capture(const DesktopRegion& region) {
  if (ShouldUseScreenCapturer()) {
    if (!screen_capturer_.get()) {
      screen_capturer_.reset(ScreenCapturer::Create(options_));
      if (excluded_window_) {
        screen_capturer_->SetExcludedWindow(excluded_window_);
      }
      screen_capturer_->Start(this);
    }
    screen_capturer_->Capture(region);
  } else {
    window_capturer_->Capture(region);
  }
}

void CroppingWindowCapturer::SetExcludedWindow(WindowId window) {
  excluded_window_ = window;
  if (screen_capturer_.get()) {
    screen_capturer_->SetExcludedWindow(window);
  }
}

bool CroppingWindowCapturer::GetWindowList(WindowList* windows) {
  return window_capturer_->GetWindowList(windows);
}

bool CroppingWindowCapturer::SelectWindow(WindowId id) {
  if (window_capturer_->SelectWindow(id)) {
    selected_window_ = id;
    return true;
  }
  return false;
}

bool CroppingWindowCapturer::BringSelectedWindowToFront() {
  return window_capturer_->BringSelectedWindowToFront();
}

SharedMemory* CroppingWindowCapturer::CreateSharedMemory(size_t size) {
  return callback_->CreateSharedMemory(size);
}

void CroppingWindowCapturer::OnCaptureCompleted(DesktopFrame* frame) {
  scoped_ptr<DesktopFrame> screen_frame(frame);

  if (!ShouldUseScreenCapturer()) {
    LOG(LS_INFO) << "Window no longer on top when ScreenCapturer finishes";
    window_capturer_->Capture(DesktopRegion());
    return;
  }

  if (!frame) {
    LOG(LS_WARNING) << "ScreenCapturer failed to capture a frame";
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  DesktopRect window_rect = GetWindowRectInVirtualScreen();
  if (window_rect.is_empty()) {
    LOG(LS_WARNING) << "Window rect is empty";
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  scoped_ptr<DesktopFrame> window_frame(
      CreateCroppedDesktopFrame(screen_frame.release(), window_rect));
  callback_->OnCaptureCompleted(window_frame.release());
}

#if !defined(OS_WIN)
// static
WindowCapturer*
CroppingWindowCapturer::Create(const DesktopCaptureOptions& options) {
  return WindowCapturer::Create(options);
}
#endif

}  // namespace webrtc
<commit_msg>Fix a platform check to use WEBRTC_WIN instead of OS_WIN.<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/desktop_capture/cropping_window_capturer.h"

#include "webrtc/modules/desktop_capture/cropped_desktop_frame.h"
#include "webrtc/system_wrappers/interface/logging.h"

namespace webrtc {

CroppingWindowCapturer::CroppingWindowCapturer(
    const DesktopCaptureOptions& options)
    : options_(options),
      callback_(NULL),
      window_capturer_(WindowCapturer::Create(options)),
      selected_window_(kNullWindowId),
      excluded_window_(kNullWindowId) {
}

CroppingWindowCapturer::~CroppingWindowCapturer() {}

void CroppingWindowCapturer::Start(DesktopCapturer::Callback* callback) {
  callback_ = callback;
  window_capturer_->Start(callback);
}

void CroppingWindowCapturer::Capture(const DesktopRegion& region) {
  if (ShouldUseScreenCapturer()) {
    if (!screen_capturer_.get()) {
      screen_capturer_.reset(ScreenCapturer::Create(options_));
      if (excluded_window_) {
        screen_capturer_->SetExcludedWindow(excluded_window_);
      }
      screen_capturer_->Start(this);
    }
    screen_capturer_->Capture(region);
  } else {
    window_capturer_->Capture(region);
  }
}

void CroppingWindowCapturer::SetExcludedWindow(WindowId window) {
  excluded_window_ = window;
  if (screen_capturer_.get()) {
    screen_capturer_->SetExcludedWindow(window);
  }
}

bool CroppingWindowCapturer::GetWindowList(WindowList* windows) {
  return window_capturer_->GetWindowList(windows);
}

bool CroppingWindowCapturer::SelectWindow(WindowId id) {
  if (window_capturer_->SelectWindow(id)) {
    selected_window_ = id;
    return true;
  }
  return false;
}

bool CroppingWindowCapturer::BringSelectedWindowToFront() {
  return window_capturer_->BringSelectedWindowToFront();
}

SharedMemory* CroppingWindowCapturer::CreateSharedMemory(size_t size) {
  return callback_->CreateSharedMemory(size);
}

void CroppingWindowCapturer::OnCaptureCompleted(DesktopFrame* frame) {
  scoped_ptr<DesktopFrame> screen_frame(frame);

  if (!ShouldUseScreenCapturer()) {
    LOG(LS_INFO) << "Window no longer on top when ScreenCapturer finishes";
    window_capturer_->Capture(DesktopRegion());
    return;
  }

  if (!frame) {
    LOG(LS_WARNING) << "ScreenCapturer failed to capture a frame";
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  DesktopRect window_rect = GetWindowRectInVirtualScreen();
  if (window_rect.is_empty()) {
    LOG(LS_WARNING) << "Window rect is empty";
    callback_->OnCaptureCompleted(NULL);
    return;
  }

  scoped_ptr<DesktopFrame> window_frame(
      CreateCroppedDesktopFrame(screen_frame.release(), window_rect));
  callback_->OnCaptureCompleted(window_frame.release());
}

#if !defined(WEBRTC_WIN)
// static
WindowCapturer*
CroppingWindowCapturer::Create(const DesktopCaptureOptions& options) {
  return WindowCapturer::Create(options);
}
#endif

}  // namespace webrtc
<|endoftext|>


<commit_before>
#ifndef kernels_cuh
#define kernels_cuh

#include "Network.hpp"
#include "IntegrationData.hpp"
#include "Globals.hpp"

void integrateNetwork(
	Network network,
	IntegrationData integrationData,
	Globals *globalsPtr
);

bool checkAsy(fern_real, fern_real, fern_real);
fern_real asymptoticUpdate(fern_real, fern_real, fern_real, fern_real);
fern_real eulerUpdate(fern_real, fern_real, fern_real, fern_real);

void populateF(fern_real *Fsign, fern_real *FsignFac, fern_real *Flux,
	unsigned short *MapFsign, unsigned short totalFsign);
inline void updatePopulations(fern_real *FplusSum, fern_real *FminusSum,
	fern_real *Y, fern_real *Yzero, unsigned short numberSpecies, fern_real dt);

fern_real reduceSum(fern_real *a, unsigned short length);
fern_real NDreduceSum(fern_real *a, unsigned short length);
fern_real reduceMax(fern_real *a, unsigned short length);

size_t integrateNetwork_sharedSize(const Network &network);
void network_print(const Network &network);

#endif
<commit_msg>Added header file.<commit_after>
#ifndef kernels_cuh
#define kernels_cuh

#include "Network.hpp"
#include "IntegrationData.hpp"
#include "Globals.hpp"
#include <cstdint>

void integrateNetwork(
	Network network,
	IntegrationData integrationData,
	Globals *globalsPtr
);

bool checkAsy(fern_real, fern_real, fern_real);
fern_real asymptoticUpdate(fern_real, fern_real, fern_real, fern_real);
fern_real eulerUpdate(fern_real, fern_real, fern_real, fern_real);

void populateF(fern_real *Fsign, fern_real *FsignFac, fern_real *Flux,
	unsigned short *MapFsign, unsigned short totalFsign);
inline void updatePopulations(fern_real *FplusSum, fern_real *FminusSum,
	fern_real *Y, fern_real *Yzero, unsigned short numberSpecies, fern_real dt);

fern_real reduceSum(fern_real *a, unsigned short length);
fern_real NDreduceSum(fern_real *a, unsigned short length);
fern_real reduceMax(fern_real *a, unsigned short length);

size_t integrateNetwork_sharedSize(const Network &network);
void network_print(const Network &network);

#endif
<|endoftext|>


<commit_before>#include "ofApp.h"

//----------------------- App -----------------------------------------------

void ofApp::setup() {
    ofxAudioVisualApp::setup();

    ofAddListener(settings.parameterChangedE(), this, &ofApp::onSettingChanged);

    isGerhard.set("Gerhard", true);
    isGerhardStrip.set("Gerhard Strip", false);
    isCircle.set("Circle", false);
    isHistory.set("History", false);
    isStream.set("Stream", false);

    visGroup.push_back(&isGerhard);
    visGroup.push_back(&isGerhardStrip);
    visGroup.push_back(&isCircle);
    visGroup.push_back(&isHistory);
    visGroup.push_back(&isStream);

    for (auto vis : visGroup){
        visualizations.add(*vis);
    }

    gui2.add(visualizations);
    ofAddListener(visualizations.parameterChangedE(), this, &ofApp::onVisualizationChanged);

    ofAddListener(startEndBin.parameterChangedE(), this, &ofApp::onBinSizeChanged);

    reset();
    resetting = false;
    history.setup(fft);
    stream.setup(this);
}

void ofApp::draw() {
    ofxAudioVisualApp::draw();

    if (resetting){
        ofPushStyle();
        ofSetColor(0);
        ofDrawRectangle(0, 0, ofGetWidth(), ofGetHeight());
        ofPopStyle();
        resetting = false;
    }

    if (isGerhard){
        gerhard.draw(this, &drawBins, threshold, symmetrical);
    }else if (isCircle){
        circle.draw(this, &drawBins, threshold);
    }else if (isHistory){
        history.draw(this, &drawBins, threshold);
    }else if (isGerhardStrip){
        gStrip.draw(this, &drawBins, threshold, symmetrical);
    }else if (isStream){
        stream.draw(this, &drawBins, threshold);
    }
}

void ofApp::keyPressed(int key) {
    ofxAudioVisualApp::keyPressed(key);

    switch (key) {
        case 'a':
            symmetrical = !symmetrical;
            break;
        case 's':
            saveScreenShots("main");
            break;
        default:
            break;
    }
}

//----------------------- GUI -----------------------------------------------

void ofApp::setupGui(){
    ofxAudioVisualApp::setupGui();
}

void ofApp::drawGui(ofEventArgs & args){
    ofxAudioVisualApp::drawGui(args);
}

void ofApp::guiKeyPressed(ofKeyEventArgs & args){
    switch (args.key){
        case 's':
            saveScreenShots("gui");
            break;
        case 'g':
            gui.saveToFile("./settings/settings1.xml");
            gui2.saveToFile("./settings/settings2.xml");
            break;
        case 'l':
            loadingSettings = true;
            gui.loadFromFile("./settings/settings1.xml");
            gui2.loadFromFile("./settings/settings2.xml");
            loadingSettings = false;
            break;
        default:
            break;
    }
}

void ofApp::onSettingChanged(ofAbstractParameter &p){
    string name = p.getName();
    if(name == "Play!") {
        reset();
    }
}

void ofApp::onVisualizationChanged(ofAbstractParameter &p){
    if(!loadingSettings){
        string name = p.getName();

        for (int i = 0; i < visGroup.size(); i++){
            if (visGroup[i]->getName() == name){
                visGroup[i]->setWithoutEventNotifications(true);
            }else{
                visGroup[i]->setWithoutEventNotifications(false);
            }
        }
    }
    reset();
}

//----------------------- Utility -----------------------------------------------

void ofApp::onBinSizeChanged(ofAbstractParameter &p){
    history.resetMesh();
}

void ofApp::reset(){
    x = 0;
    gerhard.x = 0;
    circle.theta = -90;
    gStrip.setXY(0, 0);

    resetting = true;
}

void ofApp::saveScreenShots(string contextName){
    ofImage screen;
    string timestamp = ofGetTimestampString("%Y-%m-%d-%H-%M-%S-");
    screen.grabScreen(0, 0, ofGetWidth(), ofGetHeight());
    screen.update();
    screen.save("./documentation/" + timestamp + contextName + ".png");
}<commit_msg>Typo fix<commit_after>#include "ofApp.h"

//----------------------- App -----------------------------------------------

void ofApp::setup() {
    ofxAudioVisualApp::setup();

    ofAddListener(settings.parameterChangedE(), this, &ofApp::onSettingChanged);

    isGerhard.set("Gerhard", true);
    isGerhardStrip.set("Gerhard Strip", false);
    isCircle.set("Circle", false);
    isHistory.set("History", false);
    isStream.set("Stream", false);

    visGroup.push_back(&isGerhard);
    visGroup.push_back(&isGerhardStrip);
    visGroup.push_back(&isCircle);
    visGroup.push_back(&isHistory);
    visGroup.push_back(&isStream);

    for (auto vis : visGroup){
        visualizations.add(*vis);
    }

    gui2.add(visualizations);
    ofAddListener(visualizations.parameterChangedE(), this, &ofApp::onVisualizationChanged);

    ofAddListener(startEndBin.parameterChangedE(), this, &ofApp::onBinSizeChanged);

    reset();
    resetting = false;
    history.setup(fft);
    stream.setup(this);
}

void ofApp::draw() {
    ofxAudioVisualApp::draw();

    if (resetting){
        ofPushStyle();
        ofSetColor(0);
        ofDrawRectangle(0, 0, ofGetWidth(), ofGetHeight());
        ofPopStyle();
        resetting = false;
    }

    if (isGerhard){
        gerhard.draw(this, &drawBins, threshold, symmetrical);
    }else if (isCircle){
        circle.draw(this, &drawBins, threshold);
    }else if (isHistory){
        history.draw(this, &drawBins, threshold);
    }else if (isGerhardStrip){
        gStrip.draw(this, &drawBins, threshold, symmetrical);
    }else if (isStream){
        stream.draw(this, &drawBins, threshold);
    }
}

void ofApp::keyPressed(int key) {
    ofxAudioVisualApp::keyPressed(key);

    switch (key) {
        case 'a':
            symmetrical = !symmetrical;
            break;
        case 's':
            saveScreenShots("main");
            break;
        default:
            break;
    }
}

//----------------------- GUI -----------------------------------------------

void ofApp::setupGui(){
    ofxAudioVisualApp::setupGui();
}

void ofApp::drawGui(ofEventArgs & args){
    ofxAudioVisualApp::drawGui(args);
}

void ofApp::guiKeyPressed(ofKeyEventArgs & args){
    switch (args.key){
        case 's':
            saveScreenShots("gui");
            break;
        case 'g':
            gui.saveToFile("./settings/settings1.xml");
            gui2.saveToFile("./settings/settings2.xml");
            break;
        case 'l':
            loadingSettings = true;
            gui.loadFromFile("./settings/settings1.xml");
            gui2.loadFromFile("./settings/settings2.xml");
            loadingSettings = false;
            break;
        default:
            break;
    }
}

void ofApp::onSettingChanged(ofAbstractParameter &p){
    string name = p.getName();
    if(name == "Play") {
        reset();
    }
}

void ofApp::onVisualizationChanged(ofAbstractParameter &p){
    if(!loadingSettings){
        string name = p.getName();

        for (int i = 0; i < visGroup.size(); i++){
            if (visGroup[i]->getName() == name){
                visGroup[i]->setWithoutEventNotifications(true);
            }else{
                visGroup[i]->setWithoutEventNotifications(false);
            }
        }
    }
    reset();
}

//----------------------- Utility -----------------------------------------------

void ofApp::onBinSizeChanged(ofAbstractParameter &p){
    history.resetMesh();
}

void ofApp::reset(){
    x = 0;
    gerhard.x = 0;
    circle.theta = -90;
    gStrip.setXY(0, 0);

    resetting = true;
}

void ofApp::saveScreenShots(string contextName){
    ofImage screen;
    string timestamp = ofGetTimestampString("%Y-%m-%d-%H-%M-%S-");
    screen.grabScreen(0, 0, ofGetWidth(), ofGetHeight());
    screen.update();
    screen.save("./documentation/" + timestamp + contextName + ".png");
}<|endoftext|>


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

#include "SurgSim/Devices/ReplayPoseDevice/ReplayPoseDevice.h"

#include "SurgSim/Devices/ReplayPoseDevice/ReplayPoseScaffold.h"
#include "SurgSim/Framework/Assert.h"

namespace SurgSim
{
namespace Devices
{

SURGSIM_REGISTER(SurgSim::Input::DeviceInterface, SurgSim::Devices::ReplayPoseDevice, ReplayPoseDevice);

ReplayPoseDevice::ReplayPoseDevice(const std::string& uniqueName) :
	SurgSim::Input::CommonDevice(uniqueName, ReplayPoseScaffold::buildDeviceInputData()),
	m_fileName("ReplayPoseDevice.txt"),
	m_rate(1000.0)
{
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(ReplayPoseDevice, std::string, FileName, getFileName, setFileName);
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(ReplayPoseDevice, double, Rate, getRate, setRate);
}

ReplayPoseDevice::~ReplayPoseDevice()
{
	if (isInitialized())
	{
		finalize();
	}
}

const std::string ReplayPoseDevice::getFileName() const
{
	return m_fileName;
}

void ReplayPoseDevice::setFileName(const std::string& fileName)
{
	SURGSIM_ASSERT(!isInitialized()) << "The filename can only be set before initialization";
	m_fileName = fileName;
}

double ReplayPoseDevice::getRate() const
{
	return m_rate;
}

void ReplayPoseDevice::setRate(double rate)
{
	SURGSIM_ASSERT(!isInitialized()) << "The rate can only be set before initialization";
	m_rate = rate;
}

bool ReplayPoseDevice::initialize()
{
	SURGSIM_ASSERT(!isInitialized()) << getName() << " already initialized.";
	std::shared_ptr<ReplayPoseScaffold> scaffold = ReplayPoseScaffold::getOrCreateSharedInstance();
	SURGSIM_ASSERT(scaffold);

	if (!scaffold->registerDevice(this))
	{
		return false;
	}
	m_scaffold = std::move(scaffold);

	return true;
}

bool ReplayPoseDevice::finalize()
{
	SURGSIM_ASSERT(isInitialized()) << getName() << " is not initialized, cannot finalize.";
	bool ok = m_scaffold->unregisterDevice();
	m_scaffold->stop();
	m_scaffold.reset();
	return ok;
}

bool ReplayPoseDevice::isInitialized() const
{
	return (m_scaffold != nullptr);
}

};  // namespace Devices
};  // namespace SurgSim
<commit_msg>Revert "Stop the device thread execution to fix an assertion when destroying the device."<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2015, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Devices/ReplayPoseDevice/ReplayPoseDevice.h"

#include "SurgSim/Devices/ReplayPoseDevice/ReplayPoseScaffold.h"
#include "SurgSim/Framework/Assert.h"

namespace SurgSim
{
namespace Devices
{

SURGSIM_REGISTER(SurgSim::Input::DeviceInterface, SurgSim::Devices::ReplayPoseDevice, ReplayPoseDevice);

ReplayPoseDevice::ReplayPoseDevice(const std::string& uniqueName) :
	SurgSim::Input::CommonDevice(uniqueName, ReplayPoseScaffold::buildDeviceInputData()),
	m_fileName("ReplayPoseDevice.txt"),
	m_rate(1000.0)
{
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(ReplayPoseDevice, std::string, FileName, getFileName, setFileName);
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(ReplayPoseDevice, double, Rate, getRate, setRate);
}

ReplayPoseDevice::~ReplayPoseDevice()
{
	if (isInitialized())
	{
		finalize();
	}
}

const std::string ReplayPoseDevice::getFileName() const
{
	return m_fileName;
}

void ReplayPoseDevice::setFileName(const std::string& fileName)
{
	SURGSIM_ASSERT(!isInitialized()) << "The filename can only be set before initialization";
	m_fileName = fileName;
}

double ReplayPoseDevice::getRate() const
{
	return m_rate;
}

void ReplayPoseDevice::setRate(double rate)
{
	SURGSIM_ASSERT(!isInitialized()) << "The rate can only be set before initialization";
	m_rate = rate;
}

bool ReplayPoseDevice::initialize()
{
	SURGSIM_ASSERT(!isInitialized()) << getName() << " already initialized.";
	std::shared_ptr<ReplayPoseScaffold> scaffold = ReplayPoseScaffold::getOrCreateSharedInstance();
	SURGSIM_ASSERT(scaffold);

	if (!scaffold->registerDevice(this))
	{
		return false;
	}
	m_scaffold = std::move(scaffold);

	return true;
}

bool ReplayPoseDevice::finalize()
{
	SURGSIM_ASSERT(isInitialized()) << getName() << " is not initialized, cannot finalize.";
	bool ok = m_scaffold->unregisterDevice();
	m_scaffold.reset();
	return ok;
}

bool ReplayPoseDevice::isInitialized() const
{
	return (m_scaffold != nullptr);
}

};  // namespace Devices
};  // namespace SurgSim
<|endoftext|>