text:
namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64_t nTimeLastCheckpoint;
        int64_t nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (      0, uint256("0x"))

        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        0, // * UNIX timestamp of last checkpoint block
        0,    // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        2880.0      // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 0, uint256("0x00000e5e37c42d6b67d0934399adfb0fa48b59138abb1a8842c88f4ca3d4ec96"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1373481000,
        0,
        2880.0
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET)
            return dataTestnet;
        else if (Params().NetworkID() == CChainParams::MAIN)
            return data;
        else
            return dataRegtest;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
        if (pindex==NULL)
            return 0.0;

        int64_t nNow = time(NULL);

        double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkpoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }

    uint256 GetLatestHardenedCheckpoint()
    {
        LogPrintf("GetLatestHardenedCheckpoint\n");
        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return (checkpoints.rbegin()->second);
    }

    // ppcoin: synchronized checkpoint (centrally broadcasted)
    uint256 hashSyncCheckpoint = 0;
    uint256 hashPendingCheckpoint = 0;
    CSyncCheckpoint checkpointMessage;
    CSyncCheckpoint checkpointMessagePending;
    uint256 hashInvalidCheckpoint = 0;
    CCriticalSection cs_hashSyncCheckpoint;
    std::string strCheckpointWarning;

    // ppcoin: only descendant of current sync-checkpoint is allowed
    bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
    {
        LogPrintf("ValidateSyncCheckpoint: hashCheckpoint=%s\n", hashCheckpoint.ToString().c_str());

        if ( (hashSyncCheckpoint == 0) || (!mapBlockIndex.count(hashSyncCheckpoint)) )
        {
            // NO SYNC CHECKPOINT
            return true;
        }

        if (!mapBlockIndex.count(hashSyncCheckpoint))
            return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
        if (!mapBlockIndex.count(hashCheckpoint))
            return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());

        CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
        CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];

        if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
        {
            // Received an older checkpoint, trace back from current checkpoint
            // to the same height of the received checkpoint to verify
            // that current checkpoint should be a descendant block
            CBlockIndex* pindex = pindexSyncCheckpoint;
            while (pindex->nHeight > pindexCheckpointRecv->nHeight)
                if (!(pindex = pindex->pprev))
                    return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
            if (pindex->GetBlockHash() != hashCheckpoint)
            {
                hashInvalidCheckpoint = hashCheckpoint;
                return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
            }
            return false; // ignore older checkpoint
        }

        // Received checkpoint should be a descendant block of the current
        // checkpoint. Trace back to the same height of current checkpoint
        // to verify.
        CBlockIndex* pindex = pindexCheckpointRecv;
        while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
            if (!(pindex = pindex->pprev))
                return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
        if (pindex->GetBlockHash() != hashSyncCheckpoint)
        {
            hashInvalidCheckpoint = hashCheckpoint;
            return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
        }

        LogPrintf("ValidateSyncCheckpoint: OK\n");
        return true;
    }

    bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
    {
        if (!pblocktree->WriteSyncCheckpoint(hashCheckpoint))
        {
            return error("WriteSyncCheckpoint(): failed to write to txdb sync checkpoint %s", hashCheckpoint.ToString().c_str());
        }

        hashSyncCheckpoint = hashCheckpoint;
        return true;
    }

    bool IsSyncCheckpointEnforced()
    {
        return (GetBoolArg("-checkpointenforce", true) || mapArgs.count("-checkpointkey")); // checkpoint master node is always enforced
    }

    bool AcceptPendingSyncCheckpoint()
    {
        LOCK(cs_hashSyncCheckpoint);
        if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
        {
            if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
            {
                hashPendingCheckpoint = 0;
                checkpointMessagePending.SetNull();
                LogPrintf("AcceptPendingSyncCheckpoint: FAIL1\n");
                return false;
            }

            CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
            if (IsSyncCheckpointEnforced() && !pindexCheckpoint->IsInMainChain())
            {
                CBlock block;
                if (!ReadBlockFromDisk(block, pindexCheckpoint))
                    return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
                CValidationState state;
                LogPrintf("AcceptPendingSyncCheckpoint: ConnectTip\n");
                // if (!SetBestChain(state, pindexCheckpoint))
                if (!ConnectTip(state, pindexCheckpoint))
                {
                    hashInvalidCheckpoint = hashPendingCheckpoint;
                    return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
                }
            }

            if (!WriteSyncCheckpoint(hashPendingCheckpoint))
                return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
            hashPendingCheckpoint = 0;
            checkpointMessage = checkpointMessagePending;
            checkpointMessagePending.SetNull();
            LogPrintf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
            // relay the checkpoint
            if (!checkpointMessage.IsNull())
            {
                BOOST_FOREACH(CNode* pnode, vNodes)
                    checkpointMessage.RelayTo(pnode);
            }
            return true;
        }
        return false;
    }

    // Automatically select a suitable sync-checkpoint
    uint256 AutoSelectSyncCheckpoint()
    {
        // Search backward for a block with specified depth policy
        // const CBlockIndex *pindex = pindexBest;
        // while (pindex->pprev && pindex->nHeight + (int)GetArg("-checkpointdepth", -1) > pindexBest->nHeight)
        const CBlockIndex *pindex = chainActive.Tip();
        while (pindex->pprev && pindex->nHeight + (int)GetArg("-checkpointdepth", -1) > chainActive.Tip()->nHeight)
            pindex = pindex->pprev;
        return pindex->GetBlockHash();
    }

    // Check against synchronized checkpoint
    bool CheckSyncCheckpoint(const uint256& hashBlock, const CBlockIndex* pindexPrev)
    {
        int nHeight = pindexPrev->nHeight + 1;
        LogPrintf("CheckSyncCheckpoint: nHeight=%d, hashSyncCheckpoint=%s\n", nHeight, hashSyncCheckpoint.ToString().c_str());

        LOCK(cs_hashSyncCheckpoint);

        if ((hashSyncCheckpoint == 0) || (mapBlockIndex.count(hashSyncCheckpoint) == 0))
            return true;

        // sync-checkpoint should always be accepted block
        // assert(mapBlockIndex.count(hashSyncCheckpoint));
        const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];

        if (nHeight > pindexSync->nHeight)
        {
            // trace back to same height as sync-checkpoint
            const CBlockIndex* pindex = pindexPrev;
            while (pindex->nHeight > pindexSync->nHeight)
                if (!(pindex = pindex->pprev))
                    return error("CheckSyncCheckpoint: pprev null - block index structure failure");
            if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
                return false; // only descendant of sync-checkpoint can pass check
        }
        if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
            return false; // same height with sync-checkpoint
        if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
            return false; // lower height than sync-checkpoint
        return true;
    }

    bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
    {
        LOCK(cs_hashSyncCheckpoint);
        if (hashPendingCheckpoint == 0)
            return false;
        if (hashBlock == hashPendingCheckpoint)
            return true;
        if (mapOrphanBlocksSyncCheckpoint.count(hashPendingCheckpoint)
            && hashBlock == WantedByOrphan(mapOrphanBlocksSyncCheckpoint[hashPendingCheckpoint]))
            return true;
        return false;
    }

    // ppcoin: reset synchronized checkpoint to last hardened checkpoint
    bool ResetSyncCheckpoint()
    {
        LogPrintf("ResetSyncCheckpoint\n");
        LOCK(cs_hashSyncCheckpoint);
        const uint256& hash = Checkpoints::GetLatestHardenedCheckpoint();
        if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
        {
            // checkpoint block accepted but not yet in main chain
            LogPrintf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());

            CBlock block;
            if (!ReadBlockFromDisk(block, mapBlockIndex[hash]))
                return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
            CValidationState state;
            LogPrintf("ResetSyncCheckpoint: ConnectTip\n");
            // if (!SetBestChain(state, mapBlockIndex[hash]))
            if (!ConnectTip(state, mapBlockIndex[hash]))
            {
                return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
            }
        }
        else if(!mapBlockIndex.count(hash))
        {
            // checkpoint block not yet accepted
            hashPendingCheckpoint = hash;
            checkpointMessagePending.SetNull();
            LogPrintf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
        }

        if (!WriteSyncCheckpoint((mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())? hash : Params().HashGenesisBlock()))
            return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
        LogPrintf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
        return true;
    }

    void AskForPendingSyncCheckpoint(CNode* pfrom)
    {
        LOCK(cs_hashSyncCheckpoint);
        if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocksSyncCheckpoint.count(hashPendingCheckpoint)))
            pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
    }

    // Verify sync checkpoint master pubkey and reset sync checkpoint if changed
    bool CheckCheckpointPubKey()
    {
        std::string strPubKey = "";
        std::string strMasterPubKey = TestNet() ? CSyncCheckpoint::strTestPubKey : CSyncCheckpoint::strMainPubKey;
        if (!pblocktree->ReadCheckpointPubKey(strPubKey) || strPubKey != strMasterPubKey)
        {
            // write checkpoint master key to db
            if (!pblocktree->WriteCheckpointPubKey(strMasterPubKey))
                return error("CheckCheckpointPubKey() : failed to write new checkpoint master key to db");
            if (!ResetSyncCheckpoint())
                return error("CheckCheckpointPubKey() : failed to reset sync-checkpoint");
        }
        return true;
    }

    bool SetCheckpointPrivKey(std::string strPrivKey)
    {
        // Test signing a sync-checkpoint with genesis block
        CSyncCheckpoint checkpoint;
        checkpoint.hashCheckpoint = Params().HashGenesisBlock();
        CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
        sMsg << (CUnsignedSyncCheckpoint)checkpoint;
        checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());

        CBitcoinSecret vchSecret;
        if (!vchSecret.SetString(strPrivKey))
            return error("SendSyncCheckpoint: Checkpoint master key invalid");
        // bool fCompressed;
        // CSecret secret = vchSecret.GetSecret(fCompressed);
        CKey secret = vchSecret.GetKey();
        // key.SetSecret(secret, fCompressed); // if key is not correct openssl may crash
        CKey key(secret);
        if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
            return false;

        // Test signing successful, proceed
        CSyncCheckpoint::strMasterPrivKey = strPrivKey;
        return true;
    }

    bool SendSyncCheckpoint(uint256 hashCheckpoint)
    {
        LogPrintf("SendSyncCheckpoint: hashCheckpoint=%s\n", hashCheckpoint.ToString().c_str());

        CSyncCheckpoint checkpoint;
        checkpoint.hashCheckpoint = hashCheckpoint;
        CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
        sMsg << (CUnsignedSyncCheckpoint)checkpoint;
        checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());

        if (CSyncCheckpoint::strMasterPrivKey.empty())
            return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
        CBitcoinSecret vchSecret;
        if (!vchSecret.SetString(CSyncCheckpoint::strMasterPrivKey))
            return error("SendSyncCheckpoint: Checkpoint master key invalid");
        // bool fCompressed;
        // CSecret secret = vchSecret.GetSecret(fCompressed);
        CKey secret = vchSecret.GetKey();
        // key.SetSecret(secret, fCompressed); // if key is not correct openssl may crash
        CKey key(secret);
        if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
            return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");

        if(!checkpoint.ProcessSyncCheckpoint(NULL))
        {
            LogPrintf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
            return false;
        }

        // Relay checkpoint
        {
            LOCK(cs_vNodes);
            BOOST_FOREACH(CNode* pnode, vNodes)
                checkpoint.RelayTo(pnode);
        }
        return true;
    }

    // Is the sync-checkpoint outside maturity window?
    bool IsMatureSyncCheckpoint()
    {
        LOCK(cs_hashSyncCheckpoint);
        // sync-checkpoint should always be accepted block
        assert(mapBlockIndex.count(hashSyncCheckpoint));
        const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
        // return (nBestHeight >= pindexSync->nHeight + COINBASE_MATURITY);
        return (chainActive.Tip()->nHeight >= pindexSync->nHeight + COINBASE_MATURITY);
    }

    // Is the sync-checkpoint too old?
    bool IsSyncCheckpointTooOld(unsigned int nSeconds)
    {
        LOCK(cs_hashSyncCheckpoint);
        // sync-checkpoint should always be accepted block
        assert(mapBlockIndex.count(hashSyncCheckpoint));
        const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
        return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
    }

    // ppcoin: find block wanted by given orphan block
    uint256 WantedByOrphan(const CBlock* pblockOrphan)
    {
        // Work back to the first block in the orphan chain
        while (mapOrphanBlocksSyncCheckpoint.count(pblockOrphan->hashPrevBlock))
            pblockOrphan = mapOrphanBlocksSyncCheckpoint[pblockOrphan->hashPrevBlock];
        return pblockOrphan->hashPrevBlock;
    }

}

// ppcoin: sync-checkpoint master key
const std::string CSyncCheckpoint::strMainPubKey = "0466aa7cf205be5c40f114c80d0d4087959508ace5642c9b849af1ba78d7c6b969f3e8d36b3d44e5a0ac1d2d8f3e6f7452055713943870700385544c2a04c5aa55";
const std::string CSyncCheckpoint::strTestPubKey = "041ba70a9e3afd1c0c13b7577e4f71ede2eee884df617fa28bfb0ee3fe993b9cc2835c16b794e46095bf425c4e2cdc2e628becdb196f0302840282d3d32d6c69bd";
std::string CSyncCheckpoint::strMasterPrivKey = "";

// ppcoin: verify signature of sync-checkpoint message
bool CSyncCheckpoint::CheckSignature()
{
    std::string strMasterPubKey = TestNet() ? CSyncCheckpoint::strTestPubKey : CSyncCheckpoint::strMainPubKey;
//    if (!key.Set(ParseHex(strMasterPubKey)))
//        return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
    CPubKey key(ParseHex(strMasterPubKey));
    if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
        return error("CSyncCheckpoint::CheckSignature() : verify signature failed");

    // Now unserialize the data
    CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
    sMsg >> *(CUnsignedSyncCheckpoint*)this;
    return true;
}

// ppcoin: process synchronized checkpoint
bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
{
    if (!CheckSignature())
        return false;

    LOCK(Checkpoints::cs_hashSyncCheckpoint);
    if (!mapBlockIndex.count(hashCheckpoint))
    {
        // We haven't received the checkpoint chain, keep the checkpoint as pending
        Checkpoints::hashPendingCheckpoint = hashCheckpoint;
        Checkpoints::checkpointMessagePending = *this;
        LogPrintf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
        // Ask this guy to fill in what we're missing
        if (pfrom)
        {
            // pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
			PushGetBlocks(pfrom, chainActive.Tip(), hashCheckpoint);
            // ask directly as well in case rejected earlier by duplicate
            // proof-of-stake because getblocks may not get it this time
            pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocksSyncCheckpoint.count(hashCheckpoint)? Checkpoints::WantedByOrphan(mapOrphanBlocksSyncCheckpoint[hashCheckpoint]) : hashCheckpoint));
        }
        return false;
    }

    if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
        return false;

    CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
    if (!pindexCheckpoint->IsInMainChain())
    {
        // checkpoint chain received but not yet main chain
        CBlock block;
        if (!ReadBlockFromDisk(block, pindexCheckpoint))
            return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
        CValidationState state;
        LogPrintf("ProcessSyncCheckpoint: ConnectTip\n");
        // if (!SetBestChain(state, pindexCheckpoint))
        if (!ConnectTip(state, pindexCheckpoint))
        {
            Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
            return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
        }
    }

    if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
        return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
    Checkpoints::checkpointMessage = *this;
    Checkpoints::hashPendingCheckpoint = 0;
    Checkpoints::checkpointMessagePending.SetNull();

    LogPrintf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
    return true;
}


text:
/**
 * \file md_internal.h
 *
 * \brief Message digest wrappers.
 *
 * \warning This in an internal header. Do not include directly.
 *
 * \author Adriaan de Jong <dejong@fox-it.com>
 */
/*
 *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
 *  SPDX-License-Identifier: Apache-2.0
 *
 *  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.
 *
 *  This file is part of mbed TLS (https://tls.mbed.org)
 */
#ifndef MBEDTLS_MD_WRAP_H
#define MBEDTLS_MD_WRAP_H

#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif

#include "md.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * Message digest information.
 * Allows message digest functions to be called in a generic way.
 */
struct mbedtls_md_info_t
{
    /** Digest identifier */
    mbedtls_md_type_t type;

    /** Name of the message digest */
    const char * name;

    /** Output length of the digest function in bytes */
    int size;

    /** Block length of the digest function in bytes */
    int block_size;

    /** Digest initialisation function */
    int (*starts_func)( void *ctx );

    /** Digest update function */
    int (*update_func)( void *ctx, const unsigned char *input, size_t ilen );

    /** Digest finalisation function */
    int (*finish_func)( void *ctx, unsigned char *output );

    /** Generic digest function */
    int (*digest_func)( const unsigned char *input, size_t ilen,
                        unsigned char *output );

    /** Allocate a new context */
    void * (*ctx_alloc_func)( void );

    /** Free the given context */
    void (*ctx_free_func)( void *ctx );

    /** Clone state from a context */
    void (*clone_func)( void *dst, const void *src );

    /** Internal use only */
    int (*process_func)( void *ctx, const unsigned char *input );
};

#if defined(MBEDTLS_MD2_C)
extern const mbedtls_md_info_t mbedtls_md2_info;
#endif
#if defined(MBEDTLS_MD4_C)
extern const mbedtls_md_info_t mbedtls_md4_info;
#endif
#if defined(MBEDTLS_MD5_C)
extern const mbedtls_md_info_t mbedtls_md5_info;
#endif
#if defined(MBEDTLS_RIPEMD160_C)
extern const mbedtls_md_info_t mbedtls_ripemd160_info;
#endif
#if defined(MBEDTLS_SHA1_C)
extern const mbedtls_md_info_t mbedtls_sha1_info;
#endif
#if defined(MBEDTLS_SHA256_C)
extern const mbedtls_md_info_t mbedtls_sha224_info;
extern const mbedtls_md_info_t mbedtls_sha256_info;
#endif
#if defined(MBEDTLS_SHA512_C)
extern const mbedtls_md_info_t mbedtls_sha384_info;
extern const mbedtls_md_info_t mbedtls_sha512_info;
#endif

#ifdef __cplusplus
}
#endif

#endif /* MBEDTLS_MD_WRAP_H */

redpajama_set_name: RedPajamaGithub


text:
package tlc2.debug;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.lsp4j.debug.Breakpoint;
import org.eclipse.lsp4j.debug.Capabilities;
import org.eclipse.lsp4j.debug.ConfigurationDoneArguments;
import org.eclipse.lsp4j.debug.ContinueArguments;
import org.eclipse.lsp4j.debug.ContinueResponse;
import org.eclipse.lsp4j.debug.DisconnectArguments;
import org.eclipse.lsp4j.debug.EvaluateArguments;
import org.eclipse.lsp4j.debug.EvaluateArgumentsContext;
import org.eclipse.lsp4j.debug.EvaluateResponse;
import org.eclipse.lsp4j.debug.ExceptionBreakpointsFilter;
import org.eclipse.lsp4j.debug.InitializeRequestArguments;
import org.eclipse.lsp4j.debug.NextArguments;
import org.eclipse.lsp4j.debug.OutputEventArguments;
import org.eclipse.lsp4j.debug.PauseArguments;
import org.eclipse.lsp4j.debug.ReverseContinueArguments;
import org.eclipse.lsp4j.debug.ScopesArguments;
import org.eclipse.lsp4j.debug.ScopesResponse;
import org.eclipse.lsp4j.debug.SetBreakpointsArguments;
import org.eclipse.lsp4j.debug.SetBreakpointsResponse;
import org.eclipse.lsp4j.debug.SetExceptionBreakpointsArguments;
import org.eclipse.lsp4j.debug.SetVariableArguments;
import org.eclipse.lsp4j.debug.SetVariableResponse;
import org.eclipse.lsp4j.debug.Source;
import org.eclipse.lsp4j.debug.SourceBreakpoint;
import org.eclipse.lsp4j.debug.StackFrame;
import org.eclipse.lsp4j.debug.StackTraceArguments;
import org.eclipse.lsp4j.debug.StackTraceResponse;
import org.eclipse.lsp4j.debug.StepBackArguments;
import org.eclipse.lsp4j.debug.StepInArguments;
import org.eclipse.lsp4j.debug.StepOutArguments;
import org.eclipse.lsp4j.debug.StoppedEventArguments;
import org.eclipse.lsp4j.debug.TerminateArguments;
import org.eclipse.lsp4j.debug.TerminatedEventArguments;
import org.eclipse.lsp4j.debug.Thread;
import org.eclipse.lsp4j.debug.ThreadsResponse;
import org.eclipse.lsp4j.debug.Variable;
import org.eclipse.lsp4j.debug.VariablesArguments;
import org.eclipse.lsp4j.debug.VariablesResponse;
import org.eclipse.lsp4j.debug.services.IDebugProtocolClient;
import org.eclipse.lsp4j.jsonrpc.Launcher;

import tla2sany.semantic.ModuleNode;
import tla2sany.semantic.OpDefNode;
import tla2sany.semantic.SemanticNode;
import tla2sany.st.Location;
import tlc2.TLCGlobals;
import tlc2.tool.Action;
import tlc2.tool.INextStateFunctor;
import tlc2.tool.StatefulRuntimeException;
import tlc2.tool.TLCState;
import tlc2.tool.impl.Tool;
import tlc2.util.Context;
import tlc2.value.impl.Value;

public abstract class TLCDebugger extends AbstractDebugger implements IDebugTarget {
	protected static Logger LOGGER = Logger.getLogger(TLCDebugger.class.getName());

	protected Launcher<IDebugProtocolClient> launcher;

	private Tool tool;

	public TLCDebugger() {
		this.step = Step.In;
		this.haltExp = true;
		this.haltInv = true;
	}

	public TLCDebugger(final Step s, final boolean halt) {
		this.step = s;
		this.haltExp = halt;
		this.haltInv = halt;
	}

	/*
	 * Unit testing only!!!
	 */
	TLCDebugger(final Step s, final boolean halt, final boolean executionIsHalted) {
		this.step = s;
		this.haltExp = halt;
		this.haltInv = halt;
		this.executionIsHalted = executionIsHalted;
	}

	@Override
	public IDebugTarget setTool(final Tool tool) {
		this.tool = tool;
		return this;
	}

	@Override
	public synchronized CompletableFuture<Capabilities> initialize(InitializeRequestArguments args) {
		LOGGER.finer("initialize");

		Executors.newSingleThreadExecutor().submit(() -> {
			LOGGER.finer("initialize -> initialized");
			// Signal the debugger that we are ready. It seem not relevant in what order the
			// response below and the initialized signal arrive at the debugger.
			launcher.getRemoteProxy().initialized();
		});

		// The capabilities define customizations how the debugger will interact with
		// this debuggee. Declaring no capabilities causes the most simple protocol to
		// be used.
		final Capabilities capabilities = new Capabilities();
		capabilities.setSupportsEvaluateForHovers(true);
		capabilities.setSupportsTerminateRequest(true);
		// Don't support ExceptionInfo requests. The previous git commit of the one that
		// introduces this message implements the request, and we learned that EI are
		// only useful if we wish to show the Java stack trace (which users don't care
		// about).
		capabilities.setSupportsExceptionInfoRequest(false);
		// Let users flip at runtime the value of "nohalt" that they passed as a
		// sub-command of the "-debugger" (see tlc2.TLC.java) command.
		capabilities.setExceptionBreakpointFilters(getExceptionBreakpointFilters());
		// Don't support more sophisticated configuration of exception breakpoint
		// filters such as ignoring some exceptions. When TLC hits an exception, it
		// terminates anyway.
		capabilities.setSupportsExceptionOptions(false);
		// Breakpoints:
		capabilities.setSupportsHitConditionalBreakpoints(true);
		// TODO: Log points and conditional (expression-based) breakpoints require to
		// parse TLA+ expressions after the spec has been parsed, which is not supported
		// by SANY.
		capabilities.setSupportsConditionalBreakpoints(false);
		capabilities.setSupportsLogPoints(false);
		// TODO: Implement stepping back for model-checking and simulation/generation.
		// Stepping back would be hugely useful especially because TLC's evaluation behavior might be
		// surprising (non-determinism). This can cause users to miss the stack-frame they wish to see.
		// Implementing arbitrary navigation along stack-frames is impossible unless one implements
		// undo operations for each Tool action.  However, it should be good enough to reset Tool
		// to e.g. the beginning of the evaluation of the next-state relation for state s, evaluation
		// of the invariant for state s, evaluation of state- & action-constraints for s, ... by
		// throwing a ResetEvalException.
		capabilities.setSupportsStepBack(true);
		return CompletableFuture.completedFuture(capabilities);
	}

	private ExceptionBreakpointsFilter[] getExceptionBreakpointFilters() {
		final ExceptionBreakpointsFilter filter = new ExceptionBreakpointsFilter();
		filter.setDefault_(this.haltExp);
		filter.setFilter("ExceptionBreakpointsFilter");
		filter.setLabel("Halt (break) on exceptions");

		final ExceptionBreakpointsFilter violations = new ExceptionBreakpointsFilter();
		violations.setDefault_(this.haltInv);
		violations.setFilter("InvariantBreakpointsFilter");
		violations.setLabel("Halt (break) on violations");

		return new ExceptionBreakpointsFilter[] {filter, violations};
	}

	@Override
	public synchronized CompletableFuture<Void> setExceptionBreakpoints(SetExceptionBreakpointsArguments args) {
		final List<String> asList = Arrays.asList(args.getFilters());
		this.haltExp = asList.contains("ExceptionBreakpointsFilter");
		this.haltInv = asList.contains("InvariantBreakpointsFilter");
		return CompletableFuture.completedFuture(null);
	}

	@Override
	public synchronized CompletableFuture<EvaluateResponse> evaluate(final EvaluateArguments args) {
		// See https://github.com/alygin/vscode-tlaplus/blob/master/src/main.ts
		if (EvaluateArgumentsContext.HOVER.equals(args.getContext()) && args.getExpression().startsWith("tlaplus://")) {
			return CompletableFuture.completedFuture(this.stack.stream().filter(f -> f.getId() == args.getFrameId())
					.findAny().map(f -> f.get(args)).orElse(new EvaluateResponse()));
		} else if (EvaluateArgumentsContext.REPL.equals(args.getContext())) {
			// TODO: Users can enter (arbitrary) expressions in the front-end's "Debug
			// Console". We could try to handle valid TLA+ expressions here, but SANY
			// unfortunately lacks incremental parsing.  Study related discussion started
			// in http://discuss.tlapl.us/msg01427.html and continued offline in the involved
			// inboxes.
		} else if ("variables".equals(args.getContext())) {
			// The front-end passes "variables" as the context when users select a variable
			// in the variables view and invoke the copy-to-clipboard action. Since the
			// variables view shows the plain TLA+ values, we don't have to do anything
			// here, but simply return the value. One thing to investigate is why
			// copy-to-clipboard requires a full front-end/back-end round-trip in the first
			// place. I suspect that this is a side-effect of the
			// setSupportsEvaluateForHovers capability that the back-end announces in
			// initialize above.
			// TODO Our version of LSP4J doesn't know the constant "variables" yet, which is
			// why it's hard-coded here.
			final EvaluateResponse response = new EvaluateResponse();
			response.setResult(args.getExpression());
			return CompletableFuture.completedFuture(response);
		}
		return CompletableFuture.completedFuture(new EvaluateResponse());
	}

	// See setSupportsTerminateRequest above.
	@Override
	public synchronized CompletableFuture<Void> terminate(TerminateArguments args) {
		LOGGER.finer("terminate");
		// TODO: In case the debugger is currently paused on an ASSUME, TLC will first
		// generate the initial states before stopping.
		if (TLCGlobals.mainChecker != null) {
			TLCGlobals.mainChecker.stop();
		}
		if (TLCGlobals.simulator != null) {
			TLCGlobals.simulator.stop();
		}

		if (launcher != null) {
			// Notify the front-end that the debugger has terminated. Do this before notify
			// is called in disconnect to not create a race condition, i.e. failing to send
			// terminated because TLC quit.
			launcher.getRemoteProxy().terminated(new TerminatedEventArguments());
		}

		return disconnect(new DisconnectArguments());
	}

	@Override
	public synchronized CompletableFuture<Void> disconnect(DisconnectArguments args) {
		LOGGER.finer("disconnect");

		// "Unlock" evaluation, i.e. set step to Continue and clear all breakpoints.
		// Afterwards, resume TLC in case it's waiting for the debugger too.
		breakpoints.clear();
		targetLevel = -1;
		step = Step.Continue;
		haltExp = false;
		haltInv = false;
		this.notify();

		return CompletableFuture.completedFuture(null);
	}

	@Override
	public synchronized CompletableFuture<Void> configurationDone(ConfigurationDoneArguments args) {
		LOGGER.finer("configurationDone");
		return CompletableFuture.completedFuture(null);
	}

	protected final Map<String, List<TLCSourceBreakpoint>> breakpoints = new HashMap<>();

	@Override
	public synchronized CompletableFuture<SetBreakpointsResponse> setBreakpoints(final SetBreakpointsArguments args) {
		//TODO: Confirm breakpoint locations (see tlc2.debug.TLCDebugger.matches(SemanticNode))!!!
		LOGGER.finer("setBreakpoints");

		final String module = args.getSource().getName().replaceFirst(".tla$", "");

		if (args.getBreakpoints() != null && args.getBreakpoints().length > 0) {
			breakpoints.computeIfAbsent(module, key -> new ArrayList<TLCSourceBreakpoint>()).clear();

			final ModuleNode moduleNode = tool.getModule(module);

			final SourceBreakpoint[] sbps = args.getBreakpoints();
			final Breakpoint[] bp = new Breakpoint[sbps.length];
			for (int j = 0; j < sbps.length; j++) {
				final TLCSourceBreakpoint sbp = new TLCSourceBreakpoint(module, sbps[j]);
				breakpoints.get(module).add(sbp);

				// Create the response that communicates the result of setting the breakpoint.
				// We could try to verify the location of breakpoints.
				final Breakpoint breakpoint = new Breakpoint();
				breakpoint.setColumn(sbp.getColumn());
				breakpoint.setLine(sbp.getLine());
				breakpoint.setId(j);
				// Verify breakpoints. However, we only get the beginLine and
				// (optionally) beginColumn, but not endLine or endColumn, which
				// makes this fuzzy.  This doesn't matter though, as we
				// still create the breakpoint; only the user sees a visual cue.
				// I considered only to walk tool.getActions, tool.getInvariants,
				// getStateConstraints, getActionConstraionts, ..., but this causes
				// breakpoints in a high-level spec (refinement mapping) to
				// incorrectly show breakpoints as unverified.
				breakpoint.setVerified(
						// moduleNode is null if the front-end has a spec open (with breakpoints) that is
						// not part of the debugged spec and its modules.  For example, this might be a
						// module in the current folder that is neither extended nor instantiated.
						moduleNode == null || moduleNode.walkChildren(new SemanticNode.ChildrenVisitor<Boolean>() {
							private boolean verified = false;

							public void preVisit(final SemanticNode node) {
								final Location location = node.getLocation();
								// TODO: Include beginColumn/column here and where we handle breakpoints.
								if (location.beginLine() == sbp.getLine() && location.endLine() == sbp.getLine()) {
									this.verified = true;
								}
							}

							public boolean preempt(SemanticNode node) {
								return verified || !node.getLocation().includes(sbp.getLocation());
							}

							public Boolean get() {
								return verified;
							}
						}).get());
				// TODO: Set message why the breakpoint could not be set. E.g. would be useful
				// if a user tries to add a breakpoint at a temporal property such as the
				// behavior spec. The Next relation is another candidate when TLC decomposes it
				// into sub-actions s.t. a breakpoint on Next will never hit.

				final Source source = args.getSource();
				breakpoint.setSource(source);
				bp[j] = breakpoint;
			}
			final SetBreakpointsResponse response = new SetBreakpointsResponse();
			response.setBreakpoints(bp);
			return CompletableFuture.completedFuture(response);
		} else {
			breakpoints.getOrDefault(module, new ArrayList<>()).clear();
			return CompletableFuture.completedFuture(new SetBreakpointsResponse());
		}
	}

	@Override
	public synchronized CompletableFuture<StackTraceResponse> stackTrace(StackTraceArguments args) {
		LOGGER.finer(String.format("stackTrace frame: %s, levels: %s\n", args.getStartFrame(), args.getLevels()));
		final StackTraceResponse res = new StackTraceResponse();

		if (!executionIsHalted) {
			// Returning the current stack frames to the front-end when execution is *not*
			// halted causes the front-end to briefly jump to the location of the topmost
			// stack frame.
			res.setStackFrames(new StackFrame[0]);
			res.setTotalFrames(0);
			return CompletableFuture.completedFuture(res);
		}

		int from = 0;
		if (args.getStartFrame() != null) {
			int req = args.getStartFrame();
			// within bounds.
			if (req < 0 || stack.size() - 1 < req) {
				res.setStackFrames(new StackFrame[0]);
				return CompletableFuture.completedFuture(res);
			}
			from = req;
		}

		int to = stack.size(); // No decrement by one because subList is exclusive.
		if (args.getLevels() != null) {
			int req = args.getLevels();
			// If not within bounds, ignore levels.
			if (req > 0 && from + req < to) {
				to = from + req;
			}
		}

		final List<TLCStackFrame> frames = stack.subList(from, to);
		res.setStackFrames(frames.toArray(new StackFrame[frames.size()]));
		res.setTotalFrames(stack.size());
		return CompletableFuture.completedFuture(res);
	}

	@Override
	public synchronized CompletableFuture<ScopesResponse> scopes(ScopesArguments args) {
		LOGGER.finer(String.format("scopes frame %s\n", args.getFrameId()));

		final ScopesResponse response = new ScopesResponse();

		stack.stream().filter(s -> s.getId() == args.getFrameId()).findFirst()
				.ifPresent(frame -> response.setScopes(frame.getScopes()));

		return CompletableFuture.completedFuture(response);
	}

	@Override
	public synchronized CompletableFuture<VariablesResponse> variables(VariablesArguments args) {
		final int vr = args.getVariablesReference();

		final VariablesResponse value = new VariablesResponse();

		final List<Variable> collect = new ArrayList<>();
		for (TLCStackFrame frame : this.stack) {
			collect.addAll(Arrays.asList(frame.getVariables(vr)));
		}
		value.setVariables(collect.toArray(new Variable[collect.size()]));

		return CompletableFuture.completedFuture(value);
	}

	@Override
	public synchronized CompletableFuture<SetVariableResponse> setVariable(SetVariableArguments args) {
		LOGGER.finer("setVariable");
		return CompletableFuture.completedFuture(new SetVariableResponse());
	}

	@Override
	public synchronized CompletableFuture<ThreadsResponse> threads() {
		LOGGER.finer("threads");
		Thread thread = new Thread();
		thread.setId(0);
		thread.setName("worker");
		ThreadsResponse res = new ThreadsResponse();
		res.setThreads(new Thread[] { thread });
		return CompletableFuture.completedFuture(res);
	}

	@Override
	public synchronized CompletableFuture<ContinueResponse> continue_(ContinueArguments args) {
		LOGGER.finer("continue_");
		targetLevel = -1;
		step = Step.Continue;
		this.notify();
		return CompletableFuture.completedFuture(new ContinueResponse());
	}

	@Override
	public synchronized CompletableFuture<Void> next(NextArguments args) {
		LOGGER.finer("next/stepOver");
		targetLevel = this.stack.size();
		step = Step.Over;
		this.notify();
		return CompletableFuture.completedFuture(null);
	}

	@Override
	public synchronized CompletableFuture<Void> stepIn(StepInArguments args) {
		LOGGER.finer("stepIn");
		// matches(..) below does not take targetLevel into account, thus not changing
		// it here. The reason is that it is surprising if step.in on a leaf-frame
		// would amount to resume/continue.
		step = Step.In;
		this.notify();
		return CompletableFuture.completedFuture(null);
	}

	@Override
	public synchronized CompletableFuture<Void> stepOut(StepOutArguments args) {
		LOGGER.finer("stepOut");
		targetLevel = this.stack.size();
		step = Step.Out;
		this.notify();
		return CompletableFuture.completedFuture(null);
	}

	@Override
	public synchronized CompletableFuture<Void> pause(PauseArguments args) {
		LOGGER.finer("pause");
		Executors.newSingleThreadExecutor().submit(() -> {
			LOGGER.finer("pause -> stopped");
			StoppedEventArguments eventArguments = new StoppedEventArguments();
			eventArguments.setThreadId(0);
			eventArguments.setReason("pause");
			launcher.getRemoteProxy().stopped(eventArguments);
		});
		return CompletableFuture.completedFuture(null);
	}

	@Override
	public synchronized CompletableFuture<Void> stepBack(StepBackArguments args) {
		step = Step.Reset;
		this.notify();

		return CompletableFuture.completedFuture(null);
	}

	@Override
	public synchronized CompletableFuture<Void> reverseContinue(ReverseContinueArguments args) {
		step = Step.Reset_Start;
		this.notify();

		return CompletableFuture.completedFuture(null);
	}

	// 8888888888888888888888888888888888888888888888888888888888888888888888888 //

	//TODO: Instead of maintaining the stack here, we could evaluated with CallStackTool
	// that will get the job done for us (tlc2.tool.impl.CallStackTool.callStack).
	// However, CST only keeps the SemanticNode but skips the Context and the values. We
	// would have to make CST take a function that applies a transformation for the debugger
	// and a different one when CST does its original job.
	protected final LinkedList<TLCStackFrame> stack = new LinkedList<>();

	// Initialize the debugger to immediately halt on the first frame.
	private volatile int targetLevel = 1;
	private volatile Step step = Step.In;

	private volatile boolean haltExp;
	private volatile boolean haltInv;
	private volatile boolean executionIsHalted = false;

	@Override
	public synchronized IDebugTarget pushFrame(Tool tool, SemanticNode expr, Context c) {
		final TLCStackFrame frame = new TLCStackFrame(stack.peek(), expr, c, tool);
		stack.push(frame);
		haltExecution(frame, this.stack.size());
		return this;
	}

	@Override
	public synchronized IDebugTarget pushFrame(Tool tool, SemanticNode expr, Context c, TLCState s) {
		final TLCStackFrame frame = new TLCStateStackFrame(stack.peek(), expr, c, tool, s);
		stack.push(frame);
		haltExecution(frame, this.stack.size());
		return this;
	}

	@Override
	public synchronized IDebugTarget pushFrame(Tool tool, SemanticNode expr, Context c, TLCState s,
			Action a, TLCState t) {
		final TLCStackFrame frame = new TLCActionStackFrame(stack.peek(), expr, c, tool, s, a, t);
		stack.push(frame);
		haltExecution(frame, this.stack.size());
		return this;
	}

	@Override
	public synchronized IDebugTarget pushFrame(Tool tool, OpDefNode expr, Context c, TLCState s,
			Action a, INextStateFunctor fun) {
		final TLCStackFrame frame = new TLCSuccessorsStackFrame(stack.peek(), expr, c, tool, s, a, fun);
		stack.push(frame);
		// for the fun it doesn't make sense to halt the execution *before* the
		// successor states have been generated. Instead, haltExec is called in the
		// corresponding pop method below.
		//haltExecution(frame, this.stack.size());
		return this;
	}

	@Override
	public synchronized IDebugTarget popFrame(Tool tool, OpDefNode expr, Context c, TLCState s, Action a,
			INextStateFunctor fun) {
		final TLCStackFrame frame = this.stack.peek();
		if (frame != null && matches(frame)) {
			// Check if execution/evaluation should be halted even if fun#getStates is
			// empty.  Users can set the hit count to >0 to ignore non-enabled actions
			haltExecution(frame);
		}
		return popFrame(s);
	}

	@Override
	public synchronized IDebugTarget pushFrame(TLCState s) {
		TLCStackFrame f = this.stack.peek();
		pushFrame(f.getTool(), f.getNode(), f.getContext(), s);
		return this;
	}

	@Override
	public synchronized IDebugTarget pushFrame(TLCState s, Action a, TLCState t) {
		TLCStackFrame f = this.stack.peek();
		return pushFrame(f.getTool(), f.getNode(), f.getContext(), s, a, t);
	}

	@Override
	public synchronized IDebugTarget popFrame(TLCState state) {
		TLCStackFrame f = this.stack.peek();
		return popFrame(f.getTool(), f.getNode(), f.getContext(), state);
	}

	@Override
	public synchronized IDebugTarget popFrame(TLCState s, TLCState t) {
		//TODO This swallows the predecessor!
		return popFrame(t);
	}

	@Override
	public synchronized IDebugTarget popFrame(Tool tool, SemanticNode expr, Context c) {
		if (LOGGER.isLoggable(Level.FINER)) {
			LOGGER.finer(String.format("%s Call popFrame: [%s], level: %s\n",
					new String(new char[this.stack.size()]).replace('\0', '#'), expr, this.stack.size()));
		}
		final TLCStackFrame pop = stack.pop();
		assert pop.matches(expr);
		return this;
	}

	@Override
	public synchronized IDebugTarget popFrame(Tool tool, SemanticNode expr, Context c, Value v) {
		popFrame(tool, expr, c);

		// Attach value to the parent (peeked) frame iff it matches the SemanticNode
		// from which v was evaluated.  It shouldn't be possible for peeked to be
		// null, but better be safe than sorry.
		final TLCStackFrame peeked = stack.peek();
		if (peeked != null && peeked.node.myUID == expr.myUID) {
			// Consider setting the value's source to expr iff it's null otherwise. However,
			// make sure that this doesn't introduce a regression because TLC branches
			// somewhere based on whether Value#hasSource is true.  If we are sure that
			// Value#hasSource is an invariant, tlc2.debug.TLCStackFrame.getStackVariables(List<Variable>)
			// could derive the variable's name via ((SyntaxTreeNode) v.getSource().getTreeNode()).getHumanReadableImage(),
			// which - in turn - would allow to attach values even to nodes where peeked.node.myUID != expr.myUID.
			// Not sure, if this is ever necessary though.
//			if (!v.hasSource()) {
//				// TLC's test suite doesn't produce an error/failure with v.setSource(expr).
//				v.setSource(expr);
//			}
			stack.peek().setValue(v);
		}
		return this;
	}

	@Override
	public synchronized IDebugTarget popFrame(Tool tool, SemanticNode expr, Context c, TLCState s) {
		final TLCStackFrame pop = stack.pop();
		assert pop.matches(expr);
		return this;
	}

	@Override
	public synchronized IDebugTarget popFrame(Tool tool, SemanticNode expr, Context c, Value v, TLCState t) {
		popFrame(tool, expr, c, v);
		return this;
	}

	@Override
	public synchronized IDebugTarget popFrame(Tool tool, SemanticNode expr, Context c, TLCState s, TLCState t) {
		return popFrame(tool, expr, c);
	}

	@Override
	public synchronized IDebugTarget popFrame(Tool tool, SemanticNode expr, Context c, Value v, TLCState s, TLCState t) {
		popFrame(tool, expr, c, v);
		return this;
	}

	@Override
	public synchronized IDebugTarget popExceptionFrame(Tool tool, SemanticNode expr, Context c, Value v, StatefulRuntimeException e) {
		if (LOGGER.isLoggable(Level.FINER)) {
			LOGGER.finer(String.format("%s Call popExceptionFrame: [%s], level: %s\n",
					new String(new char[this.stack.size()]).replace('\0', '#'), expr, this.stack.size()));
		}
		final TLCStackFrame pop = stack.pop();
		assert pop.matches(expr, e);
		return this;
	}

	@Override
	public synchronized IDebugTarget popExceptionFrame(Tool tool, SemanticNode expr, Context c, Value v, TLCState s, StatefulRuntimeException e) {
		return popExceptionFrame(tool, expr, c, v, e);
	}

	@Override
	public synchronized IDebugTarget popExceptionFrame(Tool tool, SemanticNode expr, Context c, Value v, TLCState s, TLCState t, StatefulRuntimeException e) {
		return popExceptionFrame(tool, expr, c, v, e);
	}

	private boolean exceptionNotYetHandled(final StatefulRuntimeException e) {
		// The debugger handles an exception such as
		// EvalException/TLCRuntimeException/InvariantViolationException) (close to) the
		// call-site in Tool to point users to the most specific location. However, the
		// exception also gets re-thrown for TLC's generic exception handling to deal
		// with it. Potentially, this causes the debugger to catch the same exception
		// again when it travels up Tool's call-stack.  Here, we make sure that the debugger
		// handles an exception only once.
		return !e.setKnown();
	}

	@Override
	public synchronized IDebugTarget pushExceptionFrame(Tool tool, SemanticNode expr, Context c, StatefulRuntimeException e) {
		if (exceptionNotYetHandled(e)) {
			return pushFrameAndHalt(haltExp, new TLCStackFrame(stack.peek(), expr, c, tool, e), e);
		}
		return this;
	}

	@Override
	public synchronized IDebugTarget pushExceptionFrame(Tool tool, SemanticNode expr, Context c,
			TLCState state, StatefulRuntimeException e) {
		if (exceptionNotYetHandled(e)) {
			return pushFrameAndHalt(haltExp, new TLCStateStackFrame(stack.peek(), expr, c, tool, state, e), e);
		}
		return this;
	}

	@Override
	public synchronized IDebugTarget pushExceptionFrame(Tool tool, SemanticNode expr, Context c, TLCState s,
			Action a, TLCState t, StatefulRuntimeException e) {
		if (exceptionNotYetHandled(e)) {
			return pushFrameAndHalt(haltExp, new TLCActionStackFrame(stack.peek(), expr, c, tool, s, a, t, e), e);
		}
		return this;
	}

	@Override
	public synchronized IDebugTarget popExceptionFrame(Tool tool, SemanticNode expr, Context c, TLCState s,
			Action a, TLCState t, StatefulRuntimeException e) {
		return popExceptionFrame(tool, expr, c, null, e);
	}

	@Override
	public synchronized IDebugTarget markInvariantViolatedFrame(Tool debugTool, SemanticNode expr, Context c, TLCState predecessor, Action a, TLCState state, StatefulRuntimeException e) {
		if (exceptionNotYetHandled(e)) {
			pushFrameAndHalt(haltInv, new TLCActionStackFrame(stack.peek(), expr, c, tool, predecessor, a, state, e), e);
		}
		return this;
	}

	private IDebugTarget pushFrameAndHalt(final boolean halt, final TLCStackFrame frame, final RuntimeException e) {
		// Calling methods duplicate the top-most stack-frame with the exception causes
		// the front-end to raise a corresponding error in the editor.

		stack.push(frame);

		// Let the client print the exception in its debug output UI.
		final OutputEventArguments oea = new OutputEventArguments();
		oea.setOutput(e.getMessage());
		if (launcher != null) {
			launcher.getRemoteProxy().output(oea);
			// Only halt the execution if a front-end/debugger is connect?
		}

		if (halt) {
			haltExecution(frame);
		}

		return this;
	}

	protected void haltExecution(final TLCStackFrame frame, final int level) {
		if (LOGGER.isLoggable(Level.FINER)) {
			LOGGER.finer(String.format("%s(%s): [%s]\n", new String(new char[level]).replace('\0', '#'), level, frame.getNode()));
		}
		if (matches(step, targetLevel, level) || matches(frame)) {
			haltExecution(frame);
		}
	}

	protected void haltExecution(final TLCStackFrame frame) {
		sendStopped(frame);

		try {
			// Halt TLC's evaluation by blocking the worker thread. This state is observable
			// externally through the value of executionIsHalted.
			executionIsHalted = true;
			this.wait();
			executionIsHalted = false;
		} catch (InterruptedException notExpectedToHappen) {
			notExpectedToHappen.printStackTrace();
			java.lang.Thread.currentThread().interrupt();
		}

		if (Step.Reset == step) {
			step = Step.In;
			if (frame.parent != null) {
				// If frame has no parent, there is nothing the debugger reset to--it marks the entry point of the evaluation.
				throw new ResetEvalException(frame.parent);
			}
		} else if (Step.Reset_Start == step) {
			step = Step.In;
			throw new ResetEvalException(stack.getLast());
		}
	}

	protected void sendStopped(final TLCStackFrame frame) {
		LOGGER.finer("loadSource -> stopped");
		if (launcher != null) {
			final StoppedEventArguments eventArguments = frame.getStoppedEventArgument();
			eventArguments.setThreadId(0);
			launcher.getRemoteProxy().stopped(eventArguments);
		}
	}

	private static boolean matches(Step dir, int targetLevel, int currentLevel) {
		if (dir == Step.In) {
			// TODO With this conditional, step.in becomes continue when one steps into a
			// leave frame.  The debuggers that I know don't continue in this case.
//			if (currentLevel >= targetLevel) {
				return true;
//			}
		} else if (dir == Step.Over) {
			if (currentLevel == targetLevel) {
				return true;
			}
		} else if (dir == Step.Out) {
			// When stepping out, level has to be greater than or zero/0;
			if (currentLevel < targetLevel || currentLevel == 0) {
				return true;
			}
		}
		return false;
	}

	private boolean matches(final TLCStackFrame frame) {
		//TODO: Better match the location.  However, it shouldn't be done down here
		// but in setBreakpoints above that lets the debuggee tell the front-end
		// that a user-defined location is "corrected" to one that matches the bounds
		// of an expression in the semantic graph that is evaluated.  In other words,
		// setBreakpoints should traverse the semantic graph trying to find the smallest
		// i.e. best match for the given editor location.  The code here should then
		// simple compare the two location instances.
		// If no breakpoints are set, stream over an empty list.
		return breakpoints.getOrDefault(frame.getNode().getLocation().source(), new ArrayList<>()).stream()
				.anyMatch(b -> {
					return frame.matches(b);
				});
	}

	public static class Factory {

		public static TLCDebugger OVERRIDE;

		public static TLCDebugger getInstance(final int port, final boolean suspend, boolean halt) throws Exception {
			if (OVERRIDE != null) {
				return OVERRIDE;
			}
			if (suspend) {
				return new AttachingDebugger(port, Step.In, halt);
			}
			return new AttachingDebugger(port, Step.Continue, halt);
		}
	}
}


text:
package fr.ms.tomcat.manager;

import fr.ms.util.ServiceLoader;

/**
 *
 * @see Marco4J
 *
 *
 * @author Marco Semiao
 *
 */
@ServiceLoader
public class Tomcat6Manager implements TomcatManager {

    private String url = "http://localhost:8080/manager";

    private String username = "admin";

    private String password = "admin";

    @Override
    public void setUrl(final String url) {
	this.url = url;

    }

    @Override
    public void setUsername(final String username) {
	this.username = username;

    }

    @Override
    public void setPassword(final String password) {
	this.password = password;

    }

    @Override
    public void deploy(final String warName, final String DocBase) {
	try {
	    final TomcatManagerImpl tomcatManager = new TomcatManagerImpl(url, username, password);
	    tomcatManager.deploy(warName, DocBase);
	} catch (final Exception e) {
	    throw new TomcatManagerException(e);
	}
    }

    @Override
    public void undeploy(final String warName) {
	try {
	    final TomcatManagerImpl tomcatManager = new TomcatManagerImpl(url, username, password);
	    tomcatManager.undeploy(warName);
	} catch (final Exception e) {
	    throw new TomcatManagerException(e);
	}
    }

    @Override
    public boolean isDeploy(final String warName) {
	try {
	    final TomcatManagerImpl tomcatManager = new TomcatManagerImpl(url, username, password);
	    return tomcatManager.isDeploy(warName);
	} catch (final Exception e) {
	    throw new TomcatManagerException(e);
	}
    }

    @Override
    public int getVersion() {
	return 6;
    }
}


text:
package org.olat.ims.cp.ui;

import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.controller.BasicController;
import org.olat.ims.cp.ContentPackage;

/**
 *
 * Description:

 * This controller controls the workflows regarding the edit-process of a
 * cp-page
 *
 *
 *

 * Initial Date: 25.07.2008

 *
 * @author sergio
 */
public class CPMetadataEditController extends BasicController {

	private Link closeLink;
	private CPMDFlexiForm mdCtr; // MetadataController
	private ContentPackage cp;
	private CPPage page;

	protected CPMetadataEditController(UserRequest ureq, WindowControl control, CPPage page, ContentPackage cp) {
		super(ureq, control);
		this.cp = cp;
		this.page = page;
		mdCtr = new CPMDFlexiForm(ureq, getWindowControl(), page);
		listenTo(mdCtr);
		putInitialPanel(mdCtr.getInitialComponent());
	}

	protected void newPageAdded(String newNodeID) {
		this.page.setIdentifier(newNodeID);
	}

	/**
	 * returns the CPPage, which is edited
	 *
	 * @return
	 */
	public CPPage getCurrentPage() {
		return page;
	}

	@Override
	protected void doDispose() {
	// nothing to do
	}

	protected void event(UserRequest ureq, Component source, Event event) {
		if (source == closeLink) {
			fireEvent(ureq, Event.CANCELLED_EVENT);
		}
	}

	protected void event(UserRequest ureq, Controller source, Event event) {
		if (source == mdCtr) {
			page = mdCtr.getPage();
			fireEvent(ureq, event);
		}

	}

}


text:
package org.primaresearch.clc.phd.system;

import java.util.Collection;

import org.primaresearch.clc.phd.ontology.Ontology;
import org.primaresearch.clc.phd.ontology.label.Label;
import org.primaresearch.clc.phd.ontology.label.LabelGroup;
import org.primaresearch.clc.phd.ontology.label.LabelGroup.TooManyLabelsInGroupException;
import org.primaresearch.clc.phd.ontology.label.LabelType;
import org.primaresearch.clc.phd.ontology.label.Labels;

/**
 * Implementation for the 'User' interface
 * @author clc
 *
 */
public class UserImpl implements User {

	private Labels labels;
	private String name;

	/**
	 * Constructor
	 */
	public UserImpl(String name) {
		this.name = name;
		labels = new Labels(Ontology.getInstance().getUserLabelSlots());
	}

	@Override
	public Collection<LabelGroup> getLabels() {
		return labels.getAllLabels();
	}

	@Override
	public Label addLabel(LabelType labelType)
			throws TooManyLabelsInGroupException {
		return labels.add(labelType);
	}

	@Override
	public void removeLabel(Label label) {
		labels.remove(label);
	}

	@Override
	public boolean hasLabels() {
		return !labels.isEmpty();
	}

	@Override
	public String getName() {
		return name;
	}

}


text:
function q = scoreq(qmin,qmax,y,x,east,north)
% PURPOSE: evaluates cross-validation score for optimal q in gwr
%          based on tricube weighting
% ------------------------------------------------------
% USAGE: score = scoreq(qmin,qmax,y,x,east,north);
% where: qmin = minimum # nearest neighbors to use in CV search
%        qmax = maximum # nearest neighbors to use in CV search
%        y    = dependent variable
%        x = matrix of explanatory variables
%     east = longitude (x-direction) coordinates
%    north = lattitude (y-direction) coordinates
% ------------------------------------------------------
% RETURNS: q = # of nearest neighbors that minimum the score
%              function
% ------------------------------------------------------
% NOTE: this function catches inversion problems
%       and uses Hoerl-Kennard ridge regression
%       if needed
% ------------------------------------------------------
% SEE ALSO: scoref which finds optimal bandwidth
%           for gaussian and exponential weighting
% ------------------------------------------------------

% written by: James P. LeSage 2/98
% University of Toledo
% Department of Economics
% Toledo, OH 43606
% jpl@jpl.econ.utoledo.edu

[n k] = size(x); res = zeros(n,1);
d = zeros(n,1);
qgrid = qmin:qmax;
nq = length(qgrid);
wt = zeros(n,nq);
for iter = 1:n;
 dx = east - east(iter,1);
 dy = north - north(iter,1);
 d = (dx.*dx + dy.*dy);
         % sort distance to find q nearest neighbors
         ds = sort(d);
         dmax = ds(qmin:qmax,1);
         for j=1:nq;
   nzip = find(d <= dmax(j,1));
          wt(nzip,j) = (1-(d(nzip,1)/dmax(j,1)).^3).^3;
   wt(iter,j) = 0.0;
         end; % end of j loop
for j=1:nq;
% computational trick to speed things up
% use wt non-zero to pull out y,x observations
nzip = find(wt(:,j) > 0);
ys = y(nzip,1).*sqrt(wt(nzip,j));
xs = matmul(x(nzip,:),sqrt(wt(nzip,j)));
bi=xs\ys;
% compute predicted values
yhat = x(iter,:)*bi;
% compute residuals
res(iter,j) = y(iter,1) - yhat;
end; % end of for j loop over q-values
end; % end of for iter loop

tmp = res.*res;
score = sum(tmp);
[smin sind] = min(score);
q = qgrid(sind);


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imos.sample.pi;

import java.util.Calendar;
import java.util.List;
import java.util.Date;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * This example code demonstrates how to perform simple state control of a GPIO
 * pin on the Raspberry Pi.
 *
 * @author Robert Savage
 */
public class MotionSensor {

    SMTPMailSample sample = new SMTPMailSample();
    int detectionCount = 0;
    Calendar cal = GregorianCalendar.getInstance();
    boolean recording, sendMail, canSendMail;
    long startTime, currentTime, timeInterval, waitingForMail, mailStartTime, moduleStartTime;
    StringBuilder fileName = new StringBuilder();
    String videoFileName;
    List<String> timeStampList = new ArrayList<>();

    public void controlGpio() throws InterruptedException {

        System.out.println("<--Pi4J--> GPIO Control Example ... started.");
        GpioController gpio = null;
        GpioPinDigitalOutput led = null;
        try {
            // create gpio controller
            gpio = GpioFactory.getInstance();

            // provision gpio pin #01 as an output pin and turn on
            led = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "MyLED", PinState.LOW);

            start(led, gpio);
            //ledBlink(led, gpio);
            //motionSensor(gpio, led);
            //temperatureSensor(led, gpio);
            //distanceSensor(gpio, led);
            pythonTemperatureSensor();

        } catch (InterruptedException e) {
            led.low();
            // stop all GPIO activity/threads by shutting down the GPIO controller
            // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
            gpio.shutdown();
            throw e;
        } finally {
            led.low();
            // stop all GPIO activity/threads by shutting down the GPIO controller
            // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
            gpio.shutdown();
            System.out.println("done");
        }

        //sample.connect(String.valueOf(detectionCount), fileName.toString());
    }

    public void pythonTemperatureSensor() {

        try {
            String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4";
            int count = 0;
            JSONArray array = new JSONArray();
            int dayOfMonth = 0;
            cal.setTime(new Date());
            dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
            while (true) {
                Process p = Runtime.getRuntime().exec(cmd);
                p.waitFor();

                StringBuilder output = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    output.append(line);
                }
                String result = output.toString(), tempStr;
                double temp, humid;
                if (!result.trim().isEmpty()) {
                    tempStr = result.substring(result.indexOf("Humid"));
                    result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                    temp = Double.parseDouble(result);
                    result = tempStr;
                    result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                    humid = Double.parseDouble(result);

                    JSONObject data = new JSONObject();
                    data.put("temp", temp);
                    data.put("humid", humid);
                    data.put("time", new Date().getTime());

                    array.put(data);
                }

                Thread.sleep(60000);
                count++;
                if (count == 60) {
                    Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, null, "");
                    cal.setTime(new Date());
                    StringBuilder builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    builder.append("-");
                    builder.append(cal.get(Calendar.HOUR_OF_DAY));
                    builder.append("_");
                    builder.append(cal.get(Calendar.MINUTE));
                    try (BufferedWriter writer = new BufferedWriter(new FileWriter(builder.toString() + "_data.json"))) {
                        writer.append(array.toString());
                    } catch (IOException ex) {

                    }
                    System.out.println(builder.toString());
                    count = 0;
                    array = new JSONArray();
                    if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                        builder = new StringBuilder();
                        builder.append(cal.get(Calendar.DAY_OF_MONTH));
                        builder.append("-");
                        builder.append(cal.get(Calendar.MONTH));
                        builder.append("-");
                        builder.append(cal.get(Calendar.YEAR));
                        String dirName = builder.toString();
                        File newDir = new File("src/main/resources/" + dirName);
                        newDir.mkdir();

                        File files = new File("src/main/resources/");
                        for (File file : files.listFiles()) {
                            if (file.getName().endsWith(".json")) {
                                file.renameTo(new File("src/main/resources/" + dirName + file.getName()));
                                file.delete();
                            }
                        }

                        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                    }
                }
            }
        } catch (IOException | InterruptedException ex) {
            Logger.getLogger(MotionSensor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void temperatureSensor(final GpioPinDigitalOutput led, final GpioController gpio) throws InterruptedException {
        // provision gpio pin #01 as an output pin and turn on
        final GpioPinDigitalInput sensor = gpio.provisionDigitalInputPin(RaspiPin.GPIO_04, "TemperatureSensor", PinPullResistance.PULL_DOWN);
        System.out.println("started");
        System.out.println(sensor.getMode().getValue());
        led.high();

        sensor.addListener((GpioPinListenerDigital) (GpioPinDigitalStateChangeEvent event) -> {
            System.out.println(event.getState().getValue());
        });

        try {
            int count = 0;
            // keep program running until user aborts
            for (;;) {
                Thread.sleep(500);
                count++;
                if (count > 200) {
                    break;
                }
            }
            System.out.println("completed");
        } catch (final Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private void start(final GpioPinDigitalOutput led, final GpioController gpio) throws InterruptedException {

    }

    private void ledBlink(final GpioPinDigitalOutput led, final GpioController gpio) throws InterruptedException {
        // set shutdown state for this pin
        led.setShutdownOptions(true, PinState.LOW);
        led.high();
        System.out.println("--> GPIO state should be: ON");

        Thread.sleep(5000);

        // turn off gpio pin #01
        led.low();
        System.out.println("--> GPIO state should be: OFF");

        Thread.sleep(5000);

        // toggle the current state of gpio pin #01 (should turn on)
        led.toggle();
        System.out.println("--> GPIO state should be: ON");

        Thread.sleep(20000);

        // toggle the current state of gpio pin #01  (should turn off)
        led.toggle();
        System.out.println("--> GPIO state should be: OFF");

        Thread.sleep(5000);

        // turn on gpio pin #01 for 1 second and then off
        System.out.println("--> GPIO state should be: ON for only 1 second");
        led.pulse(1000, true); // set second argument to 'true' use a blocking call

        // stop all GPIO activity/threads by shutting down the GPIO controller
        // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
        //gpio.shutdown();
    }

    private void distanceSensor(final GpioController gpio, final GpioPinDigitalOutput led) {
        final GpioPinDigitalInput sensor = gpio.provisionDigitalInputPin(RaspiPin.GPIO_05, "DistanceSensor", PinPullResistance.PULL_DOWN);
        System.out.println("started");
        led.high();
        sensor.addListener((GpioPinListenerDigital) (GpioPinDigitalStateChangeEvent event) -> {

            System.out.println(event.getState().getValue());
            if (event.getState().isHigh()) {

            }
        });

        int counter = 0;
        while (true) {
            if (counter > 120) {
                break;
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                Logger.getLogger(MotionSensor.class.getName()).log(Level.SEVERE, null, ex);
            }
            counter++;
        }
    }

    private void motionSensor(final GpioController gpio, final GpioPinDigitalOutput led) throws InterruptedException {
        // provision gpio pin #01 as an output pin and turn on
        final GpioPinDigitalInput sensor = gpio.provisionDigitalInputPin(RaspiPin.GPIO_04, "MotionSensor", PinPullResistance.PULL_DOWN);
        System.out.println("started");
        moduleStartTime = startTime = currentTime = System.nanoTime();
        sensor.addListener((GpioPinListenerDigital) (GpioPinDigitalStateChangeEvent event) -> {
            if (event.getState().isHigh()) {
                led.high();
                System.out.println("Motion Detected!");
                if (timeInterval > 10) {
                    recording = false;
                }
                String value = calculateTime(System.nanoTime());
                timeStampList.add(value);
                detectionCount++;
                currentTime = System.nanoTime();

                if (!recording) {
                    startTime = currentTime;
                }
                if (startTime < currentTime) {
                    timeInterval = currentTime - startTime;
                    timeInterval = timeInterval / 1000000000;
                }
                if (!recording) {
                    System.out.println("recording started");
                    recording = true;
                    Process p;
                    try {
                        createFileName();
                        videoFileName = fileName.toString();
                        //p = Runtime.getRuntime().exec("raspivid -o /home/pi/NetBeansProjects/HelloRaspberryPi/dist/" + videoFileName + " -t 10000 -td 2500,5000");
                        //p = Runtime.getRuntime().exec("raspivid -s -o ./" + videoFileName + " -t 10000 -td 2000 3000");
                        //p = Runtime.getRuntime().exec("raspivid -s -o ./" + videoFileName + " -t 10000");
                        p = Runtime.getRuntime().exec("raspivid -s -o ./" + videoFileName);
                        p.waitFor();
                    } catch (IOException | InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            if (event.getState().isLow()) {
                canSendMail = true;
                waitingForMail = 0;
                mailStartTime = currentTime;
                System.out.println("All is quiet...");
                recording = false;
                timeInterval = 0;
                Process p;
                String cmd = null;
                StringBuilder output = new StringBuilder();
                try {
                    cmd = "pgrep raspivid";
                    System.out.println(cmd);
                    p = Runtime.getRuntime().exec(cmd);
                    p.waitFor();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        output.append(line);
                    }
                    System.out.println("raspivid " + output.toString());
                    cmd = "kill " + output.toString().trim();
                    System.out.println(cmd);
                    p = Runtime.getRuntime().exec(cmd);
                    p.waitFor();
                } catch (IOException | InterruptedException ex) {
                    Logger.getLogger(MotionSensor.class.getName()).log(Level.SEVERE, null, ex);
                }

                led.low();
                System.out.println("recording ends");
            }
        });

        try {
            int count = 0;
            // keep program running until user aborts
            for (;;) {
                Thread.sleep(500);
                count++;
                if (count > 180) {
                    break;
                }
                currentTime = System.nanoTime();
                if (startTime < currentTime) {
                    timeInterval = currentTime - moduleStartTime;
                    timeInterval = timeInterval / 1000000000;
                    System.out.println(timeInterval);
                    if (canSendMail) {
                        waitingForMail = currentTime - mailStartTime;
                        waitingForMail = waitingForMail / 1000000000;

                        if (waitingForMail > 60) {
                            recording = false;
                            timeInterval = 0;
                            startTime = currentTime;
                            waitingForMail = 0;
                            canSendMail = false;
                            mailStartTime = 0;
                            System.out.println("mail sent");
                            try (BufferedWriter writer = new BufferedWriter(new FileWriter("timeStamp.txt"))) {
                                for (String time : timeStampList) {
                                    writer.append(time);
                                    writer.newLine();
                                }
                            }
                            String str = creatMp4File();
                            File files = new File("./" + str);
                            StringBuilder builder = new StringBuilder();
                            builder.append(str);
                            if (files.exists()) {
                                new Thread(() -> {
                                    sample.connect(String.valueOf(detectionCount), builder.toString(), "timeStamp.txt");
                                }).start();
                            } else {
                                new Thread(() -> {
                                    sample.connect(String.valueOf(detectionCount), videoFileName, "timeStamp.txt");
                                }).start();
                            }
                        }
                    }
                }
            }
            System.out.println("loop completed");
        } catch (final InterruptedException | IOException e) {
            System.out.println(e.getMessage());
        }
    }

    private String creatMp4File() throws IOException, InterruptedException {
        File files = new File("./");
        String cmd = "MP4Box";
        for (File file : files.listFiles()) {
            if (file.getName().endsWith("h264")) {
                System.out.println(file.getName());
                cmd += " -cat " + file.getName();
            }
        }
        String str = videoFileName;
        str = str.substring(0, str.lastIndexOf(".h264"));
        str = "new" + str + ".mp4";
        cmd += " -new " + str;
        System.out.println(cmd);
        Process p;
        p = Runtime.getRuntime().exec(cmd);
        p.waitFor();
        return str;
    }

    private void createFileName() {
        fileName = new StringBuilder();
        cal = GregorianCalendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        fileName.append(cal.get(Calendar.HOUR_OF_DAY));
        fileName.append("_");
        fileName.append(cal.get(Calendar.MINUTE));
        fileName.append("_");
        fileName.append(cal.get(Calendar.SECOND));
        fileName.append("_");
        fileName.append(cal.get(Calendar.MILLISECOND));
        fileName.append(".h264");
    }

    String calculateTime(long timeInMilliSec) {
        StringBuilder timeStamp = new StringBuilder();
        cal = GregorianCalendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        timeStamp.append(cal.get(Calendar.DAY_OF_MONTH));
        timeStamp.append("_");
        timeStamp.append(cal.get(Calendar.MONTH));
        timeStamp.append("_");
        timeStamp.append(cal.get(Calendar.YEAR));
        timeStamp.append("_");
        timeStamp.append(cal.get(Calendar.HOUR_OF_DAY));
        timeStamp.append("_");
        timeStamp.append(cal.get(Calendar.MINUTE));
        timeStamp.append("_");
        timeStamp.append(cal.get(Calendar.SECOND));
        timeStamp.append("_");
        timeStamp.append(cal.get(Calendar.MILLISECOND));
        return timeStamp.toString();
    }
}


text:
function Get-DbaDatabaseMasterKey {
    <#
.SYNOPSIS
Gets specified database master key

.DESCRIPTION
Gets specified database master key

.PARAMETER SqlInstance
The target SQL Server instance

.PARAMETER SqlCredential
Allows you to login to SQL Server using alternative credentials

.PARAMETER Database
Get master key from specific database

.PARAMETER ExcludeDatabase
The database(s) to exclude - this list is auto-populated from the server

.PARAMETER WhatIf
Shows what would happen if the command were to run. No actions are actually performed

.PARAMETER Confirm
Prompts you for confirmation before executing any changing operations within the command

.PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

.NOTES
Tags: Certificate, Databases

Website: https://dbatools.io
Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
License: MIT https://opensource.org/licenses/MIT

.EXAMPLE
Get-DbaDatabaseMasterKey -SqlInstance sql2016

Gets all master database keys

.EXAMPLE
Get-DbaDatabaseMasterKey -SqlInstance Server1 -Database db1

Gets the master key for the db1 database

#>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [Alias('Silent')]
        [switch]$EnableException
    )

    process {
        foreach ($instance in $SqlInstance) {
            try {
                Write-Message -Level Verbose -Message "Connecting to $instance"
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            }
            catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $databases = $server.Databases | Where-Object IsAccessible

            if ($Database) {
                $databases = $databases | Where-Object Name -In $Database
            }
            if ($ExcludeDatabase) {
                $databases = $databases | Where-Object Name -NotIn $ExcludeDatabase
            }

            foreach ($db in $databases) {
                if (!$db.IsAccessible) {
                    Write-Message -Level Warning -Message "Database $db is not accessible. Skipping."
                    continue
                }

                $masterkey = $db.MasterKey

                if (!$masterkey) {
                    Write-Message -Message "No master key exists in the $db database on $instance" -Target $db -Level Verbose
                    continue
                }

                Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name ComputerName -value $server.NetName
                Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name InstanceName -value $server.ServiceName
                Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName
                Add-Member -Force -InputObject $masterkey -MemberType NoteProperty -Name Database -value $db.Name

                Select-DefaultView -InputObject $masterkey -Property ComputerName, InstanceName, SqlInstance, Database, CreateDate, DateLastModified, IsEncryptedByServer
            }
        }
    }
}


text:
The Base WiFi Command
=====================

A base module to query the device for interface information.

The Base WiFi Command
---------------------

.. uml::

   BaseClass <|-- BaseWifiCommand

.. module:: apetools.commands.basewificommand
.. autosummary::
   :toctree: api

   BaseWifiCommand
   BaseWifiCommand.operating_system
   BaseWifiCommand.interface
   BaseWifiCommand.rssi
   BaseWifiCommand.bitrate
   BaseWifiCommand.mac_address


text:
package org.apache.maven.artifact.resolver;

import java.util.List;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;

/**
 * @author Jason van Zyl
 */
public class ArtifactResolutionException extends AbstractArtifactResolutionException {
    @SuppressWarnings("checkstyle:parameternumber")
    public ArtifactResolutionException(
            String message,
            String groupId,
            String artifactId,
            String version,
            String type,
            String classifier,
            List<ArtifactRepository> remoteRepositories,
            List<String> path,
            Throwable t) {
        super(message, groupId, artifactId, version, type, classifier, remoteRepositories, path, t);
    }

    public ArtifactResolutionException(
            String message,
            String groupId,
            String artifactId,
            String version,
            String type,
            String classifier,
            Throwable t) {
        super(message, groupId, artifactId, version, type, classifier, null, null, t);
    }

    public ArtifactResolutionException(String message, Artifact artifact) {
        super(message, artifact);
    }

    public ArtifactResolutionException(String message, Artifact artifact, List<ArtifactRepository> remoteRepositories) {
        super(message, artifact, remoteRepositories);
    }

    public ArtifactResolutionException(String message, Artifact artifact, Throwable cause) {
        super(message, artifact, null, cause);
    }

    public ArtifactResolutionException(
            String message, Artifact artifact, List<ArtifactRepository> remoteRepositories, Throwable cause) {
        super(message, artifact, remoteRepositories, cause);
    }
}


text:
<!DOCTYPE html>

    <title>Protocols  Reference</title>
    <link rel="stylesheet" type="text/css" href="css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="css/highlight.css" />
    <meta charset='utf-8'>

HydraKit Docs (52% documented)

        HydraKit Reference

        Protocols  Reference

            Classes

                Hydra

                – Result

            Protocols

                HydraObject

                URLSessionProtocol

Protocols

The following protocols are available globally.

                    HydraObject

Object passed to Hydra method must be conform to this protocol

                        See more

Declaration

Swift

public protocol HydraObject

                    URLSessionProtocol

Undocumented

                        See more

© 2017 Maxime. All rights reserved. (Last updated: 2017-06-28)

Generated by jazzy ♪♫ v0.8.2, a Realm project.