コード例 #1
0
ファイル: perfclock.cpp プロジェクト: neivv/teippi
double PerfClock::Stop()
{
    double tmp = GetTime();
    running = false;
    return tmp;
}
コード例 #2
0
ファイル: mining.cpp プロジェクト: Explore77/litecoin
UniValue getblocktemplate(const JSONRPCRequest& request)
{
    if (request.fHelp || request.params.size() > 1)
        throw std::runtime_error(
            "getblocktemplate ( TemplateRequest )\n"
            "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
            "It returns data needed to construct a block to work on.\n"
            "For full specification, see BIPs 22, 23, 9, and 145:\n"
            "    https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
            "    https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
            "    https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
            "    https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n"

            "\nArguments:\n"
            "1. template_request         (json object, optional) A json object in the following spec\n"
            "     {\n"
            "       \"mode\":\"template\"    (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n"
            "       \"capabilities\":[     (array, optional) A list of strings\n"
            "           \"support\"          (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
            "           ,...\n"
            "       ],\n"
            "       \"rules\":[            (array, optional) A list of strings\n"
            "           \"support\"          (string) client side supported softfork deployment\n"
            "           ,...\n"
            "       ]\n"
            "     }\n"
            "\n"

            "\nResult:\n"
            "{\n"
            "  \"version\" : n,                    (numeric) The preferred block version\n"
            "  \"rules\" : [ \"rulename\", ... ],    (array of strings) specific block rules that are to be enforced\n"
            "  \"vbavailable\" : {                 (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
            "      \"rulename\" : bitnumber          (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
            "      ,...\n"
            "  },\n"
            "  \"vbrequired\" : n,                 (numeric) bit mask of versionbits the server requires set in submissions\n"
            "  \"previousblockhash\" : \"xxxx\",     (string) The hash of current highest block\n"
            "  \"transactions\" : [                (array) contents of non-coinbase transactions that should be included in the next block\n"
            "      {\n"
            "         \"data\" : \"xxxx\",             (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
            "         \"txid\" : \"xxxx\",             (string) transaction id encoded in little-endian hexadecimal\n"
            "         \"hash\" : \"xxxx\",             (string) hash encoded in little-endian hexadecimal (including witness data)\n"
            "         \"depends\" : [                (array) array of numbers \n"
            "             n                          (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n"
            "             ,...\n"
            "         ],\n"
            "         \"fee\": n,                    (numeric) difference in value between transaction inputs and outputs (in Satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n"
            "         \"sigops\" : n,                (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n"
            "         \"weight\" : n,                (numeric) total transaction weight, as counted for purposes of block limits\n"
            "         \"required\" : true|false      (boolean) if provided and true, this transaction must be in the final block\n"
            "      }\n"
            "      ,...\n"
            "  ],\n"
            "  \"coinbaseaux\" : {                 (json object) data that should be included in the coinbase's scriptSig content\n"
            "      \"flags\" : \"xx\"                  (string) key name is to be ignored, and value included in scriptSig\n"
            "  },\n"
            "  \"coinbasevalue\" : n,              (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
            "  \"coinbasetxn\" : { ... },          (json object) information for coinbase transaction\n"
            "  \"target\" : \"xxxx\",                (string) The hash target\n"
            "  \"mintime\" : xxx,                  (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
            "  \"mutable\" : [                     (array of string) list of ways the block template may be changed \n"
            "     \"value\"                          (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
            "     ,...\n"
            "  ],\n"
            "  \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
            "  \"sigoplimit\" : n,                 (numeric) limit of sigops in blocks\n"
            "  \"sizelimit\" : n,                  (numeric) limit of block size\n"
            "  \"weightlimit\" : n,                (numeric) limit of block weight\n"
            "  \"curtime\" : ttt,                  (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
            "  \"bits\" : \"xxxxxxxx\",              (string) compressed target of next block\n"
            "  \"height\" : n                      (numeric) The height of the next block\n"
            "}\n"

            "\nExamples:\n"
            + HelpExampleCli("getblocktemplate", "")
            + HelpExampleRpc("getblocktemplate", "")
         );

    LOCK(cs_main);

    std::string strMode = "template";
    UniValue lpval = NullUniValue;
    std::set<std::string> setClientRules;
    int64_t nMaxVersionPreVB = -1;
    if (!request.params[0].isNull())
    {
        const UniValue& oparam = request.params[0].get_obj();
        const UniValue& modeval = find_value(oparam, "mode");
        if (modeval.isStr())
            strMode = modeval.get_str();
        else if (modeval.isNull())
        {
            /* Do nothing */
        }
        else
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
        lpval = find_value(oparam, "longpollid");

        if (strMode == "proposal")
        {
            const UniValue& dataval = find_value(oparam, "data");
            if (!dataval.isStr())
                throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");

            CBlock block;
            if (!DecodeHexBlk(block, dataval.get_str()))
                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");

            uint256 hash = block.GetHash();
            BlockMap::iterator mi = mapBlockIndex.find(hash);
            if (mi != mapBlockIndex.end()) {
                CBlockIndex *pindex = mi->second;
                if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
                    return "duplicate";
                if (pindex->nStatus & BLOCK_FAILED_MASK)
                    return "duplicate-invalid";
                return "duplicate-inconclusive";
            }

            CBlockIndex* const pindexPrev = chainActive.Tip();
            // TestBlockValidity only supports blocks built on the current Tip
            if (block.hashPrevBlock != pindexPrev->GetBlockHash())
                return "inconclusive-not-best-prevblk";
            CValidationState state;
            TestBlockValidity(state, Params(), block, pindexPrev, false, true);
            return BIP22ValidationResult(state);
        }

        const UniValue& aClientRules = find_value(oparam, "rules");
        if (aClientRules.isArray()) {
            for (unsigned int i = 0; i < aClientRules.size(); ++i) {
                const UniValue& v = aClientRules[i];
                setClientRules.insert(v.get_str());
            }
        } else {
            // NOTE: It is important that this NOT be read if versionbits is supported
            const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
            if (uvMaxVersion.isNum()) {
                nMaxVersionPreVB = uvMaxVersion.get_int64();
            }
        }
    }

    if (strMode != "template")
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");

    if(!g_connman)
        throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");

    if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
        throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Litecoin is not connected!");

    if (IsInitialBlockDownload())
        throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Litecoin is downloading blocks...");

    static unsigned int nTransactionsUpdatedLast;

    if (!lpval.isNull())
    {
        // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
        uint256 hashWatchedChain;
        boost::system_time checktxtime;
        unsigned int nTransactionsUpdatedLastLP;

        if (lpval.isStr())
        {
            // Format: <hashBestChain><nTransactionsUpdatedLast>
            std::string lpstr = lpval.get_str();

            hashWatchedChain.SetHex(lpstr.substr(0, 64));
            nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
        }
        else
        {
            // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
            hashWatchedChain = chainActive.Tip()->GetBlockHash();
            nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
        }

        // Release the wallet and main lock while waiting
        LEAVE_CRITICAL_SECTION(cs_main);
        {
            checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);

            boost::unique_lock<boost::mutex> lock(csBestBlock);
            while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
            {
                if (!cvBlockChange.timed_wait(lock, checktxtime))
                {
                    // Timeout: Check transactions for update
                    if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
                        break;
                    checktxtime += boost::posix_time::seconds(10);
                }
            }
        }
        ENTER_CRITICAL_SECTION(cs_main);

        if (!IsRPCRunning())
            throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
        // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
    }

    const struct VBDeploymentInfo& segwit_info = VersionBitsDeploymentInfo[Consensus::DEPLOYMENT_SEGWIT];
    // If the caller is indicating segwit support, then allow CreateNewBlock()
    // to select witness transactions, after segwit activates (otherwise
    // don't).
    bool fSupportsSegwit = setClientRules.find(segwit_info.name) != setClientRules.end();

    // Update block
    static CBlockIndex* pindexPrev;
    static int64_t nStart;
    static std::unique_ptr<CBlockTemplate> pblocktemplate;
    // Cache whether the last invocation was with segwit support, to avoid returning
    // a segwit-block to a non-segwit caller.
    static bool fLastTemplateSupportsSegwit = true;
    if (pindexPrev != chainActive.Tip() ||
        (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) ||
        fLastTemplateSupportsSegwit != fSupportsSegwit)
    {
        // Clear pindexPrev so future calls make a new block, despite any failures from here on
        pindexPrev = nullptr;

        // Store the pindexBest used before CreateNewBlock, to avoid races
        nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
        CBlockIndex* pindexPrevNew = chainActive.Tip();
        nStart = GetTime();
        fLastTemplateSupportsSegwit = fSupportsSegwit;

        // Create new block
        CScript scriptDummy = CScript() << OP_TRUE;
        pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy, fSupportsSegwit);
        if (!pblocktemplate)
            throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");

        // Need to update only after we know CreateNewBlock succeeded
        pindexPrev = pindexPrevNew;
    }
    CBlock* pblock = &pblocktemplate->block; // pointer for convenience
    const Consensus::Params& consensusParams = Params().GetConsensus();

    // Update nTime
    UpdateTime(pblock, consensusParams, pindexPrev);
    pblock->nNonce = 0;

    // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
    const bool fPreSegWit = (THRESHOLD_ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache));

    UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");

    UniValue transactions(UniValue::VARR);
    std::map<uint256, int64_t> setTxIndex;
    int i = 0;
    for (const auto& it : pblock->vtx) {
        const CTransaction& tx = *it;
        uint256 txHash = tx.GetHash();
        setTxIndex[txHash] = i++;

        if (tx.IsCoinBase())
            continue;

        UniValue entry(UniValue::VOBJ);

        entry.push_back(Pair("data", EncodeHexTx(tx)));
        entry.push_back(Pair("txid", txHash.GetHex()));
        entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex()));

        UniValue deps(UniValue::VARR);
        for (const CTxIn &in : tx.vin)
        {
            if (setTxIndex.count(in.prevout.hash))
                deps.push_back(setTxIndex[in.prevout.hash]);
        }
        entry.push_back(Pair("depends", deps));

        int index_in_template = i - 1;
        entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
        int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
        if (fPreSegWit) {
            assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
            nTxSigOps /= WITNESS_SCALE_FACTOR;
        }
        entry.push_back(Pair("sigops", nTxSigOps));
        entry.push_back(Pair("weight", GetTransactionWeight(tx)));

        transactions.push_back(entry);
    }

    UniValue aux(UniValue::VOBJ);
    aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));

    arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);

    UniValue aMutable(UniValue::VARR);
    aMutable.push_back("time");
    aMutable.push_back("transactions");
    aMutable.push_back("prevblock");

    UniValue result(UniValue::VOBJ);
    result.push_back(Pair("capabilities", aCaps));

    UniValue aRules(UniValue::VARR);
    UniValue vbavailable(UniValue::VOBJ);
    for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
        Consensus::DeploymentPos pos = Consensus::DeploymentPos(j);
        ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
        switch (state) {
            case THRESHOLD_DEFINED:
            case THRESHOLD_FAILED:
                // Not exposed to GBT at all
                break;
            case THRESHOLD_LOCKED_IN:
                // Ensure bit is set in block version
                pblock->nVersion |= VersionBitsMask(consensusParams, pos);
                // FALL THROUGH to get vbavailable set...
            case THRESHOLD_STARTED:
            {
                const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
                vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit));
                if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
                    if (!vbinfo.gbt_force) {
                        // If the client doesn't support this, don't indicate it in the [default] version
                        pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
                    }
                }
                break;
            }
            case THRESHOLD_ACTIVE:
            {
                // Add to rules only
                const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
                aRules.push_back(gbt_vb_name(pos));
                if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
                    // Not supported by the client; make sure it's safe to proceed
                    if (!vbinfo.gbt_force) {
                        // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
                        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
                    }
                }
                break;
            }
        }
    }
    result.push_back(Pair("version", pblock->nVersion));
    result.push_back(Pair("rules", aRules));
    result.push_back(Pair("vbavailable", vbavailable));
    result.push_back(Pair("vbrequired", int(0)));

    if (nMaxVersionPreVB >= 2) {
        // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
        // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
        // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
        // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
        aMutable.push_back("version/force");
    }

    result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
    result.push_back(Pair("transactions", transactions));
    result.push_back(Pair("coinbaseaux", aux));
    result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue));
    result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
    result.push_back(Pair("target", hashTarget.GetHex()));
    result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
    result.push_back(Pair("mutable", aMutable));
    result.push_back(Pair("noncerange", "00000000ffffffff"));
    int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
    int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
    if (fPreSegWit) {
        assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
        nSigOpLimit /= WITNESS_SCALE_FACTOR;
        assert(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
        nSizeLimit /= WITNESS_SCALE_FACTOR;
    }
    result.push_back(Pair("sigoplimit", nSigOpLimit));
    result.push_back(Pair("sizelimit", nSizeLimit));
    if (!fPreSegWit) {
        result.push_back(Pair("weightlimit", (int64_t)MAX_BLOCK_WEIGHT));
    }
    result.push_back(Pair("curtime", pblock->GetBlockTime()));
    result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
    result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));

    if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) {
        result.push_back(Pair("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end())));
    }

    return result;
}
コード例 #3
0
void CNetToDisneyDlg::BeginTimer()
{
	m_nTimerId = 1;
	this->SetTimer(m_nTimerId, GetTime(), NULL);
}
コード例 #4
0
ファイル: bcltest.c プロジェクト: Grumbel/rfactortools
int TestFile( char *name, int algo, int verbose )
{
  unsigned int  insize, outsize, bufsize, *work, k, err_count;
  unsigned char *in, *out, *buf;
  FILE          *f;
  double        t0, t_comp, t_uncomp;

  printf( "Testing %s...", name );

  /* Open input file */
  f = fopen( name, "rb" );
  if( !f )
  {
    printf( "unable to open!\n" );
    return 0;
  }

  /* Get input size */
  insize = GetFileSize( f );
  if( insize < 1 )
  {
    printf( "empty file!\n" );
    fclose( f );
    return 0;
  }

  /* Worst case output buffer size */
  bufsize = (insize*104+50)/100 + 384;

  /* Allocate memory */
  in = (unsigned char *) malloc( insize + 2*bufsize );
  if( !in )
  {
    printf( "out of memory!\n" );
    fclose( f );
    return 0;
  }

  /* Pointers to compression buffer and output memory */
  buf = &in[ insize ];
  out = &buf[ bufsize ];

  /* Read and close input file */
  fread( in, 1, insize, f );
  fclose( f );

  /* Compress and decompress */
  switch( algo )
  {
    case 1:
      t0 = GetTime();
      outsize = RLE_Compress( in, insize, buf, bufsize );
      t_comp = GetTime() - t0;
      t0 = GetTime();
      RLE_Uncompress( buf, outsize, out, insize );
      t_uncomp = GetTime() - t0;
      break;
    case 2:
      t0 = GetTime();
      outsize = Huffman_Compress( in, buf, insize );
      t_comp = GetTime() - t0;
      t0 = GetTime();
      Huffman_Uncompress( buf, out, outsize, insize );
      t_uncomp = GetTime() - t0;
      break;
    case 3:
      t0 = GetTime();
      outsize = Rice_Compress( in, buf, insize, RICE_FMT_UINT8 );
      t_comp = GetTime() - t0;
      t0 = GetTime();
      Rice_Uncompress( buf, out, outsize, insize, RICE_FMT_UINT8 );
      t_uncomp = GetTime() - t0;
      break;
    case 4:
      t0 = GetTime();
      outsize = Rice_Compress( in, buf, insize, RICE_FMT_UINT16 );
      t_comp = GetTime() - t0;
      t0 = GetTime();
      Rice_Uncompress( buf, out, outsize, insize, RICE_FMT_UINT16 );
      t_uncomp = GetTime() - t0;
      break;
    case 5:
      t0 = GetTime();
      outsize = Rice_Compress( in, buf, insize, RICE_FMT_UINT32 );
      t_comp = GetTime() - t0;
      t0 = GetTime();
      Rice_Uncompress( buf, out, outsize, insize, RICE_FMT_UINT32 );
      t_uncomp = GetTime() - t0;
      break;
    case 6:
      t0 = GetTime();
      outsize = Rice_Compress( in, buf, insize, RICE_FMT_INT8 );
      t_comp = GetTime() - t0;
      t0 = GetTime();
      Rice_Uncompress( buf, out, outsize, insize, RICE_FMT_INT8 );
      t_uncomp = GetTime() - t0;
      break;
    case 7:
      t0 = GetTime();
      outsize = Rice_Compress( in, buf, insize, RICE_FMT_INT16 );
      t_comp = GetTime() - t0;
      t0 = GetTime();
      Rice_Uncompress( buf, out, outsize, insize, RICE_FMT_INT16 );
      t_uncomp = GetTime() - t0;
      break;
    case 8:
      t0 = GetTime();
      outsize = Rice_Compress( in, buf, insize, RICE_FMT_INT32 );
      t_comp = GetTime() - t0;
      t0 = GetTime();
      Rice_Uncompress( buf, out, outsize, insize, RICE_FMT_INT32 );
      t_uncomp = GetTime() - t0;
      break;
    case 9:
      t0 = GetTime();
      outsize = LZ_Compress( in, buf, insize );
      t_comp = GetTime() - t0;
      t0 = GetTime();
      LZ_Uncompress( buf, out, outsize );
      t_uncomp = GetTime() - t0;
      break;
    case 10:
      work = malloc( sizeof(unsigned int) * (65536+insize) );
      if( work )
      {
        t0 = GetTime();
        outsize = LZ_CompressFast( in, buf, insize, work );
        t_comp = GetTime() - t0;
        free( work );
        t0 = GetTime();
        LZ_Uncompress( buf, out, outsize );
        t_uncomp = GetTime() - t0;
      }
      else
      {
        printf( "unable to allocate working buffer!\n" );
        t_comp = 0.0;
        t_uncomp = 0.0;
        outsize = 0;
      }
      break;
    case 11:
      t0 = GetTime();
      outsize = SF_Compress( in, buf, insize );
      t_comp = GetTime() - t0;
      t0 = GetTime();
      SF_Uncompress( buf, out, outsize, insize );
      t_uncomp = GetTime() - t0;
      break;
    default:
      /* Should never happen... */
      outsize = 0;
      t_comp = 0.0;
      t_uncomp = 0.0;
  }

  err_count = 0;
  if(outsize > 0)
  {
    /* Show compression result */
    if( verbose )
    {
      printf( "\n  Compression: %d/%d bytes (%.1f%%)", outsize, insize,
              100*(float)outsize/(float)insize );
    }

    /* Compare input / output data */
    for( k = 0; k < insize; ++ k )
    {
      if( in[ k ] != out[ k ] )
      {
        if( err_count == 0 ) printf( "\n" );
        if( err_count == 30 ) printf( "    ...\n" );
        else if( err_count < 30 )
        {
            printf( "    %d: %d != %d\n", k, out[ k ], in[ k ] );
        }
        ++ err_count;
      }
    }

    /* Did we have success? */
    if( err_count == 0 )
    {
      printf( " - OK!\n" );
      if( verbose )
      {
        printf( "    Compression speed: %.1f KB/s (%.2f ms)\n",
                (double) insize / (1024.0 * t_comp), 1000.0 * t_comp );
        printf( "    Uncompression speed: %.1f KB/s (%.2f ms)\n",
                (double) insize / (1024.0 * t_uncomp), 1000.0 * t_uncomp );
      }
    }
    else
    {
      printf( "    *******************************\n" );
      printf( "    ERROR: %d faulty bytes\n", err_count );
      printf( "    *******************************\n" );
    }
  }

  /* Free all memory */
  free( in );

  return (outsize > 0) && (err_count == 0);
}
コード例 #5
0
static void* iep_process_thread(void *param) 
{
    int i, cnt = 0;

    mem_region_t *mr = (mem_region_t*)param;

    uint32_t phy_src, phy_reg, phy_dst;
    int len_src, len_reg, len_dst;
    uint8_t *vir_reg, *vir_src, *vir_dst;
    iep_img src;
    iep_img dst;

    int datalen = 0;

    len_reg = mr->len_reg;
    len_src = mr->len_src;
    len_dst = mr->len_dst;

    phy_reg = mr->phy_reg;
    phy_src = mr->phy_src;
    phy_dst = mr->phy_dst;

    vir_reg = mr->vir_reg;
    vir_src = mr->vir_src;
    vir_dst = mr->vir_dst;

    iep_interface *api = iep_interface::create_new();

    FILE *srcfile = fopen(mr->src_url, "rb");
    FILE *dstfile = fopen(mr->dst_url, "wb");

    switch (mr->src_fmt) {
    case IEP_FORMAT_ABGR_8888:
    case IEP_FORMAT_ARGB_8888:
    case IEP_FORMAT_BGRA_8888:
    case IEP_FORMAT_RGBA_8888:
        datalen = mr->src_w * mr->src_h * 4;
        break;
    case IEP_FORMAT_BGR_565:
    case IEP_FORMAT_RGB_565:
    case IEP_FORMAT_YCbCr_422_P:
    case IEP_FORMAT_YCbCr_422_SP:
    case IEP_FORMAT_YCrCb_422_P:
    case IEP_FORMAT_YCrCb_422_SP:
        datalen = mr->src_w * mr->src_h * 2;
        src.v_addr = phy_src + mr->src_w * mr->src_h + mr->src_w * mr->src_h / 2;
        break;
    case IEP_FORMAT_YCbCr_420_P:
    case IEP_FORMAT_YCbCr_420_SP:
    case IEP_FORMAT_YCrCb_420_P:
    case IEP_FORMAT_YCrCb_420_SP:
        datalen = mr->src_w * mr->src_h * 3 / 2;
        src.v_addr = phy_src + mr->src_w * mr->src_h + mr->src_w * mr->src_h / 4;
        break;
    default:
        ;
    }

    ALOGD("%s %d\n", __func__, __LINE__);

    fread(vir_src, 1, datalen, srcfile);

    int64_t intime = GetTime();
    
    src.act_w = mr->src_w;
    src.act_h = mr->src_h;
    src.x_off = 0;
    src.y_off = 0;
    src.vir_w = mr->src_w;
    src.vir_h = mr->src_h;
    src.format = mr->src_fmt;
    src.mem_addr = phy_src;
    src.uv_addr  = phy_src + mr->src_w * mr->src_h;

    switch (mr->dst_fmt) {
    case IEP_FORMAT_ABGR_8888:
    case IEP_FORMAT_ARGB_8888:
    case IEP_FORMAT_BGRA_8888:
    case IEP_FORMAT_RGBA_8888:
        datalen = mr->dst_w * mr->dst_h * 4;
        break;
    case IEP_FORMAT_BGR_565:
    case IEP_FORMAT_RGB_565:
    case IEP_FORMAT_YCbCr_422_P:
    case IEP_FORMAT_YCbCr_422_SP:
    case IEP_FORMAT_YCrCb_422_P:
    case IEP_FORMAT_YCrCb_422_SP:
        datalen = mr->dst_w * mr->dst_h * 2;
        dst.v_addr = phy_dst + mr->dst_w * mr->dst_h + mr->dst_w * mr->dst_h / 2;
        break;
    case IEP_FORMAT_YCbCr_420_P:
    case IEP_FORMAT_YCbCr_420_SP:
    case IEP_FORMAT_YCrCb_420_P:
    case IEP_FORMAT_YCrCb_420_SP:
        datalen = mr->dst_w * mr->dst_h * 3 / 2;
        dst.v_addr = phy_dst + mr->dst_w * mr->dst_h + mr->dst_w * mr->dst_h / 4;
        break;
    default:
        ;
    }

    dst.act_w = mr->dst_w;
    dst.act_h = mr->dst_h;
    dst.x_off = 0;
    dst.y_off = 0;
    dst.vir_w = mr->dst_w;
    dst.vir_h = mr->dst_h;
    dst.format = mr->dst_fmt;
    dst.mem_addr = phy_dst;
    dst.uv_addr = phy_dst + mr->dst_w * mr->dst_h;

    api->init(&src, &dst);

    switch (mr->testcase) {
    case TEST_CASE_DENOISE:
        {
            FILE *cfgfile = fopen(mr->cfg_url, "r");

            if (cfgfile == NULL) {
                api->config_yuv_denoise();
            } else {
                ;
            }
        }
        break;
    case TEST_CASE_YUVENHANCE:
        {
            FILE *cfgfile = fopen(mr->cfg_url, "r");

            if (cfgfile == NULL) {
                api->config_yuv_enh();
            } else {
                iep_param_YUV_color_enhance_t yuvparam;
                parse_cfg_file(cfgfile, &yuvparam);
                api->config_yuv_enh(&yuvparam);
                fclose(cfgfile);
            }
        }
        break;
    case TEST_CASE_RGBENHANCE:
        {
            FILE *cfgfile = fopen(mr->cfg_url, "r");

            if (cfgfile == NULL) {
                api->config_color_enh();
            } else {
                iep_param_RGB_color_enhance_t rgbparam;
                parse_cfg_file(cfgfile, &rgbparam);
                api->config_color_enh(&rgbparam);
                fclose(cfgfile);
            }
        }
        break;
    case TEST_CASE_DEINTERLACE:
        {
            iep_img src1;
            iep_img dst1;
            iep_param_yuv_deinterlace_t yuv_dil;
            
            fread(vir_src + datalen, 1, datalen, srcfile);
    
            src1.act_w = mr->src_w;
            src1.act_h = mr->src_h;
            src1.x_off = 0;
            src1.y_off = 0;
            src1.vir_w = mr->src_w;
            src1.vir_h = mr->src_h;
            src1.format = mr->src_fmt;
            src1.mem_addr = phy_src + datalen;
            src1.uv_addr  = phy_src + datalen + mr->src_w * mr->src_h;

            dst1.act_w = mr->dst_w;
            dst1.act_h = mr->dst_h;
            dst1.x_off = 0;
            dst1.y_off = 0;
            dst1.vir_w = mr->dst_w;
            dst1.vir_h = mr->dst_h;
            dst1.format = mr->dst_fmt;
            dst1.mem_addr = phy_dst + datalen;
            dst1.uv_addr = phy_dst + datalen + mr->dst_w * mr->dst_h;

            FILE *cfgfile = fopen(mr->cfg_url, "r");

            if (cfgfile == NULL) {
                yuv_dil.high_freq_en = 1;
                yuv_dil.dil_mode = IEP_DEINTERLACE_MODE_I4O1;
                yuv_dil.field_order = FIELD_ORDER_BOTTOM_FIRST;
                yuv_dil.dil_ei_mode = 0;
                yuv_dil.dil_ei_smooth = 0;
                yuv_dil.dil_ei_sel = 0;
                yuv_dil.dil_ei_radius = 0;
            } else {
                parse_cfg_file(cfgfile, &yuv_dil);
                fclose(cfgfile);
            }
            
            api->config_yuv_deinterlace(&yuv_dil, &src1, &dst1);
        }
        break;
    default:
        ;
    }

#if 0
    iep_param_direct_path_interface_t dpi;

    dpi.enable = 1;
    dpi.off_x = 0;
    dpi.off_y = 0;
    dpi.width = mr->dst_w;
    dpi.height = mr->dst_h;
    dpi.layer = 1;
    
    if (0 > api->config_direct_lcdc_path(&dpi)) {
        ALOGE("Failure to Configure DIRECT LCDC PATH\n");
    }
#endif

    if (0 == api->run_sync()) {
        ALOGD("%d success\n", getpid());
    } else {
        ALOGE("%d failure\n", getpid());
    }

    ALOGD("%s consume %lld\n", __func__, GetTime() - intime);

    fwrite(vir_dst, 1, datalen, dstfile);

    fclose(srcfile);
    fclose(dstfile);

    iep_interface::reclaim(api);

    return NULL;
}
コード例 #6
0
ファイル: Stripifier.cpp プロジェクト: xoddark/amd-tootle
//=================================================================================================================================
/// Generates an efficient vertex index buffer from the input vertex indices
///
/// \param pVertexIndicesIN Input vertex index buffer
/// \param uiTriangleCount The number of triangles specified within the input buffer
/// \param pVertexIndicesOUT Output efficient vertex index buffer
///
//=================================================================================================================================
void Stripifier::Process(const unsigned int* pVertexIndicesIN,
                         const unsigned int uiTriangleCount,
                         unsigned int* pVertexIndicesOUT,
                         unsigned int* pnFaceRemapOut)
{
    if (pVertexIndicesIN == NULL)
    {
        pVertexIndicesOUT = NULL;
        return;
    }

    FaceManager faceManager;

    UINT uVertIndexSize = uiTriangleCount * 3;

    faceManager.ResizeFaceRemap(uiTriangleCount);

#ifdef _TIMING
    _TIME tStart = GetTime();
    faceManager.m_tMakeNeighbors = 0;
    faceManager.m_tAdjacency = 0;
    faceManager.m_tDropNeighbors = 0;
    faceManager.m_tAddFaces = 0;
    faceManager.m_tAdjLoop = 0;
    faceManager.m_tPush = 0;
    faceManager.m_tSortBins = 0;
#endif

    // create faces
    for (UINT u = 0; u < uVertIndexSize; u += 3)
    {
        if (false == faceManager.MakeFace(pVertexIndicesIN[u], pVertexIndicesIN[u + 1], pVertexIndicesIN[u + 2], u / 3))
        {
            pVertexIndicesOUT = NULL;
            return;
        }
    }

#ifdef _TIMING
    time_t tFinish = GetTime() - tStart;
    printf("###################\n");
    printf("#Cluster Size: %u\n", uiTriangleCount);
    printf("#\tMake time: %d\n", tFinish);
    printf("#\t\tNeighbors time: %d\n", faceManager.m_tMakeNeighbors);
    printf("#\t\tAdjacLoop time: %d\n", faceManager.m_tAdjLoop);
    printf("#\t\t\tAdjacency time: %d\n", faceManager.m_tAdjacency);
    printf("#\t\tPush Tris time: %d\n", faceManager.m_tPush);
#endif

    // now all faces should be in their respective bins
    faceManager.Stripify();

#ifdef _TIMING
    tFinish = GetTime() - tStart;
    printf("#\tStripify time: %d\n", faceManager.m_tStripify);
    printf("#\t\tSort bins time: %d\n", faceManager.m_tSortBins);
    printf("#\t\tDropNeigh time: %d\n", faceManager.m_tDropNeighbors);
    printf("#\t\tAdd Faces time: %d\n", faceManager.m_tAddFaces);
    printf("#Overall Time: %d\n\n", tFinish);
#endif

    VertList vl = faceManager.GetStrippedList();

    for (UINT u = 0; u < uVertIndexSize; u++)
    {
        pVertexIndicesOUT[ u ] = vl[ u ];
    }

    if (pnFaceRemapOut)
    {
        std::vector<UINT> pnFaceRemap = faceManager.GetFaceRemap();

        for (UINT i = 0; i < uiTriangleCount; i++)
        {
            pnFaceRemapOut[ i ] = pnFaceRemap[ i ];
        }
    }
}
コード例 #7
0
ファイル: gameplayer.cpp プロジェクト: elfring/OHSystem
bool CGamePlayer :: Update( void *fd )
{
    // wait 4 seconds after joining before sending the /whois or /w
    // if we send the /whois too early battle.net may not have caught up with where the player is and return erroneous results

    if( m_WhoisShouldBeSent && !m_Spoofed && !m_WhoisSent && !m_JoinedRealm.empty( ) && GetTime( ) - m_JoinTime >= 4 )
    {
        // todotodo: we could get kicked from battle.net for sending a command with invalid characters, do some basic checking

        for( vector<CBNET *> :: iterator i = m_Game->m_GHost->m_BNETs.begin( ); i != m_Game->m_GHost->m_BNETs.end( ); ++i )
        {
            if( (*i)->GetServer( ) == m_JoinedRealm )
            {
                if( m_Game->GetGameState( ) == GAME_PUBLIC )
                {
                    if( (*i)->GetPasswordHashType( ) == "pvpgn" )
                        (*i)->QueueChatCommand( "/whereis " + m_Name );
                    else
                        (*i)->QueueChatCommand( "/whois " + m_Name );
                }
                else if( m_Game->GetGameState( ) == GAME_PRIVATE )
                    (*i)->QueueChatCommand( m_Game->m_GHost->m_Language->SpoofCheckByReplying( ), m_Name, true );
            }
        }

        m_WhoisSent = true;
    }

    // check for socket timeouts
    // if we don't receive anything from a player for 30 seconds we can assume they've dropped
    // this works because in the lobby we send pings every 5 seconds and expect a response to each one
    // and in the game the Warcraft 3 client sends keepalives frequently (at least once per second it looks like)

    if( m_Socket && GetTime( ) - m_Socket->GetLastRecv( ) >= 30 )
        m_Game->EventPlayerDisconnectTimedOut( this );

    // make sure we're not waiting too long for the first MAPSIZE packet

    /*    	if( m_ConnectionState == 1 && GetTicks( ) - m_ConnectionTime > 5000 && !m_Game->GetGameLoaded() && !m_Game->GetGameLoading() )
        {
            CONSOLE_Print( "[DENY] Kicking player: MAPSIZE not received within five seconds" );
            m_DeleteMe = true;
                SetLeftReason( "MAPSIZE not received within five seconds" );
                SetLeftCode( PLAYERLEAVE_LOBBY );
                m_Game->OpenSlot( m_Game->GetSIDFromPID( GetPID( ) ), false );
            }
    */
    // disconnect if the player is downloading too slowly

    // make this a bit dynamically, first 10 KB/s is a bit too low, increasing to 100KB/s
    //decreasing the checktime to 5 seconds
    // adding an actual playercheck how many players are ingame, if there less than 1 open slots we deny users with a download rate under 500KB/s
    if( m_DownloadStarted && !m_DownloadFinished && !m_Game->GetGameLoaded() && !m_Game->GetGameLoading() && GetLastMapPartSent( ) > 0 && m_Game->m_GHost->m_KickSlowDownloader )
    {
        uint32_t downloadingTime = GetTicks( ) - m_StartedDownloadingTicks;

        if( downloadingTime > 5000 && m_Level < 1)
        {
            if( GetLastMapPartAcked( ) / downloadingTime < 500 && m_Game->GetSlotsOccupied( ) <= 1 )
            {
                m_DeleteMe = true;
                SetLeftReason( "download speed too low" );
                SetLeftCode( PLAYERLEAVE_LOBBY );
                m_Game->SendAllChat( m_Game->m_GHost->m_Language->UserWasKickedForSlowDownloadRate( m_Name ) );
                m_Game->OpenSlot( m_Game->GetSIDFromPID( GetPID( ) ), false );
            }
            else if( GetLastMapPartAcked( ) / downloadingTime < 100 )
            {
                m_DeleteMe = true;
                SetLeftReason( "download speed too low" );
                SetLeftCode( PLAYERLEAVE_LOBBY );
                m_Game->SendAllChat( m_Game->m_GHost->m_Language->UserWasKickedForSlowDownloadRate( m_Name ) );
                m_Game->OpenSlot( m_Game->GetSIDFromPID( GetPID( ) ), false );
            }
        }
    }

    // unmute player
    if( GetMuted( ) && m_MutedAuto && GetTicks( ) - m_MutedTicks > 30000  )
    {
        SetMuted( false );
        m_Game->SendChat( m_PID, "["+m_Game->m_GHost->m_BotManagerName+"] "+m_Game->m_GHost->m_Language->UserWasAutomaticallyUnmuted( ) );
        m_MuteMessages.clear( );
    }

    // GProxy++ acks

    if( m_GProxy && GetTime( ) - m_LastGProxyAckTime >= 10 )
    {
        if( m_Socket )
            m_Socket->PutBytes( m_Game->m_GHost->m_GPSProtocol->SEND_GPSS_ACK( m_TotalPacketsReceived ) );

        m_LastGProxyAckTime = GetTime( );
    }

    // base class update

    CPotentialPlayer :: Update( fd );
    bool Deleting;

    if( m_GProxy && m_Game->GetGameLoaded( ) )
        Deleting = m_DeleteMe || m_Error;
    else
        Deleting = m_DeleteMe || m_Error || m_Socket->HasError( ) || !m_Socket->GetConnected( );

    // try to find out why we're requesting deletion
    // in cases other than the ones covered here m_LeftReason should have been set when m_DeleteMe was set

    if( m_Error )
    {
        m_Game->EventPlayerDisconnectPlayerError( this );
        m_Socket->Reset( );
        return Deleting;
    }

    if( m_Socket )
    {
        if( m_Socket->HasError( ) )
        {
            m_Game->EventPlayerDisconnectSocketError( this );
            m_Socket->Reset( );
        }
        else if( !m_Socket->GetConnected( ) )
        {
            m_Game->EventPlayerDisconnectConnectionClosed( this );
            m_Socket->Reset( );
        }
    }

    return Deleting;
}
コード例 #8
0
ファイル: test_bitcoin.cpp プロジェクト: Xekyo/bitcoin
TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(chainName)
{
    const CChainParams& chainparams = Params();
        // Ideally we'd move all the RPC tests to the functional testing framework
        // instead of unit tests, but for now we need these here.

        RegisterAllCoreRPCCommands(tableRPC);
        ClearDatadirCache();
        pathTemp = fs::temp_directory_path() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(100000)));
        fs::create_directories(pathTemp);
        gArgs.ForceSetArg("-datadir", pathTemp.string());

        // Note that because we don't bother running a scheduler thread here,
        // callbacks via CValidationInterface are unreliable, but that's OK,
        // our unit tests aren't testing multiple parts of the code at once.
        GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);

        mempool.setSanityCheck(1.0);
        pblocktree = new CBlockTreeDB(1 << 20, true);
        pcoinsdbview = new CCoinsViewDB(1 << 23, true);
        pcoinsTip = new CCoinsViewCache(pcoinsdbview);
        if (!LoadGenesisBlock(chainparams)) {
            throw std::runtime_error("LoadGenesisBlock failed.");
        }
        {
            CValidationState state;
            if (!ActivateBestChain(state, chainparams)) {
                throw std::runtime_error("ActivateBestChain failed.");
            }
        }
        nScriptCheckThreads = 3;
        for (int i=0; i < nScriptCheckThreads-1; i++)
            threadGroup.create_thread(&ThreadScriptCheck);
        g_connman = std::unique_ptr<CConnman>(new CConnman(0x1337, 0x1337)); // Deterministic randomness for tests.
        connman = g_connman.get();
        RegisterNodeSignals(GetNodeSignals());
}
コード例 #9
0
ファイル: test_bitcoin.cpp プロジェクト: Bluecoreg/bitcoin
TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(chainName)
{
    const CChainParams& chainparams = Params();
        // Ideally we'd move all the RPC tests to the functional testing framework
        // instead of unit tests, but for now we need these here.

        RegisterAllCoreRPCCommands(tableRPC);
        ClearDatadirCache();
        pathTemp = fs::temp_directory_path() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(100000)));
        fs::create_directories(pathTemp);
        gArgs.ForceSetArg("-datadir", pathTemp.string());

        // We have to run a scheduler thread to prevent ActivateBestChain
        // from blocking due to queue overrun.
        threadGroup.create_thread(boost::bind(&CScheduler::serviceQueue, &scheduler));
        GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);

        mempool.setSanityCheck(1.0);
        pblocktree.reset(new CBlockTreeDB(1 << 20, true));
        pcoinsdbview.reset(new CCoinsViewDB(1 << 23, true));
        pcoinsTip.reset(new CCoinsViewCache(pcoinsdbview.get()));
        if (!LoadGenesisBlock(chainparams)) {
            throw std::runtime_error("LoadGenesisBlock failed.");
        }
        {
            CValidationState state;
            if (!ActivateBestChain(state, chainparams)) {
                throw std::runtime_error("ActivateBestChain failed.");
            }
        }
        nScriptCheckThreads = 3;
        for (int i=0; i < nScriptCheckThreads-1; i++)
            threadGroup.create_thread(&ThreadScriptCheck);
        g_connman = std::unique_ptr<CConnman>(new CConnman(0x1337, 0x1337)); // Deterministic randomness for tests.
        connman = g_connman.get();
        peerLogic.reset(new PeerLogicValidation(connman, scheduler));
}
コード例 #10
0
ファイル: LKHmain.cpp プロジェクト: dcshen/OFEC
ReturnFlag LKH::LKHAlg::run_()
{
	GainType Cost, OldOptimum;
    double Time, LastTime = GetTime();

    if (SubproblemSize > 0) {
        if (DelaunayPartitioning)
            SolveDelaunaySubproblems();
        else if (KarpPartitioning)
            SolveKarpSubproblems();
        else if (KCenterPartitioning)
            SolveKCenterSubproblems();
        else if (KMeansPartitioning)
            SolveKMeansSubproblems();
        else if (RohePartitioning)
            SolveRoheSubproblems();
        else if (MoorePartitioning || SierpinskiPartitioning)
            SolveSFCSubproblems();
        else
            SolveTourSegmentSubproblems();
    }
    AllocateStructures();
    CreateCandidateSet();
    InitializeStatistics();

    if (Norm != 0)
        BestCost = PLUS_INFINITY;
    else {
        /* The ascent has solved the problem! */
        Optimum = BestCost = (GainType) LowerBound;
        UpdateStatistics(Optimum, GetTime() - LastTime);
        RecordBetterTour();
        RecordBestTour();
        WriteTour(OutputTourFileName, BestTour, BestCost);
        WriteTour(TourFileName, BestTour, BestCost);
        Runs = 0;
    }

    /* Find a specified number (Runs) of local optima */
    for (Run = 1; Run <= Runs; Run++) {
        LastTime = GetTime();
        Cost = FindTour();      /* using the Lin-Kernighan heuristic */
        if (*MaxPopulationSize > 1) {
            /* Genetic algorithm */
            int i;
            for (i = 0; i < *PopulationSize; i++) {
                GainType OldCost = Cost;
                Cost = MergeTourWithIndividual(i,this);
                if (TraceLevel >= 1 && Cost < OldCost) {
                    printff("  Merged with %d: Cost = " GainFormat, i + 1,
                            Cost);
                    if (Optimum != MINUS_INFINITY && Optimum != 0)
                        printff(", Gap = %0.4f%%",
                                100.0 * (Cost - Optimum) / Optimum);
                    printff("\n");
                }
            }
            if (!HasFitness(Cost)) {
                if (*PopulationSize < *MaxPopulationSize) {
                    AddToPopulation(Cost,this);
                    if (TraceLevel >= 1)
                        PrintPopulation(this);
                } else if (Cost < Fitness.get()[*PopulationSize - 1]) {
                    i = ReplacementIndividual(Cost,this);
                    ReplaceIndividualWithTour(i, Cost,this);
                    if (TraceLevel >= 1)
                        PrintPopulation(this);
                }
            }
        } else if (Run > 1)
            Cost = MergeBetterTourWithBestTour();
        if (Cost < BestCost) {
            BestCost = Cost;
            RecordBetterTour();
            RecordBestTour();
            WriteTour(OutputTourFileName, BestTour, BestCost);
            WriteTour(TourFileName, BestTour, BestCost);
        }
        OldOptimum = Optimum;
        if (Cost < Optimum) {
            if (FirstNode->InputSuc) {
                Node *N = FirstNode;
                while ((N = N->InputSuc = N->Suc) != FirstNode);
            }
            Optimum = Cost;
            printff("*** New optimum = " GainFormat " ***\n\n", Optimum);
        }
        Time = fabs(GetTime() - LastTime);
        UpdateStatistics(Cost, Time);
        if (TraceLevel >= 1 && Cost != PLUS_INFINITY) {
			printff("Run %d: Cost = " GainFormat, Global::msp_global->m_runId, Cost);
            if (Optimum != MINUS_INFINITY && Optimum != 0)
                printff(", Gap = %0.4f%%",
                        100.0 * (Cost - Optimum) / Optimum);
        //    printff(", Time = %0.2f sec. %s\n\n", Time,
         //           Cost < Optimum ? "<" : Cost == Optimum ? "=" : "");
			printff(", Time = %0.2f sec. \n", Time);
        }
        if (StopAtOptimum && Cost == OldOptimum && *MaxPopulationSize >= 1) {
            Runs = Run;
            break;
        }
        if (*PopulationSize >= 2 &&
            (*PopulationSize == *MaxPopulationSize ||
             Run >= 2 * *MaxPopulationSize) && Run < Runs) {
            Node *N;
            int Parent1, Parent2;
            Parent1 = LinearSelection(*PopulationSize, 1.25,this);
            do
                Parent2 = LinearSelection(*PopulationSize, 1.25,this);
            while (Parent2 == Parent1);
            ApplyCrossover(Parent1, Parent2,this);
            N = FirstNode;
            do {
                int d = (this->*C)(N, N->Suc);
                AddCandidate(N, N->Suc, d, INT_MAX);
                AddCandidate(N->Suc, N, d, INT_MAX);
                N = N->InitialSuc = N->Suc;
            }
            while (N != FirstNode);
        }
		mv_cost[Global::msp_global->m_runId]=Cost;
        SRandom(++Seed);
    }
 //   PrintStatistics();
	freeAll();
	FreeStructures();
	return Return_Terminate;
}
コード例 #11
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x64;
        pchMessageStart[1] = 0x72;
        pchMessageStart[2] = 0xe8;
        pchMessageStart[3] = 0xa6;
        vAlertPubKey = ParseHex("04a82e43bebee0af77bb6d4f830c5b2095b7479a480e91bbbf3547fb261c5e6d1be2c27e3c57503f501480f5027371ec62b2be1b6f00fc746e4b3777259e7f6a78");
        nDefaultPort = 62621;
        nRPCPort = 6420;
        bnProofOfWorkLimit[ALGO_SHA256D] = CBigNum(~uint256(0) >> 20);
        bnProofOfWorkLimit[ALGO_SCRYPT]  = CBigNum(~uint256(0) >> 20);
        bnProofOfWorkLimit[ALGO_GROESTL]   = CBigNum(~uint256(0) >> 20);
        //nSubsidyHalvingInterval = 524160; // ~ every 6 months (2880 blocks per day including all algorithms)

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
  
        const char* pszTimestamp = "Ukraine nearing point of no return - UN";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 1 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("04e941763c7750969e751bee1ffbe96a651a0feb131db046546c219ea40bff40b95077dc9ba1c05af991588772d8daabbda57386c068fb9bc7477c5e28702d5eb9") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = BLOCK_VERSION_DEFAULT;
        genesis.nTime    = 1400582300;
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 263480;
        
        //// debug print
        hashGenesisBlock = genesis.GetHash();
       while (hashGenesisBlock > bnProofOfWorkLimit[ALGO_SCRYPT].getuint256()){
            if (++genesis.nNonce==0) break;
            hashGenesisBlock = genesis.GetHash();
        }

        printf("MAIN: %s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit[ALGO_SHA256D].GetCompact());
        genesis.print();

        assert(hashGenesisBlock == uint256("0x000003070f466e13150a395e05856c99c5f70f9934e1d1cc0aa6dd8024de7743"));
        assert(genesis.hashMerkleRoot == uint256("0xda9dc50395fb1134b8bf04ffff1963ee78b1d7c4b423466b85a5ed352ded5cf5"));

        //vSeeds.push_back(CDNSSeedData("trinity.com", "trinity.com"));
        //vSeeds.push_back(CDNSSeedData("182.18.175.110", "182.18.175.110"));


        base58Prefixes[PUBKEY_ADDRESS] = 30; //Trinity address starts with D
        base58Prefixes[SCRIPT_ADDRESS] = 5;
        base58Prefixes[SECRET_KEY] = 177;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time' 
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
コード例 #12
0
ファイル: mandel_orig.c プロジェクト: cesarpastorini/sthread
int	main(int argc, char *argv[])
{
   pthread_t    *tid;
   double	grid_coord[4];
   double	t0, t1;
   int		i, n, nx, ny, x, y, nthr = 1;
   FILE		*fp;
  
 /* Coordenadas do universo de cálculo */
   
   grid_coord[0] = -2.0;      /*x canto superior esquerdo */
   grid_coord[1] = 1.25;      /*y canto superior esquerdo */
   grid_coord[2] = 0.5;       /*x1 canto inferior direito  */
   grid_coord[3] = -1.25;     /*y1 canto inferior direito  */
 
 /* Inicialização das variáveis para determinar regiões */ 
   
   nx = IMAGE_SIZE/REGION_SIZE;
   ny = IMAGE_SIZE/REGION_SIZE;
   scale_x =  (grid_coord[2] - grid_coord[0]) / IMAGE_SIZE;
   scale_y = -((grid_coord[1] - grid_coord[3]) /IMAGE_SIZE);
   translate_x = grid_coord[0];
   translate_y = grid_coord[1];   

   grid = (char *)malloc(sizeof(char)*IMAGE_SIZE*IMAGE_SIZE);

   counter = nx*ny; 
   work = (struct work_t *)malloc(sizeof(struct work_t)*counter);

   if ( argc == 2 ) 
      nthr = atoi(argv[1]);

   tid = (pthread_t *)malloc(sizeof(pthread_t)*nthr);
   if ( tid == NULL || work == NULL || grid == NULL) {
      printf("Memory allocation error...\n");
      exit(0);
   }

   /* Definição da unidade de trabalho: cada uma é uma região delimitada
    * pelas diagonais de coordenadas (ulx,uly) e (urx, ury).
    */

   i = 0;
   for(y = 0; y < IMAGE_SIZE; y += REGION_SIZE)
      for(x = 0; x < IMAGE_SIZE; x += REGION_SIZE) {
         work[i].ulx = x;
         work[i].uly = y;
         work[i].lrx = (x + REGION_SIZE > IMAGE_SIZE)? IMAGE_SIZE - 1 : x + REGION_SIZE - 1;
	 work[i].lry = (y + REGION_SIZE > IMAGE_SIZE)? IMAGE_SIZE - 1 : y + REGION_SIZE - 1;
         i++;
   }

   /* Efetua a criação de 'nthr' th reads para avaliar o fractal de Mandelbrot e espera até
    * que todas as threads não tenham mais trabalho para realizar.
    */

   printf("\nCalculando com %d threads... espere, por favor!\n", nthr);
   t0 = GetTime();
   for (i = 0; i < nthr; i++)
       pthread_create(&tid[i], NULL, (void *)evaluate, NULL);

   for (i = 0; i < nthr; i++)
       pthread_join(tid[i], NULL);
 
   t1 = GetTime();

   printf("--------------------------------------------\n");
   printf("Execution time for %2d threads: %.2f usecs\n", nthr, t1-t0);
   printf("--------------------------------------------\n");

 /* Geração de um arquivo ppm para a conferência visual de que o Fractal de Mandelbrot foi
  * calculado corretamente.
  */

   fp = fopen("mandel.ppm", "w");
   if (fp == NULL ) {
       printf("File open error...\n");
       exit(0);
   }
  
   fprintf(fp,"P3\n");
   fprintf(fp,"%d %d\n",IMAGE_SIZE, IMAGE_SIZE);
   fprintf(fp,"7\n");

   for(n=0; n < IMAGE_SIZE*IMAGE_SIZE; n++)
      fprintf(fp,"%d %d %d \n", (grid[n]>>5)&6, (grid[n]>>3)&7, (grid[n])&7);
		  
   fprintf(fp,"\n");
 
   fclose(fp);
   free(grid);
   free(work);
   free(tid);
   exit(0);
}
コード例 #13
0
	/**
	 * Adjusts the servo gimbal based on the color tracked.
	 * Driving the robot or operating an arm based on color input from gimbal-mounted 
	 * camera is currently left as an exercise for the teams.
	 */
	void Autonomous(void)
	{
		DPRINTF(LOG_DEBUG, "Autonomous");				
		
		DPRINTF(LOG_DEBUG, "SERVO - looking for COLOR %s ABOVE %s", td2.name, td1.name);
		
		// initialize position and destination variables
		// position settings range from -1 to 1
		// setServoPositions is a wrapper that handles the conversion to range for servo 
		horizontalDestination = 0.0;		// final destination range -1.0 to +1.0
		verticalDestination = 0.0;
		
		// initialize pan variables
		// incremental tasking toward dest (-1.0 to 1.0)
		float incrementH, incrementV;
		// pan needs a 1-up number for each call
		int panIncrement = 0;							
		
		// current position range -1.0 to +1.0
		horizontalPosition = RangeToNormalized(horizontalServo->Get(),1);	
		verticalPosition = RangeToNormalized(verticalServo->Get(),1);			
		
		// set servos to start at center position
		setServoPositions(horizontalDestination, verticalDestination);

		// for controlling loop execution time 
		float loopTime = 0.1;		
		//float loopTime = 0.05;											
		double currentTime = GetTime();
		double lastTime = currentTime;
										
		// search variables 
		bool foundColor = 0; 
		double savedImageTimestamp = 0.0;
		bool staleImage = false; 
				
		while( IsAutonomous() )	
		{
			//GetWatchdog().Feed();		// turn watchdog off while debugging	

			// calculate gimbal position based on colors found 
			if ( FindTwoColors(td1, td2, ABOVE, &par1, &par2) ){
				//PrintReport(&par2);
				foundColor = true;
				// reset pan		
				panIncrement = 0;  		
				if (par1.imageTimestamp == savedImageTimestamp) {
					// This image has been processed already, 
					// so don't do anything for this loop 
					staleImage = true;
					DPRINTF(LOG_DEBUG, "STALE IMAGE");
					
				} else {
					// The target was recognized
					// save the timestamp
					staleImage = false;
					savedImageTimestamp = par1.imageTimestamp;	
					DPRINTF(LOG_DEBUG,"image timetamp: %lf", savedImageTimestamp);

					// Here is where your game-specific code goes
					// when you recognize the target
					
					// get center of target 
					// Average the color two particles to get center x & y of combined target
					horizontalDestination = (par1.center_mass_x_normalized + par2.center_mass_x_normalized) / 2;	
					verticalDestination = (par1.center_mass_y_normalized + par2.center_mass_y_normalized) / 2;							
				}
			} else {  // need to pan 
				foundColor = false;
			} 
								
			if(foundColor && !staleImage) {	
				/* Move the servo a bit each loop toward the destination.
				 * Alternative ways to task servos are to move immediately vs.
				 * incrementally toward the final destination. Incremental method
				 * reduces the need for calibration of the servo movement while
				 * moving toward the target.
				 */
				incrementH = horizontalDestination - horizontalPosition;
				// you may need to reverse this based on your vertical servo installation
				//incrementV = verticalPosition - verticalDestination;
				incrementV = verticalDestination - verticalPosition;
				adjustServoPositions( incrementH, incrementV );  
				
				ShowActivity ("** %s & %s found: Servo: x: %f  y: %f ** ", 
						td1.name, td2.name, horizontalDestination, verticalDestination);	
				
			} else { //if (!staleImage) {  // new image, but didn't find two colors
				
				// adjust sine wave for panning based on last movement direction
				if(horizontalDestination > 0.0)	{ sinStart = PI/2.0; }
				else { sinStart = -PI/2.0; }

				/* pan to find color after a short wait to settle servos
				 * panning must start directly after panInit or timing will be off */				
				if (panIncrement == 3) {
					panInit(8.0);		// number of seconds for a pan
				}
				else if (panIncrement > 3) {					
					panForTarget(horizontalServo, sinStart);	
					
					/* Vertical action: In case the vertical servo is pointed off center,
					 * center the vertical after several loops searching */
					if (panIncrement == 20) { verticalServo->Set( 0.5 );	}
				}
				panIncrement++;		

				ShowActivity ("** %s and %s not found                                    ", td1.name, td2.name);
			}  // end if found color

			// sleep to keep loop at constant rate
			// this helps keep pan consistant
			// elapsed time can vary significantly due to debug printout
			currentTime = GetTime();			
			lastTime = currentTime;					
			if ( loopTime > ElapsedTime(lastTime) ) {
				Wait( loopTime - ElapsedTime(lastTime) );	// seconds
			}			
		}  // end while
	
		DPRINTF(LOG_DEBUG, "end Autonomous");
		ShowActivity ("Autonomous end                                            ");
		
	}  // end autonomous
コード例 #14
0
ファイル: slog.cpp プロジェクト: yohoj/ITS
//    3. 写日志
// modename - 模块名称
// leve – 日志级别
// fmt – 格式化的字符串(日志内容)
bool SLog::Log(const char *modname, int level,  const char *fmt, ...)
{

    bool b = false;
    if(Init(level) == false)
    {
        return false;
    }
    time_t t;
    struct tm tm;
    t = time(NULL);
    localtime_r(&t,&tm);
    char curtime[32];
    int len = 0;
    va_list ap;
    strcpy(curtime,GetTime());
    curtime[strlen(curtime)-1] = '\0';
    char LEVEL[8];
    switch(level)
    {
    case DEBUG:
        strcpy(LEVEL,"DEBUG");
        break;
    case COMMON:
        strcpy(LEVEL,"COMMON");
        break;
    case WARNING:
        strcpy(LEVEL,"WARNING");
        break;
    case ERROR:
        strcpy(LEVEL,"ERROR");
        break;
    }
    len = snprintf(log,MAX_LOG_LENGTH,"[%04d-%02d-%02d %02d:%02d:%02d][%s][%s]:",
                   tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec,modname,LEVEL);
    va_start(ap,fmt);
    len = vsnprintf(log+len,MAX_LOG_LENGTH-len,fmt,ap);
    va_end(ap);
    if(level == DEBUG)
    {
        cout<<log<<endl;
        return true;
    }
    if(level >= 2)
    {
        cout<<log<<endl;
    }
   if(lseek(fd,0,SEEK_END) == -1)
   {
       fd = open(filename,O_RDWR|O_CREAT,0666);
       lseek(fd,0,SEEK_END);
   }
   len = write(fd,log,strlen(log));
   if(len <= 0)
   {
       perror("write");
       return false;
   }
   write(fd,"\n",strlen("\n"));

   //  SetOutputStd(b);
    return true;
}
コード例 #15
0
ファイル: Stripifier.cpp プロジェクト: xoddark/amd-tootle
//=================================================================================================================================
/// Makes a Face from the specified vertex indices and associates it with neighbors that have already been created
///
/// \param uVertexIndex1 the first vertex index of the face
/// \param uVertexIndex2 the second vertex index of the face
/// \param uVertexIndex3 the third vertex index of the face
/// \param nID           the ID of the face
///
/// \return false if memory could not be allocated for the face; true otherwise
//=================================================================================================================================
bool FaceManager::MakeFace(UINT uVertexIndex1, UINT uVertexIndex2, UINT uVertexIndex3, UINT nID)
{
#ifdef _TIMING
    _TIME tMNStart;
    _TIME tAdjStart;

    tMNStart = GetTime();
#endif
    Face* pFace;

    try
    {
        pFace = new Face(uVertexIndex1, uVertexIndex2, uVertexIndex3);
    }
    catch (std::bad_alloc&)
    {
        // ran out of memory
        return false;
    }

#ifdef _TIMING
    m_tMakeNeighbors += GetTime() - tMNStart;

    tMNStart = GetTime();
#endif

    int nAdjacency = -1;
    Face* pIterFace = NULL;

    for (FaceRefList::iterator f = m_faces.begin(); f != m_faces.end() && pFace->Degree() < 3; f++)
    {
        pIterFace = *f;

        // finding adjacency is expensize, only do it if the face doesn't already have three neighbors
        if (pIterFace->Degree() < 3)
        {
#ifdef _TIMING
            tAdjStart = GetTime();
#endif
            nAdjacency = GetFaceAdjacency(*pFace, *pIterFace);

#ifdef _TIMING
            m_tAdjacency += (GetTime() - tAdjStart);
#endif

            if (nAdjacency >= 0)
            {
                pFace->AddNeighbor(pIterFace, (nAdjacency / 10));
                pIterFace->AddNeighbor(pFace, (nAdjacency % 10));
            }
        }
    }

#ifdef _TIMING
    m_tAdjLoop += (GetTime() - tMNStart);

    tMNStart = GetTime();
#endif

    // set ID for the face.  This is used for computing faceRemap.
    pFace->SetID(nID);

    // add to the total list of faces
    // push front since this face is likely to be used in upcoming faces
    // and the loop above will work best if the neighbors are found early
    m_faces.push_front(pFace);
#ifdef _TIMING
    m_tPush += GetTime() - tMNStart;
#endif
    return true;
}
コード例 #16
0
void CMasternode::Check(bool fForce)
{
    AssertLockHeld(cs_main);
    LOCK(cs);

    if (ShutdownRequested()) return;

    if (!fForce && (GetTime() - nTimeLastChecked < MASTERNODE_CHECK_SECONDS)) return;
    nTimeLastChecked = GetTime();

    LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is in %s state\n", outpoint.ToStringShort(), GetStateString());

    //once spent, stop doing the checks
    if (IsOutpointSpent()) return;

    int nHeight = 0;
    if (!fUnitTest) {
        Coin coin;
        if (!GetUTXOCoin(outpoint, coin)) {
            nActiveState = MASTERNODE_OUTPOINT_SPENT;
            LogPrint(MCLog::MN, "CMasternode::Check -- Failed to find Masternode UTXO, masternode=%s\n", outpoint.ToStringShort());
            return;
        }

        nHeight = chainActive.Height();
    }

    if (IsPoSeBanned()) {
        if (nHeight < nPoSeBanHeight) return; // too early?
        // Otherwise give it a chance to proceed further to do all the usual checks and to change its state.
        // Masternode still will be on the edge and can be banned back easily if it keeps ignoring mnverify
        // or connect attempts. Will require few mnverify messages to strengthen its position in mn list.
        LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is unbanned and back in list now\n", outpoint.ToStringShort());
        DecreasePoSeBanScore();
    } else if (nPoSeBanScore >= MASTERNODE_POSE_BAN_MAX_SCORE) {
        nActiveState = MASTERNODE_POSE_BAN;
        // ban for the whole payment cycle
        nPoSeBanHeight = nHeight + mnodeman.size();
        LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is banned till block %d now\n", outpoint.ToStringShort(), nPoSeBanHeight);
        return;
    }

    int nActiveStatePrev = nActiveState;
    bool fOurMasternode = fMasternodeMode && activeMasternode.pubKeyMasternode == pubKeyMasternode;

    // masternode doesn't meet payment protocol requirements ...
    bool fRequireUpdate = nProtocolVersion < mnpayments.GetMinMasternodePaymentsProto() ||
                          // or it's our own node and we just updated it to the new protocol but we are still waiting for activation ...
                          (fOurMasternode && nProtocolVersion < PROTOCOL_VERSION);

    if (fRequireUpdate) {
        nActiveState = MASTERNODE_UPDATE_REQUIRED;
        if (nActiveStatePrev != nActiveState) {
            LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString());
        }
        return;
    }

    // keep old masternodes on start, give them a chance to receive updates...
    bool fWaitForPing = !masternodeSync.IsMasternodeListSynced() && !IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS);

    if (fWaitForPing && !fOurMasternode) {
        // ...but if it was already expired before the initial check - return right away
        if (IsExpired() || IsSentinelPingExpired() || IsNewStartRequired()) {
            LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is in %s state, waiting for ping\n", outpoint.ToStringShort(), GetStateString());
            return;
        }
    }

    // don't expire if we are still in "waiting for ping" mode unless it's our own masternode
    if (!fWaitForPing || fOurMasternode) {
        if (!IsPingedWithin(MASTERNODE_NEW_START_REQUIRED_SECONDS)) {
            nActiveState = MASTERNODE_NEW_START_REQUIRED;
            if (nActiveStatePrev != nActiveState) {
                LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString());
            }
            return;
        }

        if (!IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS)) {
            nActiveState = MASTERNODE_EXPIRED;
            if (nActiveStatePrev != nActiveState) {
                LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString());
            }
            return;
        }

        // part 1: expire based on machinecoind ping
        bool fSentinelPingActive = masternodeSync.IsSynced() && mnodeman.IsSentinelPingActive();
        bool fSentinelPingExpired = fSentinelPingActive && !IsPingedWithin(MASTERNODE_SENTINEL_PING_MAX_SECONDS);
        LogPrint(MCLog::MN, "CMasternode::Check -- outpoint=%s, GetAdjustedTime()=%d, fSentinelPingExpired=%d\n",
            outpoint.ToStringShort(), GetAdjustedTime(), fSentinelPingExpired);

        if (fSentinelPingExpired) {
            nActiveState = MASTERNODE_SENTINEL_PING_EXPIRED;
            if (nActiveStatePrev != nActiveState) {
                LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString());
            }
            return;
        }
    }

    // We require MNs to be in PRE_ENABLED until they either start to expire or receive a ping and go into ENABLED state
    // Works on mainnet/testnet only and not the case on regtest.
    if (Params().NetworkIDString() != CBaseChainParams::REGTEST) {
        if (lastPing.sigTime - sigTime < MASTERNODE_MIN_MNP_SECONDS) {
            nActiveState = MASTERNODE_PRE_ENABLED;
            if (nActiveStatePrev != nActiveState) {
                LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString());
            }
            return;
        }
    }

    if (!fWaitForPing || fOurMasternode) {
        // part 2: expire based on sentinel info
        bool fSentinelPingActive = masternodeSync.IsSynced() && mnodeman.IsSentinelPingActive();
        bool fSentinelPingExpired = fSentinelPingActive && !lastPing.fSentinelIsCurrent;

        LogPrint(MCLog::MN, "CMasternode::Check -- outpoint=%s, GetAdjustedTime()=%d, fSentinelPingExpired=%d\n",
            outpoint.ToStringShort(), GetAdjustedTime(), fSentinelPingExpired);

        if (fSentinelPingExpired) {
            nActiveState = MASTERNODE_SENTINEL_PING_EXPIRED;
            if (nActiveStatePrev != nActiveState) {
                LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString());
            }
            return;
        }
    }

    nActiveState = MASTERNODE_ENABLED; // OK
    if (nActiveStatePrev != nActiveState) {
        LogPrint(MCLog::MN, "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString());
    }
}
コード例 #17
0
ファイル: Stripifier.cpp プロジェクト: xoddark/amd-tootle
//=================================================================================================================================
/// Generates an efficient list from the previously created faces
///
/// \return true
//=================================================================================================================================
bool FaceManager::Stripify(void)
{
#ifdef _TIMING
    _TIME tStartStripify = GetTime();
#endif

    for (FaceRefList::iterator iFace = m_faces.begin(); iFace != m_faces.end(); iFace++)
    {
        m_degreeBins[(*iFace)->Degree() ].push_front(*iFace);
    }

#ifdef _TIMING
    m_tSortBins += (GetTime() - tStartStripify);
#endif

    UINT uWalkMode = START;
    UINT uFirstTurn = START;

    UINT nodesLeft = (UINT)m_faces.size();
    bool bFirstDirection = true;
    bool bRepeatedTurn = false;
    int stripIndex = -1;
    FaceStrips strips;
    Face* pCurFace = NULL;

    // variables that need to get declared before the switch statement
    Face* pNextFace = NULL;
    Face* pGateFace = NULL;
    UINT uGateEdge;
    UINT uBackEdge = 0;
    UINT uFirstEdge = 1;

    // make sure that the starting edge is in the 0-2 range
    uFirstEdge %= 3;

    while (nodesLeft > 0)
    {
        if (uWalkMode == START)
        {
            bFirstDirection = true;
            stripIndex++;
            strips.push_back(FaceStrip());

            pCurFace = NULL;

            // stop when a face with lowest degree is found
            // this means we'll start along edges and the strip will work its way inward
            // Provided good improvement (~10%)
            for (UINT uDegree = 0; uDegree < 4 && pCurFace == NULL; uDegree++)
            {
                if (m_degreeBins[uDegree].size() > 0)
                {
                    // pick a face that has not already been processed
                    for (FaceRefList::iterator iter = m_degreeBins[uDegree].begin();
                         iter != m_degreeBins[uDegree].end() && pCurFace == NULL;
                         iter++)
                    {
                        if (*iter != NULL && (*iter)->WasProcessed() == false)
                        {
                            pCurFace = *(iter);
                        }
                    }
                }
            }

            // first face has been chosen
            // now choose the direction to travel
            uGateEdge = uFirstEdge;
            pNextFace = NULL;
            UINT uLowestDegree = 4;

            for (UINT uEdge = 0; uEdge < 3; uEdge++)
            {
                // use GateFace as a temporary place holder
                pGateFace = pCurFace->GetNeighbors()[(uFirstEdge + uEdge) % 3 ];

                if (pGateFace != NULL && pGateFace->WasProcessed() == false)
                {
                    if (pGateFace->Degree() < uLowestDegree)
                    {
                        // make the next face the neighbor with the highest degree
                        uLowestDegree = pGateFace->Degree();
                        pNextFace = pGateFace;
                        uGateEdge = (uFirstEdge + uEdge) % 3;
                        uBackEdge = pNextFace->GetEdge(pCurFace);
                    }
                }
            }

            // Add first face in this strip
            AddFaceToStrip(pCurFace, strips[ stripIndex ], START, uGateEdge);
            nodesLeft--;

            if (pNextFace != NULL)
            {
                uWalkMode = LEFT;
                uFirstTurn = START;
            }
            else
            {
                // no next face found
                uWalkMode = FINISH;
            }
        } // end if uWalkMode == START

        if (uWalkMode == RIGHT)
        {
            UINT uEnterEdge = uBackEdge;
            pCurFace = pNextFace;
            pNextFace = NULL;
            uGateEdge = (uBackEdge + 1) % 3;
            pGateFace = pCurFace->GetNeighbors()[ uGateEdge ];

            if (pGateFace != NULL && pGateFace->WasProcessed() == false)
            {
                bRepeatedTurn = false;
                pNextFace = pGateFace;
                uBackEdge = pNextFace->GetEdge(pCurFace);
                uWalkMode = LEFT;

                if (uFirstTurn == START)
                {
                    uFirstTurn = RIGHT;
                }
            }
            else
            {
                // continuing to the right, need to indicate that it is a
                // repeated turn, so the output of the vertices should be different!
                bRepeatedTurn = true;
                uGateEdge = (uBackEdge + 2) % 3;
                pGateFace = pCurFace->GetNeighbors()[ uGateEdge ];

                if (pGateFace != NULL && pGateFace->WasProcessed() == false)
                {
                    pNextFace = pGateFace;
                    uBackEdge = pNextFace->GetEdge(pCurFace);

                    if (uFirstTurn == START)
                    {
                        uFirstTurn = LEFT;
                    }
                }
            }

            if (bRepeatedTurn)
            {
                AddFaceToStrip(pCurFace, strips[ stripIndex ], LEFT, uEnterEdge);
            }
            else
            {
                AddFaceToStrip(pCurFace, strips[ stripIndex ], RIGHT, uEnterEdge);
            }

            nodesLeft--;

            if (pNextFace == NULL)
            {
                uWalkMode = FINISH;
            }
        }
        else if (uWalkMode == LEFT)
        {
            UINT uEnterEdge = uBackEdge;
            pCurFace = pNextFace;
            pNextFace = NULL;
            uGateEdge = (uBackEdge + 2) % 3;
            pGateFace = pCurFace->GetNeighbors()[ uGateEdge ];

            if (pGateFace != NULL && pGateFace->WasProcessed() == false)
            {
                bRepeatedTurn = false;
                pNextFace = pGateFace;
                uBackEdge = pNextFace->GetEdge(pCurFace);
                uWalkMode = RIGHT;

                if (uFirstTurn == START)
                {
                    uFirstTurn = LEFT;
                }
            }
            else
            {
                // continuing to the left, need to indicate that it is a
                // repeated turn, so the output of the vertices should be different!
                bRepeatedTurn = true;
                uGateEdge = (uBackEdge + 1) % 3;
                pGateFace = pCurFace->GetNeighbors()[ uGateEdge ];

                if (pGateFace != NULL && pGateFace->WasProcessed() == false)
                {
                    pNextFace = pGateFace;
                    uBackEdge = pNextFace->GetEdge(pCurFace);

                    if (uFirstTurn == START)
                    {
                        uFirstTurn = RIGHT;
                    }
                }
            }

            if (bRepeatedTurn)
            {
                AddFaceToStrip(pCurFace, strips[ stripIndex ], RIGHT, uEnterEdge);
            }
            else
            {
                AddFaceToStrip(pCurFace, strips[ stripIndex ], LEFT, uEnterEdge);
            }

            nodesLeft--;

            if (pNextFace == NULL)
            {
                uWalkMode = FINISH;
            }
        }

        if (uWalkMode == FINISH)
        {
            bRepeatedTurn = false;
            uWalkMode = START;

            //int nStrips = strips.size() -1;
            //int nTris = strips[ nStrips ].size();
            //if ( nTris > 2 )
            //{
            //   printf( " %d,", nTris );
            //   printf( "\nRotated list:" );
            //   int nRecentVertsStart = m_vertList.size() - (nTris*3);
            //   for ( int i = nRecentVertsStart; i < m_vertList.size(); i+=3 )
            //   {
            //      printf( " %2d %2d %2d,", m_vertList[i], m_vertList[i+1], m_vertList[i+2] );
            //   }
            //   printf("\n");
            //}

        }
    }

    // At this point, the strips should have all the data in them,
    // the triangles are in a good strip order, but the vertices may
    // have to be rotated to make it have good 2 vertex cache reuse
    //for ( UINT i = 0; i < strips.size(); i++ )
    //{
    //   printf( "\nStrip %3d has %4d triangles:", i, strips[i].size() );
    //   for ( FaceStrip::iterator fsi = strips[i].begin(); fsi != strips[i].end(); fsi++ )
    //   {
    //      printf( " %2d %2d %2d,", (*fsi)->First(), (*fsi)->Second(), (*fsi)->Third() );
    //   }
    //}
    //printf( "\nRotated list:" );
    //for ( UINT i = 0; i < m_vertList.size(); i+=3 )
    //{
    //   printf( " %2d %2d %2d,", m_vertList[i], m_vertList[i+1], m_vertList[i+2] );
    //}
    //printf("\n");

#ifdef _TIMING
    m_tStripify = GetTime() - tStartStripify;
#endif

    return true;
}
コード例 #18
0
ファイル: isdf06.cpp プロジェクト: Nielk1/bz2-sp-fixes
void isdf06Mission::Execute(void)
{

    /*
    	Stuff in 6
    	You are responsible for
    	the northern aproach to the base
    	Alien units approach from the south
    	and you battle them.

    	Shabayev discovers a scrap pool.
    	She highlights it.
    	You must go to it and destroy a
    	scion scavenger.

    	You are given control of
    	constructor.  Your job is to build
    	a bunker and a gun tower around it
    	to protect it.

    	Once the bunker is built
    	you are told to go on the
    	offensive.


    	At the first place
    	you go you find the
    	voyager probe.

    	The second is the
    	climatic battle.
    */

    player = GetPlayerHandle();

    if (!start_done)
    {
        start_done=true;
        /*
        	This is one of our three
        	key bases on the Planet
        	You must defend this approach.
        */
        ClearObjectives();
        AddObjective("isdf0601.otf",WHITE,20.0f);
        AudioMessage("isdf0601.wav");
        // Manson:
        // Prepare for enemy attacks
        // You are a reserve for a counter attack
        // or in case they break through.
        attack_wave_time=GetTime()+10.0f;
        wave_launched=false;
        SetScrap(1,20);
        SetIndependence(escav,0);
        escav=BuildObject("fvscav",2,"pool");
        Goto(escav,scrap_pool,0);
        Handle temp=GetHandle("gtow1");
        AddHealth(temp,-2500);
        temp=GetHandle("gtow2");
        AddHealth(temp,-2500);
        GiveWeapon(player, "gshadow_c");
        /*
        turret1=BuildObject("ivturr",3,"turret1");
        turret2=BuildObject("ivturr",3,"turret2");
        Deploy(turret1);
        Deploy(turret2);
        */
    }

    if ((!IsAlive(constructor)) && (mission_state>1) && (mission_state!=99))
    {
        // you loose
        AudioMessage("isdf0607.wav");
        // Manson:
        // That constructor was vital
        // to our effort.  I'm pulling
        // back immeadiately.
        FailMission(GetTime()+15.0f,"isdf06l2.txt");
        mission_state=99;  // out of the loop
    }

    switch (mission_state)
    {
    case 0: // attack starts
        if ((!warning) &&
                (GetDistance(atk1,turret1)<250.0f))
        {
            AudioMessage("isdf0602.wav");
            warning=true;
        }
        if ((!wave_launched) && (GetTime()>attack_wave_time))
        {
            atk1=BuildObject("fvtank",2,"attack_start1");
            Goto(atk1,"attack_path1");
            SetSkill(atk1,3);
            atk2=BuildObject("fvtank",2,"attack_start1");
            Goto(atk2,"attack_path1");
            SetSkill(atk2,3);
            atk3=BuildObject("fvsent",2,"attack_start1");
            Goto(atk3,"attack_path1");
            SetSkill(atk3,3);
            atk4=BuildObject("fvsent",2,"attack_start1");
            Goto(atk4,"attack_path1");
            SetSkill(atk4,3);
            atk5=BuildObject("fvtank",2,"attack_start2");
            Goto(atk5,"attack_path2");
            SetSkill(atk5,3);
            atk6=BuildObject("fvtank",2,"attack_start2");
            Goto(atk6,"attack_path2");
            SetSkill(atk6,3);
            atk7=BuildObject("fvsent",2,"attack_start2");
            Goto(atk7,"attack_path2");
            SetSkill(atk7,3);
            //		atk8=BuildObject("fvsent",2,"attack_start2");
            //		Goto(atk8,"attack_path2");
            //		SetSkill(atk8,3);
            wave_launched=true;
        }
        if ((wave_launched) && (!IsAlive(atk1))
                && (!IsAlive(atk2))
                && (!IsAlive(atk3))
                && (!IsAlive(atk4))
                && (!IsAlive(atk5))
                && (!IsAlive(atk6))
                && (!IsAlive(atk7))
                && (!IsAlive(atk8)))
        {
            warning=false;
            wave_launched=false;
            wave_count++;
            if (!repair_hint)
            {
                repair_hint=true;
                AudioMessage("isdf0612.wav");
                /*
                	MANSON
                	Take advantage of the
                	breaks between attacks
                	to repair your forces at the service
                	bay.
                */
            }
            if (wave_count==2)
            {
                back1=BuildObject("fvarch",2,"back1");
                Goto(back1,"back_door");
                back2=BuildObject("fvarch",2,"back2");
                Goto(back2,"back_door");
                back3=BuildObject("fvsent",2,"back3");
                Goto(back3,"back_door");
                SetObjectiveOn(back1);
                AudioMessage("isdf0614.wav");
            }
            if (wave_count>(2)) //was 2
            {
                if ((!IsAlive(back1))
                        && (!IsAlive(back2))
                        && (!IsAlive(back3)))
                {

                    mission_state++;
                    SetObjectiveOn(escav);
                    ClearObjectives();
                    AddObjective("isdf0602.otf",WHITE,10.0f);
                    AudioMessage("isdf0603.wav");
                    // Shabayev
                    // I have detected the scavenger
                    // which is supplying the enemy.
                    // Its time to counter attack.
                    // Manson
                    // Alright, Cooke, you heard
                    // the lieutenant.  Get that
                    // scavenger
                    AudioMessage("isdf0604.wav");
                }
            }
            else attack_wave_time=GetTime()+5.0f;
            // hold back your forces
            if ((GetDistance(turret1,mbike1)<50.0f) && (!defend_warning))
            {
                AudioMessage("isdf0610.wav");
                // MansoN:
                // Cooke, hold back your forces.
                defend_warning=true;

            }
        }
        break;
    case 1: // shabayev highlights the scavenger
        /*
        */
        if (scav_count<3)
        {
            FailMission(GetTime()+5.0f,"isdf06l1.txt");
            mission_state=99;
        }
        else
        {

            if ((GetDistance(player,escav)<150.0f)
                    && (!got_to_scav))
            {
                AudioMessage("isdf0605.wav");
                // Shabayev: Attack!
                got_to_scav=true;

            }
            if (!IsAlive(escav))
            {
                ClearObjectives();
                AddObjective("isdf0603.otf",WHITE,10.0f);

                constructor=BuildObject("ivcon6",1,"constructor_spawn");
                int grp=GetFirstEmptyGroup();
                SetGroup(constructor,grp);
                Goto(constructor,"pool",0);

                mission_state++;
                AudioMessage("isdf0606.wav");
                // Manson:
                // Cooke, I'm sending you a
                // constructor to fortify your
                // position.  Use the constructor
                // to build defenses around that
                // scrap pool.
            }
        }
        break;
    case 2:	 // you get a constructor
        if (GetDistance(constructor,"pool")<250.0f)
        {
            AudioMessage("isdf0611.wav");
            // Shabayev
            // Build a communications bunker to
            // anchor the base.
            // Once you have a communications bunker
            // build two adjacent
            // gun towers
            // The gun towers will be powered from
            // the surplus power of the main base.
            // Good luck.

            ConstructionMessage();
            // spawn in attackers
            scout1=BuildObject("fvscout",2,"patrol_spawn");
            scout2=BuildObject("fvscout",2,"patrol_spawn");
            if (IsAlive(mbike1))
            {
                Attack(scout1,player);
            }
            else
            {
                Attack(scout1,player);
            }
            if (IsAlive(mbike2))
            {
                Attack(scout2,player);
            }
            else Attack(scout2,mbike2);
            mission_state++;
        }

        break;
    case 3:
        if ((!IsAlive(scout1)) && (!IsAlive(scout2)))
        {
            scout1=BuildObject("fvscout",2,"patrol_spawn");
            scout2=BuildObject("fvscout",2,"patrol_spawn");
            if (IsAlive(mbike1))
            {
                Attack(scout1,mbike1);
            }
            else Attack(scout1,player);
            if (IsAlive(mbike2))
            {
                Attack(scout2,mbike2);
            }
            else	Attack(scout2,player);
        }
        if ((cbunker!=NULL) && (guntow1!=NULL)
                && (guntow2!=NULL))
        {
            AudioMessage("isdf0608.wav");
            /*
            	Manson:
            	Great!
            	I'm sending a scavenger to secure
            	that pool.
            	Prepare for further orders.

            */
            // more cannon foder to get pulverized
            atk1=BuildObject("fvtank",2,"patrol_spawn1");
            Attack(atk1,guntow1);  // cannon foder
            atk2=BuildObject("fvtank",2,"patrol_spawn2");
            Attack(atk2,guntow2);  // cannon foder

            // FraKTal says this scav doesn't want to deploy on its
            // own. So, put it under 100% human control - NM 6/27/03
#if 0
            // was
            scav=BuildObject("ivscav",3,"constructor_spawn");
#else
            // now
            scav=BuildObject("ivscav",1,"constructor_spawn");
#endif

            Goto(scav,"pool");
            ClearObjectives();
            AddObjective("isdf0607.otf",WHITE,10.0f);
            mission_state++;
        }
        break;
    case 4:  // when the scavenger gets there-- attack!!
        if (GetDistance(scav,"pool")<100.0f)
        {
            AudioMessage("isdf0609.wav");
            AudioMessage("isdf0613.wav");
            // Shabayev:
            // Its time we finish them off.
            // All forces, converge on the enemy base!
            SetObjectiveOn(goal);
            mission_state++;
            // spawn in patrols
            atk1=BuildObject("fvtank",2,"patrol_spawn2");
            atk2=BuildObject("fvtank",2,"patrol_spawn2");
            atk3=BuildObject("fvsent",2,"patrol_spawn");
            atk4=BuildObject("fvsent",2,"patrol_spawn");
            Patrol(atk1,"patrol");
            Patrol(atk2,"patrol");
            Patrol(atk3,"patrol");
            Patrol(atk4,"patrol");
            // spawn in attackers
            atk1=BuildObject("ivtank",3,"constructor_spawn");
            atk2=BuildObject("ivtank",3,"constructor_spawn");
            Goto(atk1,goal);
            Goto(atk2,goal);
            BuildObject("ibbomb",1,"bomber");  // you get a bomber
//					BuildObject("ivbomb",1,"bomber");
            ClearObjectives();
            AddObjective("isdf0608.otf",WHITE,10.0f);
        }
        break;
    case 5:  // test to destroy base
        time_counter++;
        if (time_counter%1200==0) // every minute 1/2
        {
            atk1=BuildObject("fvtank",2,"patrol_spawn2");
            atk2=BuildObject("fvtank",2,"patrol_spawn2");
            Patrol(atk1,"patrol");
            Patrol(atk2,"patrol");
        }
        if (!IsAlive(goal))
        {
            // you win
            SucceedMission(GetTime()+20.0f,"isdf06w1.txt");
            mission_state++;
            ClearObjectives();
            AddObjective("isdf0609.otf",WHITE,10.0f);
        }
        break;
    case 6:
        // cineractive
        // Through the worm hole
        break;

    } // switch
}
コード例 #19
0
int main(int argc, char *argv[])
{
    GainType Cost;
    double Time, LastTime = GetTime();

    /* Read the specification of the problem */
    if (argc >= 2)
        ParameterFileName = argv[1];
    ReadParameters();
    MaxMatrixDimension = 10000;
    ReadProblem();

    if (SubproblemSize > 0) {
        if (DelaunayPartitioning)
            SolveDelaunaySubproblems();
        else if (KarpPartitioning)
            SolveKarpSubproblems();
        else if (KMeansPartitioning)
            SolveKMeansSubproblems();
        else if (RohePartitioning)
            SolveRoheSubproblems();
        else if (SierpinskiPartitioning || MoorePartitioning)
            SolveSFCSubproblems();
        else
            SolveTourSegmentSubproblems();
        return EXIT_SUCCESS;
    }
    AllocateStructures();
    CreateCandidateSet();
    InitializeStatistics();

    if (Norm != 0)
        BestCost = PLUS_INFINITY;
    else {
        /* The ascent has solved the problem! */
        Optimum = BestCost = (GainType) LowerBound;
        UpdateStatistics(Optimum, GetTime() - LastTime);
        RecordBetterTour();
        RecordBestTour();
        WriteTour(OutputTourFileName, BestTour, BestCost);
        WriteTour(TourFileName, BestTour, BestCost);
        Runs = 0;
    }

    /* Find a specified number (Runs) of local optima */
    for (Run = 1; Run <= Runs; Run++) {
        LastTime = GetTime();
        Cost = FindTour();      /* using the Lin-Kernighan heuristic */
        if (MaxPopulationSize > 0) {
            /* Genetic algorithm */
            int i;
            for (i = 0; i < PopulationSize; i++)
                Cost = MergeTourWithIndividual(i);
            if (!HasFitness(Cost)) {
                if (PopulationSize < MaxPopulationSize) {
                    AddToPopulation(Cost);
                    if (TraceLevel >= 1)
                        PrintPopulation();
                } else if (Cost < Fitness[PopulationSize - 1]) {
                    ReplaceIndividualWithTour(PopulationSize - 1, Cost);
                    if (TraceLevel >= 1)
                        PrintPopulation();
                }
            }
        } else if (Run > 1)
            Cost = MergeBetterTourWithBestTour();
        if (Cost < BestCost) {
            BestCost = Cost;
            RecordBetterTour();
            RecordBestTour();
            WriteTour(OutputTourFileName, BestTour, BestCost);
            WriteTour(TourFileName, BestTour, BestCost);
        }
        if (Cost < Optimum) {
            if (FirstNode->InputSuc) {
                Node *N = FirstNode;
                while ((N = N->InputSuc = N->Suc) != FirstNode);
            }
            Optimum = Cost;
            printff("*** New optimum = " GainFormat " ***\n\n", Optimum);
        }
        Time = fabs(GetTime() - LastTime);
        UpdateStatistics(Cost, Time);
        if (TraceLevel >= 1 && Cost != PLUS_INFINITY) {
            printff("Run %d: Cost = " GainFormat, Run, Cost);
            if (Optimum != MINUS_INFINITY && Optimum != 0)
                printff(", Gap = %0.3f%%",
                        100.0 * (Cost - Optimum) / Optimum);
            printff(", Time = %0.1f sec. %s\n\n", Time,
                    Cost < Optimum ? "<" : Cost == Optimum ? "=" : "");
        }
        if (PopulationSize >= 2 && Run >= MaxPopulationSize &&
            Run < Runs) {
            Node *N;
            int Parent1, Parent2;
            Parent1 = LinearSelection(PopulationSize, 1.25);
            do
                Parent2 = LinearSelection(PopulationSize, 1.25);
            while (Parent1 == Parent2);
            ApplyCrossover(Parent1, Parent2);
            N = FirstNode;
            do {
                int d = C(N, N->Suc);
                AddCandidate(N, N->Suc, d, INT_MAX);
                AddCandidate(N->Suc, N, d, INT_MAX);
                N = N->InitialSuc = N->Suc; 
            } 
            while (N != FirstNode);
        }
        SRandom(++Seed);
    }
    PrintStatistics();
    return EXIT_SUCCESS;
}
コード例 #20
0
ファイル: mgquery.c プロジェクト: plbogen/CSDL
/* files.  Then calls  query ()  to perform the querying. */
int
main (int argc, char **argv)
{
  ProgTime StartTime;
  int decomp = 0;
  int ch;

  msg_prefix = argv[0];
  GetTime (&StartTime);

  /* Initialise the environment with default values */

  InitEnv ();

  read_mgrc_file ();

  OutFile = stdout;
  InFile = stdin;

  opterr = 0;
  while ((ch = getopt (argc, argv, "Df:d:h")) != -1)
    switch (ch)
      {
      case 'f':
	SetEnv ("mgname", optarg, NULL);
	break;
      case 'd':
	SetEnv ("mgdir", optarg, NULL);
	break;
      case 'D':
	decomp = 1;
	break;
      case 'h':
      case '?':
	fprintf (stderr, "usage: %s [-D] [-f base name of collection]"
		 "[-d data directory] [collection]\n", argv[0]);
	exit (1);
      }

  PushEnv ();

  if (decomp == 0)
    {

      Init_ReadLine ();

      /* write a first prompt, let the user start thinking */
      if (!BooleanEnv (GetEnv ("expert"), 0) && isatty (fileno (InFile)))
	{
	  fprintf (stderr, "\n\n\t     FULL TEXT RETRIEVAL QUERY PROGRAM\n");
	  fprintf (stderr, "%24s%s\n\n", "", *"30 Jul 1999" == '%' ? __DATE__ : "30 Jul 1999");
	  fprintf (stderr, "\n");
	  fprintf (stderr, "  mgquery version " VERSION ", Copyright (C) 1994 Neil Sharman\n");
	  fprintf (stderr, "  mgquery comes with ABSOLUTELY NO WARRANTY; for details type `.warranty'\n");
	  fprintf (stderr, "  This is free software, and you are welcome to redistribute it\n");
	  fprintf (stderr, "  under certain conditions; type `.conditions' for details.\n");
	  fprintf (stderr, "\n");
	}
    }
  if (optind < argc)
    search_for_collection (argv[optind]);

  if (decomp == 0)
    {
      query ();
    }
  else
    {
      int i;
      InitQueryTimes iqt;
      query_data *qd;

      qd = InitQuerySystem (GetDefEnv ("mgdir", "./"),
			    GetDefEnv ("mgname", ""),
			    &iqt);
      if (!qd)
	FatalError (1, mg_errorstrs[mg_errno], mg_error_data);


      start_up_stats (qd, iqt);

      Display_Stats (stderr);
      for (i = 0; i < qd->td->cth.num_of_docs; i++)
	{
	  RawDocOutput (qd, i + 1, stdout);
	  putc ('\2', stdout);
	}
      Message ("%s", ElapsedTime (&StartTime, NULL));

      FinishQuerySystem (qd);
    }

  UninitEnv ();
  exit (0);
}
コード例 #21
0
ファイル: gameplayer.cpp プロジェクト: elfring/OHSystem
void CGamePlayer :: ProcessPackets( )
{
    if( !m_Socket )
        return;

    CIncomingAction *Action = NULL;
    CIncomingChatPlayer *ChatPlayer = NULL;
    CIncomingMapSize *MapSize = NULL;
    bool HasMap = false;
    uint32_t CheckSum = 0;
    uint32_t Pong = 0;

    // process all the received packets in the m_Packets queue

    while( !m_Packets.empty( ) )
    {
        CCommandPacket *Packet = m_Packets.front( );
        m_Packets.pop( );

        if( Packet->GetPacketType( ) == W3GS_HEADER_CONSTANT )
        {
            switch( Packet->GetID( ) )
            {
            case CGameProtocol :: W3GS_LEAVEGAME:
                m_Game->EventPlayerLeft( this, m_Protocol->RECEIVE_W3GS_LEAVEGAME( Packet->GetData( ) ) );
                break;

            case CGameProtocol :: W3GS_GAMELOADED_SELF:
                if( m_Protocol->RECEIVE_W3GS_GAMELOADED_SELF( Packet->GetData( ) ) )
                {
                    if( !m_FinishedLoading && m_Game->GetGameLoading( ) )
                    {
                        m_FinishedLoading = true;
                        m_FinishedLoadingTicks = GetTicks( );
                        m_Game->EventPlayerLoaded( this );
                    }
                    else
                    {
                        // we received two W3GS_GAMELOADED_SELF packets from this player!
                    }
                }

                break;

            case CGameProtocol :: W3GS_OUTGOING_ACTION:
                Action = m_Protocol->RECEIVE_W3GS_OUTGOING_ACTION( Packet->GetData( ), m_PID );

                if( Action )
                {
                    // don't delete Action here because the game is going to store it in a queue and delete it later
                    m_Game->EventPlayerAction( this, Action );
                }

                break;

            case CGameProtocol :: W3GS_OUTGOING_KEEPALIVE:
                CheckSum = m_Protocol->RECEIVE_W3GS_OUTGOING_KEEPALIVE( Packet->GetData( ) );
                m_CheckSums.push( CheckSum );
                ++m_SyncCounter;
                m_Game->EventPlayerKeepAlive( this, CheckSum );
                break;

            case CGameProtocol :: W3GS_CHAT_TO_HOST:
                ChatPlayer = m_Protocol->RECEIVE_W3GS_CHAT_TO_HOST( Packet->GetData( ) );

                if( ChatPlayer )
                {
                    // determine if we should auto-mute this player
                    if( ChatPlayer->GetType( ) == CIncomingChatPlayer :: CTH_MESSAGE || ChatPlayer->GetType( ) == CIncomingChatPlayer :: CTH_MESSAGEEXTRA )
                    {
                        if( m_Level <= 1 &&! GetMuted( ) )
                        {
                            m_MuteMessages.push_back( GetTicks( ) );

                            if( m_MuteMessages.size( ) > 7 )
                                m_MuteMessages.erase( m_MuteMessages.begin( ) );

                            uint32_t RecentCount = 0;
                            for( unsigned int i = 0; i < m_MuteMessages.size( ); ++i )
                            {
                                if( GetTicks( ) - m_MuteMessages[i] < 5000 )
                                {
                                    RecentCount++;
                                }
                            }

                            if( m_Game->m_GHost->m_AutoMuteSpammer && RecentCount >= 7 )
                            {
                                m_Count++;
                                if(  m_Count == 1 )
                                {
                                    SetMuted( true );
                                    m_MutedAuto = true;
                                    m_Game->SendChat( m_PID, "["+m_Game->m_GHost->m_BotManagerName+"] "+m_Game->m_GHost->m_Language->SpamWarning( ) );
                                    m_MuteMessages.clear( );
                                    m_Game->SendAllChat( "["+m_Game->m_GHost->m_BotManagerName+"] " + m_Game->m_GHost->m_Language->UserWasMutedForReason( m_Name, "spamming" ) );
                                }
                                if( m_Count == 2 )
                                {
                                    m_Game->SendAllChat( m_Game->m_GHost->m_Language->UserIgnoerNotify( m_Name ) );
                                    m_Game->SendChat( m_PID, "["+m_Game->m_GHost->m_BotManagerName+"] "+m_Game->m_GHost->m_Language->SpamWarning2( ) );
                                    SetMuted( true );
                                    m_Game->m_Pairedpenps.push_back( Pairedpenp( string(), m_Game->m_GHost->m_DB->Threadedpenp( m_Name, "Spam" , m_Game->m_GHost->m_BotManagerName, 1, "add" ) ) );
                                    m_MutedAuto = true;
                                    m_Game->SendAllChat( "["+m_Game->m_GHost->m_BotManagerName+"] " + m_Game->m_GHost->m_Language->UserWasMutedForReason( m_Name, "spamming" ) );
                                }
                                if( m_Count == 3 )
                                {
				    m_Game->BanPlayerByPenality( m_Name, GetExternalIPString( ), m_Game->m_GHost->m_BotManagerName, m_PenalityLevel, "Spam" );
                                    SetMuted( true );
                                    m_Game->SendAllChat( "["+m_Game->m_GHost->m_BotManagerName+"] " + m_Game->m_GHost->m_Language->UserWasMutedForReason( m_Name, "spamming" ) );

                                }
                            }

                            //we adding this condition not in the next condition to avoid a jump into ghost.cpp to check if the message was a flame message or not
                            if(m_Game->m_GHost->m_FlameCheck)
                            {
                                //now check for flamers
                                if( m_Game->m_GHost->FlameCheck( ChatPlayer->GetMessage( ) ) )
                                {
                                    m_FlameMessages.push_back( GetTicks( ) );

                                    if( m_FlameMessages.size( ) > 10 )
                                        m_FlameMessages.erase( m_FlameMessages.begin( ) );

                                    RecentCount = 0;

                                    for( unsigned int i = 0; i < m_FlameMessages.size( ); ++i )
                                    {
                                        if( GetTicks( ) - m_FlameMessages[i] < 60000 )
                                            RecentCount++;
                                    }

                                    if( RecentCount == 1 )
                                    {
                                        m_Game->SendChat( m_PID, "["+m_Game->m_GHost->m_BotManagerName+"] "+m_Game->m_GHost->m_Language->FlameWarn ());
                                    }

                                    if( RecentCount == 2 )
                                    {
                                        m_Game->SendChat( m_PID, "["+m_Game->m_GHost->m_BotManagerName+"] "+m_Game->m_GHost->m_Language->FlameWarn2 () );
                                        SetMuted( true );
                                        m_MutedAuto = true;
                                        m_Game->SendAllChat( "["+m_Game->m_GHost->m_BotManagerName+"] " + m_Game->m_GHost->m_Language->UserWasMutedForReason( m_Name, "flaming" ) );
                                    }

                                    if( RecentCount == 3 )
                                    {
                                        m_Game->SendChat( m_PID, m_Game->m_GHost->m_Language->FlameWarn3 () );
                                        SetMuted( true );
                                        m_Game->m_Pairedpenps.push_back( Pairedpenp( string(), m_Game->m_GHost->m_DB->Threadedpenp( m_Name, "Flame/Insult" , m_Game->m_GHost->m_BotManagerName, 1, "add" ) ) );
                                        m_MutedAuto = true;
                                        m_Game->SendAllChat( "["+m_Game->m_GHost->m_BotManagerName+"] " + m_Game->m_GHost->m_Language->UserWasMutedForReason( m_Name, "flaming" ) );
                                    }

                                    if( RecentCount == 4 )
                                    {
					m_Game->BanPlayerByPenality( m_Name, GetExternalIPString( ), m_Game->m_GHost->m_BotManagerName, m_PenalityLevel, "Flame/Insult" );
                                        SetMuted( true );
                                        m_Game->SendAllChat( "["+m_Game->m_GHost->m_BotManagerName+"] " + m_Game->m_GHost->m_Language->UserWasMutedForReason( m_Name, "flaming" ) );

                                    }
                                    if( RecentCount == 5 )
                                    {
                                        //some people simple dont understand the ban policy.
                                        m_Game->BanPlayerByPenality( m_Name, GetExternalIPString( ), m_Game->m_GHost->m_BotManagerName, m_PenalityLevel, "Flame/Insult" );
					SetMuted( true );
                                        m_Game->SendAllChat( "["+m_Game->m_GHost->m_BotManagerName+"] " + m_Game->m_GHost->m_Language->UserWasMutedForReason( m_Name, "flaming" ) );

                                    }
                                }
                            }
                        }
                    }
                    m_Game->EventPlayerChatToHost( this, ChatPlayer );
                }
                delete ChatPlayer;
                ChatPlayer = NULL;
                break;

            case CGameProtocol :: W3GS_DROPREQ:
                // todotodo: no idea what's in this packet

                if( !m_DropVote )
                {
                    m_DropVote = true;
                    m_Game->EventPlayerDropRequest( this );
                }

                break;

            case CGameProtocol :: W3GS_MAPSIZE:
                MapSize = m_Protocol->RECEIVE_W3GS_MAPSIZE( Packet->GetData( ), m_Game->m_GHost->m_Map->GetMapSize( ) );

                if( MapSize )
                    m_Game->EventPlayerMapSize( this, MapSize );

                delete MapSize;
                MapSize = NULL;
                break;

            case CGameProtocol :: W3GS_PONG_TO_HOST:
                Pong = m_Protocol->RECEIVE_W3GS_PONG_TO_HOST( Packet->GetData( ) );

                // we discard pong values of 1
                // the client sends one of these when connecting plus we return 1 on error to kill two birds with one stone

                if( Pong != 1 )
                {
                    // we also discard pong values when we're downloading because they're almost certainly inaccurate
                    // this statement also gives the player a 5 second grace period after downloading the map to allow queued (i.e. delayed) ping packets to be ignored

                    if( !m_DownloadStarted || ( m_DownloadFinished && GetTime( ) - m_FinishedDownloadingTime >= 5 ) )
                    {
                        // we also discard pong values when anyone else is downloading if we're configured to

                        if( m_Game->m_GHost->m_PingDuringDownloads || !m_Game->IsDownloading( ) )
                        {
                            m_Pings.push_back( GetTicks( ) - Pong );

                            if( m_Pings.size( ) > 20 )
                                m_Pings.erase( m_Pings.begin( ) );
                        }
                    }
                }

                m_Game->EventPlayerPongToHost( this, Pong );
                break;
            }
        }
        else if( Packet->GetPacketType( ) == GPS_HEADER_CONSTANT )
        {
            BYTEARRAY Data = Packet->GetData( );

            if( Packet->GetID( ) == CGPSProtocol :: GPS_INIT )
            {
                if( m_Game->m_GHost->m_Reconnect )
                {
                    m_GProxy = true;
                    m_Socket->PutBytes( m_Game->m_GHost->m_GPSProtocol->SEND_GPSS_INIT( m_Game->m_GHost->m_ReconnectPort, m_PID, m_GProxyReconnectKey, m_Game->GetGProxyEmptyActions( ) ) );
                    //CONSOLE_Print( "[GAME: " + m_Game->GetGameName( ) + "] player [" + m_Name + "] is using GProxy++" );
                }
                else
                {
                    // todotodo: send notice that we're not permitting reconnects
                    // note: GProxy++ should never send a GPS_INIT message if bot_reconnect = 0 because we don't advertise the game with invalid map dimensions
                    // but it would be nice to cover this case anyway
                }
            }
            else if( Packet->GetID( ) == CGPSProtocol :: GPS_RECONNECT )
            {
                // this is handled in ghost.cpp
            }
            else if( Packet->GetID( ) == CGPSProtocol :: GPS_ACK && Data.size( ) == 8 )
            {
                uint32_t LastPacket = UTIL_ByteArrayToUInt32( Data, false, 4 );
                uint32_t PacketsAlreadyUnqueued = m_TotalPacketsSent - m_GProxyBuffer.size( );

                if( LastPacket > PacketsAlreadyUnqueued )
                {
                    uint32_t PacketsToUnqueue = LastPacket - PacketsAlreadyUnqueued;

                    if( PacketsToUnqueue > m_GProxyBuffer.size( ) )
                        PacketsToUnqueue = m_GProxyBuffer.size( );

                    while( PacketsToUnqueue > 0 )
                    {
                        m_GProxyBuffer.pop( );
                        --PacketsToUnqueue;
                    }
                }
            }
        }

        delete Packet;
    }
}
コード例 #22
0
ファイル: mgquery.c プロジェクト: plbogen/CSDL
void 
query (void)
{
  ProgTime TotalStartTime, TotalInvfTime, TotalTextTime;
  InitQueryTimes iqt;
  query_data *qd;

  TotalStartTime.RealTime = TotalStartTime.CPUTime = 0;
  TotalInvfTime.RealTime = TotalInvfTime.CPUTime = 0;
  TotalTextTime.RealTime = TotalTextTime.CPUTime = 0;

  qd = InitQuerySystem (GetDefEnv ("mgdir", "./"),
			GetDefEnv ("mgname", ""),
			&iqt);
  if (!qd)
    FatalError (1, mg_errorstrs[mg_errno], mg_error_data);
  start_up_stats (qd, iqt);


  while (1)
    {
      ProgTime StartTime, InvfTime, TextTime;
      char QueryType;
      char OutputType;
      char *line;
      ResetFileStats (qd);
      qd->max_mem_in_use = qd->mem_in_use = 0;

      qd->tot_hops_taken += qd->hops_taken;
      qd->tot_num_of_ptrs += qd->num_of_ptrs;
      qd->tot_num_of_accum += qd->num_of_accum;
      qd->tot_num_of_terms += qd->num_of_terms;
      qd->tot_num_of_ans += qd->num_of_ans;
      qd->tot_text_idx_lookups += qd->text_idx_lookups;
      qd->hops_taken = qd->num_of_ptrs = 0;
      qd->num_of_accum = qd->num_of_ans = qd->num_of_terms = 0;
      qd->text_idx_lookups = 0;

      Display_Stats (stderr);
      Clear_Stats ();
      line = get_query (qd);
      if (!line || Quitting)
	break;

      GetPostProc (line);

      GetTime (&StartTime);

      FreeQueryDocs (qd);

      QueryType = get_query_type ();
      OutputType = get_output_type ();
      /* No point in hiliting words on a docnum query */
      if (OutputType == OUTPUT_HILITE && QueryType == QUERY_DOCNUMS)
	OutputType = OUTPUT_TEXT;

      switch (QueryType)
	{
	case QUERY_BOOLEAN:
	  {
	    char *maxdocs;
	    BooleanQueryInfo bqi;
	    maxdocs = GetDefEnv ("maxdocs", "all");
	    bqi.MaxDocsToRetrieve = strcmp (maxdocs, "all") ? atoi (maxdocs) : -1;
	    BooleanQuery (qd, line, &bqi);
	    break;
	  }
	case QUERY_APPROX:
	case QUERY_RANKED:
	  {
	    char *maxdocs;
	    char *maxterms;
	    char *maxaccum;
	    RankedQueryInfo rqi;
	    maxdocs = GetDefEnv ("maxdocs", "all");
	    maxterms = GetDefEnv ("max_terms", "all");
	    maxaccum = GetDefEnv ("max_accumulators", "all");
	    rqi.Sort = BooleanEnv (GetEnv ("sorted_terms"), 0);
	    rqi.QueryFreqs = BooleanEnv (GetEnv ("qfreq"), 1);
	    rqi.Exact = QueryType == QUERY_RANKED;
	    rqi.MaxDocsToRetrieve = strcmp (maxdocs, "all") ? atoi (maxdocs) : -1;
	    rqi.MaxTerms = strcmp (maxterms, "all") ? atoi (maxterms) : -1;
	    rqi.MaxParasToRetrieve = rqi.MaxDocsToRetrieve;
	    if (qd->id->ifh.InvfLevel == 3 && GetEnv ("maxparas"))
	      rqi.MaxParasToRetrieve = atoi (GetEnv ("maxparas"));
	    rqi.AccumMethod = toupper (*GetDefEnv ("accumulator_method", "A"));
	    rqi.MaxAccums = strcmp (maxaccum, "all") ? atoi (maxaccum) : -1;
	    rqi.HashTblSize = IntEnv (GetEnv ("hash_tbl_size"), 1000);
	    rqi.StopAtMaxAccum = BooleanEnv (GetEnv ("stop_at_max_accum"), 0);
	    rqi.skip_dump = GetEnv ("skip_dump");
	    RankedQuery (qd, line, &rqi);
	    break;
	  }
	case QUERY_DOCNUMS:
	  {
	    DocnumsQuery (qd, line);
	    break;
	  }
	}

      GetTime (&InvfTime);

      if (qd->DL)
	MoreDocs (qd, line, OutputType);

      GetTime (&TextTime);

      if (BooleanEnv (GetEnv ("timestats"), 0) ||
	  BooleanEnv (GetEnv ("briefstats"), 0))
	QueryTimeStats (&StartTime, &InvfTime, &TextTime);

      if (BooleanEnv (GetEnv ("diskstats"), 0) ||
	  BooleanEnv (GetEnv ("briefstats"), 0))
	File_Stats (qd);

      if (BooleanEnv (GetEnv ("memstats"), 0) ||
	  BooleanEnv (GetEnv ("briefstats"), 0))
	MemStats (qd);

      if (BooleanEnv (GetEnv ("sizestats"), 0))
	SizeStats (qd);

      TotalInvfTime.RealTime += InvfTime.RealTime - StartTime.RealTime;
      TotalInvfTime.CPUTime += InvfTime.CPUTime - StartTime.CPUTime;
      TotalTextTime.RealTime += TextTime.RealTime - StartTime.RealTime;
      TotalTextTime.CPUTime += TextTime.CPUTime - StartTime.CPUTime;
    }

  if (isatty (fileno (InFile)) && !Quitting)
    fprintf (stderr, "\n");

  shut_down_stats (qd, &TotalStartTime, &TotalInvfTime, &TotalTextTime);

  Display_Stats (stderr);

}
コード例 #23
0
ファイル: test_bitcoin.cpp プロジェクト: JeremyRubin/bitcoin
BasicTestingSetup::BasicTestingSetup(const std::string& chainName)
    : m_path_root(fs::temp_directory_path() / "test_bitcoin" / strprintf("%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(1 << 30))))
{
    SHA256AutoDetect();
    ECC_Start();
    SetupEnvironment();
    SetupNetworking();
    InitSignatureCache();
    InitScriptExecutionCache();
    fCheckBlockIndex = true;
    // CreateAndProcessBlock() does not support building SegWit blocks, so don't activate in these tests.
    // TODO: fix the code to support SegWit blocks.
    gArgs.ForceSetArg("-vbparams", strprintf("segwit:0:%d", (int64_t)Consensus::BIP9Deployment::NO_TIMEOUT));
    SelectParams(chainName);
    noui_connect();
}
コード例 #24
0
ファイル: init.cpp プロジェクト: dmp1ce/namecoin
bool AppInit2(int argc, char* argv[])
{
#ifdef _MSC_VER
    // Turn off microsoft heap dump noise
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
    // Disable confusing "helpful" text message on abort, ctrl-c
    _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifndef __WXMSW__
    umask(077);
#endif
#ifndef __WXMSW__
    // Clean shutdown on SIGTERM
    struct sigaction sa;
    sa.sa_handler = HandleSIGTERM;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGHUP, &sa, NULL);
#endif

    //
    // Parameters
    //
    ParseParameters(argc, argv);

    if (mapArgs.count("-datadir"))
    {
        filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
        strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
    }

    ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir

    if (mapArgs.count("-?") || mapArgs.count("--help"))
    {
        string beta = VERSION_IS_BETA ? _(" beta") : "";
        string strUsage = string() +
          _("Bitcoin version") + " " + FormatVersion(VERSION) + pszSubVer + beta + "\n\n" +
          _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
            "  bitcoin [options]                   \t  " + "\n" +
            "  bitcoin [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +
            "  bitcoin [options] help              \t\t  " + _("List commands\n") +
            "  bitcoin [options] help <command>    \t\t  " + _("Get help for a command\n") +
          _("Options:\n") +
            "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)\n") +
            "  -gen             \t\t  " + _("Generate coins\n") +
            "  -gen=0           \t\t  " + _("Don't generate coins\n") +
            "  -min             \t\t  " + _("Start minimized\n") +
            "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +
            "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +
            "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +
            "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +
            "  -nolisten        \t  "   + _("Don't accept connections from outside\n") +
            "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send\n") +
#ifdef GUI
            "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +
            "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +
#endif
            "  -testnet         \t\t  " + _("Use the test network\n") +
            "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +
            "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +
            "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
            "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address\n") +
            "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
            "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)\n") +
            "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions\n");

#ifdef USE_SSL
        strUsage += string() +
            _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +
            "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
            "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)\n") +
            "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)\n") +
            "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
#endif

        strUsage += string() +
            "  -?               \t\t  " + _("This help message\n");

#if defined(__WXMSW__) && defined(GUI)
        // Tabs make the columns line up in the message box
        wxMessageBox(strUsage, "Bitcoin", wxOK);
#else
        // Remove tabs
        strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
        fprintf(stderr, "%s", strUsage.c_str());
#endif
        return false;
    }

    fDebug = GetBoolArg("-debug");

    fDaemon = GetBoolArg("-daemon");

    if (fDaemon)
        fServer = true;
    else
        fServer = GetBoolArg("-server");

    /* force fServer and fDaemon when running without GUI */
#ifndef GUI
    fServer = true;
    fDaemon = true;
#endif

    fPrintToConsole = GetBoolArg("-printtoconsole");
    fPrintToDebugger = GetBoolArg("-printtodebugger");

    fTestNet = GetBoolArg("-testnet");
    fNoListen = GetBoolArg("-nolisten");
    fLogTimestamps = GetBoolArg("-logtimestamps");

    for (int i = 1; i < argc; i++)
        if (!IsSwitchChar(argv[i][0]))
            fCommandLine = true;

    if (fCommandLine)
    {
        int ret = CommandLineRPC(argc, argv);
        exit(ret);
    }

#ifndef GUI
    if (fDaemon)
    {
        // Daemonize
        pid_t pid = fork();
        if (pid < 0)
        {
            fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
            return false;
        }
        if (pid > 0)
            return true;

        pid_t sid = setsid();
        if (sid < 0)
            fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
    }
#endif

    if (!fDebug && !pszSetDataDir[0])
        ShrinkDebugFile();
    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    printf("Bitcoin version %s%s%s\n", FormatVersion(VERSION).c_str(), pszSubVer, VERSION_IS_BETA ? _(" beta") : "");
#ifdef GUI
    printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
    printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
    printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
#endif
    printf("Default data directory %s\n", GetDefaultDataDir().c_str());

    if (GetBoolArg("-loadblockindextest"))
    {
        CTxDB txdb("r");
        txdb.LoadBlockIndex();
        PrintBlockTree();
        return false;
    }

    //
    // Limit to single instance per user
    // Required to protect the database files if we're going to keep deleting log.*
    //
#if defined(__WXMSW__) && defined(GUI)
    // wxSingleInstanceChecker doesn't work on Linux
    wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
    for (int i = 0; i < strMutexName.size(); i++)
        if (!isalnum(strMutexName[i]))
            strMutexName[i] = '.';
    wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
    if (psingleinstancechecker->IsAnotherRunning())
    {
        printf("Existing instance found\n");
        unsigned int nStart = GetTime();
        loop
        {
            // Show the previous instance and exit
            HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
            if (hwndPrev)
            {
                if (IsIconic(hwndPrev))
                    ShowWindow(hwndPrev, SW_RESTORE);
                SetForegroundWindow(hwndPrev);
                return false;
            }

            if (GetTime() > nStart + 60)
                return false;

            // Resume this instance if the other exits
            delete psingleinstancechecker;
            Sleep(1000);
            psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
            if (!psingleinstancechecker->IsAnotherRunning())
                break;
        }
    }
コード例 #25
0
ファイル: util.cpp プロジェクト: alanxu89/bitcoin
#include <sys/prctl.h>
#endif

#ifdef HAVE_MALLOPT_ARENA_MAX
#include <malloc.h>
#endif

#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/conf.h>
#include <thread>

// Application startup time (used for uptime calculation)
const int64_t nStartupTime = GetTime();

const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
const char * const BITCOIN_PID_FILENAME = "bitcoind.pid";

ArgsManager gArgs;

CTranslationInterface translationInterface;

/** Init OpenSSL library multithreading support */
static std::unique_ptr<CCriticalSection[]> ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
{
    if (mode & CRYPTO_LOCK) {
        ENTER_CRITICAL_SECTION(ppmutexOpenSSL[i]);
    } else {
コード例 #26
0
ファイル: captureOpenCV.c プロジェクト: DonghunP/carSDK
static unsigned int CaptureThread(void *params)
{
    int i = 0;
    NvU64 stime, ctime;
    NvMediaTime t1 = {0}, t2 = {0}, st = {0}, ct = {0};
    CaptureContext *ctx = (CaptureContext *)params;
    NvMediaVideoSurface *releaseList[4] = {NULL}, **relList;
    NvMediaRect primarySrcRect;
    NvMediaPrimaryVideo primaryVideo;

    primarySrcRect.x0 = 0;
    primarySrcRect.y0 = 0;
    primarySrcRect.x1 = ctx->inputWidth;
    primarySrcRect.y1 = ctx->inputHeight;

    primaryVideo.next = NULL;
    primaryVideo.previous = NULL;
    primaryVideo.previous2 = NULL;
    primaryVideo.srcRect = &primarySrcRect;
    primaryVideo.dstRect = NULL;


    NvSemaphoreDecrement(ctx->semStart, NV_TIMEOUT_INFINITE);

    if(ctx->timeNotCount)
    {
        GetTime(&t1);
        AddTime(&t1, ctx->last * 1000000LL, &t1);
        GetTime(&t2);
        printf("timeNotCount\n");
    }
    GetTime(&st);
    stime = (NvU64)st.tv_sec * 1000000000LL + (NvU64)st.tv_nsec;

    while((ctx->timeNotCount? (SubTime(&t1, &t2)): ((unsigned int)i < ctx->last)) && !stop)
    {
        GetTime(&ct);
        ctime = (NvU64)ct.tv_sec * 1000000000LL + (NvU64)ct.tv_nsec;

        printf("frame=%3d, time=%llu.%09llu[s] \n", i, (ctime-stime)/1000000000LL, (ctime-stime)%1000000000LL);

        //printf("frame=%3d, time=%llu.%09llu[s] \n", i, (ctime-stime)/1000000000LL, (ctime-stime)%1000000000LL);

        pthread_mutex_lock(&mutex);            // for ControlThread()

        if(!(capSurf = NvMediaVideoCaptureGetFrame(ctx->capture, ctx->timeout)))
        { // TBD
            MESSAGE_PRINTF("NvMediaVideoCaptureGetFrame() failed in %sThread\n", ctx->name);
            stop = NVMEDIA_TRUE;
            break;
        }

        if(i%3 == 0)                        // once in three loop = 10 Hz
            pthread_cond_signal(&cond);        // ControlThread() is called

        pthread_mutex_unlock(&mutex);        // for ControlThread()

        primaryVideo.current = capSurf;
        primaryVideo.pictureStructure = NVMEDIA_PICTURE_STRUCTURE_TOP_FIELD;

        if(NVMEDIA_STATUS_OK != NvMediaVideoMixerRender(ctx->mixer, // mixer
                                                        NVMEDIA_OUTPUT_DEVICE_0, // outputDeviceMask
                                                        NULL, // background
                                                        &primaryVideo, // primaryVideo
                                                        NULL, // secondaryVideo
                                                        NULL, // graphics0
                                                        NULL, // graphics1
                                                        releaseList, // releaseList
                                                        NULL)) // timeStamp
        { // TBD
            MESSAGE_PRINTF("NvMediaVideoMixerRender() failed for the top field in %sThread\n", ctx->name);
            stop = NVMEDIA_TRUE;
        }

        primaryVideo.pictureStructure = NVMEDIA_PICTURE_STRUCTURE_BOTTOM_FIELD;
        if(NVMEDIA_STATUS_OK != NvMediaVideoMixerRender(ctx->mixer, // mixer
                                                        NVMEDIA_OUTPUT_DEVICE_0, // outputDeviceMask
                                                        NULL, // background
                                                        &primaryVideo, // primaryVideo
                                                        NULL, // secondaryVideo
                                                        NULL, // graphics0
                                                        NULL, // graphics1
                                                        releaseList, // releaseList
                                                        NULL)) // timeStamp
        { // TBD
            MESSAGE_PRINTF("NvMediaVideoMixerRender() failed for the bottom field in %sThread\n", ctx->name);
            stop = NVMEDIA_TRUE;
        }

        if(ctx->fileDumpEnabled)
        {
            if(!DumpFrame(ctx->fout, capSurf))
            { // TBD
                MESSAGE_PRINTF("DumpFrame() failed in %sThread\n", ctx->name);
                stop = NVMEDIA_TRUE;
            }

            if(!ctx->displayEnabled)
                releaseList[0] = capSurf;
        }

        relList = &releaseList[0];

        while(*relList)
        {
            if(NvMediaVideoCaptureReturnFrame(ctx->capture, *relList) != NVMEDIA_STATUS_OK)
            { // TBD
                MESSAGE_PRINTF("NvMediaVideoCaptureReturnFrame() failed in %sThread\n", ctx->name);
                stop = NVMEDIA_TRUE;
                break;
            }
            relList++;
        }

        if(ctx->timeNotCount)
            GetTime(&t2);

        i++;
    } // while end

    // Release any left-over frames
//    if(ctx->displayEnabled && capSurf && capSurf->type != NvMediaSurfaceType_YV16x2) // To allow returning frames after breaking out of the while loop in case of error
    if(ctx->displayEnabled && capSurf)
    {
        NvMediaVideoMixerRender(ctx->mixer, // mixer
                                NVMEDIA_OUTPUT_DEVICE_0, // outputDeviceMask
                                NULL, // background
                                NULL, // primaryVideo
                                NULL, // secondaryVideo
                                NULL, // graphics0
                                NULL, // graphics1
                                releaseList, // releaseList
                                NULL); // timeStamp

        relList = &releaseList[0];

        while(*relList)
        {
            if(NvMediaVideoCaptureReturnFrame(ctx->capture, *relList) != NVMEDIA_STATUS_OK)
                MESSAGE_PRINTF("NvMediaVideoCaptureReturnFrame() failed in %sThread\n", ctx->name);

            relList++;
        }
    }

    NvSemaphoreIncrement(ctx->semDone);
    return 0;
}
コード例 #27
0
ファイル: clientmodel.cpp プロジェクト: CapTake/core
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "chainparams.h"
#include "alert.h"
#include "main.h"
#include "ui_interface.h"

#include <QDateTime>
#include <QTimer>
#include <QDebug>

static const int64_t nClientStartupTime = GetTime();

ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), optionsModel(optionsModel),
    cachedNumBlocks(0), numBlocksAtStartup(-1), pollTimer(0)
{
    pollTimer = new QTimer(this);
    pollTimer->setInterval(MODEL_UPDATE_DELAY);
    pollTimer->start();
    connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
コード例 #28
0
ファイル: captureOpenCV.c プロジェクト: DonghunP/carSDK
void *ControlThread(void *unused)
{
    int i=0;
    char fileName[30];
    NvMediaTime pt1 ={0}, pt2 = {0};
    NvU64 ptime1, ptime2;
    struct timespec;

    IplImage* imgOrigin;
    IplImage* imgCanny;

    // cvCreateImage
    imgOrigin = cvCreateImage(cvSize(RESIZE_WIDTH, RESIZE_HEIGHT), IPL_DEPTH_8U, 3);
    imgCanny = cvCreateImage(cvGetSize(imgOrigin), IPL_DEPTH_8U, 1);

    int angle, speed;
    IplImage* imgOrigin;
    IplImage* imgResult;
    unsigned char status;

    unsigned int gain;

    CarControlInit();
    PositionControlOnOff_Write(UNCONTROL);
    SpeedControlOnOff_Write(1);

    //speed controller gain set
    //P-gain
    gain = SpeedPIDProportional_Read();        // default value = 10, range : 1~50
    printf("SpeedPIDProportional_Read() = %d \n", gain);
    gain = 20;
    SpeedPIDProportional_Write(gain);

    //I-gain
    gain = SpeedPIDIntegral_Read();        // default value = 10, range : 1~50
    printf("SpeedPIDIntegral_Read() = %d \n", gain);
    gain = 20;
    SpeedPIDIntegral_Write(gain);

    //D-gain
    gain = SpeedPIDDifferential_Read();        // default value = 10, range : 1~50
    printf("SpeedPIDDefferential_Read() = %d \n", gain);
    gain = 20;
    SpeedPIDDifferential_Write(gain);
    angle = 1460;
    SteeringServoControl_Write(angle);
    // cvCreateImage
    imgOrigin = cvCreateImage(cvSize(RESIZE_WIDTH, RESIZE_HEIGHT), IPL_DEPTH_8U, 3);

    imgResult = cvCreateImage(cvGetSize(imgOrigin), IPL_DEPTH_8U, 1);
    int flag = 1;
    while(1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);


        GetTime(&pt1);
        ptime1 = (NvU64)pt1.tv_sec * 1000000000LL + (NvU64)pt1.tv_nsec;



        Frame2Ipl(imgOrigin); // save image to IplImage structure & resize image from 720x480 to 320x240
        pthread_mutex_unlock(&mutex);


        cvCanny(imgOrigin, imgCanny, 100, 100, 3);

        sprintf(fileName, "captureImage/imgCanny%d.png", i);
        cvSaveImage(fileName , imgCanny, 0);
		Frame2Ipl(imgOrigin, imgResult); // save image to IplImage structure & resize image from 720x480 to 320x240
        pthread_mutex_unlock(&mutex);


        //cvCanny(imgOrigin, imgCanny, 100, 100, 3);

        sprintf(fileName, "captureImage/imgyuv%d.png", i);
        cvSaveImage(fileName , imgOrigin, 0);


        //sprintf(fileName, "captureImage/imgOrigin%d.png", i);
        //cvSaveImage(fileName, imgOrigin, 0);


        // TODO : control steering angle based on captured image ---------------

        //speed set
        speed = DesireSpeed_Read();
        printf("DesireSpeed_Read() = %d \n", speed);
        //speed = -10;
        //DesireSpeed_Write(speed);
        if(flag == 1){
            if(greenlight>1000)
            {
                printf("right go\n");
                Winker_Write(LEFT_ON);
                usleep(1000000);
                //Winker_Write(ALL_OFF);
                angle = 1400;
                SteeringServoControl_Write(angle);
                speed = 10;
                DesireSpeed_Write(speed);
                speed = DesireSpeed_Read();
                printf("DesireSpeed_Read() = %d \n", speed);
                sleep(1);
                flag = 0;
            }
            else
            {
                printf("left go\n");
                Winker_Write(RIGHT_ON);
                usleep(10000);
                Winker_Write(ALL_OFF);

                speed = 20;
                DesireSpeed_Write(speed);
                usleep(1300000);
                angle = 1950;
                SteeringServoControl_Write(angle);
                usleep(5000000);
                angle = 1460;
                SteeringServoControl_Write(angle);
                usleep(1000000);
                speed = 0;
                DesireSpeed_Write(speed);
                flag = 0;
            }
        }

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

        GetTime(&pt2);
        ptime2 = (NvU64)pt2.tv_sec * 1000000000LL + (NvU64)pt2.tv_nsec;
        printf("--------------------------------operation time=%llu.%09llu[s]\n", (ptime2-ptime1)/1000000000LL, (ptime2-ptime1)%1000000000LL);


        i++;
    }

}
コード例 #29
0
ファイル: NCSF.cpp プロジェクト: soneek/SDATStuff
// Get time on SSEQ, will run the player at least once (without "playing" the
// music), if the song is one-shot (and not looping), it will run the player
// a second time, "playing" the song to determine when silence has occurred.
// After which, it will store the data in the tags for the SSEQ.
void GetTime(const std::string &filename, const SDAT *sdat, const SSEQ *sseq, TagList &tags, bool verbose, uint32_t numberOfLoops, uint32_t fadeLoop, uint32_t fadeOneShot)
{
	auto player = std::unique_ptr<TimerPlayer>(new TimerPlayer());
	player->Setup(sseq);
	player->maxSeconds = 6000;
	auto looponeplayer = std::unique_ptr<TimerPlayer>(new TimerPlayer());
	looponeplayer->Setup(sseq);
	looponeplayer->maxSeconds = 6000;
	auto looptwoplayer = std::unique_ptr<TimerPlayer>(new TimerPlayer());
	looptwoplayer->Setup(sseq);
	looptwoplayer->maxSeconds = 6000;
	// Get the time, without "playing" the notes
	Time length = GetTime(player.get(), 20, numberOfLoops);
	// Get the loop start and end positions
	Time lonelength = GetTime(looponeplayer.get(), 20, 1);
	Time ltwolengths = GetTime(looptwoplayer.get(), 20, 2);
	double lstart = lonelength.time - (ltwolengths.time - lonelength.time);
	// If the length was for a one-shot song, get the time again, this time "playing" the notes
	bool gotLength = false;
	if (static_cast<int>(length.time) != -1 && length.type == END)
	{
		player.reset(new TimerPlayer());
		player->Setup(sseq);
		player->sbnk = sdat->infoSection.BANKrecord.entries[sseq->info.bank].sbnk;
		for (int i = 0; i < 4; ++i)
			if (player->sbnk->info.waveArc[i] != 0xFFFF)
				player->swar[i] = sdat->infoSection.WAVEARCrecord.entries[player->sbnk->info.waveArc[i]].swar;
		player->maxSeconds = length.time + 30;
		player->doNotes = true;
		Time oldLength = length;
		length = GetTime(player.get(), 40, numberOfLoops);
		if (static_cast<int>(length.time) != -1)
			gotLength = true;
		else
			length = oldLength;
	}
	if (static_cast<int>(length.time) != -1)
	{
		if (length.type == LOOP) {
			tags["fade"] = stringify(fadeLoop);
			std::string lsString = SecondsToStringMs(lstart);
			std::string leString = SecondsToStringMs(lonelength.time);
			tags["loopstart_ms"] = lsString;
			tags["loopend_ms"] = leString;
		}
		else
			tags["fade"] = stringify(fadeOneShot);
		if (!static_cast<int>(length.time))
			length.time = 1;
		std::string lengthString = SecondsToString(std::ceil(length.time));
		tags["length"] = lengthString;
		if (verbose)
		{
			std::cout << "Time for " << filename << ": " << lengthString << " (" << (length.type == LOOP ? "timed to 2 loops" : "one-shot") << ")\n";
			if (length.type == END && !gotLength)
				std::cout << "(NOTE: Was unable to detect silence at the end of the track, time may be inaccurate.)\n";
		}
	}
	else if (verbose)
	{
		tags.Remove("fade");
		tags.Remove("length");
		std::cout << "Unable to calculate time for " << filename << "\n";
	}
}
コード例 #30
0
 TestingSetup() {
     fPrintToDebugger = true; // don't want to write to debug.log file
     noui_connect();
     bitdb.MakeMock();
     pathTemp = GetTempPath() / strprintf("test_"+ COIN_NAME + "_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
     boost::filesystem::create_directories(pathTemp);
     mapArgs["-datadir"] = pathTemp.string();
     pblocktree = new CBlockTreeDB(1 << 20, true);
     pcoinsdbview = new CCoinsViewDB(1 << 23, true);
     pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
     InitBlockIndex();
     bool fFirstRun;
     pwalletMain = new CWallet("wallet.dat");
     pwalletMain->LoadWallet(fFirstRun);
     RegisterWallet(pwalletMain);
     nScriptCheckThreads = 3;
     for (int i=0; i < nScriptCheckThreads-1; i++)
         threadGroup.create_thread(&ThreadScriptCheck);
 }