text:
using namespace json_spirit;
using namespace std;

extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
extern enum Checkpoints::CPMode CheckpointsMode;
extern void spj(const CScript& scriptPubKey, Object& out, bool fIncludeHex);

double BitsToDouble(unsigned int nBits)
{
    // Floating point number that is a multiple of the minimum difficulty,
    // minimum difficulty = 1.0.
    int nShift = (nBits >> 24) & 0xff;

    double dDiff = (double)0x0000ffff / (double)(nBits & 0x00ffffff);

    while (nShift < 29)
    {
        dDiff *= 256.0;
        nShift++;
    };

    while (nShift > 29)
    {
        dDiff /= 256.0;
        nShift--;
    };

    return dDiff;
};

double GetDifficulty(const CBlockIndex* blockindex)
{
    if (blockindex == NULL)
    {
        if (pindexBest == NULL)
            return 1.0;
        else
            blockindex = GetLastBlockIndex(pindexBest, false);
    };

    return BitsToDouble(blockindex->nBits);
}

double GetPoWMHashPS()
{
    int nPoWInterval = 72;
    int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;

    CBlockIndex* pindex = pindexGenesisBlock;
    CBlockIndex* pindexPrevWork = pindexGenesisBlock;

    while (pindex)
    {
        if (pindex->IsProofOfWork())
        {
            int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
            nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
            nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
            pindexPrevWork = pindex;
        }

        pindex = pindex->pnext;
    }

    return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}

double GetPoSKernelPS()
{
    int nPoSInterval = 72;
    double dStakeKernelsTriedAvg = 0;
    int nStakesHandled = 0, nStakesTime = 0;

    CBlockIndex* pindex = pindexBest;;
    CBlockIndex* pindexPrevStake = NULL;

    while (pindex && nStakesHandled < nPoSInterval)
    {
        if (pindex->IsProofOfStake())
        {
            dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0;
            nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
            pindexPrevStake = pindex;
            nStakesHandled++;
        };

        pindex = pindex->pprev;
    };

    return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0;
}

Object blockHeader2ToJSON(const CBlock& block, const CBlockIndex* blockindex)
{
    Object result;
    result.push_back(Pair("version", block.nVersion));
    if (blockindex->pprev)
        result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
    result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
    result.push_back(Pair("time", block.GetBlockTime()));
    result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
    result.push_back(Pair("nonce", (uint64_t)block.nNonce));
    return result;
}

Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
    Object result;
    result.push_back(Pair("hash", block.GetHash().GetHex()));
    CMerkleTx txGen(block.vtx[0]);
    txGen.SetMerkleBranch(&block);
    result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
    result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
    result.push_back(Pair("height", blockindex->nHeight));
    result.push_back(Pair("version", block.nVersion));
    result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
    result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
    result.push_back(Pair("time", (int64_t)block.GetBlockTime()));
    result.push_back(Pair("nonce", (uint64_t)block.nNonce));
    result.push_back(Pair("bits", HexBits(block.nBits)));
    result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
    result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
    result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
    if (blockindex->pprev)
        result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
    if (blockindex->pnext)
        result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));

    result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
    result.push_back(Pair("proofhash", blockindex->hashProof.GetHex()));
    result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
    result.push_back(Pair("modifier", strprintf("%016" PRIx64, blockindex->nStakeModifier)));
    result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
    Array txinfo;
    for (const CTransaction& tx : block.vtx)
    {
        if (fPrintTransactionDetail)
        {
            Object entry;

            entry.push_back(Pair("txid", tx.GetHash().GetHex()));
            TxToJSON(tx, 0, entry);

            txinfo.push_back(entry);
        }
        else
            txinfo.push_back(tx.GetHash().GetHex());
    }

    result.push_back(Pair("tx", txinfo));

    if (block.IsProofOfStake())
        result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));

    return result;
}

Value dumpbootstrap(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 2)
        throw runtime_error(
            "dumpbootstrap \"destination\" \"blocks\"\n"
            "\nCreates a bootstrap format block dump of the blockchain in destination, which can be a directory or a path with filename, up to the given block number.");

    string strDest = params[0].get_str();
    int nBlocks = params[1].get_int();
    if (nBlocks < 0 || nBlocks > nBestHeight)
        throw runtime_error("Block number out of range.");

    boost::filesystem::path pathDest(strDest);
    if (boost::filesystem::is_directory(pathDest))
        pathDest /= "bootstrap.dat";

    try {
        FILE* file = fopen(pathDest.string().c_str(), "wb");
        if (!file)
            throw JSONRPCError(RPC_MISC_ERROR, "Error: Could not open bootstrap file for writing.");

        CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
        if (!fileout)
            throw JSONRPCError(RPC_MISC_ERROR, "Error: Could not open bootstrap file for writing.");

        for (int nHeight = 0; nHeight <= nBlocks; nHeight++)
        {
            CBlock block;
            CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
            block.ReadFromDisk(pblockindex, true);
            fileout << FLATDATA(pchMessageStart) << fileout.GetSerializeSize(block) << block;
        }
    } catch(const boost::filesystem::filesystem_error &e) {
        throw JSONRPCError(RPC_MISC_ERROR, "Error: Bootstrap dump failed!");
    }

    return Value::null;
}

Value proofofdata(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1)
    throw runtime_error(
        "proofofdata\n"
        "\nArguments:\n"
        "1. \"filelocation\"          (string, required) The file location of the file to upload (e.g. /home/name/file.jpg)\n"
        "Returns the Denarius address and transaction ID of the proof of data submission of the file hashed into a D address");

    Object obj;
    std::string userFile = params[0].get_str();
    std::ifstream dataFile;

    if(userFile == "")
    {
        return 0; //return with no value prev
    }

    std::string filename = userFile.c_str();

    boost::filesystem::path p(filename);
    std::string basename = p.filename().string();

    dataFile.open(userFile.c_str(), std::ios::binary);
    std::vector<char> dataContents((std::istreambuf_iterator<char>(dataFile)), std::istreambuf_iterator<char>());

    printf("POD Upload File Start: %s\n", basename.c_str());

    //Hash the file for Denarius POD
    uint256 datahash = SerializeHash(dataContents);
    CKeyID keyid(Hash160(datahash.begin(), datahash.end()));
    CBitcoinAddress baddr = CBitcoinAddress(keyid);
    std::string addr = baddr.ToString();

    CAmount nAmount = 0.001 * COIN; // 0.001 D Fee

    // Wallet comments
    CWalletTx wtx;
    wtx.mapValue["comment"] = basename.c_str();
    std::string sNarr = "POD";
    wtx.mapValue["to"]      = "Proof of Data";

    // Comment
    // CWalletTx wtx;
    // CScript podScript = CScript() << OP_RETURN; //CScript()
    // if (!basename.c_str().empty()) {
    //     if (basename.c_str().length() > MAX_OP_RETURN_RELAY - 3) //Max 45 Bytes
    //         throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Comment cannot be longer than %u characters", MAX_OP_RETURN_RELAY - 3));
    //     podScript << ToByteVector("POD: " + basename.c_str());
    // }

    if (pwalletMain->IsLocked())
    {
        obj.push_back(Pair("error",  "Error, Your wallet is locked! Please unlock your wallet!"));
        //ui->txLineEdit->setText("ERROR: Your wallet is locked! Cannot send POD. Unlock your wallet!");
    } else if (pwalletMain->GetBalance() < 0.001) {
        obj.push_back(Pair("error",  "Error, You need at least 0.001 D to send POD!"));
        //ui->txLineEdit->setText("ERROR: You need at least a 0.001 D balance to send POD.");
    } else {
        //std::string sNarr;
        std::string strError = pwalletMain->SendMoneyToDestination(baddr.Get(), nAmount, sNarr, wtx);

        if(strError != "")
        {
            obj.push_back(Pair("error",  strError.c_str()));
        }

        obj.push_back(Pair("filename",           basename.c_str()));
        //obj.push_back(Pair("sizebytes",        size));
        obj.push_back(Pair("podaddress",         addr.c_str()));
        obj.push_back(Pair("podtxid",            wtx.GetHash().GetHex()));
    }

    return obj;

}

Value getbestblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getbestblockhash\n"
            "Returns the hash of the best block in the longest block chain.");

    return hashBestChain.GetHex();
}

Value getblockcount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getblockcount\n"
            "Returns the number of blocks in the longest block chain.");

    return nBestHeight;
}

Value getdifficulty(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getdifficulty\n"
            "Returns the difficulty as a multiple of the minimum difficulty.");

    Object obj;
    obj.push_back(Pair("proof-of-work",        GetDifficulty()));
    obj.push_back(Pair("proof-of-stake",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));
    obj.push_back(Pair("search-interval",      (int)nLastCoinStakeSearchInterval));
    return obj;
}

Value settxfee(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
        throw runtime_error(
            "settxfee <amount>\n"
            "<amount> is a real and is rounded to the nearest 0.01");

    nTransactionFee = AmountFromValue(params[0]);
    nTransactionFee = (nTransactionFee / CENT) * CENT;  // round to cent

    return true;
}

Value getrawmempool(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getrawmempool\n"
            "Returns all transaction ids in memory pool.");

    vector<uint256> vtxid;
    mempool.queryHashes(vtxid);

    Array a;
    for (const uint256& hash : vtxid)
        a.push_back(hash.ToString());

    return a;
}

Value getblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getblockhash <index>\n"
            "Returns hash of block in best-block-chain at <index>.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
    return pblockindex->phashBlock->GetHex();
}

//New getblock RPC Command for Denariium Compatibility
Value getblock(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock \"blockhash\" ( verbosity ) \n"
            "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
            "If verbosity is 1, returns an Object with information about block <hash>.\n"
            "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n"
            "\nArguments:\n"
            "1. \"blockhash\"          (string, required) The block hash\n"
            "2. verbosity              (numeric, optional, default=1) 0 for hex encoded data, 1 for a json object, and 2 for json object with transaction data\n"
            "\nResult (for verbosity = 0):\n"
            "\"data\"             (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
            "\nResult (for verbosity = 1):\n"
            "{\n"
            "  \"hash\" : \"hash\",     (string) the block hash (same as provided)\n"
            "  \"confirmations\" : n,   (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
            "  \"size\" : n,            (numeric) The block size\n"
            "  \"strippedsize\" : n,    (numeric) The block size excluding witness data\n"
            "  \"weight\" : n           (numeric) The block weight as defined in BIP 141\n"
            "  \"height\" : n,          (numeric) The block height or index\n"
            "  \"version\" : n,         (numeric) The block version\n"
            "  \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
            "  \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
            "  \"tx\" : [               (array of string) The transaction ids\n"
            "     \"transactionid\"     (string) The transaction id\n"
            "     ,...\n"
            "  ],\n"
            "  \"time\" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
            "  \"mediantime\" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
            "  \"nonce\" : n,           (numeric) The nonce\n"
            "  \"bits\" : \"1d00ffff\", (string) The bits\n"
            "  \"difficulty\" : x.xxx,  (numeric) The difficulty\n"
            "  \"previousblockhash\" : \"hash\",  (string) The hash of the previous block\n"
            "  \"nextblockhash\" : \"hash\"       (string) The hash of the next block\n"
            "}\n"
            "\nResult (for verbosity = 2):\n"
            "{\n"
            "  ...,                     Same output as verbosity = 1.\n"
            "  \"tx\" : [               (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
            "         ,...\n"
            "  ],\n"
            "  ,...                     Same output as verbosity = 1.\n"
            "}\n"
            "\nExamples:\n"
        );

    LOCK(cs_main);

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);
    //std::string strHash = params[0].get_str();
	//uint256 hash(uint256S(strHash));

    int verbosity = 1;
    if (params.size() > 1) {
            verbosity = params[1].get_bool() ? 1 : 0;
    }

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];

	if(!block.ReadFromDisk(pblockindex, true)){
        // Block not found on disk. This could be because we have the block
        // header in our index but don't have the block (for example if a
        // non-whitelisted node sends us an unrequested long chain of valid
        // blocks, we add the headers to our index, but don't accept the
        // block).
		throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
	}

	block.ReadFromDisk(pblockindex, true);

    if (verbosity <= 0)
    {
        CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
        ssBlock << block;
        std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
		//strHex.insert(0, "testar ");
        return strHex;
    }

    //return blockToJSON(block, pblockindex, verbosity >= 2);
	return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

Value getblockheader(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblockheader \"hash\" ( verbose )\n"
            "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash' header.\n"
            "If verbose is true, returns an Object with information about block <hash> header.\n"
            "\nArguments:\n"
            "1. \"hash\"          (string, required) The block hash\n"
            "2. verbose           (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
            "\nResult (for verbose = true):\n"
            "{\n"
            "  \"version\" : n,         (numeric) The block version\n"
            "  \"previousblockhash\" : \"hash\",  (string) The hash of the previous block\n"
            "  \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
            "  \"time\" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
            "  \"bits\" : \"1d00ffff\", (string) The bits\n"
            "  \"nonce\" : n,           (numeric) The nonce\n"
            "}\n"
            "\nResult (for verbose=false):\n"
            "\"data\"             (string) A string that is serialized, hex-encoded data for block 'hash' header.\n"
            "\nExamples:\n"
            );

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);

    bool fVerbose = true;
    if (params.size() > 1)
        fVerbose = params[1].get_bool();

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];

	if(!block.ReadFromDisk(pblockindex, true)){
        // Block not found on disk. This could be because we have the block
        // header in our index but don't have the block (for example if a
        // non-whitelisted node sends us an unrequested long chain of valid
        // blocks, we add the headers to our index, but don't accept the
        // block).
		throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
	}

	block.ReadFromDisk(pblockindex, true);

    if (!fVerbose) {
        CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
        ssBlock << block;
        std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
        return strHex;
    }

    return blockHeader2ToJSON(block, pblockindex);
}

//Old getblock RPC Command, Not deprecated
Value getblock_old(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock <hash> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-hash.");

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

Value getblockbynumber(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblockbynumber <number> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-number.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;

    uint256 hash = *pblockindex->phashBlock;

    pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

Value setbestblockbyheight(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "setbestblockbyheight <height>\n"
            "Sets the tip of the chain with a block at <height>.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block height out of range.");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;

    uint256 hash = *pblockindex->phashBlock;

    pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    Object result;

    CTxDB txdb;
    {
        LOCK(cs_main);

        if (!block.SetBestChain(txdb, pblockindex))
            result.push_back(Pair("result", "failure"));
        else
            result.push_back(Pair("result", "success"));

    };

    return result;
}

// ppcoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getcheckpoint\n"
            "Show info of synchronized checkpoint.\n");

    Object result;
    CBlockIndex* pindexCheckpoint;

    result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
    pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
    result.push_back(Pair("height", pindexCheckpoint->nHeight));
    result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));

    // Check that the block satisfies synchronized checkpoint
    if (CheckpointsMode == Checkpoints::STRICT)
        result.push_back(Pair("policy", "strict"));

    if (CheckpointsMode == Checkpoints::ADVISORY)
        result.push_back(Pair("policy", "advisory"));

    if (CheckpointsMode == Checkpoints::PERMISSIVE)
        result.push_back(Pair("policy", "permissive"));

    if (mapArgs.count("-checkpointkey"))
        result.push_back(Pair("checkpointmaster", true));

    return result;
}

Value gettxout(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 2 || params.size() > 3)
        throw runtime_error(
            "gettxout \"txid\" n ( includemempool )\n"
            "\nReturns details about an unspent transaction output.\n"
            "\nArguments:\n"
            "1. \"txid\"       (string, required) The transaction id\n"
            "2. n              (numeric, required) vout value\n"
            "3. includemempool  (boolean, optional) Whether to included the mem pool\n"
            "\nResult:\n"
            "{\n"
            "  \"bestblock\" : \"hash\",    (string) the block hash\n"
            "  \"confirmations\" : n,       (numeric) The number of confirmations\n"
            "  \"value\" : x.xxx,           (numeric) The transaction value in btc\n"
            "  \"scriptPubKey\" : {         (json object)\n"
            "     \"asm\" : \"code\",       (string) \n"
            "     \"hex\" : \"hex\",        (string) \n"
            "     \"reqSigs\" : n,          (numeric) Number of required signatures\n"
            "     \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
            "     \"addresses\" : [          (array of string) array of bitcoin addresses\n"
            "        \"bitcoinaddress\"     (string) bitcoin address\n"
            "        ,...\n"
            "     ]\n"
            "  },\n"
            "  \"version\" : n,            (numeric) The version\n"
            "  \"coinbase\" : true|false   (boolean) Coinbase or not\n"
            "  \"coinstake\" : true|false  (boolean) Coinstake or not\n"
            "}\n"
        );

    LOCK(cs_main);

    Object ret;

    uint256 hash;
    hash.SetHex(params[0].get_str());
    int n = params[1].get_int();
    bool mem = true;
    if (params.size() == 3)
        mem = params[2].get_bool();

    CTransaction tx;
    uint256 hashBlock = 0;
    if (!GetTransaction(hash, tx, hashBlock, mem))
      return Value::null;

    if (n<0 || (unsigned int)n>=tx.vout.size() || tx.vout[n].IsNull())
      return Value::null;

    ret.push_back(Pair("bestblock", pindexBest->GetBlockHash().GetHex()));
    if (hashBlock == 0)
      ret.push_back(Pair("confirmations", 0));
    else
    {
      map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
      if (mi != mapBlockIndex.end() && (*mi).second)
      {
        CBlockIndex* pindex = (*mi).second;
        if (pindex->IsInMainChain())
        {
          bool isSpent=false;
          CBlockIndex* p = pindex;
          p=p->pnext;
          for (; p; p = p->pnext)
          {
            CBlock block;
            CBlockIndex* pblockindex = mapBlockIndex[p->GetBlockHash()];
            block.ReadFromDisk(pblockindex, true);
            for (const CTransaction& tx : block.vtx)
            {
              for (const CTxIn& txin : tx.vin)
              {
                if( hash == txin.prevout.hash &&
                   (int64_t)txin.prevout.n )
                {
                  printf("spent at block %s\n", block.GetHash().GetHex().c_str());
                  isSpent=true; break;
                }
              }

              if(isSpent) break;
            }

            if(isSpent) break;
          }

          if(isSpent)
            return Value::null;

          ret.push_back(Pair("confirmations", pindexBest->nHeight - pindex->nHeight + 1));
        }
        else
          return Value::null;
      }
    }

    ret.push_back(Pair("value", ValueFromAmount(tx.vout[n].nValue)));
    Object o;
    spj(tx.vout[n].scriptPubKey, o, true);
    ret.push_back(Pair("scriptPubKey", o));
    ret.push_back(Pair("coinbase", tx.IsCoinBase()));
    ret.push_back(Pair("coinstake", tx.IsCoinStake()));

    return ret;
}

Value getblockchaininfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
                "getblockchaininfo\n"
                "Returns an object containing various state info regarding block chain processing.\n"
                "\nResult:\n"
                "{\n"
                "  \"chain\": \"xxxx\",        (string) current chain (main, testnet)\n"
                "  \"blocks\": xxxxxx,         (numeric) the current number of blocks processed in the server\n"
                "  \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
                "  \"difficulty\": xxxxxx,     (numeric) the current difficulty\n"
                "  \"initialblockdownload\": xxxx, (bool) estimate of whether this D node is in Initial Block Download mode.\n"
                "  \"moneysupply\": xxxx, (numeric) the current supply of D in circulation\n"
                "}\n"
        );

    proxyType proxy;
    GetProxy(NET_IPV4, proxy);

    Object obj, diff;
    std::string chain = "testnet";
    if(!fTestNet)
        chain = "main";
    obj.push_back(Pair("chain",          chain));
    obj.push_back(Pair("blocks",         (int)nBestHeight));
    obj.push_back(Pair("bestblockhash",  hashBestChain.GetHex()));

    diff.push_back(Pair("proof-of-work",  GetDifficulty()));
    diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));

    obj.push_back(Pair("difficulty",     diff));
    obj.push_back(Pair("initialblockdownload",  IsInitialBlockDownload()));
    obj.push_back(Pair("moneysupply",   ValueFromAmount(pindexBest->nMoneySupply)));
    //obj.push_back(Pair("size_on_disk",   CalculateCurrentUsage()));
    return obj;
}


text:
<component name="libraryTable">
  <library name="Gradle: org.springframework.boot:spring-boot-starter-json:2.0.2.RELEASE">
    <CLASSES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-json/2.0.2.RELEASE/5edda979838ced5314b8f58a958fe9d6b4b3badd/spring-boot-starter-json-2.0.2.RELEASE.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-json/2.0.2.RELEASE/b8ef1a1c75874d84844e0dc319ca8285412a821f/spring-boot-starter-json-2.0.2.RELEASE-sources.jar!/" />
    </SOURCES>
  </library>
</component>

redpajama_set_name: RedPajamaGithub


text:
module Ramsey
  module Utility
    module BTree
      Kindah.class_template! :Leaf, location: self do
        class_methods do |order|
          def inspect
            "Leaf<#{order}>"
          end
        end

        instance_methods do
          extend Forwardable
          def initialize(children = Ramsey::Utility::SortedFiniteVector(2*order - 1).new)
            @children = children
          end
          attr_reader :children

          def leaf?
            true
          end

          delegate [:full?] => :children

          # returns a thing to replace in the tree
          def insert(datum)
            return split.insert(datum) if full?
            children << datum
            return self
          end

          def search(key)
            return unless idx = children.find_index { |c| c.key == key }
            children[idx].value
          end

          def split
            #left, median, right = @children.split_at_median

            #left_vector = Ramsey::Utility::BTree::Leaf(order).new(left + median)
            #right_vector = Ramsey::Utility::BTree::Leaf(order).new(right)
            #median_key = median.key

            Ramsey::Utility::BTree::InternalNode(order).new
          end

          def inspect
            "Leaf<#{order}> |#{children}|"
          end
          alias to_s inspect
        end
      end
    end
  end
end


text:
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.

#include "stdafx.h"
#include "occimpl.h"

#define new DEBUG_NEW

/////////////////////////////////////////////////////////////////////////////
// CCmdTarget construction/destruction

CCmdTarget::CCmdTarget()
{
	// capture module state where object was constructed
	m_pModuleState = AfxGetModuleState();
	ASSERT(m_pModuleState != NULL);

	// initialize state
#ifndef _AFX_NO_OLE_SUPPORT
	m_dwRef = 1;
	m_pOuterUnknown = NULL;
	m_xInnerUnknown = 0;
	m_xDispatch.m_vtbl = 0;
	m_bResultExpected = TRUE;
	m_xConnPtContainer.m_vtbl = 0;
#endif
}

CCmdTarget::~CCmdTarget()
{
#ifndef _AFX_NO_OLE_SUPPORT
	if (m_xDispatch.m_vtbl != 0)
		((COleDispatchImpl*)&m_xDispatch)->Disconnect();
	ASSERT(m_dwRef <= 1);
#endif
	m_pModuleState = NULL;
}

/////////////////////////////////////////////////////////////////////////////
// CCmdTarget windows message dispatching

AFX_STATIC BOOL AFXAPI _AfxDispatchCmdMsg(CCmdTarget* pTarget, UINT nID, int nCode,
	AFX_PMSG pfn, void* pExtra, UINT_PTR nSig, AFX_CMDHANDLERINFO* pHandlerInfo)
		// return TRUE to stop routing
{
	ENSURE_VALID(pTarget);
	UNUSED(nCode);   // unused in release builds

	union MessageMapFunctions mmf;
	mmf.pfn = pfn;
	BOOL bResult = TRUE; // default is ok

	if (pHandlerInfo != NULL)
	{
		// just fill in the information, don't do it
		pHandlerInfo->pTarget = pTarget;
		pHandlerInfo->pmf = mmf.pfn;
		return TRUE;
	}

	switch (nSig)
	{
	default:    // illegal
		ASSERT(FALSE);
		return 0;
		break;

	case AfxSigCmd_v:
		// normal command or control notification
		ASSERT(CN_COMMAND == 0);        // CN_COMMAND same as BN_CLICKED
		ASSERT(pExtra == NULL);
		(pTarget->*mmf.pfnCmd_v_v)();
		break;

	case AfxSigCmd_b:
		// normal command or control notification
		ASSERT(CN_COMMAND == 0);        // CN_COMMAND same as BN_CLICKED
		ASSERT(pExtra == NULL);
		bResult = (pTarget->*mmf.pfnCmd_b_v)();
		break;

	case AfxSigCmd_RANGE:
		// normal command or control notification in a range
		ASSERT(CN_COMMAND == 0);        // CN_COMMAND same as BN_CLICKED
		ASSERT(pExtra == NULL);
		(pTarget->*mmf.pfnCmd_v_u)(nID);
		break;

	case AfxSigCmd_EX:
		// extended command (passed ID, returns bContinue)
		ASSERT(pExtra == NULL);
		bResult = (pTarget->*mmf.pfnCmd_b_u)(nID);
		break;

	case AfxSigNotify_v:
		{
			AFX_NOTIFY* pNotify = (AFX_NOTIFY*)pExtra;
			ENSURE(pNotify != NULL);
			ASSERT(pNotify->pResult != NULL);
			ASSERT(pNotify->pNMHDR != NULL);
			(pTarget->*mmf.pfnNotify_v_NMHDR_pl)(pNotify->pNMHDR, pNotify->pResult);
		}
		break;

	case AfxSigNotify_b:
		{
			AFX_NOTIFY* pNotify = (AFX_NOTIFY*)pExtra;
			ENSURE(pNotify != NULL);
			ASSERT(pNotify->pResult != NULL);
			ASSERT(pNotify->pNMHDR != NULL);
			bResult = (pTarget->*mmf.pfnNotify_b_NMHDR_pl)(pNotify->pNMHDR, pNotify->pResult);
		}
		break;

	case AfxSigNotify_RANGE:
		{
			AFX_NOTIFY* pNotify = (AFX_NOTIFY*)pExtra;
			ENSURE(pNotify != NULL);
			ASSERT(pNotify->pResult != NULL);
			ASSERT(pNotify->pNMHDR != NULL);
			(pTarget->*mmf.pfnNotify_v_u_NMHDR_pl)(nID, pNotify->pNMHDR,
				pNotify->pResult);
		}
		break;

	case AfxSigNotify_EX:
		{
			AFX_NOTIFY* pNotify = (AFX_NOTIFY*)pExtra;
			ENSURE(pNotify != NULL);
			ASSERT(pNotify->pResult != NULL);
			ASSERT(pNotify->pNMHDR != NULL);
			bResult = (pTarget->*mmf.pfnNotify_b_u_NMHDR_pl)(nID, pNotify->pNMHDR,
				pNotify->pResult);
		}
		break;

	case AfxSigCmdUI:
		{
			// ON_UPDATE_COMMAND_UI or ON_UPDATE_COMMAND_UI_REFLECT case
			ASSERT(CN_UPDATE_COMMAND_UI == (UINT)-1);
			ASSERT(nCode == CN_UPDATE_COMMAND_UI || nCode == 0xFFFF);
			ENSURE_ARG(pExtra != NULL);
			CCmdUI* pCmdUI = (CCmdUI*)pExtra;
			ASSERT(!pCmdUI->m_bContinueRouting);    // idle - not set
			(pTarget->*mmf.pfnCmdUI_v_C)(pCmdUI);
			bResult = !pCmdUI->m_bContinueRouting;
			pCmdUI->m_bContinueRouting = FALSE;     // go back to idle
		}
		break;

	case AfxSigCmdUI_RANGE:
		{
			// ON_UPDATE_COMMAND_UI case
			ASSERT(nCode == CN_UPDATE_COMMAND_UI);
			ENSURE_ARG(pExtra != NULL);
			CCmdUI* pCmdUI = (CCmdUI*)pExtra;
			ASSERT(pCmdUI->m_nID == nID);           // sanity assert
			ASSERT(!pCmdUI->m_bContinueRouting);    // idle - not set
			(pTarget->*mmf.pfnCmdUI_v_C_u)(pCmdUI, nID);
			bResult = !pCmdUI->m_bContinueRouting;
			pCmdUI->m_bContinueRouting = FALSE;     // go back to idle
		}
		break;

	// general extensibility hooks
	case AfxSigCmd_v_pv:
		(pTarget->*mmf.pfnCmd_v_pv)(pExtra);
		break;
	case AfxSigCmd_b_pv:
		bResult = (pTarget->*mmf.pfnCmd_b_pv)(pExtra);
		break;
	/*
	case AfxSig_vv:
		// normal command or control notification
		ASSERT(CN_COMMAND == 0);        // CN_COMMAND same as BN_CLICKED
		ASSERT(pExtra == NULL);
		(pTarget->*mmf.pfn_COMMAND)();
		break;

	case AfxSig_bv:
		// normal command or control notification
		ASSERT(CN_COMMAND == 0);        // CN_COMMAND same as BN_CLICKED
		ASSERT(pExtra == NULL);
		bResult = (pTarget->*mmf.pfn_bCOMMAND)();
		break;

	case AfxSig_vw:
		// normal command or control notification in a range
		ASSERT(CN_COMMAND == 0);        // CN_COMMAND same as BN_CLICKED
		ASSERT(pExtra == NULL);
		(pTarget->*mmf.pfn_COMMAND_RANGE)(nID);
		break;

	case AfxSig_bw:
		// extended command (passed ID, returns bContinue)
		ASSERT(pExtra == NULL);
		bResult = (pTarget->*mmf.pfn_COMMAND_EX)(nID);
		break;

	case AfxSig_vNMHDRpl:
		{
			AFX_NOTIFY* pNotify = (AFX_NOTIFY*)pExtra;
			ENSURE(pNotify != NULL);
			ASSERT(pNotify->pResult != NULL);
			ASSERT(pNotify->pNMHDR != NULL);
			(pTarget->*mmf.pfn_NOTIFY)(pNotify->pNMHDR, pNotify->pResult);
		}
		break;
	case AfxSig_bNMHDRpl:
		{
			AFX_NOTIFY* pNotify = (AFX_NOTIFY*)pExtra;
			ENSURE(pNotify != NULL);
			ASSERT(pNotify->pResult != NULL);
			ASSERT(pNotify->pNMHDR != NULL);
			bResult = (pTarget->*mmf.pfn_bNOTIFY)(pNotify->pNMHDR, pNotify->pResult);
		}
		break;
	case AfxSig_vwNMHDRpl:
		{
			AFX_NOTIFY* pNotify = (AFX_NOTIFY*)pExtra;
			ENSURE(pNotify != NULL);
			ASSERT(pNotify->pResult != NULL);
			ASSERT(pNotify->pNMHDR != NULL);
			(pTarget->*mmf.pfn_NOTIFY_RANGE)(nID, pNotify->pNMHDR,
				pNotify->pResult);
		}
		break;
	case AfxSig_bwNMHDRpl:
		{
			AFX_NOTIFY* pNotify = (AFX_NOTIFY*)pExtra;
			ENSURE(pNotify != NULL);
			ASSERT(pNotify->pResult != NULL);
			ASSERT(pNotify->pNMHDR != NULL);
			bResult = (pTarget->*mmf.pfn_NOTIFY_EX)(nID, pNotify->pNMHDR,
				pNotify->pResult);
		}
		break;
	case AfxSig_cmdui:
		{
			// ON_UPDATE_COMMAND_UI or ON_UPDATE_COMMAND_UI_REFLECT case
			ASSERT(CN_UPDATE_COMMAND_UI == (UINT)-1);
			ASSERT(nCode == CN_UPDATE_COMMAND_UI || nCode == 0xFFFF);
			ENSURE_ARG(pExtra != NULL);
			CCmdUI* pCmdUI = (CCmdUI*)pExtra;
			ASSERT(!pCmdUI->m_bContinueRouting);    // idle - not set
			(pTarget->*mmf.pfn_UPDATE_COMMAND_UI)(pCmdUI);
			bResult = !pCmdUI->m_bContinueRouting;
			pCmdUI->m_bContinueRouting = FALSE;     // go back to idle
		}
		break;

	case AfxSig_cmduiw:
		{
			// ON_UPDATE_COMMAND_UI case
			ASSERT(nCode == CN_UPDATE_COMMAND_UI);
			ENSURE_ARG(pExtra != NULL);
			CCmdUI* pCmdUI = (CCmdUI*)pExtra;
			ASSERT(pCmdUI->m_nID == nID);           // sanity assert
			ASSERT(!pCmdUI->m_bContinueRouting);    // idle - not set
			(pTarget->*mmf.pfn_UPDATE_COMMAND_UI_RANGE)(pCmdUI, nID);
			bResult = !pCmdUI->m_bContinueRouting;
			pCmdUI->m_bContinueRouting = FALSE;     // go back to idle
		}
		break;

	// general extensibility hooks
	case AfxSig_vpv:
		(pTarget->*mmf.pfn_OTHER)(pExtra);
		break;
	case AfxSig_bpv:
		bResult = (pTarget->*mmf.pfn_OTHER_EX)(pExtra);
		break;
	*/

	}
	return bResult;
}

// compare two pointers to GUIDs -- TRUE if both pointers are NULL
// or both pointers point to same GUID; FALSE otherwise

#define IsEqualNULLGuid(pGuid1, pGuid2) \
	(((pGuid1) == NULL && (pGuid2) == NULL) || \
	 ((pGuid1) != NULL && (pGuid2) != NULL && \
		IsEqualGUID(*(pGuid1), *(pGuid2))))

BOOL CCmdTarget::OnCmdMsg(UINT nID, int nCode, void* pExtra,
	AFX_CMDHANDLERINFO* pHandlerInfo)
{
#ifndef _AFX_NO_OCC_SUPPORT
	// OLE control events are a special case
	if (nCode == CN_EVENT)
	{
		ENSURE(afxOccManager != NULL);
		return afxOccManager->OnEvent(this, nID, (AFX_EVENT*)pExtra, pHandlerInfo);
	}
#endif // !_AFX_NO_OCC_SUPPORT

	// determine the message number and code (packed into nCode)
	const AFX_MSGMAP* pMessageMap;
	const AFX_MSGMAP_ENTRY* lpEntry;
	UINT nMsg = 0;

#ifndef _AFX_NO_DOCOBJECT_SUPPORT
	if (nCode == CN_OLECOMMAND)
	{
		BOOL bResult = FALSE;

		const AFX_OLECMDMAP* pOleCommandMap;
		const AFX_OLECMDMAP_ENTRY* pEntry;

		ENSURE_ARG(pExtra != NULL);
		COleCmdUI* pUI = (COleCmdUI*) pExtra;
		const GUID* pguidCmdGroup = pUI->m_pguidCmdGroup;

#ifdef _AFXDLL
		for (pOleCommandMap = GetCommandMap(); pOleCommandMap->pfnGetBaseMap != NULL && !bResult;
			pOleCommandMap = pOleCommandMap->pfnGetBaseMap())
#else
		for (pOleCommandMap = GetCommandMap(); pOleCommandMap != NULL && !bResult;
			pOleCommandMap = pOleCommandMap->pBaseMap)
#endif
		{
			for (pEntry = pOleCommandMap->lpEntries;
				pEntry->cmdID != 0 && pEntry->nID != 0 && !bResult;
				pEntry++)
			{
				if (nID == pEntry->cmdID &&
					IsEqualNULLGuid(pguidCmdGroup, pEntry->pguid))
				{
					pUI->m_nID = pEntry->nID;
					bResult = TRUE;
				}
			}
		}

		return bResult;
	}
#endif

	if (nCode != CN_UPDATE_COMMAND_UI)
	{
		nMsg = HIWORD(nCode);
		nCode = LOWORD(nCode);
	}

	// for backward compatibility HIWORD(nCode)==0 is WM_COMMAND
	if (nMsg == 0)
		nMsg = WM_COMMAND;

	// look through message map to see if it applies to us

	for (pMessageMap = GetMessageMap(); pMessageMap->pfnGetBaseMap != NULL;
	  pMessageMap = (*pMessageMap->pfnGetBaseMap)())
	{
		// Note: catches BEGIN_MESSAGE_MAP(CMyClass, CMyClass)!
		ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)());
		lpEntry = AfxFindMessageEntry(pMessageMap->lpEntries, nMsg, nCode, nID);
		if (lpEntry != NULL)
		{
			// found it
#ifdef _DEBUG
			if (nCode == CN_COMMAND)
				TRACE(traceCmdRouting, 1, "SENDING command id 0x%04X to %hs target.\n", nID,
					GetRuntimeClass()->m_lpszClassName);
			else if (nCode > CN_COMMAND)
				TRACE(traceCmdRouting, 1, "SENDING control notification %d from control id 0x%04X to %hs window.\n",
					nCode, nID, GetRuntimeClass()->m_lpszClassName);
#endif //_DEBUG
			return _AfxDispatchCmdMsg(this, nID, nCode,
				lpEntry->pfn, pExtra, lpEntry->nSig, pHandlerInfo);
		}
	}
	return FALSE;   // not handled
}

/////////////////////////////////////////////////////////////////////////////
// Hook to disable automation handlers

#ifndef _AFX_NO_OLE_SUPPORT

BOOL CCmdTarget::IsInvokeAllowed(DISPID)
{
	return TRUE;    // normally, invoke is always allowed
}

#endif // !_AFX_NO_OLE_SUPPORT

/////////////////////////////////////////////////////////////////////////////
// Stubs for OLE type library functions

#ifndef _AFX_NO_OLE_SUPPORT

BOOL CCmdTarget::GetDispatchIID(IID*)
{
	// Subclass must implement (typically via COleControl implementation)
	return FALSE;
}

UINT CCmdTarget::GetTypeInfoCount()
{
	// Subclass must implement (typically via IMPLEMENT_OLETYPELIB macro)
	return 0;
}

CTypeLibCache* CCmdTarget::GetTypeLibCache()
{
	// Subclass must implement (typically via IMPLEMENT_OLETYPELIB macro)
	return NULL;
}

HRESULT CCmdTarget::GetTypeLib(LCID, LPTYPELIB*)
{
	// Subclass must implement (typically via IMPLEMENT_OLETYPELIB macro)
	return TYPE_E_CANTLOADLIBRARY;
}

#endif // !_AFX_NO_OLE_SUPPORT

/////////////////////////////////////////////////////////////////////////////
// CCmdTarget routines that delegate to the WinApp

void CCmdTarget::BeginWaitCursor()
	{ AfxGetApp()->DoWaitCursor(1); }
void CCmdTarget::EndWaitCursor()
	{ AfxGetApp()->DoWaitCursor(-1); }
void CCmdTarget::RestoreWaitCursor()
	{ AfxGetApp()->DoWaitCursor(0); }

/////////////////////////////////////////////////////////////////////////////
// Root of message maps

const AFX_MSGMAP* CCmdTarget::GetMessageMap() const
{
	return GetThisMessageMap();
}

const AFX_MSGMAP* CCmdTarget::GetThisMessageMap()
{
	static const AFX_MSGMAP_ENTRY _messageEntries[] =
	{
		{ 0, 0, AfxSig_end, 0 }     // nothing here
	};
	static const AFX_MSGMAP messageMap =
	{
		NULL,
		&_messageEntries[0]
	};
	return &messageMap;
}

/////////////////////////////////////////////////////////////////////////////
// Root of dispatch maps

#ifndef _AFX_NO_OLE_SUPPORT

UINT CCmdTarget::_dispatchEntryCount = (UINT)-1;
DWORD CCmdTarget::_dwStockPropMask = (DWORD)-1;

const AFX_DISPMAP CCmdTarget::dispatchMap =
{
	NULL,
	&CCmdTarget::_dispatchEntries[0],
	&CCmdTarget::_dispatchEntryCount,
	&CCmdTarget::_dwStockPropMask
};

const AFX_DISPMAP* CCmdTarget::GetDispatchMap() const
{
	return &CCmdTarget::dispatchMap;
}

#ifdef _AFXDLL
const AFX_DISPMAP* CCmdTarget::GetThisDispatchMap()
{
	return &CCmdTarget::dispatchMap;
}
#endif

const AFX_DISPMAP_ENTRY CCmdTarget::_dispatchEntries[] =
{
	{ NULL, -1, NULL, 0, (AFX_PMSG)NULL, (AFX_PMSG)NULL, (size_t)-1,
	  afxDispCustom }
	// nothing here
};

#endif //!_AFX_NO_OLE_SUPPORT

/////////////////////////////////////////////////////////////////////////////
// Root of event sink maps

#ifndef _AFX_NO_OCC_SUPPORT

UINT CCmdTarget::_eventsinkEntryCount = (UINT)-1;

const AFX_EVENTSINKMAP CCmdTarget::eventsinkMap =
{
	NULL,
	&CCmdTarget::_eventsinkEntries[0],
	&CCmdTarget::_eventsinkEntryCount
};

const AFX_EVENTSINKMAP* CCmdTarget::GetEventSinkMap() const
{
	return &CCmdTarget::eventsinkMap;
}

#ifdef _AFXDLL
const AFX_EVENTSINKMAP* CCmdTarget::GetThisEventSinkMap()
{
	return &CCmdTarget::eventsinkMap;
}
#endif

const AFX_EVENTSINKMAP_ENTRY CCmdTarget::_eventsinkEntries[] =
{
	{ NULL, -1, NULL, 0, (AFX_PMSG)NULL, (AFX_PMSG)NULL, (size_t)-1,
	  afxDispCustom, (UINT)-1, (UINT)-1 }
	// nothing here
};

#endif //!_AFX_NO_OCC_SUPPORT

/////////////////////////////////////////////////////////////////////////////
// Root of interface maps

#ifndef _AFX_NO_OLE_SUPPORT

const AFX_INTERFACEMAP* CCmdTarget::GetInterfaceMap() const
{
	return &CCmdTarget::interfaceMap;
}

#ifdef _AFXDLL
const AFX_INTERFACEMAP* CCmdTarget::GetThisInterfaceMap()
{
	return &CCmdTarget::interfaceMap;
}
#endif

const AFX_INTERFACEMAP CCmdTarget::interfaceMap =
{
	NULL,
	&CCmdTarget::_interfaceEntries[0]
};

const AFX_INTERFACEMAP_ENTRY CCmdTarget::_interfaceEntries[] =
{
#ifndef _AFX_NO_OLE_SUPPORT
	INTERFACE_PART(CCmdTarget, IID_IDispatch, Dispatch)
#endif
	{ NULL, (size_t)-1 }    // end of entries
};

void CCmdTarget::OnFinalRelease()
{
#ifndef _AFX_NO_OLE_SUPPORT
	AfxLockGlobals(CRIT_TYPELIBCACHE);

	// release the typelib cache, if any
	CTypeLibCache* pTypeLibCache = GetTypeLibCache();
	if (pTypeLibCache != NULL)
		pTypeLibCache->Unlock();

	AfxUnlockGlobals(CRIT_TYPELIBCACHE);
#endif

	delete this;
}

BOOL CCmdTarget::OnCreateAggregates()
{
	return TRUE;
}

LPUNKNOWN CCmdTarget::GetInterfaceHook(const void*)
{
	return NULL;
}

#endif //!_AFX_NO_OLE_SUPPORT

/////////////////////////////////////////////////////////////////////////////
// Root of connection maps

#ifndef _AFX_NO_OLE_SUPPORT

const AFX_CONNECTIONMAP* CCmdTarget::GetConnectionMap() const
{
	return &CCmdTarget::connectionMap;
}

#ifdef _AFXDLL
const AFX_CONNECTIONMAP* CCmdTarget::GetThisConnectionMap()
{
	return &CCmdTarget::connectionMap;
}
#endif

const AFX_CONNECTIONMAP CCmdTarget::connectionMap =
{
	NULL,
	&CCmdTarget::_connectionEntries[0]
};

const AFX_CONNECTIONMAP_ENTRY CCmdTarget::_connectionEntries[] =
{
	{ NULL, (size_t)-1 }    // end of entries
};

LPCONNECTIONPOINT CCmdTarget::GetConnectionHook(const IID&)
{
	return NULL;
}

BOOL CCmdTarget::GetExtraConnectionPoints(CPtrArray*)
{
	return FALSE;
}

#endif //!_AFX_NO_OLE_SUPPORT

/////////////////////////////////////////////////////////////////////////////
// Root of command target maps

#ifndef _AFX_NO_DOCOBJECT_SUPPORT

const AFX_OLECMDMAP CCmdTarget::commandMap =
{
	NULL,
	&CCmdTarget::_commandEntries[0]
};

const AFX_OLECMDMAP_ENTRY CCmdTarget::_commandEntries[] =
{
	{ NULL, 0, 0 }    // end of entries
};

const AFX_OLECMDMAP* CCmdTarget::GetCommandMap() const
{
	return &CCmdTarget::commandMap;
}

#ifdef _AFXDLL
const AFX_OLECMDMAP* CCmdTarget::GetThisCommandMap()
{
	return &CCmdTarget::commandMap;
}
#endif

#endif //!_AFX_NO_DOCOBJECT_SUPPORT

/////////////////////////////////////////////////////////////////////////////
// Special access to view routing info

CView* CCmdTarget::GetRoutingView()
{
	return GetRoutingView_();
}

CFrameWnd* CCmdTarget::GetRoutingFrame()
{
	return GetRoutingFrame_();
}

/////////////////////////////////////////////////////////////////////////////
// CCmdUI - User Interface for a command

// CCmdUI is a protocol class for all command handler variants
//      CCmdUI is an implementation class for menus and general dialog
//        controls (usually buttons)

CCmdUI::CCmdUI()
{
	// zero out everything
	m_nID = m_nIndex = m_nIndexMax = 0;
	m_pMenu = m_pSubMenu = m_pParentMenu = NULL;
	m_pOther = NULL;
	m_bEnableChanged = m_bContinueRouting = FALSE;
}

// default CCmdUI implementation only works for Menu Items
void CCmdUI::Enable(BOOL bOn)
{
	if (m_pMenu != NULL)
	{
		if (m_pSubMenu != NULL)
			return; // don't change popup menus indirectly

		ENSURE(m_nIndex < m_nIndexMax);
		m_pMenu->EnableMenuItem(m_nIndex, MF_BYPOSITION |
			(bOn ? MF_ENABLED : (MF_DISABLED | MF_GRAYED)));
	}
	else
	{
		// enable/disable a control (i.e. child window)
		ENSURE(m_pOther != NULL);

		// if control has the focus, move the focus before disabling
		if (!bOn && (::GetFocus() == m_pOther->m_hWnd))
			m_pOther->GetParent()->SendMessage(WM_NEXTDLGCTL, 0, FALSE);
		m_pOther->EnableWindow(bOn);
	}
	m_bEnableChanged = TRUE;
}

void CCmdUI::SetCheck(int nCheck)
{
	if (m_pMenu != NULL)
	{
		if (m_pSubMenu != NULL)
			return; // don't change popup menus indirectly

		// place checkmark next to menu item
		ENSURE(m_nIndex < m_nIndexMax);
		m_pMenu->CheckMenuItem(m_nIndex, MF_BYPOSITION |
			(nCheck ? MF_CHECKED : MF_UNCHECKED));
	}
	else
	{
		// we can only check buttons or controls acting like buttons
		ENSURE(m_pOther != NULL);
		if (m_pOther->SendMessage(WM_GETDLGCODE) & DLGC_BUTTON)
			m_pOther->SendMessage(BM_SETCHECK, nCheck);
		// otherwise ignore it
	}
}

AFX_STATIC void AFXAPI _AfxLoadDotBitmap(); // for swap tuning

void CCmdUI::SetRadio(BOOL bOn)
{
	SetCheck(bOn ? 1 : 0); // this default works for most things as well
	if (m_pMenu != NULL)
	{
		if (m_pSubMenu != NULL)
			return; // don't change popup menus indirectly

		// for menu item - use dot instead of checkmark
		ENSURE(m_nIndex < m_nIndexMax);

		if (afxData.hbmMenuDot == NULL)
			_AfxLoadDotBitmap();    // in INIT segment

		if (afxData.hbmMenuDot != NULL)
			SetMenuItemBitmaps(m_pMenu->m_hMenu, m_nIndex, MF_BYPOSITION,
				NULL, afxData.hbmMenuDot);
	}
}

void CCmdUI::SetText(LPCTSTR lpszText)
{
	ENSURE_ARG(lpszText != NULL);
	ASSERT(AfxIsValidString(lpszText));

	if (m_pMenu != NULL)
	{
		if (m_pSubMenu != NULL)
			return; // don't change popup menus indirectly

		// get current menu state so it doesn't change
		UINT nState = m_pMenu->GetMenuState(m_nIndex, MF_BYPOSITION);
		nState &= ~(MF_BITMAP|MF_OWNERDRAW|MF_SEPARATOR);

		// set menu text
		ENSURE(m_nIndex < m_nIndexMax);
		VERIFY(m_pMenu->ModifyMenu(m_nIndex, MF_BYPOSITION |
			MF_STRING | nState, m_nID, lpszText));
	}
	else
	{
		ENSURE(m_pOther != NULL);
		AfxSetWindowText(m_pOther->m_hWnd, lpszText);
	}
}

BOOL CCmdUI::DoUpdate(CCmdTarget* pTarget, BOOL bDisableIfNoHndler)
{
	if (m_nID == 0 || LOWORD(m_nID) == 0xFFFF)
		return TRUE;     // ignore invalid IDs

	ENSURE_VALID(pTarget);

	m_bEnableChanged = FALSE;
	BOOL bResult = pTarget->OnCmdMsg(m_nID, CN_UPDATE_COMMAND_UI, this, NULL);
	if (!bResult)
		ASSERT(!m_bEnableChanged); // not routed

	if (bDisableIfNoHndler && !m_bEnableChanged)
	{
		AFX_CMDHANDLERINFO info;
		info.pTarget = NULL;
		BOOL bHandler = pTarget->OnCmdMsg(m_nID, CN_COMMAND, this, &info);

#ifdef _DEBUG
		if (!bHandler)
			TRACE(traceCmdRouting, 1, "No handler for command ID 0x%04X, disabling it.\n", m_nID);
#endif
		// Enable or Disable based on whether there is a handler there
		Enable(bHandler);
	}
	return bResult;
}

/////////////////////////////////////////////////////////////////////////////
// Special init

AFX_STATIC_DATA const BYTE _afxDot[] =
	{ 0x6, 0xF, 0xF, 0xF, 0x6 }; // simple byte bitmap, 1=> bit on
#define DOT_WIDTH   4
#define DOT_HEIGHT  5

AFX_STATIC void AFXAPI _AfxLoadDotBitmap()
{
	ASSERT(afxData.hbmMenuDot == NULL);
	// attempt to load special bitmap, else default to arrow
	CSize size = ::GetMenuCheckMarkDimensions();
	ENSURE(size.cx > 4 && size.cy > 5); // not too small please
	if (size.cx > 32)
		size.cx = 32;
	int iwRow = (size.cx + 15) >> 4;    // # of WORDs per raster line
	int nShift = (size.cx - DOT_WIDTH) / 2;     // # of bits to shift over
	nShift += ((iwRow * 16) - size.cx); // padding for word alignment
	if (nShift > 16 - DOT_WIDTH)
		nShift = 16 - DOT_WIDTH;    // maximum shift for 1 word

	if (size.cy > 32)
		size.cy = 32;

	// bitmap 2/4/4/4/2 pixels wide - centered (0 => black)
	BYTE rgbBitmap[32 * 2 * sizeof(WORD)];
	memset(rgbBitmap, 0xff, sizeof(rgbBitmap));

	BYTE* pbOut = &rgbBitmap[iwRow * sizeof(WORD) *
							((size.cy - (DOT_HEIGHT+1)) >> 1)];
	const BYTE* pbIn = _afxDot;
	for (int y = 0; y < DOT_HEIGHT; y++)
	{
		WORD w = (WORD)~(((DWORD)*pbIn++) << nShift);
		// bitmaps are always hi-lo
		pbOut[0] = HIBYTE(w);
		pbOut[1] = LOBYTE(w);
		pbOut += iwRow * sizeof(WORD);
	}

	afxData.hbmMenuDot = ::CreateBitmap(size.cx, size.cy, 1, 1,
			(LPVOID)rgbBitmap);
	if (afxData.hbmMenuDot == NULL)
	{
		TRACE(traceAppMsg, 0, "Warning: using system arrow bitmap instead of dot.\n");
		#define OBM_MNARROW         32739
		afxData.hbmMenuDot = ::LoadBitmap(NULL, MAKEINTRESOURCE(OBM_MNARROW));
	}
}

/////////////////////////////////////////////////////////////////////////////
// CCmdTarget diagnostics

#ifdef _DEBUG
void CCmdTarget::Dump(CDumpContext& dc) const
{
	CObject::Dump(dc);

#ifndef _AFX_NO_OLE_SUPPORT
	if (m_xDispatch.m_vtbl != 0)
	{
		dc << "with IDispatch (OLE Automation) capability\n";
		dc << "m_bResultExpected = " << m_bResultExpected << "\n";
	}
	if (m_xConnPtContainer.m_vtbl != 0)
	{
		dc << "with OLE Connection Point capability\n";
	}
	if (GetInterfaceMap() != &CCmdTarget::interfaceMap)
	{
		dc << "with OLE capability";
		dc << "\nm_dwRef = " << m_dwRef;
		dc << "\nm_pOuterUnknown = " << m_pOuterUnknown;
		if (m_xInnerUnknown != 0)
			dc << "\nwith aggregation capability";
		dc << "\n";
	}
#endif //!_AFX_NO_OLE_SUPPORT
}

void CCmdTarget::AssertValid() const
{
	CObject::AssertValid();
}
#endif

IMPLEMENT_DYNAMIC(CCmdTarget, CObject)

/////////////////////////////////////////////////////////////////////////////


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-title" content="BP Logger">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <title>BP Logger</title>

    <link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css">
      <link rel="stylesheet" href="/css/main.css">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
          Toggle navigation

        </button>
        BP Logger

            Nueva medida

            Historico

Blood pressure

Blood pressure 7 days

Pulse

Blood pressure distribution

Sistolic distribution


text:
set -xe

# want 1 script to rule them all
# but this part is not needed on MACOS
if [[ ! $OS == 'macos-latest' ]]; then
  if [ ! -z "$WITH_SUDO" ]; then
    sudo apt-get update
    sudo apt-get install -y gcc g++ curl libpq-dev postgresql-client
  else
    apt-get update
    apt-get install -y gcc g++ curl libpq-dev postgresql-client
  fi
fi
conda config --set always_yes yes --set changeps1 no
conda update -q conda
conda info -a
conda create --name=${ENV_NAME}  python=$PYTHON --quiet

if [[ $PYTHON == 2.7 ]]; then
  conda env update -n ${ENV_NAME} -f ci/${ENV_NAME}_py2.yaml
else
  conda env update -n ${ENV_NAME} -f ci/${ENV_NAME}.yaml
fi

source activate ${ENV_NAME}
conda list -n ${ENV_NAME}

# check that the python version matches the desired one; exit immediately if not
PYVER=`python -c "import sys; print('{:d}.{:d}'.format(sys.version_info.major, sys.version_info.minor))"`
if [[ $PYVER != $PYTHON ]]; then
  exit 1;
fi


text:
cask 'leap-motion' do
  version '2.2.6'
  sha256 '3fe11385d960823d888f1946705a2d7c91d693618a0df371d9724794cb081ddf'

  url 'https://warehouse.leapmotion.com/apps/4101/download'
  name 'Leap Motion'
  homepage 'https://www.leapmotion.com/setup'
  license :gratis

  pkg 'Leap Motion.pkg'

  uninstall :script => '/Applications/Leap Motion.app/Contents/MacOS/uninstall'
end


text:
package me.williamhester.reddit.models;

/** The response object from /api/v1/me */
public class MeResponse {
  private String name;

  public String getName() {
    return name;
  }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Rabenhorst's Kryptogamen-Flora, Pilze - Die Flechtenparasiten 2(8): 219 (1930)

#### Original name
Melaspilea leciographoides Vouaux

### Remarks
null


text:
<?php

namespace Swarming\SubscribePro\Model\Config;

use Magento\Store\Model\ScopeInterface;

class Advanced extends General
{
    /**
     * @param string|null $websiteCode
     * @return string
     */
    public function getCacheLifeTime($websiteCode = null)
    {
        return $this->scopeConfig->getValue('swarming_subscribepro/advanced/cache_lifetime', ScopeInterface::SCOPE_WEBSITE, $websiteCode);
    }

    /**
     * @param string|null $websiteCode
     * @return array
     */
    public function getWebhookIpAddresses($websiteCode = null)
    {
        $ipAddresses = $this->scopeConfig->getValue('swarming_subscribepro/advanced/webhook_ipaddresses', ScopeInterface::SCOPE_WEBSITE, $websiteCode);
        return $this->explodeIps($ipAddresses);
    }

    /**
     * @param $ipAddress
     * @param string|null $websiteCode
     * @return bool
     */
    public function isWebhookIpAllowed($ipAddress, $websiteCode = null)
    {
        return in_array($ipAddress, $this->getWebhookIpAddresses($websiteCode));
    }

    /**
     * @param string|null $websiteCode
     * @return bool
     */
    public function isDebuggingEnabled($websiteCode = null)
    {
        return $this->scopeConfig->isSetFlag('swarming_subscribepro/advanced/enable_debugging', ScopeInterface::SCOPE_WEBSITE, $websiteCode);
    }

    /**
     * @param string $ips
     * @return array
     */
    protected function explodeIps($ips)
    {
        return empty($ips) ? [] : explode(',', str_replace(' ', '', $ips));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StorageService.Queries.GetStorage
{
    public class Storage
    {
        public string Id { get; set; }

        public Item[] Items { get; set; }
    }
}


text:
var IE6UPDATE_OPTIONS = {
    icons_path: "../images/"
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace ENVision
{
    class LVTextTextAdapter : BaseAdapter
    {
        public List<DataTwoItems> myItems = new List<DataTwoItems>();
        public List<Boolean> appliedEvent;
        private Activity _activity;

        public LVTextTextAdapter(Activity activity, List<DataTwoItems> itemList)
        {
            _activity = activity;
            myItems = itemList;
        }

        public override int Count
        {
            get
            {
                return myItems.Count;
            }
        }

        public override Java.Lang.Object GetItem(int position)
        {
            return null;
        }

        public override long GetItemId(int position)
        {
            return position;
        }

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            ViewHolder holder;

            if (convertView == null)
            {
                holder = new ViewHolder();
                convertView = _activity.LayoutInflater.Inflate(Resource.Layout.LVTextTextLayout, parent, false);
                holder.text1View = convertView.FindViewById<TextView>(Resource.Id.et1);
                holder.text2View = convertView.FindViewById<TextView>(Resource.Id.et2);

                convertView.Tag = holder;
            }
            else
                holder = convertView.Tag as ViewHolder;

            holder.reference = position;

            var view = convertView ?? _activity.LayoutInflater.Inflate(Resource.Layout.LVTextEditLayout, parent, false);

            DataTwoItems item = myItems.ElementAt(position);

            holder.text1View.Text = item.item1;
            holder.text2View.Text = item.item2;

            return convertView;
        }

        private class ViewHolder : Java.Lang.Object
        {
            public TextView text1View;
            public TextView text2View;
            public int reference;
        }
    }
}


text:
package com.netflix.atlas.chart.util

import java.awt.Font

import scala.util.Using

/**
  * Helper functions for working with fonts.
  */
object Fonts {

  private def loadTrueTypeFont(resource: String): Font = {
    Using.resource(getClass.getClassLoader.getResourceAsStream(resource)) { in =>
      Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(12.0f)
    }
  }

  /**
    * Load a font from the system or from the classpath.
    */
  def loadFont(font: String): Font = {
    if (font.endsWith(".ttf"))
      loadTrueTypeFont(font)
    else
      new Font(font, Font.PLAIN, 12)
  }

  /**
    * Font that is provided with the library and thus will be available on all systems. There
    * may be slight differences in the rendering on different versions of the JDK.
    */
  val default: Font = loadFont("fonts/RobotoMono-Regular.ttf")

  /**
    * Returns true if the JDK and OS being used match those used to generate the blessed
    * reference images for test cases. On other systems there will be slight differences in
    * the font rendering causing diffs.
    */
  def shouldRunTests: Boolean = {
    // May work on others, but 15 is the earliest confirmed to have consistent rendering
    // at this point
    val isAtLeastJdk15 = System.getProperty("java.specification.version").toDouble >= 15.0
    val isMacOS = System.getProperty("os.name") == "Mac OS X"
    isAtLeastJdk15 && isMacOS
  }
}


text:
/*
 *  FirmataLightSensor.js
 *
 *  David Janes
 *  IOTDB
 *  2014-05-01
 */

"use strict";

var iotdb = require("iotdb")

exports.Model = iotdb.make_model('FirmataLightSensor')
    .product("http://www.seeedstudio.com/depot/Grove-Light-Sensor-p-746.html")
    .facet(":device.sensor.light")
    .help("make sure to set initd.pin")
    .attribute(
        iotdb.make_unit(":sensor.light")
            .reading()
    )
    .driver_identity(":firmata")
    .driver_setup(function(paramd) {
        paramd.initd.pins = "value:mode=analog-input"
    })
    .make()
    ;


text:
<?xml version="1.0" encoding="utf-8" ?>
<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.2">
  <CommandSet xml:lang="en-au" Name="PlayerCommandset_en-au">
    <AppName> Player Sample </AppName>
    <Example> Play / Pause / Go forward / Go back </Example>

    <Command Name="buildit_pause">
      <Example> Pause </Example>
      <ListenFor> pause </ListenFor>
      <Feedback> Pausing </Feedback>
      <Navigate />
    </Command>

    <Command Name="buildit_play">
      <Example> Play </Example>
      <ListenFor> play </ListenFor>
      <ListenFor> resume </ListenFor>
      <Feedback> Resuming </Feedback>
      <Navigate />
    </Command>

    <Command Name="buildit_forward">
      <Example> Forward </Example>
      <ListenFor> [go] forward </ListenFor>
      <Feedback> Seeking forward... </Feedback>
      <Navigate />
    </Command>
    <Command Name="buildit_back">
      <Example> Back </Example>
      <ListenFor> [go] back </ListenFor>
      <Feedback> Seeking backward... </Feedback>
      <Navigate />
    </Command>
  </CommandSet>

  <CommandSet xml:lang="en-us" Name="PlayerCommandset_en-us">
    <AppName> Player Sample </AppName>
    <Example> Play / Pause / Go forward / Go back </Example>

    <Command Name="buildit_pause">
      <Example> Pause </Example>
      <ListenFor> pause </ListenFor>
      <Feedback> Pausing </Feedback>
      <Navigate />
    </Command>

    <Command Name="buildit_play">
      <Example> Play </Example>
      <ListenFor> play </ListenFor>
      <ListenFor> resume </ListenFor>
      <Feedback> Resuming </Feedback>
      <Navigate />
    </Command>

    <Command Name="buildit_forward">
      <Example> Forward </Example>
      <ListenFor> [go] forward </ListenFor>
      <Feedback> Seeking forward... </Feedback>
      <Navigate />
    </Command>
    <Command Name="buildit_back">
      <Example> Back </Example>
      <ListenFor> [go] back </ListenFor>
      <Feedback> Seeking backward... </Feedback>
      <Navigate />
    </Command>
  </CommandSet>

  <CommandSet xml:lang="en-nz" Name="PlayerCommandset_en-nz">
    <AppName> Player Sample </AppName>
    <Example> Play / Pause / Go forward / Go back </Example>

    <Command Name="buildit_pause">
      <Example> Pause </Example>
      <ListenFor> pause </ListenFor>
      <Feedback> Pausing </Feedback>
      <Navigate />
    </Command>

    <Command Name="buildit_play">
      <Example> Play </Example>
      <ListenFor> play </ListenFor>
      <ListenFor> resume </ListenFor>
      <Feedback> Resuming </Feedback>
      <Navigate />
    </Command>

    <Command Name="buildit_forward">
      <Example> Forward </Example>
      <ListenFor> [go] forward </ListenFor>
      <Feedback> Seeking forward... </Feedback>
      <Navigate />
    </Command>
    <Command Name="buildit_back">
      <Example> Back </Example>
      <ListenFor> [go] back </ListenFor>
      <Feedback> Seeking backward... </Feedback>
      <Navigate />
    </Command>
  </CommandSet>
</VoiceCommands>


text:
cd "$(dirname "$0")"
if [ ! -d node_modules ];then
    sudo npm install
    bower install
fi
grunt watch


text:
<!doctype html>

        <meta charset="utf-8">

        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

        <title>SettingsManager NodeJS Example</title>

SettingsManager NodeJS Example

Example NodeJS use of the SettingsManager library

Load the SettingsManager library using require:

let SettingsManager = require('@hal313/settings-manager');
let settingsManager = new SettingsManager();
/* code here*/

Run the sample

node docs/examples/nodejs/nodejs-test.js

                    <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#js-code-container" aria-expanded="false" aria-controls="code-container">
                        Show Code
                    </button>


text:
<?php

namespace PHPPM\Commands;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ConfigCommand extends Command
{
    use ConfigTrait;

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('config')
            ->addOption('show-option', null, InputOption::VALUE_REQUIRED, 'Instead of writing the config, only show the given option.', '')
            ->setDescription('Configure config file, default - ppm.json');

        $this->configurePPMOptions($this);
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $configPath = $this->getConfigPath($input, true);
        if (!$configPath) {
            $configPath = $this->file;
        }
        $config = $this->loadConfig($input, $output);

        if ($input->getOption('show-option')) {
            echo $config[$input->getOption('show-option')];
            return 0;
        }

        $this->renderConfig($output, $config);

        $newContent = json_encode($config, JSON_PRETTY_PRINT);
        if (file_exists($configPath) && $newContent === file_get_contents($configPath)) {
            $output->writeln(sprintf('No changes to %s file.', realpath($configPath)));
            return 0;
        }

        file_put_contents($configPath, $newContent);
        $output->writeln(sprintf('<info>%s file written.</info>', realpath($configPath)));

        return 0;
    }
}


text:
namespace SecondAttempt
{
    //A loot table should contain
    public class LootTable
    {
        //TO DO: Item initialization and constructors.
        //Will contain a list of loot objects. A loot object should contain the item an enemy can drop as well as their drop chance. Drop chance will probably be in the range 1 - 100.
    }
}


text:
Wsus-client Cookbook
====================
[![Cookbook Version][cookbook_version]][cookbook]
[![Build Status][build_status]][build_status]

Configures WSUS clients to retrieve approved updates.

Testing
-------
The PowerShell script will always fail if run via the winrm vagrant provider
as the IUpdateSession::CreateUpdateDownloader is not available remotely.

Logs
---------------
The Microsoft.Update.Session object keeps a log in: C:\Windows\WindowsUpdate.log

Requirements
------------
This cookbook recommends Chef 11+.

### Platforms
* Windows XP
* Windows Vista
* Windows Server 2003 R2
* Windows 7
* Windows Server 2008 (R1, R2)
* Windows 8 and 8.1
* Windows Server 2012 (R1, R2)

Usage
-----
Using this cookbook is quite easy; add the desired recipes to the run list of a node, or role.
Adjust any attributes as desired. For example, to configure a windows server role that connects to your WSUS server:

```ruby
$ cat roles/updated_windows_server.rb
name 'updated_windows_server'
description 'Setup a windows server to keep up-to-date'

run_list(
  'wsus-client::default'
)

default_attributes(
  wsus_client: {
    wsus_server: 'http://wsus-server.my-corporation.com:8530',
    update_group: 'updated_server2015',
  },
)
```

Providers & Resources
---------------------

## update
This provider allows to synchronously download and/or install available windows updates.

### Actions
Action   | Description
---------|---------------------------
download | Download available updates
install  | Install downloaded updates

> NOTE: The default behavior is `[:download, :install]`

### Attributes
Attribute     | Description                                         | Type         | Default
--------------|-----------------------------------------------------|--------------|------------------------
actions       | An array of actions to perform (see. actions above) | Symbol array | `[:download, :install]`
name          | Name of the resource                                | String       |

Recipes
-------

## wsus-client::default
Convenience recipe that configures WSUS client and performs a synchronous update.
It basically includes `wsus-client::configure` and `wsus-client::update`

## wsus-client::configure
This recipe modifies the Windows registry to configure [WSUS update settings][wsus_registry].

### Attributes
The following attributes are used to configure the `wsus-client::configure` recipe, accessible via `node['wsus_client'][attribute]`.

Attribute                    | Description                                                                                | Type                | Default
-----------------------------|--------------------------------------------------------------------------------------------------------|---------------------|--------
wsus_server                  |Defines a custom WSUS server to use instead of Microsoft Windows Update server                          |String, URI          |`nil`
update_group                 |Defines the current computer update group. (see [client-side targeting][client_targeting])              |String               |`nil`
disable_windows_update_access|Disables access to Windows Update (or your WSUS server)                                                 |TrueClass, FalseClass|`false`
enable_non_microsoft_updates |Allows signed non-Microsoft updates.                                                                    |TrueClass, FalseClass|`true`
allow_user_to_install_updates|Authorizes Users to approve or disapprove updates.                                                      |TrueClass, FalseClass|`false`
auto_install_minor_updates   |Defines whether minor update should be automatically installed.                                         |TrueClass, FalseClass|`false`
no_reboot_with_logged_users  |Disables automatic reboot with logged-on users.                                                         |TrueClass, FalseClass|`true`
automatic_update_behavior    |Defines auto update behavior.                                                                           |Symbol`*`            |`:disabled`
detection_frequency          |Defines times in hours between detection cycles.                                                        |FixNum               |`22`
schedule_install_day         |Defines the day of the week to schedule update install.                                                 |Symbol`**`           |`:every_day`
schedule_install_time        |Defines the time of day in 24-hour format to schedule update install.                                   |FixNum (1-23)        |`0`
schedule_retry_wait          |Defines the time in minutes to wait at startup before applying update from a missed scheduled time      |FixNum (0-60)        |`0`
reboot_warning               |Defines time in minutes of the restart warning countdown after reboot-required updates automatic install|FixNum (1-30)        |`5`
reboot_prompt_timeout        |Defines time in minutes between prompts for a scheduled restart                                         |FixNum (1-1440)      |`10`

`*` automatic_update_behavior values are:

```ruby
# :disabled  = Disables automatic updates
# :detect    = Only notify users of new updates
# :download  = Download updates, but let users install them
# :install   = Download and install updates
# :manual    = Lets the users configure the behavior
```

`**` schedule_install_day possible values are: `:every_day`, `:sunday`, `:monday`, `:tuesday`, `:wednesday`, `:thursday`, `:friday`, `:saturday`

## wsus-client::update
This recipe performs a synchronous detection and install of available Windows updates.

### Attributes
The following attributes are used to configure the `wsus-client::update` recipe, accessible via `node['wsus_client'][attribute]`.

Attribute     | Description                                                              | Type                  | Default
--------------|--------------------------------------------------------------------------|-----------------------|--------
download_only | Determines whether available update should be installed once downloaded. | TrueClass, FalseClass | `false`

Contributing
------------
1. Fork the [repository on Github][repository]
2. Create a named feature branch (like `add_component_x`)
3. Write your change
4. Write tests for your change (if applicable)
5. Run the tests, ensuring they all pass
6. Submit a Pull Request using Github

License and Authors
-------------------
Authors: [Baptiste Courtois][author] (<b.courtois@criteo.com>)

```text
Copyright 2014-2015, Criteo.

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.
```

[author]:                   https://github.com/Annih
[repository]:               https://github.com/criteo-cookbooks/wsus-client
[client_targeting]:         https://technet.microsoft.com/library/cc720450
[wsus_registry]:            https://technet.microsoft.com/library/dd939844
[build_status]:             https://api.travis-ci.org/criteo-cookbooks/wsus-client.svg?branch=master
[cookbook_version]:         https://img.shields.io/cookbook/v/wsus-client.svg
[cookbook]:                 https://supermarket.chef.io/cookbooks/wsus-client


text:
Upload video quickly to [Streamable](http://streamable.com).

[![Build Status](https://travis-ci.org/remixz/to-streamable.svg?branch=master)](https://travis-ci.org/remixz/to-streamable)

[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)

## Installation

[![NPM](https://nodei.co/npm/to-streamable.png)](https://nodei.co/npm/to-streamable/)

```
npm install -g to-streamable
```

## Usage

```
Usage: to-streamable [options] [path to video file]
If no video path is passed, then stdin is used.

Options:

  --help, -h     Prints this help message.

  --version, -v  Prints current version.

  --setup        Launches a wizard to save Streamable username and password.

  --auth         Sets the username and password used for uploading.
                 Must be in a colon pair. `to-streamable --auth=user:pass`
                 If passed, this is preferred over any saved authentication.

  --no-resize    Tells Streamable to not resize final video.

  --mute         Tells Streamable to mute final video.
```

## API

### `let vid = require('to-streamable')(<opts>)`

Returns a new `to-streamable` instance. `opts` is an object. Valid parameters:

* `file` - A `Readable` stream of the video. (i.e. `fs.createReadStream('/path/to/video')`) This is passed to `request`'s `formData` option. Required.
* `auth` - An object containing a `username` and `password` property of your Streamable credentials. Required.
* `params` - An array of parameters to add to the request. Valid options are `noresize` and `mute`. See the [Streamable API Docs](http://streamable.com/documentation) for more info.

Example:

```js
let opts = {
  file: fs.createReadStream('/path/to/file'),
  auth: {
    username: 'foo',
    password: 'bar'
  },
  params: ['mute']
}
```

### `vid.upload([cb(err, res)])`

Starts the upload of the video. `cb` is an optional callback function. Called with parameters `err`, containing an `Error`, if any, and `res`, with the object response from the Streamable API. See the [Streamable API Docs](http://streamable.com/documentation) for format.

### `vid.status([cb(err, res)])`

Retrieves the status of the video upload. `vid.upload()` must be called beforehand. `cb` is an optional callback function. Called with parameters `err`, containing an `Error`, if any, and `res`, with the object response from the Streamable API. See the [Streamable API Docs](http://streamable.com/documentation) for format.


text:
package io.vertx.ext.auth.oauth2.providers;

import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.ext.auth.oauth2.OAuth2Auth;
import io.vertx.ext.auth.oauth2.OAuth2Options;
import io.vertx.ext.auth.oauth2.OAuth2FlowType;

/**
 * Simplified factory to create an {@link OAuth2Auth} for SoundCloud.
 *
 * @author Paulo Lopes
 */
@VertxGen
public interface SoundcloudAuth {

  /**
   * Create a OAuth2Auth provider for SoundCloud
   *
   * @param clientId     the client id given to you by SoundCloud
   * @param clientSecret the client secret given to you by SoundCloud
   */
  static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret) {
    return create(vertx, clientId, clientSecret, new HttpClientOptions());
  }

  /**
   * Create a OAuth2Auth provider for SoundCloud
   *
   * @param clientId          the client id given to you by SoundCloud
   * @param clientSecret      the client secret given to you by SoundCloud
   * @param httpClientOptions custom http client options
   */
  static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, HttpClientOptions httpClientOptions) {
    return
      OAuth2Auth.create(vertx, new OAuth2Options()
        .setHttpClientOptions(httpClientOptions)
        .setFlow(OAuth2FlowType.AUTH_CODE)
        .setClientId(clientId)
        .setClientSecret(clientSecret)
        .setSite("https://api.soundcloud.com")
        .setTokenPath("/oauth2/token")
        .setAuthorizationPath("/connect")
        .setUserInfoPath("/me.json"));
  }
}


text:
<?xml version="1.0"?>
<ruleset name="Phpfastcache Standards">
    <description>The Phpfastcache Coding Standards</description>

    <arg name="colors"/>
    <arg value="p"/>
    <ini name="memory_limit" value="256M"/>
    <rule ref="PSR12"/>

    <exclude-pattern>tests/*</exclude-pattern>
    <exclude-pattern>bin/*</exclude-pattern>
    <exclude-pattern>docs/*</exclude-pattern>
    <exclude-pattern>vendor/*</exclude-pattern>

    <rule ref="Generic.Files.LineLength">
        <properties>
            <property name="lineLimit" value="170"/>
            <property name="absoluteLineLimit" value="170"/>
        </properties>
    </rule>
</ruleset>


text:
package org.apache.jena.hadoop.rdf.io.output;

import java.io.IOException;
import java.io.Writer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.jena.hadoop.rdf.io.output.writers.QuadsToTriplesWriter;
import org.apache.jena.hadoop.rdf.io.registry.HadoopRdfIORegistry;
import org.apache.jena.hadoop.rdf.types.QuadWritable;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFLanguages;
import org.apache.jena.sparql.core.Quad ;

/**
 * An output format for RDF triples/quads that dynamically selects the
 * appropriate triple/quad writer to use based on the file extension of the
 * output file.
 *

 * For example this is useful when the output format may be controlled by a user
 * supplied filename i.e. the desired RDF output format is not precisely known
 * in advance.
 *

 *
Warning

 *

 * Where the format is determined to be triples the quads are converted into
 * triples are thus will lose any graph information that might be carried.
 *

 *
 * @param <TKey>
 *            Key type
 */
public abstract class TriplesOrQuadsOutputFormat<TKey> extends AbstractNodeTupleOutputFormat<TKey, Quad, QuadWritable> {

    @Override
    protected RecordWriter<TKey, QuadWritable> getRecordWriter(Writer writer, Configuration config, Path outputPath)
            throws IOException {
        Lang lang = RDFLanguages.filenameToLang(outputPath.getName());
        if (lang == null)
            throw new IOException("There is no registered RDF language for the output file " + outputPath.toString());

        if (!RDFLanguages.isQuads(lang) && !RDFLanguages.isTriples(lang))
            throw new IOException(lang.getName() + " is not a RDF triples/quads format");

        if (HadoopRdfIORegistry.hasQuadWriter(lang)) {
            // Supports quads directly
            return HadoopRdfIORegistry.<TKey> createQuadWriter(lang, writer, config);
        } else {
            // Try to create a triples writer and wrap downwards from quads
            // This will throw an error if a triple writer is not available
            return new QuadsToTriplesWriter<TKey>(HadoopRdfIORegistry.<TKey> createTripleWriter(lang, writer, config));
        }
    }

}


text:
"use strict"

let chai = require('chai');
chai.use(require('chai-as-promised'));
let expect = chai.expect;
let promiseTools = require('../src');

describe('timeout', () => {
    it('should resolve if the underlying promise resolves', () => {
        let p = promiseTools.delay(10).then(() => "done");
        return expect(promiseTools.timeout(p, 1000)).to.eventually.equal("done");
    });

    it('should reject if the underlying promise reject', () => {
        let p = promiseTools.delay(10).then(() => {throw new Error("Boom")});
        return expect(promiseTools.timeout(p, 1000)).to.eventually.be.rejectedWith("Boom");
    });

    it('should reject if the underlying promise fails to resolve in time', () => {
        let p = promiseTools.delay(100).then(() => "done");
        return expect(promiseTools.timeout(p, 1)).to.eventually.be.rejectedWith(promiseTools.TimeoutError);
    });

    it('should reject if the underlying promise fails to reject in time', () => {
        let p = promiseTools.delay(100).then(() => {throw new Error("Boom")});
        return expect(promiseTools.timeout(p, 1)).to.eventually.be.rejectedWith(promiseTools.TimeoutError);
    });
});


text:
package org.kiji.hadoop.configurator;

import java.lang.reflect.Field;
import java.util.Collection;

import org.apache.hadoop.conf.Configuration;

/**
 * This class encapsulates everything there is to know about a Hadoop
 * configuration variable declaration.
 */
public class ConfigurationVariable {
  private Field mField;
  private HadoopConf mAnnotation;

  /**
   * Constructs a ConfigurationVariable instance.
   *
   * @param field The variable that has the annotation on it.
   * @param annotation The annotation on the field.
   */
  public ConfigurationVariable(Field field, HadoopConf annotation) {
    mField = field;
    mAnnotation = annotation;
  }

  /**
   * Gets the configuration key that should be used to populate the field.
   *
   * @return The key that was specified in the HadoopConf annotation.
   */
  public String getKey() {
    return mAnnotation.key();
  }

  /**
   * Populates an object's field with the value read from a Configuration instance.
   *
   * @param instance The object to populate.
   * @param conf The configuration to read from.
   * @throws IllegalAccessException If the field cannot be set on the object.
   * @throws HadoopConfigurationException If there is a problem with the annotation definition.
   */
  public void setValue(Object instance, Configuration conf) throws IllegalAccessException {
    final String key = getKey();
    if (null == key) {
      throw new HadoopConfigurationException("Missing 'key' attribute of @HadoopConf on "
          + instance.getClass().getName() + "." + mField.getName());
    }
    if (null == conf.get(key) && mAnnotation.defaultValue().isEmpty()) {
      // Nothing set in the configuration, and no default value
      // specified. Just leave the field alone.
      return;
    }

    if (!mField.isAccessible()) {
      mField.setAccessible(true);
    }

    try {
      if (boolean.class == mField.getType()) {
        mField.setBoolean(instance, conf.getBoolean(key, getDefaultBoolean(instance)));
      } else if (float.class == mField.getType()) {
        mField.setFloat(instance, conf.getFloat(key, getDefaultFloat(instance)));
      } else if (double.class == mField.getType()) {
        mField.setDouble(instance, conf.getFloat(key, getDefaultDouble(instance)));
      } else if (int.class == mField.getType()) {
        mField.setInt(instance, conf.getInt(key, getDefaultInt(instance)));
      } else if (long.class == mField.getType()) {
        mField.setLong(instance, conf.getLong(key, getDefaultLong(instance)));
      } else if (mField.getType().isAssignableFrom(String.class)) {
        mField.set(instance, conf.get(key, getDefaultString(instance)));
      } else if (mField.getType().isAssignableFrom(Collection.class)) {
        mField.set(instance, conf.getStringCollection(key));
      } else if (String[].class == mField.getType()) {
        mField.set(instance, conf.getStrings(key));
      } else {
        throw new HadoopConfigurationException("Unsupported field type annotated by @HadoopConf: "
            + instance.getClass().getName() + "." + mField.getName());
      }
    } catch (NumberFormatException e) {
      // That's okay. The default value for the field will be kept.
    }
  }

  /**
   * Gets the default value as a boolean.
   *
   * @param instance The object instance.
   * @return The default boolean value.
   * @throws IllegalAccessException If the field cannot be read.
   */
  private boolean getDefaultBoolean(Object instance) throws IllegalAccessException {
    String defaultValue = mAnnotation.defaultValue();
    if (defaultValue.isEmpty()) {
      return mField.getBoolean(instance);
    }
    return Boolean.parseBoolean(defaultValue);
  }

  /**
   * Gets the default value as a float.
   *
   * @param instance The object instance.
   * @return The default float value.
   * @throws IllegalAccessException If the field cannot be read.
   */
  private float getDefaultFloat(Object instance) throws IllegalAccessException {
    String defaultValue = mAnnotation.defaultValue();
    if (defaultValue.isEmpty()) {
      return mField.getFloat(instance);
    }
    return Float.parseFloat(defaultValue);
  }

  /**
   * Gets the default value as a double.
   *
   * @param instance The object instance.
   * @return The default double value.
   * @throws IllegalAccessException If the field cannot be read.
   */
  private float getDefaultDouble(Object instance) throws IllegalAccessException {
    String defaultValue = mAnnotation.defaultValue();
    if (defaultValue.isEmpty()) {
      return (float) mField.getDouble(instance);
    }
    return Float.parseFloat(defaultValue);
  }

  /**
   * Gets the default value as an int.
   *
   * @param instance The object instance.
   * @return The default int value.
   * @throws IllegalAccessException If the field cannot be read.
   */
  private int getDefaultInt(Object instance) throws IllegalAccessException {
    String defaultValue = mAnnotation.defaultValue();
    if (defaultValue.isEmpty()) {
      return mField.getInt(instance);
    }
    return Integer.parseInt(defaultValue);
  }

  /**
   * Gets the default value as a long.
   *
   * @param instance The object instance.
   * @return The default long value.
   * @throws IllegalAccessException If the field cannot be read.
   */
  private long getDefaultLong(Object instance) throws IllegalAccessException {
    String defaultValue = mAnnotation.defaultValue();
    if (defaultValue.isEmpty()) {
      return mField.getLong(instance);
    }
    return Long.parseLong(defaultValue);
  }

  /**
   * Gets the default value as a string.
   *
   * @param instance The object instance.
   * @return The default string value.
   * @throws IllegalAccessException If the field cannot be read.
   */
  private String getDefaultString(Object instance) throws IllegalAccessException {
    String defaultValue = mAnnotation.defaultValue();
    if (defaultValue.isEmpty()) {
      return (String) mField.get(instance);
    }
    return defaultValue;
  }
}