当前位置: 首页>>代码示例>>C++>>正文


C++ map::count方法代码示例

本文整理汇总了C++中std::map::count方法的典型用法代码示例。如果您正苦于以下问题:C++ map::count方法的具体用法?C++ map::count怎么用?C++ map::count使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在std::map的用法示例。


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

示例1: fetch_inputs

bool transaction::fetch_inputs(
    db_tx & dbtx, const std::map<sha256, transaction_index> & test_pool,
    const bool & best_block, const bool & create_block,
    transaction::previous_t & inputs, bool & invalid
    )
{
    /**
     * If the transaction is invalid this will be set to true.
     */
    invalid = false;

    /**
     * Coinbase transactions have no inputs to fetch.
     */
    if (is_coin_base())
    {
        return true;
    }
    
    for (auto i = 0; i < m_transactions_in.size(); i++)
    {
        auto previous_out = m_transactions_in[i].previous_out();
        
        if (inputs.count(previous_out.get_hash()) > 0)
        {
            continue;
        }
        
        /**
         * Read the transaction index.
         */
        auto & tx_index = inputs[previous_out.get_hash()].first;
        
        bool found = true;
        
        if (
            (best_block || create_block) &&
            test_pool.count(previous_out.get_hash()) > 0
            )
        {
            /**
             * Get the transaction index from the current proposed changes.
             */
            tx_index = test_pool.find(previous_out.get_hash())->second;
        }
        else
        {
            /**
             * Read transaction index from transaction database.
             */
            found = dbtx.read_transaction_index(
                previous_out.get_hash(), tx_index
            );
        }
        
        if (found == false && (best_block || create_block))
        {
            if (create_block)
            {
                return false;
            }
            else
            {
                log_error(
                    "Transaction " << get_hash().to_string().substr(0, 10) <<
                    " previous transaction " <<
                    previous_out.get_hash().to_string().substr(0, 10) <<
                    " index entry not found."
                );

                return false;
            }
        }
        
        /**
         * Read previous transaction.
         */
        auto & tx_prev = inputs[previous_out.get_hash()].second;
        
        if (
            found == false ||
            tx_index.get_transaction_position() == transaction_position(1, 1, 1)
            )
        {
            if (
                transaction_pool::instance().exists(
                previous_out.get_hash()) == false
                )
            {
                log_debug(
                    "Transaction failed to fetch inputs, " <<
                    get_hash().to_string().substr(0, 10) <<
                    " pool previous transaction not found " <<
                    previous_out.get_hash().to_string().substr(0, 10) << "."
                );
                
                return false;
            }
            
            tx_prev = transaction_pool::instance().lookup(
//.........这里部分代码省略.........
开发者ID:xCoreDev,项目名称:vcash,代码行数:101,代码来源:transaction.cpp

示例2: queryKey

/// Microsoft helper function for getting the contents of a registry key
void queryKey(const std::string& hive,
              const std::string& key,
              QueryData& results) {
  if (kRegistryHives.count(hive) != 1) {
    return;
  }

  HKEY hRegistryHandle;
  auto ret = RegOpenKeyEx(kRegistryHives.at(hive),
                          TEXT(key.c_str()),
                          0,
                          KEY_READ,
                          &hRegistryHandle);

  if (ret != ERROR_SUCCESS) {
    return;
  }

  const DWORD maxKeyLength = 255;
  const DWORD maxValueName = 16383;
  TCHAR achClass[MAX_PATH] = TEXT("");
  DWORD cchClassName = MAX_PATH;
  DWORD cSubKeys = 0;
  DWORD cbMaxSubKey;
  DWORD cchMaxClass;
  DWORD cValues;
  DWORD cchMaxValueName;
  DWORD cbMaxValueData;
  DWORD cbSecurityDescriptor;
  DWORD retCode;
  FILETIME ftLastWriteTime;
  retCode = RegQueryInfoKey(hRegistryHandle,
                            achClass,
                            &cchClassName,
                            nullptr,
                            &cSubKeys,
                            &cbMaxSubKey,
                            &cchMaxClass,
                            &cValues,
                            &cchMaxValueName,
                            &cbMaxValueData,
                            &cbSecurityDescriptor,
                            &ftLastWriteTime);

  TCHAR achKey[maxKeyLength];
  DWORD cbName;

  // Process registry subkeys
  if (cSubKeys > 0) {
    for (DWORD i = 0; i < cSubKeys; i++) {
      cbName = maxKeyLength;
      retCode = RegEnumKeyEx(hRegistryHandle,
                             i,
                             achKey,
                             &cbName,
                             nullptr,
                             nullptr,
                             nullptr,
                             &ftLastWriteTime);
      if (retCode != ERROR_SUCCESS) {
        continue;
      }
      Row r;
      fs::path keyPath(key);
      r["hive"] = hive;
      r["key"] = keyPath.string();
      r["subkey"] = (keyPath / achKey).string();
      r["name"] = "(Default)";
      r["type"] = "REG_SZ";
      r["data"] = "(value not set)";
      r["mtime"] = std::to_string(filetimeToUnixtime(ftLastWriteTime));
      results.push_back(r);
    }
  }

  if (cValues <= 0) {
    return;
  }

  BYTE* bpDataBuff = new BYTE[cbMaxValueData];
  DWORD cchValue = maxKeyLength;
  TCHAR achValue[maxValueName];

  // Process registry values
  for (size_t i = 0, retCode = ERROR_SUCCESS; i < cValues; i++) {
    size_t cnt = 0;
    ZeroMemory(bpDataBuff, cbMaxValueData);
    cchValue = maxValueName;
    achValue[0] = '\0';

    retCode = RegEnumValue(hRegistryHandle,
                           static_cast<DWORD>(i),
                           achValue,
                           &cchValue,
                           nullptr,
                           nullptr,
                           nullptr,
                           nullptr);

//.........这里部分代码省略.........
开发者ID:pombredanne,项目名称:osquery,代码行数:101,代码来源:registry.cpp

示例3: conTCPObjectConnect

const char* conTCPObjectConnect(Linker::SimObject *obj, S32 argc, const char *argv[])
{
	if (sRunningTCPObjects.count(obj->mId) >= 1)
		TCPObject_Disconnect(sRunningTCPObjects[obj->mId].get());
		
	DX::TCPObject *operand = new DX::TCPObject((unsigned int)obj);

	// Copy the hostname over
	char *desired_hostname = (char*)malloc(strlen(argv[2]) + 1);
	memcpy(desired_hostname, argv[2], strlen(argv[2]) + 1);

	// Create the connection info
	ConnectionInformation *connection = new ConnectionInformation;
	connection->target_hostname = desired_hostname;
	connection->buffer_length = 0;
	connection->is_connected = false;
	connection->socket = 0;

	// Hack: Store the Ptr to our connection information struct in the old unused state value
	operand->state = (unsigned int)connection;

	//ConnectionInformation *connection = (ConnectionInformation*)parameters;
	char *target_hostname = strlwr(connection->target_hostname);

	// Is it an IP we got?
	if (strstr(target_hostname, "ip:"))
		target_hostname += 3; // Chop off the 'ip:' segment

	// Did we get a port #?
	unsigned int desired_port = 0;
	char *port_delineator = strstr(target_hostname, ":");
	if (port_delineator)
	{
		port_delineator[0] = 0x00; // NULL Terminate the IP Segment
		port_delineator += 1;
		desired_port = atoi(port_delineator);
	}
	else
	{
		Con::errorf(0, "No Port");
		operand->CallMethod("onConnectFailed", 1, S32ToCharPtr(1));
		return "NO_PORT";
	}

	// Perform a DNS Lookup
	wchar_t hostname_dns[128];
	std::mbstowcs(hostname_dns, target_hostname, strlen(target_hostname) + 1);

	PDNS_RECORD dns_record;
	if (DnsQuery(hostname_dns, DNS_TYPE_A, DNS_QUERY_BYPASS_CACHE, NULL, &dns_record, NULL))
	{
		Con::errorf(0, "DNS Resolution Failed");
		operand->CallMethod("onDNSFailed", 0);
		return "FAILED_DNS";
	}
	IN_ADDR result_address;
	result_address.S_un.S_addr = dns_record->Data.A.IpAddress;

	DNS_FREE_TYPE freetype;
	DnsRecordListFree(dns_record, freetype);

	target_hostname = inet_ntoa(result_address);

	SOCKADDR_IN target_host;
	target_host.sin_family = AF_INET;
	target_host.sin_port = htons(desired_port);
	target_host.sin_addr.s_addr = inet_addr(target_hostname);

	Con::errorf(0, "Target %s on port %u SimID %u", target_hostname, desired_port, operand->identifier);

	// Create the Socket
	connection->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (connection->socket == INVALID_SOCKET)
	{
		Con::errorf(0, "Failed to create Socket!");
		operand->CallMethod("onConnectFailed", 2, S32ToCharPtr(2), S32ToCharPtr(WSAGetLastError()));
		return "FAILED_SOCKET_CREATION";
	}

	// Set Blocking Mode (a non-zero for imode = non-blocking)
	u_long imode = 1;
	ioctlsocket(connection->socket, FIONBIO, &imode);

	sRunningTCPObjects[obj->mId] = std::unique_ptr<DX::TCPObject>(operand);

	// Attempt the Connection
	connect(connection->socket, (SOCKADDR*)&target_host, sizeof(target_host));

	if (getsockopt(connection->socket, SOL_SOCKET, SO_ERROR, NULL, NULL) < 0)
	{
		operand->CallMethod("onConnectFailed", 2, S32ToCharPtr(3), S32ToCharPtr(WSAGetLastError()));
		return "CANNOT_CONNECT";
	}
	else
	{
		operand->CallMethod("onConnected", 0);
		return "SUCCESS";
	}

	return "UNKNOWN_ERROR";
//.........这里部分代码省略.........
开发者ID:Ragora,项目名称:T2-CPP,代码行数:101,代码来源:DXTCPObjects.cpp

示例4: Analyze

 void Analyze(ControlCenter* Data)
 {
     while(!Library.empty())
     {
         Information Tem=GetInformation();
         bool Reflesh=false;
         if(Tem.Target==RegeditID)
         {
             switch(Tem.Category1)
             {
                 case VIEWLOCATION:
                     Location.X=Tem.Data1.f;
                     Location.Y=Tem.Data2.f;
                     Location.Z=Tem.Data3.f;
                     Reflesh=true;
                     break;
                 case VIEWANGLE:
                     AngleUp=Tem.Data1;
                     AngleRight=Tem.Data2;
                     Front.Set(cos(AngleUp)*sin(AngleRight),sin(AngleUp),-cos(AngleUp)*cos(AngleRight));
                     Up.Set(-sin(AngleUp)*sin(AngleRight),cos(AngleUp),sin(AngleUp)*cos(AngleRight));
                     Reflesh=true;
                     break;
             }
             if(Reflesh)
             {
                 Information Tr=Tem;
                 Tr.Target=Tem.Resource;
                 Tr.Resource=Tem.Target;
                 Out(Tr);
             }
         }
         if(OwnKey)
         {
             if(Tem.Target==INFALL&&Tem.Category1==INFEVENT)
             {
                 if(Tem.Category2==INFKEY)
                 {
                     if(Tem.Category3==INFKEYDOWN)
                     {
                         if(Key.count(Tem.Data1)>0)
                         {
                             Key[Tem.Data1]=true;
                         }
                     }else if(Tem.Category3==INFKEYUP)
                     {
                         if(Key.count(Tem.Data1)>0)
                         {
                             Key[Tem.Data1]=false;
                         }
                     }
                 }
             }
         }
     }
     if(Key['w'])
     {
         Location=Location+Front.Uint(MOVESPEED);
     }
     if(Key['s'])
     {
         Location=Location-Front.Uint(MOVESPEED);
     }
     if(Key['a'])
     {
         AngleRight-=MOVESPEEDANGLE;
         Front.Set(cos(AngleUp)*sin(AngleRight),sin(AngleUp),-cos(AngleUp)*cos(AngleRight));
     }
     if(Key['d'])
     {
         AngleRight+=MOVESPEEDANGLE;
         Front.Set(cos(AngleUp)*sin(AngleRight),sin(AngleUp),-cos(AngleUp)*cos(AngleRight));
     }
     if(Key['q'])
     {
         Location=Location+(Up&Front).Uint(MOVESPEED);
     }
     if(Key['e'])
     {
         Location=Location-(Up&Front).Uint(MOVESPEED);
     }
     if(Key['r'])
     {
         Location=Location+Up.Uint(MOVESPEED);
     }
     if(Key['f'])
     {
         Location=Location-Up.Uint(MOVESPEED);
     }
 }
开发者ID:QNewU,项目名称:test_physical_carshing_testing,代码行数:90,代码来源:view.cpp

示例5: finalize_vehicles

/**
 *Works through cached vehicle definitions and creates vehicle objects from them.
 */
void game::finalize_vehicles()
{
    int part_x = 0, part_y = 0;
    std::string part_id = "";
    vehicle *next_vehicle;

    std::map<point, bool> cargo_spots;

    while (!vehprototypes.empty()) {
        cargo_spots.clear();
        vehicle_prototype *proto = vehprototypes.front();
        vehprototypes.pop();

        next_vehicle = new vehicle(proto->id.c_str());
        next_vehicle->name = _(proto->name.c_str());

        for (size_t i = 0; i < proto->parts.size(); ++i) {
            point p = proto->parts[i].first;
            part_x = p.x;
            part_y = p.y;

            part_id = proto->parts[i].second;
            if (vehicle_part_types.count(part_id) == 0) {
                debugmsg("unknown vehicle part %s in %s", part_id.c_str(), proto->id.c_str());
                continue;
            }

            if(next_vehicle->install_part(part_x, part_y, part_id) < 0) {
                debugmsg("init_vehicles: '%s' part '%s'(%d) can't be installed to %d,%d",
                         next_vehicle->name.c_str(), part_id.c_str(),
                         next_vehicle->parts.size(), part_x, part_y);
            }
            if ( vehicle_part_types[part_id].has_flag("CARGO") ) {
                cargo_spots[p] = true;
            }
        }

        for (auto &i : proto->item_spawns) {
            if (cargo_spots.find(point(i.x, i.y)) == cargo_spots.end()) {
                debugmsg("Invalid spawn location (no CARGO vpart) in %s (%d, %d): %d%%",
                         proto->name.c_str(), i.x, i.y, i.chance);
            }
            for (auto &j : i.item_ids) {
                if( !item::type_is_defined( j ) ) {
                    debugmsg("unknown item %s in spawn list of %s", j.c_str(), proto->id.c_str());
                }
            }
            for (auto &j : i.item_groups) {
                if (!item_group::group_is_defined(j)) {
                    debugmsg("unknown item group %s in spawn list of %s", j.c_str(), proto->id.c_str());
                }
            }
        }
        next_vehicle->item_spawns = proto->item_spawns;

        if (vtypes.count(next_vehicle->type) > 0) {
            delete vtypes[next_vehicle->type];
        }
        vtypes[next_vehicle->type] = next_vehicle;
        delete proto;
    }
}
开发者ID:Abbysynth,项目名称:Cataclysm-DDA,代码行数:65,代码来源:veh_typedef.cpp

示例6: collectDependentEntities

void IfcPPModel::collectDependentEntities( shared_ptr<IfcPPEntity>& entity, std::map<IfcPPEntity*, shared_ptr<IfcPPEntity> >& target_map )
{
	if( !entity )
	{
		return;
	}
	//if( entity->m_id < 0 )
	//{
	//	entity->setId( next_entity_id );
	//	++next_entity_id;
	//}

	auto ele_assembly = dynamic_pointer_cast<IfcElementAssembly>( entity );
	if( ele_assembly )
	{
		int assembly_id = ele_assembly->m_id;
		std::vector<weak_ptr<IfcRelAggregates> >& vec_is_decomposed_by = ele_assembly->m_IsDecomposedBy_inverse;
		for( size_t ii = 0; ii < vec_is_decomposed_by.size(); ++ii )
		{
			const weak_ptr<IfcRelAggregates>& is_decomposed_weak_ptr = vec_is_decomposed_by[ii];
			if( auto is_decomposed_ptr = is_decomposed_weak_ptr.lock() )
			{
				int rel_aggregates_id = is_decomposed_ptr->m_id;

				shared_ptr<IfcPPEntity> as_ifcpp_entity = is_decomposed_ptr;
				collectDependentEntities( as_ifcpp_entity, target_map );
			}
		}
	}

	std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > > vec_attributes;
	entity->getAttributes( vec_attributes );
	for( size_t ii = 0; ii < vec_attributes.size(); ++ii )
	{
		shared_ptr<IfcPPObject>& attribute = vec_attributes[ii].second;
		if( !attribute )
		{
			// empty attribute
			continue;
		}
		shared_ptr<IfcPPEntity> attribute_entity = dynamic_pointer_cast<IfcPPEntity>( attribute );
		if( attribute_entity )
		{
			if( target_map.count( attribute_entity.get() ) == 0 )
			{
				target_map[attribute_entity.get()] = attribute_entity;
				collectDependentEntities( attribute_entity, target_map );
			}
			continue;
		}

		auto attribute_object_vector = dynamic_pointer_cast<IfcPPAttributeObjectVector>( attribute );
		if( attribute_object_vector )
		{
			std::vector<shared_ptr<IfcPPObject> >& vec_of_attributes = attribute_object_vector->m_vec;

			for( size_t jj = 0; jj < vec_of_attributes.size(); ++jj )
			{
				shared_ptr<IfcPPObject>& attribute_object = vec_of_attributes[jj];

				auto attribute_entity = dynamic_pointer_cast<IfcPPEntity>( attribute_object );
				if( attribute_entity )
				{
					if( target_map.count( attribute_entity.get() ) == 0 )
					{
						target_map[attribute_entity.get()] = attribute_entity;
						collectDependentEntities( attribute_entity, target_map );
					}
				}
			}
		}
	}

	if( target_map.count( entity.get() ) == 0 )
	{
		target_map[entity.get()] = entity;
	}
}
开发者ID:PanicSheep,项目名称:ifcplusplus,代码行数:78,代码来源:IfcPPModel.cpp

示例7: pinchToVG

/**
 * Create a VG grpah from a pinch thread set.
 */
vg::VG pinchToVG(stPinchThreadSet* threadSet, std::map<int64_t, std::string>& threadSequences) {
    // Make an empty graph
    vg::VG graph;
    
    // Remember what nodes have been created for what segments. Only the first
    // segment in a block (the "leader") gets a node. Segments without blocks
    // are also themselves leaders and get nodes.
    std::map<stPinchSegment*, vg::Node*> nodeForLeader;
    
    std::cerr << "Making pinch graph into vg graph with " << threadSequences.size() << " relevant threads" << std::endl;
    
    // This is the cleverest way to loop over Benedict's iterators.
    auto segmentIterator = stPinchThreadSet_getSegmentIt(threadSet);
    while(auto segment = stPinchThreadSetSegmentIt_getNext(&segmentIterator)) {
        // For every segment, we need to make a VG node for it or its block (if
        // it has one).
        
#ifdef debug
        std::cerr << "Found segment " << segment << std::endl;
#endif
        
        // See if the segment is in a block
        auto block = stPinchSegment_getBlock(segment);
        
        // Get the leader segment: first in the block, or this segment if no block
        auto leader = getLeader(segment);
        
        if(nodeForLeader.count(leader)) {
            // A node has already been made for this block.
            continue;
        }
        
        // Otherwise, we need the sequence
        std::string sequence;
        
        if(block) {
            // Get the sequence by scanning through the block for the first sequence
            // that isn't all Ns, if any.
            auto segmentIterator = stPinchBlock_getSegmentIterator(block);
            while(auto sequenceSegment = stPinchBlockIt_getNext(&segmentIterator)) {
                if(!threadSequences.count(stPinchSegment_getName(sequenceSegment))) {
                    // This segment is part of a staple. Pass it up
                    continue;
                }
                
                // Go get the sequence of the thread, and clip out the part relevant to this segment.
                sequence = threadSequences.at(stPinchSegment_getName(sequenceSegment)).substr(
                    stPinchSegment_getStart(sequenceSegment), stPinchSegment_getLength(sequenceSegment));
                    
                // If necessary, flip the segment around
                if(getOrientation(sequenceSegment)) {
                    sequence = vg::reverse_complement(sequence);
                }
                
                if(std::count(sequence.begin(), sequence.end(), 'N') +
                    std::count(sequence.begin(), sequence.end(), 'n') < sequence.size()) {\
                    
                    // The sequence has some non-N characters
                    // If it's not all Ns, break
                    break;
                }
                
                // Otherwise try the next segment
            }
        } else {
            // Just pull the sequence from the lone segment
            sequence = threadSequences.at(stPinchSegment_getName(segment)).substr(
                stPinchSegment_getStart(segment), stPinchSegment_getLength(segment));
                
            // It doesn't need to flip, since it can't be backwards in a block
        }
        
            
        // Make a node in the graph to represent the block
        vg::Node* node = graph.create_node(sequence);
        
        // Remember it
        nodeForLeader[leader] = node;
#ifdef debug
        std::cerr << "Made node: " << pb2json(*node) << std::endl;
#endif
            
    }
    
    // Now go through the segments again and wire them up.
    segmentIterator = stPinchThreadSet_getSegmentIt(threadSet);
    while(auto segment = stPinchThreadSetSegmentIt_getNext(&segmentIterator)) {
        // See if the segment is in a block
        auto block = stPinchSegment_getBlock(segment);
        
        // Get the leader segment: first in the block, or this segment if no block
        auto leader = getLeader(segment);
        
        // We know we have a node already
        auto node = nodeForLeader.at(leader);
        
        // What orientation is this node in for the purposes of this edge
//.........这里部分代码省略.........
开发者ID:adamnovak,项目名称:corg,代码行数:101,代码来源:main.cpp

示例8: select_block_from_candidates

bool kernel::select_block_from_candidates(
    std::vector<std::pair<std::int64_t, sha256> > & sorted_by_timestamp,
    std::map<sha256, block_index *> & selected_blocks,
    const std::int64_t & selection_interval_stop,
    const std::uint64_t & previous_stake_modifier,
    const block_index ** index_selected
    )
{
    bool selected = false;
    
    sha256 hash_best = 0;
    
    *index_selected = 0;
    
    for (auto & item : sorted_by_timestamp)
    {
        if (globals::instance().block_indexes().count(item.second) == 0)
        {
            log_error(
                "Kernel, select block from candidates failed to find block "
                "index for candidate block " << item.second.to_string() << "."
            );
            
            return false;
        }
        
        const auto & index = globals::instance().block_indexes()[item.second];
        
        if (selected && index->time() > selection_interval_stop)
        {
            break;
        }
        
        if (selected_blocks.count(index->get_block_hash()) > 0)
        {
            continue;
        }
        
        /*
         * Compute the selection hash by hashing its proof-hash and the
         * previous proof-of-stake modifier.
         */
        sha256 hash_proof =
            index->is_proof_of_stake() ?
            index->hash_proof_of_stake() : index->get_block_hash()
        ;
        
        /**
         * Allocate the buffer to calculate the hash of the
         * selection.
         */
        data_buffer buffer;
        
        /**
         * Write the hash of the proof.
         */
        buffer.write_sha256(hash_proof);
        
        /**
         * Write the previous stake modifier.
         */
        buffer.write_uint64(previous_stake_modifier);
        
        /**
         * Calculate the sha256d hash of the hash of the proof and
         * the previous stake modifier.
         */
        auto hash_selection = sha256::from_digest(&hash::sha256d(
            reinterpret_cast<std::uint8_t *>(buffer.data()),
            buffer.size())[0]
        );

        /**
         * Divide by 2**32 so that Proof-of-Stake blocks are favored over
         * Proof-of-Work blocks.
         */
        if (index->is_proof_of_stake())
        {
            hash_selection >>= 32;
        }
        
        if (selected && hash_selection < hash_best)
        {
            hash_best = hash_selection;
            
            *index_selected = reinterpret_cast<const block_index *> (index);
        }
        else if (selected == false)
        {
            selected = true;
            
            hash_best = hash_selection;
            
            *index_selected = reinterpret_cast<const block_index *> (index);
        }
    }
开发者ID:greenmo000,项目名称:vcash,代码行数:96,代码来源:kernel.cpp

示例9: has_map_type

 bool has_map_type(const std::string& map_type_name) const {
     return m_callbacks.count(map_type_name) != 0;
 }
开发者ID:KnockSoftware,项目名称:osrm-backend,代码行数:3,代码来源:map.hpp

示例10: Process

void WorldServer::Process(){
	WorldConnection::Process();
	if (!Connected())
		return;

	ServerPacket *pack = nullptr;
	while((pack = tcpc.PopPacket())){
		Log.Out(Logs::General, Logs::Netcode, "Received Opcode: %4X", pack->opcode);
		//DumpPacket(pack);
		switch(pack->opcode) {
			case 0: { break; }
			case ServerOP_KeepAlive: { break; }
			case ServerOP_WIRemoteCallResponse: {
				char *id = nullptr;
				char *session_id = nullptr;
				char *error = nullptr;

				id = new char[pack->ReadUInt32() + 1];
				pack->ReadString(id);

				session_id = new char[pack->ReadUInt32() + 1];
				pack->ReadString(session_id);

				error = new char[pack->ReadUInt32() + 1];
				pack->ReadString(error);

				uint32 param_count = pack->ReadUInt32();
				std::map<std::string, std::string> params;
				for(uint32 i = 0; i < param_count; ++i) {
					char *first = new char[pack->ReadUInt32() + 1];
					pack->ReadString(first);

					char *second = new char[pack->ReadUInt32() + 1];
					pack->ReadString(second);

					params[first] = second;

					safe_delete_array(first);
					safe_delete_array(second);
				}

				//send the response to client...
				rapidjson::StringBuffer s;
				rapidjson::Writer<rapidjson::StringBuffer> writer(s);

				writer.StartObject();
				writer.String("id");
				if(strlen(id) == 0) {
					writer.Null();
				} else {
					writer.String(id);
				}

				if(strlen(error) != 0) {
					writer.String("error");
					writer.Bool(true);

					writer.String("result");
					writer.String(error);
				} else {
					writer.String("error");
					writer.Null();
					writer.String("result");
					writer.StartObject();
					auto iter = params.begin();
					while(iter != params.end()) {
						writer.String(iter->first.c_str());
						writer.String(iter->second.c_str());
						++iter;
					}
					writer.EndObject();
				}
				writer.EndObject();

				if(sessions.count(session_id) != 0) {
					per_session_data_eqemu *session = sessions[session_id];
					session->send_queue->push_back(s.GetString());
				}

				safe_delete_array(id);
				safe_delete_array(session_id);
				safe_delete_array(error);
				break;
			}

			case ServerOP_WIRemoteCallToClient:
			{
				char *session_id = nullptr;
				char *method = nullptr;

				session_id = new char[pack->ReadUInt32() + 1];
				pack->ReadString(session_id);

				method = new char[pack->ReadUInt32() + 1];
				pack->ReadString(method);

				uint32 param_count = pack->ReadUInt32();
				std::vector<std::string> params(param_count);
				for(uint32 i = 0; i < param_count; ++i) {
					char *p = new char[pack->ReadUInt32() + 1];
//.........这里部分代码省略.........
开发者ID:UnityEQ,项目名称:UnityEQServer,代码行数:101,代码来源:worldserver.cpp

示例11:

bool string_id<requirement_data>::is_valid() const
{
    return requirements_all.count( *this );
}
开发者ID:CrAzYPiLoT-SS13,项目名称:Cataclysm-DDA,代码行数:4,代码来源:requirements.cpp

示例12: strcmp

static tree
build_common_decl (gfc_common_head *com, tree union_type, bool is_init)
{
  tree decl, identifier;

  identifier = gfc_sym_mangled_common_id (com);
  decl = gfc_map_of_all_commons.count(identifier)
	 ? gfc_map_of_all_commons[identifier] : NULL_TREE;

  /* Update the size of this common block as needed.  */
  if (decl != NULL_TREE)
    {
      tree size = TYPE_SIZE_UNIT (union_type);

      /* Named common blocks of the same name shall be of the same size
	 in all scoping units of a program in which they appear, but
	 blank common blocks may be of different sizes.  */
      if (!tree_int_cst_equal (DECL_SIZE_UNIT (decl), size)
	  && strcmp (com->name, BLANK_COMMON_NAME))
	gfc_warning ("Named COMMON block '%s' at %L shall be of the "
		     "same size as elsewhere (%lu vs %lu bytes)", com->name,
		     &com->where,
		     (unsigned long) TREE_INT_CST_LOW (size),
		     (unsigned long) TREE_INT_CST_LOW (DECL_SIZE_UNIT (decl)));

      if (tree_int_cst_lt (DECL_SIZE_UNIT (decl), size))
	{
	  DECL_SIZE (decl) = TYPE_SIZE (union_type);
	  DECL_SIZE_UNIT (decl) = size;
	  DECL_MODE (decl) = TYPE_MODE (union_type);
	  TREE_TYPE (decl) = union_type;
	  layout_decl (decl, 0);
	}
     }

  /* If this common block has been declared in a previous program unit,
     and either it is already initialized or there is no new initialization
     for it, just return.  */
  if ((decl != NULL_TREE) && (!is_init || DECL_INITIAL (decl)))
    return decl;

  /* If there is no backend_decl for the common block, build it.  */
  if (decl == NULL_TREE)
    {
      if (com->is_bind_c == 1 && com->binding_label)
	decl = build_decl (input_location, VAR_DECL, identifier, union_type);
      else
	{
	  decl = build_decl (input_location, VAR_DECL, get_identifier (com->name),
			     union_type);
	  gfc_set_decl_assembler_name (decl, identifier);
	}

      TREE_PUBLIC (decl) = 1;
      TREE_STATIC (decl) = 1;
      DECL_IGNORED_P (decl) = 1;
      if (!com->is_bind_c)
	DECL_ALIGN (decl) = BIGGEST_ALIGNMENT;
      else
        {
	  /* Do not set the alignment for bind(c) common blocks to
	     BIGGEST_ALIGNMENT because that won't match what C does.  Also,
	     for common blocks with one element, the alignment must be
	     that of the field within the common block in order to match
	     what C will do.  */
	  tree field = NULL_TREE;
	  field = TYPE_FIELDS (TREE_TYPE (decl));
	  if (DECL_CHAIN (field) == NULL_TREE)
	    DECL_ALIGN (decl) = TYPE_ALIGN (TREE_TYPE (field));
	}
      DECL_USER_ALIGN (decl) = 0;
      GFC_DECL_COMMON_OR_EQUIV (decl) = 1;

      gfc_set_decl_location (decl, &com->where);

      if (com->threadprivate)
	DECL_TLS_MODEL (decl) = decl_default_tls_model (decl);

      /* Place the back end declaration for this common block in
         GLOBAL_BINDING_LEVEL.  */
      gfc_map_of_all_commons[identifier] = pushdecl_top_level (decl);
    }

  /* Has no initial values.  */
  if (!is_init)
    {
      DECL_INITIAL (decl) = NULL_TREE;
      DECL_COMMON (decl) = 1;
      DECL_DEFER_OUTPUT (decl) = 1;
    }
  else
    {
      DECL_INITIAL (decl) = error_mark_node;
      DECL_COMMON (decl) = 0;
      DECL_DEFER_OUTPUT (decl) = 0;
    }
  return decl;
}
开发者ID:Nodplus,项目名称:gcc,代码行数:98,代码来源:trans-common.c

示例13: LoadTributes

bool ZoneDatabase::LoadTributes() {
	char errbuf[MYSQL_ERRMSG_SIZE];
	MYSQL_RES *result;
	MYSQL_ROW row;

	TributeData t;
	memset(&t.tiers, 0, sizeof(t.tiers));
	t.tier_count = 0;

	tribute_list.clear();

	const char *query = "SELECT id,name,descr,unknown,isguild FROM tributes";
	if (RunQuery(query, strlen(query), errbuf, &result)) {
		int r;
		while ((row = mysql_fetch_row(result))) {
			r = 0;
			uint32 id = atoul(row[r++]);
			t.name = row[r++];
			t.description = row[r++];
			t.unknown = strtoul(row[r++], nullptr, 10);
			t.is_guild = atol(row[r++])==0?false:true;

			tribute_list[id] = t;
		}
		mysql_free_result(result);
	} else {
		LogFile->write(EQEMuLog::Error, "Error in LoadTributes first query '%s': %s", query, errbuf);
		return false;
	}


	const char *query2 = "SELECT tribute_id,level,cost,item_id FROM tribute_levels ORDER BY tribute_id,level";
	if (RunQuery(query2, strlen(query2), errbuf, &result)) {
		int r;
		while ((row = mysql_fetch_row(result))) {
			r = 0;
			uint32 id = atoul(row[r++]);

			if(tribute_list.count(id) != 1) {
				LogFile->write(EQEMuLog::Error, "Error in LoadTributes: unknown tribute %lu in tribute_levels", (unsigned long)id);
				continue;
			}

			TributeData &cur = tribute_list[id];

			if(cur.tier_count >= MAX_TRIBUTE_TIERS) {
				LogFile->write(EQEMuLog::Error, "Error in LoadTributes: on tribute %lu: more tiers defined than permitted", (unsigned long)id);
				continue;
			}

			TributeLevel_Struct &s = cur.tiers[cur.tier_count];

			s.level = atoul(row[r++]);
			s.cost = atoul(row[r++]);
			s.tribute_item_id = atoul(row[r++]);
			cur.tier_count++;
		}
		mysql_free_result(result);
	} else {
		LogFile->write(EQEMuLog::Error, "Error in LoadTributes level query '%s': %s", query, errbuf);
		return false;
	}

	return true;
}
开发者ID:Derision,项目名称:Server,代码行数:65,代码来源:tribute.cpp

示例14: connect_inputs

bool transaction::connect_inputs(
    db_tx & tx_db,
    std::map<sha256, std::pair<transaction_index, transaction> > & inputs,
    std::map<sha256, transaction_index> & test_pool,
    const transaction_position & position_tx_this,
    const block_index * ptr_block_index,
    const bool & connect_block, const bool & create_new_block,
    const bool & strict_pay_to_script_hash, const bool & check_signature,
    std::vector<script_checker> * script_checker_checks
    )
{
    if (is_coin_base() == false)
    {
        std::int64_t value_in = 0;
        std::int64_t fees = 0;
        
        for (auto i = 0; i < m_transactions_in.size(); i++)
        {
            auto & prev_out = m_transactions_in[i].previous_out();
            
            assert(inputs.count(prev_out.get_hash()) > 0);
            
            auto & tx_index = inputs[prev_out.get_hash()].first;
            
            auto & tx_previous = inputs[prev_out.get_hash()].second;

            if (
                prev_out.n() >= tx_previous.transactions_out().size() ||
                prev_out.n() >= tx_index.spent().size()
                )
            {
                log_error(
                    "Transaction connect inputs failed, " <<
                    get_hash().to_string().substr(0, 10) <<
                    " previous out n is out of range [" << prev_out.n() <<
                    "-" << tx_previous.transactions_out().size() << "]" <<
                    " previous transaction " <<
                    prev_out.get_hash().to_string() << "\n" <<
                    tx_previous.to_string()
                );
                
                return false;
            }
            
            /**
             * If previous is coinbase or coinstake, check that it's matured.
             */
            if (tx_previous.is_coin_base() || tx_previous.is_coin_stake())
            {
                for (
                    auto pindex = ptr_block_index;
                    pindex && ptr_block_index->height() - pindex->height() <
                    (constants::test_net ?
                    static_cast<std::int32_t> (constants::coinbase_maturity_test_network) :
                    static_cast<std::int32_t> (constants::coinbase_maturity));
                    pindex = pindex->block_index_previous()
                    )
                {
                    if (
                        pindex->block_position() ==
                        tx_index.get_transaction_position().block_position() &&
                        pindex->file() ==
                        tx_index.get_transaction_position().file_index()
                        )
                    {
                        log_error(
                            "Transaction connect inputs failed, tried to "
                            "spend " << (tx_previous.is_coin_base() ?
                            "coinbase" : "coinstake") << " at depth " <<
                            pindex->height() << "."
                        );
                        
                        return false;
                    }
                }
            }
            
            /**
             * Check the transaction timestamp (ppcoin).
             */
            if (tx_previous.time() > m_time)
            {
                log_error(
                    "Transaction connect inputs failed, timestamp is earlier "
                    "than the input transaction."
                );
                
                return false;
            }
            
            /**
             * Check for negative or overflow input values.
             */
            value_in += tx_previous.transactions_out()[prev_out.n()].value();
            
            if (
                utility::money_range(
                tx_previous.transactions_out()[prev_out.n()].value()) == false ||
                utility::money_range(value_in) == false
                )
//.........这里部分代码省略.........
开发者ID:xCoreDev,项目名称:vcash,代码行数:101,代码来源:transaction.cpp

示例15: ProcessMessageInstantX

void ProcessMessageInstantX(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
    if(fLiteMode) return; //disable all sandstorm/stormnode related functionality
    if(!IsSporkActive(SPORK_2_INSTANTX)) return;
    if(!stormnodeSync.IsBlockchainSynced()) return;

    if (strCommand == "ix")
    {
        //LogPrintf("ProcessMessageInstantX::ix\n");
        CDataStream vMsg(vRecv);
        CTransaction tx;
        vRecv >> tx;

        CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash());
        pfrom->AddInventoryKnown(inv);

        if(mapTxLockReq.count(tx.GetHash()) || mapTxLockReqRejected.count(tx.GetHash())){
            return;
        }

        if(!IsIXTXValid(tx)){
            return;
        }

        BOOST_FOREACH(const CTxOut o, tx.vout){
            // IX supports normal scripts and unspendable scripts (used in SS collateral and Budget collateral).
            // TODO: Look into other script types that are normal and can be included
            if(!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()){
                LogPrintf("ProcessMessageInstantX::ix - Invalid Script %s\n", tx.ToString().c_str());
                return;
            }
        }

        int nBlockHeight = CreateNewLock(tx);

        bool fMissingInputs = false;
        //CValidationState state;

        bool fAccepted = false;
        {
            LOCK(cs_main);
            //TODO (Amir): Pass state to AcceptToMemoryPool
            fAccepted = AcceptToMemoryPool(mempool, tx, true, &fMissingInputs);
        }
        if (fAccepted)
        {
            RelayInv(inv);

            DoConsensusVote(tx, nBlockHeight);

            mapTxLockReq.insert(make_pair(tx.GetHash(), tx));

            LogPrintf("ProcessMessageInstantX::ix - Transaction Lock Request: %s %s : accepted %s\n",
                pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
                tx.GetHash().ToString().c_str()
            );

            return;

        } else {
            mapTxLockReqRejected.insert(make_pair(tx.GetHash(), tx));

            // can we get the conflicting transaction as proof?

            LogPrintf("ProcessMessageInstantX::ix - Transaction Lock Request: %s %s : rejected %s\n",
                pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
                tx.GetHash().ToString().c_str()
            );

            BOOST_FOREACH(const CTxIn& in, tx.vin){
                if(!mapLockedInputs.count(in.prevout)){
                    mapLockedInputs.insert(make_pair(in.prevout, tx.GetHash()));
                }
            }

            // resolve conflicts
            std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(tx.GetHash());
            if (i != mapTxLocks.end()){
                //we only care if we have a complete tx lock
                if((*i).second.CountSignatures() >= INSTANTX_SIGNATURES_REQUIRED){
                    if(!CheckForConflictingLocks(tx)){
                        LogPrintf("ProcessMessageInstantX::ix - Found Existing Complete IX Lock\n");

                        //reprocess the last 15 blocks
                        ReprocessBlocks(15);
                        mapTxLockReq.insert(make_pair(tx.GetHash(), tx));
                    }
                }
            }

            return;
        }
    }
开发者ID:Infernoman,项目名称:DarkSilk-Release-Candidate,代码行数:93,代码来源:instantx.cpp


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