• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ Hash函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中Hash函数的典型用法代码示例。如果您正苦于以下问题:C++ Hash函数的具体用法?C++ Hash怎么用?C++ Hash使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Hash函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: CollectDataFlow

int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
                    const Vector<SizedFile> &CorporaFiles) {
  Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
         DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
  MkDir(DirPath);
  auto Temp = TempPath(".dft");
  for (auto &F : CorporaFiles) {
    // For every input F we need to collect the data flow and the coverage.
    // Data flow collection may fail if we request too many DFSan tags at once.
    // So, we start from requesting all tags in range [0,Size) and if that fails
    // we then request tags in [0,Size/2) and [Size/2, Size), and so on.
    // Function number => DFT.
    std::unordered_map<size_t, Vector<uint8_t>> DFTMap;
    std::unordered_set<std::string> Cov;
    std::queue<std::pair<size_t, size_t>> Q;
    Q.push({0, F.Size});
    while (!Q.empty()) {
      auto R = Q.front();
      Printf("\n\n\n********* Trying: [%zd, %zd)\n", R.first, R.second);
      Q.pop();
      Command Cmd;
      Cmd.addArgument(DFTBinary);
      Cmd.addArgument(std::to_string(R.first));
      Cmd.addArgument(std::to_string(R.second));
      Cmd.addArgument(F.File);
      Cmd.addArgument(Temp);
      Printf("CMD: %s\n", Cmd.toString().c_str());
      if (ExecuteCommand(Cmd)) {
        // DFSan has failed, collect tags for two subsets.
        if (R.second - R.first >= 2) {
          size_t Mid = (R.second + R.first) / 2;
          Q.push({R.first, Mid});
          Q.push({Mid, R.second});
        }
      } else {
        Printf("********* Success: [%zd, %zd)\n", R.first, R.second);
        std::ifstream IF(Temp);
        std::string L;
        while (std::getline(IF, L, '\n')) {
          // Data flow collection has succeeded.
          // Merge the results with the other runs.
          if (L.empty()) continue;
          if (L[0] == 'C') {
            // Take coverage lines as is, they will be the same in all attempts.
            Cov.insert(L);
          } else if (L[0] == 'F') {
            size_t FunctionNum = 0;
            std::string DFTString;
            if (ParseDFTLine(L, &FunctionNum, &DFTString)) {
              auto &DFT = DFTMap[FunctionNum];
              if (DFT.empty()) {
                // Haven't seen this function before, take DFT as is.
                DFT = DFTStringToVector(DFTString);
              } else if (DFT.size() == DFTString.size()) {
                // Have seen this function already, merge DFTs.
                DFTStringAppendToVector(&DFT, DFTString);
              }
            }
          }
        }
      }
    }
    auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
    // Dump combined DFT to disk.
    Printf("Producing DFT for %s\n", OutPath.c_str());
    std::ofstream OF(OutPath);
    for (auto &DFT: DFTMap)
      OF << "F" << DFT.first << " " << DFT.second << std::endl;
    for (auto &C : Cov)
      OF << C << std::endl;
  }
  RemoveFile(Temp);
  // Write functions.txt.
  Command Cmd;
  Cmd.addArgument(DFTBinary);
  Cmd.setOutputFile(DirPlusFile(DirPath, "functions.txt"));
  ExecuteCommand(Cmd);
  return 0;
}
开发者ID:matrc,项目名称:llvm-project,代码行数:79,代码来源:FuzzerDataFlowTrace.cpp


示例2: Write

bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
{
    nWalletDBUpdateCounter++;

    if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
               keyMeta, false))
        return false;

    // hash pubkey/privkey to accelerate wallet load
    std::vector<unsigned char> vchKey;
    vchKey.reserve(vchPubKey.size() + vchPrivKey.size());
    vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
    vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());

    return Write(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false);
}
开发者ID:marcusfox0,项目名称:polis,代码行数:16,代码来源:walletdb.cpp


示例3: unordered_map

	explicit unordered_map(
		size_type bucket_count = unordered_map_default_bucket_count,
		const Hash& hash = Hash(),
		const KeyEqual& equal = KeyEqual(),
		const Allocator& alloc = Allocator())
			: _Base(bucket_count, hash, equal, alloc) {}
开发者ID:zapster,项目名称:cacao-travis,代码行数:6,代码来源:unordered_map.hpp


示例4: Hash

int HashFunction::MakeAddress (string key, unsigned int depth){

   unsigned int hash = Hash(key);
   return MakeAddress(hash,depth);
}
开发者ID:estebaneze,项目名称:datos022011-tp1-vane,代码行数:5,代码来源:HashFunction.cpp


示例5: vulnerability

uint256 CBlock::BuildMerkleTree(bool* fMutated) const
{
    /* WARNING! If you're reading this because you're learning about crypto
       and/or designing a new system that will use merkle trees, keep in mind
       that the following merkle tree algorithm has a serious flaw related to
       duplicate txids, resulting in a vulnerability (CVE-2012-2459).

       The reason is that if the number of hashes in the list at a given time
       is odd, the last one is duplicated before computing the next level (which
       is unusual in Merkle trees). This results in certain sequences of
       transactions leading to the same merkle root. For example, these two
       trees:

                    A               A
                  /  \            /   \
                B     C         B       C
               / \    |        / \     / \
              D   E   F       D   E   F   F
             / \ / \ / \     / \ / \ / \ / \
             1 2 3 4 5 6     1 2 3 4 5 6 5 6

       for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
       6 are repeated) result in the same root hash A (because the hash of both
       of (F) and (F,F) is C).

       The vulnerability results from being able to send a block with such a
       transaction list, with the same merkle root, and the same block hash as
       the original without duplication, resulting in failed validation. If the
       receiving node proceeds to mark that block as permanently invalid
       however, it will fail to accept further unmodified (and thus potentially
       valid) versions of the same block. We defend against this by detecting
       the case where we would hash two identical hashes at the end of the list
       together, and treating that identically to the block having an invalid
       merkle root. Assuming no double-SHA256 collisions, this will detect all
       known ways of changing the transactions without affecting the merkle
       root.
    */
    vMerkleTree.clear();
    vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
    for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
        vMerkleTree.push_back(it->GetHash());
    int j = 0;
    bool mutated = false;
    for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
    {
        for (int i = 0; i < nSize; i += 2)
        {
            int i2 = std::min(i+1, nSize-1);
            if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
                // Two identical hashes at the end of the list at a particular level.
                mutated = true;
            }
            vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
                                       BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
        }
        j += nSize;
    }
    if (fMutated) {
        *fMutated = mutated;
    }
    return (vMerkleTree.empty() ? uint256() : vMerkleTree.back());
}
开发者ID:Whiteblock,项目名称:zcash,代码行数:62,代码来源:block.cpp


示例6: NiAdminThread

// Management thread
void NiAdminThread(THREAD *thread, void *param)
{
	NAT_ADMIN *a = (NAT_ADMIN *)param;
	NAT *n;
	SOCK *s;
	UCHAR random[SHA1_SIZE];
	UINT err;
	// Validate arguments
	if (thread == NULL || param == NULL)
	{
		return;
	}

	// Random number generation
	Rand(random, sizeof(random));

	a->Thread = thread;
	AddRef(a->Thread->ref);
	s = a->Sock;
	AddRef(s->ref);

	n = a->Nat;

	LockList(n->AdminList);
	{
		Add(n->AdminList, a);
	}
	UnlockList(n->AdminList);

	NoticeThreadInit(thread);

	err = ERR_AUTH_FAILED;

	if (StartSSL(s, n->AdminX, n->AdminK))
	{
		PACK *p;

		// Send the random number
		p = NewPack();
		PackAddData(p, "auth_random", random, sizeof(random));

		if (HttpServerSend(s, p))
		{
			PACK *p;
			// Receive a password
			p = HttpServerRecv(s);
			if (p != NULL)
			{
				UCHAR secure_password[SHA1_SIZE];
				UCHAR secure_check[SHA1_SIZE];

				if (PackGetData2(p, "secure_password", secure_password, sizeof(secure_password)))
				{
					SecurePassword(secure_check, n->HashedPassword, random);

					if (Cmp(secure_check, secure_password, SHA1_SIZE) == 0)
					{
						UCHAR test[SHA1_SIZE];
						// Password match
						Hash(test, "", 0, true);
						SecurePassword(test, test, random);

#if	0
						if (Cmp(test, secure_check, SHA1_SIZE) == 0 && s->RemoteIP.addr[0] != 127)
						{
							// A client can not connect from the outside with blank password
							err = ERR_NULL_PASSWORD_LOCAL_ONLY;
						}
						else
#endif

						{
							// Successful connection
							err = ERR_NO_ERROR;
							NiAdminMain(n, s);
						}
					}
				}

				FreePack(p);
			}
		}

		FreePack(p);

		if (err != ERR_NO_ERROR)
		{
			p = PackError(err);
			HttpServerSend(s, p);
			FreePack(p);
		}
	}

	Disconnect(s);
	ReleaseSock(s);
}
开发者ID:52M,项目名称:SoftEtherVPN,代码行数:97,代码来源:Nat.c


示例7: ZHashValue

	/*
	ZHashValue value override.  Uses the Java 6 string hash function.  Equivalent to a call
	to Hash.

	@return (ZHashValue) - hash code for this string
	*/
	operator ZHashValue () const 
		{ return Hash(); }
开发者ID:crertel,项目名称:onizuka-oculus-client,代码行数:8,代码来源:ZBasicString.hpp


示例8: MyHashMap

 /**
  * Constructor.
  * @param n initial table size.
  * @param hash hash function.
  * @param equal equality function.
  */
 MyHashMap(size_t n, Hash const& hash = Hash(), Equal const& equal = Equal())
         : Table(n, hash, equal) {
 }
开发者ID:K-Sonoda,项目名称:graphillion,代码行数:9,代码来源:MyHashTable.hpp


示例9: Hash

int TPZWillamWarnke::ClassId() const{
    return Hash("TPZWillamWarnke") ^ WILLAMWARNKEPARENT::ClassId() << 1;
}
开发者ID:labmec,项目名称:neopz,代码行数:3,代码来源:TPZWillamWarnke.cpp


示例10: MyHashTable

 /**
  * Constructor.
  * @param n initial table size.
  * @param hash hash function.
  * @param equal equality function
  */
 MyHashTable(size_t n, Hash const& hash = Hash(), Equal const& equal =
         Equal())
         : hashFunc(hash), eqFunc(equal), tableCapacity_(0), tableSize_(0),
           maxSize_(0), size_(0), table(0), collisions_(0) {
     initialize(n);
 }
开发者ID:K-Sonoda,项目名称:graphillion,代码行数:12,代码来源:MyHashTable.hpp


示例11: hash

	Hash hash(const Provider& provider)
	{
		auto tmp = simstd::make_unique<HashImpl>(provider);
		return tmp->is_valid() ? Hash(simstd::move(tmp)) : Hash();
	}
开发者ID:andrew-grechkin,项目名称:cpp,代码行数:5,代码来源:crypt_Hash.cpp


示例12: Process

float Process(YARPImageOf<YarpPixelBGR>& ref, 
	      YARPImageOf<YarpPixelBGR>& target)
{
  static float bounce = 0;
  static int hash_ref[HASH_SIZE];
  static int hash_target[HASH_SIZE];
  static int hash_target_ylo[HASH_SIZE];
  static int hash_target_yhi[HASH_SIZE];
//  printf("Clearing hash tables\n");
  for (int r=0; r<HASH_SIZE; r++)
    {
      hash_ref[r] = hash_target[r] = 0;
      hash_target_ylo[r] = hash_target_yhi[r] = 0;
    }
//  printf("Comparing images\n");
  int h = ref.GetHeight();
  int w = ref.GetWidth();
  assert(h==target.GetHeight());
  assert(w==target.GetWidth());
  for (int y=0; y<h; y++)
    {
      for (int x=0; x<w; x++)
	{
	  YarpPixelBGR pix_ref = ref(x,y);
	  YarpPixelBGR pix_target = target(x,y);
	  int idx_ref = Hash(pix_ref);
	  int idx_target = Hash(pix_target);
	  hash_ref[idx_ref]++;
	  hash_target[idx_target]++;
	  if (y>=h/2)
	    {
	      hash_target_yhi[idx_target]++;
	    }
	  else
	    {
	      hash_target_ylo[idx_target]++;
	    }
	}
    }
  int votes = 0;
  float dir = 0;
  for (int r=0; r<HASH_SIZE; r++)
    {
      int diff = hash_ref[r] - hash_target[r];
      if (fabs(diff)>3)
	{
	  int hi = hash_target_yhi[r];
	  int lo = hash_target_ylo[r];
	  if (fabs(hi-lo)>3)
	    {
	      float power = fabs(hi-lo)*fabs(diff);
	      if (power>20) power = 20;
	      float direction = power;
	      if (diff>0)
		{
		  if (hi<lo)
		    {
		      direction = -direction;
		    }
		}
	      else
		{
		  if (hi>lo)
		    {
		      direction = -direction;
		    }
		}
	      
	      votes++;
	      dir += direction;
	    }
	}
    }
  printf("%8d votes, verdict is %8.4g ", votes, dir);
  bounce = 0.8*bounce + 0.2*((dir>0)?1:-1);
  if (bounce>0.5) printf("LOOK DOWN");
  if (bounce<-0.5) printf("LOOK UP");
  printf("\n");
  return dir;
}
开发者ID:robotology-legacy,项目名称:yarp1,代码行数:80,代码来源:camcal.cpp


示例13: TCSP_LoadKeyByUUID_Internal

TSS_RESULT
TCSP_LoadKeyByUUID_Internal(TCS_CONTEXT_HANDLE hContext,	/* in */
			    TSS_UUID *KeyUUID,			/* in */
			    TCS_LOADKEY_INFO * pLoadKeyInfo,	/* in, out */
			    TCS_KEY_HANDLE * phKeyTCSI)		/* out */
{
	UINT32 keyslot = 0, keySize;
	UINT32 ordinal;
	TSS_RESULT result;
	TSS_UUID parentUuid;
	BYTE keyBlob[0x1000];
	UINT16 blobSize = sizeof(keyBlob);
	UINT64 offset;
	TCS_KEY_HANDLE parentTCSKeyHandle;

	if (TPM_VERSION_IS(1,2))
		ordinal = TPM_ORD_LoadKey2;
	else
		ordinal = TPM_ORD_LoadKey;

	LogDebugFn("Enter: uuid: 0x%lx auth? 0x%x ***********", (unsigned long)KeyUUID,
		  pLoadKeyInfo == NULL ? 0xdeadbeef : pLoadKeyInfo->authData.AuthHandle);

	if ((result = ctx_verify_context(hContext)))
		return result;

	memset(&parentUuid, 0, sizeof(TSS_UUID));

	if (pLoadKeyInfo &&
	    memcmp(&pLoadKeyInfo->parentKeyUUID, &parentUuid, sizeof(TSS_UUID))) {
		if (ps_get_key_by_uuid(&pLoadKeyInfo->keyUUID, keyBlob, &blobSize))
			return TCSERR(TSS_E_PS_KEY_NOTFOUND);

		if (mc_get_handles_by_uuid(&pLoadKeyInfo->parentKeyUUID, &parentTCSKeyHandle,
					   &keyslot))
			return TCSERR(TCS_E_KM_LOADFAILED);

		return LoadKeyByBlob_Internal(ordinal, hContext, parentTCSKeyHandle,
					      blobSize, keyBlob,
					      &pLoadKeyInfo->authData,
					      phKeyTCSI, &keyslot);
	}

	/* if KeyUUID is already loaded, increment the ref count and return */
	if (mc_get_handles_by_uuid(KeyUUID, phKeyTCSI, &keyslot) == TSS_SUCCESS) {
		if (keyslot) {
			if (ctx_mark_key_loaded(hContext, *phKeyTCSI)) {
				LogError("Error marking key as loaded");
				return TCSERR(TSS_E_INTERNAL_ERROR);
			}
			return TSS_SUCCESS;
		}
	}
	/*********************************************************************
	 *	The first thing to do in this func is setup all the info and make sure
	 *		that we get it all from either the keyfile or the keyCache
	 *		also, it's important to return if the key is already loaded
	 ***********************************************************************/
	LogDebugFn("calling ps_get_key_by_uuid");
	if (ps_get_key_by_uuid(KeyUUID, keyBlob, &blobSize))
		return TCSERR(TSS_E_PS_KEY_NOTFOUND);
	/* convert UINT16 to UIN32 */
	keySize = blobSize;

	LogDebugFn("calling getParentUUIDByUUID");
	/*---	Get my parent's UUID.  Since My key is registered, my parent should be as well. */
	if ((result = getParentUUIDByUUID(KeyUUID, &parentUuid)))
		return TCSERR(TCS_E_KM_LOADFAILED);

	if ((result = TCSP_LoadKeyByUUID_Internal(hContext, &parentUuid,
						  pLoadKeyInfo, &parentTCSKeyHandle)))
		return result;

	LogDebugFn("calling LoadKeyByBlob_Internal");
	/*******************************************************
	 * If no errors have happend up till now, then the parent is loaded and ready for use.
	 * The parent's TCS Handle should be in parentTCSKeyHandle.
	 ******************************************************/
	if ((result = LoadKeyByBlob_Internal(ordinal, hContext, parentTCSKeyHandle,
					     keySize, keyBlob,
					     NULL,
					     phKeyTCSI, &keyslot))) {
		LogDebugFn("LoadKeyByBlob_Internal returned 0x%x", result);
		if (result == TCPA_E_AUTHFAIL && pLoadKeyInfo) {
			BYTE blob[1000];

			/* set up a load key info struct */
			memcpy(&pLoadKeyInfo->parentKeyUUID, &parentUuid, sizeof(TSS_UUID));
			memcpy(&pLoadKeyInfo->keyUUID, KeyUUID, sizeof(TSS_UUID));

			/* calculate the paramDigest */
			offset = 0;
			LoadBlob_UINT32(&offset, ordinal, blob);
			LoadBlob(&offset, keySize, blob, keyBlob);
			if (Hash(TSS_HASH_SHA1, offset, blob,
				 (BYTE *)&pLoadKeyInfo->paramDigest.digest))
				result = TCSERR(TSS_E_INTERNAL_ERROR);

			result = TCSERR(TCS_E_KM_LOADFAILED);
		}
//.........这里部分代码省略.........
开发者ID:cooljeanius,项目名称:trousers-0.3.11.2,代码行数:101,代码来源:tcsi_ps.c


示例14: GroupNodeDef_Init

void GroupNodeDef_Init()
{
	str4cpy(gGroupNodeDef.mName, "group");
	gGroupNodeDef.mHash = Hash(gGroupNodeDef.mName);
	gGroupNodeDef.mAllocSize = sizeof(Group);
}
开发者ID:8c6794b6,项目名称:supercollider,代码行数:6,代码来源:SC_Group.cpp


示例15: ThreadSendAlert

void ThreadSendAlert()
{
    if (!mapArgs.count("-sendalert") && !mapArgs.count("-printalert"))
        return;

    MilliSleep(60*1000); // Wait a minute so we get connected

    //
    // Alerts are relayed around the network until nRelayUntil, flood
    // filling to every node.
    // After the relay time is past, new nodes are told about alerts
    // when they connect to peers, until either nExpiration or
    // the alert is cancelled by a newer alert.
    // Nodes never save alerts to disk, they are in-memory-only.
    //
    CAlert alert;
    alert.nRelayUntil   = GetTime() + 15 * 60;
    alert.nExpiration   = GetTime() + 365 * 60 * 60;
    alert.nID           = 1000;  // use https://github.com/zcash/zcash/wiki/specification#assigned-numbers to keep track of alert IDs
    alert.nCancel       = 0;   // cancels previous messages up to this ID number

    // These versions are protocol versions
    // 170002 : 1.0.0
    alert.nMinVer       = 170002;
    alert.nMaxVer       = 170002;

    //
    // main.cpp: 
    //  1000 for Misc warnings like out of disk space and clock is wrong
    //  2000 for longer invalid proof-of-work chain 
    //  Higher numbers mean higher priority
    //  4000 or higher will put the RPC into safe mode
    alert.nPriority     = 5000;
    alert.strComment    = "";
    alert.strStatusBar  = "URGENT: Upgrade required: see https://z.cash";
    alert.strRPCError   = "URGENT: Upgrade required: see https://z.cash";

    // Set specific client version/versions here. If setSubVer is empty, no filtering on subver is done:
    // alert.setSubVer.insert(std::string("/MagicBean:0.7.2/"));

    // Sign
    const CChainParams& chainparams = Params();
    std::string networkID = chainparams.NetworkIDString();
    bool fIsTestNet = networkID.compare("test") == 0;
    std::vector<unsigned char> vchTmp(ParseHex(fIsTestNet ? pszTestNetPrivKey : pszPrivKey));
    CPrivKey vchPrivKey(vchTmp.begin(), vchTmp.end());

    CDataStream sMsg(SER_NETWORK, CLIENT_VERSION);
    sMsg << *(CUnsignedAlert*)&alert;
    alert.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
    CKey key;
    if (!key.SetPrivKey(vchPrivKey, false))
    {
        printf("ThreadSendAlert() : key.SetPrivKey failed\n");
        return;
    }
    if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
    {
        printf("ThreadSendAlert() : key.Sign failed\n");
        return;
    }

    // Test
    CDataStream sBuffer(SER_NETWORK, CLIENT_VERSION);
    sBuffer << alert;
    CAlert alert2;
    sBuffer >> alert2;
    if (!alert2.CheckSignature(chainparams.AlertKey()))
    {
        printf("ThreadSendAlert() : CheckSignature failed\n");
        return;
    }
    assert(alert2.vchMsg == alert.vchMsg);
    assert(alert2.vchSig == alert.vchSig);
    alert.SetNull();
    printf("\nThreadSendAlert:\n");
    printf("hash=%s\n", alert2.GetHash().ToString().c_str());
    printf("%s\n", alert2.ToString().c_str());
    printf("vchMsg=%s\n", HexStr(alert2.vchMsg).c_str());
    printf("vchSig=%s\n", HexStr(alert2.vchSig).c_str());

    // Confirm
    if (!mapArgs.count("-sendalert"))
        return;
    while (vNodes.size() < 1 && !ShutdownRequested())
        MilliSleep(500);
    if (ShutdownRequested())
        return;

    // Send
    printf("ThreadSendAlert() : Sending alert\n");
    int nSent = 0;
    {
        LOCK(cs_vNodes);
        BOOST_FOREACH(CNode* pnode, vNodes)
        {
            if (alert2.RelayTo(pnode))
            {
                printf("ThreadSendAlert() : Sent alert to %s\n", pnode->addr.ToString().c_str());
                nSent++;
//.........这里部分代码省略.........
开发者ID:aniemerg,项目名称:zcash,代码行数:101,代码来源:sendalert.cpp


示例16: GetTimeMillis

CMasternodePaymentDB::ReadResult CMasternodePaymentDB::Read(CMasternodePayments& objToLoad, bool fDryRun)
{

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

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

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

    CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);

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


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

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


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

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

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

    LogPrintf("Loaded info from mnpayments.dat  %dms\n", GetTimeMillis() - nStart);
    LogPrintf("  %s\n", objToLoad.ToString());
    if(!fDryRun) {
        LogPrintf("Masternode payments manager - cleaning....\n");
        objToLoad.CleanPaymentList();
        LogPrintf("Masternode payments manager - result:\n");
        LogPrintf("  %s\n", objToLoad.ToString());
    }

    return Ok;
}
开发者ID:winhackua,项目名称:zetcoin,代码行数:89,代码来源:masternode-payments.cpp


示例17: strlen

TDBTSettingHandle CSettings::FindSetting(TDBTSettingDescriptor & Descriptor)
{
	if (Descriptor.Flags & DBT_SDF_FoundValid)
		return Descriptor.FoundHandle;

	uint32_t namelength = static_cast<uint32_t>( strlen(Descriptor.pszSettingName) );
	uint32_t namehash;

	if (Descriptor.Flags & DBT_SDF_HashValid)
	{
		namehash = Descriptor.Hash;
	} else {
		namehash = Hash(Descriptor.pszSettingName, namelength);
		Descriptor.Hash = namehash;
		Descriptor.Flags = Descriptor.Flags | DBT_SDF_HashValid;
	}

	Descriptor.Flags = Descriptor.Flags & ~DBT_SDF_FoundValid;

	CSettingsTree * tree;
	TDBTSettingHandle res = 0;
	CBlockManager * file = &m_BlockManagerPri;
	if (Descriptor.Entity == 0)
		file = &m_BlockManagerSet;

	CBlockManager::ReadTransaction trans(*file);

	if ((Descriptor.Entity == 0) || (Descriptor.Options == 0))
	{
		tree = getSettingsTree(Descriptor.Entity);
		if (tree == NULL)
			return DBT_INVALIDPARAM;

		res = tree->_FindSetting(namehash, Descriptor.pszSettingName, namelength);

		if (res)
		{
			Descriptor.FoundInEntity = Descriptor.Entity;
			Descriptor.FoundHandle = res;
			Descriptor.Flags = Descriptor.Flags | DBT_SDF_FoundValid;
		}

		if (Descriptor.Entity == 0)
			res = res | cSettingsFileFlag;

		return res;
	}

	uint32_t cf = m_Entities.getFlags(Descriptor.Entity);
	if (cf == DBT_INVALIDPARAM)
		return DBT_INVALIDPARAM;

	// search the setting
	res = 0;

	TDBTEntityIterFilter f;
	f.cbSize = sizeof(f);
	if (cf & DBT_NF_IsGroup)
	{
		f.fDontHasFlags = 0;
		f.fHasFlags = DBT_NF_IsGroup;
	} else {
		f.fDontHasFlags = DBT_NF_IsGroup;
		f.fHasFlags = 0;
	}
	f.Options = Descriptor.Options;

	TDBTEntityIterationHandle i = m_Entities.IterationInit(f, Descriptor.Entity);
	if ((i == DBT_INVALIDPARAM) || (i == 0))
		return DBT_INVALIDPARAM;

	TDBTEntityHandle e = m_Entities.IterationNext(i);
	TDBTEntityHandle found = 0;
	while ((res == 0) && (e != 0))
	{
		tree = getSettingsTree(e);
		if (tree)
		{
			res = tree->_FindSetting(namehash, Descriptor.pszSettingName, namelength);
			found = e;
		}

		e = m_Entities.IterationNext(i);
	}

	m_Entities.IterationClose(i);

	if (res)
	{
		Descriptor.FoundInEntity = found;
		Descriptor.FoundHandle = res;
		Descriptor.Flags = Descriptor.Flags | DBT_SDF_FoundValid;
	}

	return res;
}
开发者ID:BackupTheBerlios,项目名称:mgoodies-svn,代码行数:96,代码来源:Settings.cpp


示例18: main

int main(int argc, char* argv[])
{
  TEnv Env(argc, argv);
  TStr PrefixPath = Env.GetArgs() > 1 ? Env.GetArg(1) : TStr("");

  double ts1 = Tick();
  TTableContext Context;
  TVec<PTable> NodeTblV = TVec<PTable>();
  TVec<PTable> EdgeTblV = TVec<PTable>();
  Schema NodeSchema = Schema();
  Schema EdgeSchema = Schema();
  LoadFlickrTables(PrefixPath, Context, NodeTblV, NodeSchema, EdgeTblV, EdgeSchema);

  double ts2 = Tick();

  int ExpectedSz = 0;
  for (TVec<PTable>::TIter it = NodeTblV.BegI(); it < NodeTblV.EndI(); it++) {
    PTable Table = *it;
    ExpectedSz += Table->GetNumRows();
  }

  THash<TStr, TInt> Hash(ExpectedSz);
  TStrV OriNIdV(ExpectedSz);

  MergeNodeTables(NodeTblV, NodeSchema, Hash, OriNIdV);
  PTable EdgeTable = MergeEdgeTables(EdgeTblV, EdgeSchema, Hash, Context);

  double ts3 = Tick();
  TStrV V;
  TStrV VE;
  VE.Add(EdgeSchema.GetVal(2).GetVal1());
  PNEANet Graph = TSnap::ToNetwork<PNEANet>(EdgeTable, EdgeSchema.GetVal(0).GetVal1(), EdgeSchema.GetVal(1).GetVal1(),
						V, V, VE, aaLast);
  double ts4 = Tick();

  //int nExps = 1;
  int nExps = 40;
  TIntFltH PageRankResults;
  for (int i = 0; i < nExps; i++) {
    PageRankResults = TIntFltH(ExpectedSz);
#ifdef USE_OPENMP
    TSnap::GetWeightedPageRankMP2(Graph, PageRankResults, EdgeSchema.GetVal(2).GetVal1(), 0.849999999999998, 0.0001, 10);
#else
    TSnap::GetWeightedPageRank(Graph, PageRankResults, EdgeSchema.GetVal(2).GetVal1(), 0.849999999999998, 0.0001, 10);
#endif
  }
  double ts5 = Tick();

  PSOut ResultOut = TFOut::New(PrefixPath + TStr("page-rank-results.tsv"));
  for (TIntFltH::TIter it = PageRankResults.BegI(); it < PageRankResults.EndI(); it++) {
    ResultOut->PutStrFmtLn("%s\t%f9", OriNIdV[it.GetKey()].CStr(), it.GetDat().Val);
  }
  double ts6 = Tick();

  bool isPar = false;
#ifdef USE_OPENMP
  isPar = true;
#endif

//  PSOut FeaturesOut = TFOut::New(PrefixPath + "features.txt");
//  FeaturesOut->PutStrFmtLn("Photo %d", PPhotoTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Users %d", PUserTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Tags %d", PTagTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Comments %d", PCommentTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Locations %d", PLocationTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Photo - Owner %d", PPhotoOwnerTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Photo - Comment %d", PPhotoCommentTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Photo - Location %d", PPhotoLocationTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Comment - User %d", PCommentUserTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Comment - User %d", PCommentUserTbl->GetNumRows().Val);
////  FeaturesOut->PutStrFmtLn("Photo - Tagger %d", PPhotoTaggerTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Tagger - Tag %d", PTaggerTagTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Total number of nodes = %d", Graph->GetNodes());
//  FeaturesOut->PutStrFmtLn("Total number of edges = %d", Graph->GetEdges());

  PSOut TimeOut = TFOut::New(PrefixPath + TStr("time.txt"), true);
  TimeOut->PutStrFmtLn("Experiment Weighted - %s - %s", PrefixPath.CStr(), (isPar ? "Parallel" : "Sequential"));
  TimeOut->PutStrFmtLn("Input Time = %f", GetCPUTimeUsage(ts1, ts2));
  TimeOut->PutStrFmtLn("Preprocessing Time = %f", GetCPUTimeUsage(ts2, ts3));
  TimeOut->PutStrFmtLn("Conversion Time = %f", GetCPUTimeUsage(ts3, ts4));
  TimeOut->PutStrFmtLn("Computing Time = %f", GetCPUTimeUsage(ts4, ts5)/nExps);
  TimeOut->PutStrFmtLn("Output Time = %f", GetCPUTimeUsage(ts5, ts6));

  return 0;
}
开发者ID:IsmaelAli,项目名称:snap,代码行数:85,代码来源:benchmark-weighted.cpp


示例19: trans

TDBTSettingHandle CSettings::WriteSetting(TDBTSetting & Setting, TDBTSettingHandle hSetting)
{
	uint32_t sig = cSettingSignature;
	uint32_t size = 0;
	TSetting * setting = NULL;

	if (!hSetting && !(Setting.Descriptor && Setting.Descriptor->Entity))
		return DBT_INVALIDPARAM;

	CBlockManager * file = &m_BlockManagerPri;
	bool fileflag = false;

	if (hSetting & cSettingsFileFlag)
	{
		file = &m_BlockManagerSet;
		hSetting = hSetting & ~cSettingsFileFlag;
		fileflag = true;
	}

	CSettingsTree * tree = NULL;

	if (hSetting == 0)
	{
		if (Setting.Descriptor->Entity == 0)
		{
			file = &m_BlockManagerSet;
			fileflag = true;
		}

		CBlockManager::WriteTransaction trans(*file);
		
		if ((Setting.Descriptor) && (Setting.Descriptor->pszSettingName)) // setting needs a name
		{
			tree = getSettingsTree(Setting.Descriptor->Entity);
			_EnsureModuleExists(Setting.Descriptor->pszSettingName);
		}

	} else {
		CBlockManager::WriteTransaction trans(*file);

		setting = file->ReadBlock<TSetting>(hSetting, size, sig);

		if (setting) // check if hSetting is valid
			tree = getSettingsTree(setting->Entity);
	}

	if (tree == NULL)
		return DBT_INVALIDPARAM;

	uint32_t blobsize = 0;

	if (Setting.Type & DBT_STF_VariableLength)
	{
		switch (Setting.Type)
		{
			case DBT_ST_ANSI: case DBT_ST_UTF8:
				{
					if (Setting.Value.Length == 0)
						blobsize = static_cast<uint32_t>(strlen(Setting.Value.pAnsi) + 1);
					else
						blobsize = Setting.Value.Length;
				} break;
			case DBT_ST_WCHAR:
				{
					if (Setting.Value.Length == 0)
						blobsize = sizeof(wchar_t) * static_cast<uint32_t>(wcslen(Setting.Value.pWide) + 1);
					else
						blobsize = sizeof(wchar_t) * (Setting.Value.Length);
				} break;
			default:
				blobsize = Setting.Value.Length;
				break;
		}
	}

	size = sizeof(TSetting) + static_cast<uint32_t>(strlen(Setting.Descriptor->pszSettingName)) + 1 + blobsize;

	if (hSetting == 0) // create new setting
	{
		setting = file->CreateBlock<TSetting>(hSetting, cSettingSignature, size);

		setting->Entity = Setting.Descriptor->Entity;
		setting->Flags = 0;
		setting->AllocSize = blobsize;

		if (Setting.Descriptor && (Setting.Descriptor->Flags & DBT_SDF_HashValid))
		{
			tree->_AddSetting(Setting.Descriptor->Hash, hSetting);
		} else  {
			tree->_AddSetting(Hash(Setting.Descriptor->pszSettingName, static_cast<uint32_t>(strlen(Setting.Descriptor->pszSettingName))), hSetting);
		}

	} else {
		uint32_t tmp = 0;
		setting = file->ReadBlock<TSetting>(hSetting, tmp, sig);

		if (((Setting.Type & DBT_STF_VariableLength) == 0) && (setting->Type & DBT_STF_VariableLength))
		{ // shrink setting (variable size->fixed size)
			file->ResizeBlock(hSetting, setting, size);
		}
//.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:mgoodies-svn,代码行数:101,代码来源:Settings.cpp


示例20: InsertHashTable

void InsertHashTable(char *key, int value)
{
	int addr = Hash(key);
	while (vertex_hash_table[addr] != -1) addr = (addr + 1) % hash_table_size;
	vertex_hash_table[addr] = value;
}
开发者ID:AdeDZY,项目名称:LINE,代码行数:6,代码来源:reconstruct.cpp



注:本文中的Hash函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ HashString函数代码示例发布时间:2022-05-30
下一篇:
C++ HasShadowManager函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap