Example #1
0
    void PolygonManager::addPolygon(std::shared_ptr<Polygon> poly)
    {
        if (m_sharedPolygons.count(poly->getId()) > 0) {
            CITYGML_LOG_WARN(m_logger, "Duplicate definition of Polygon with id '" << poly->getId() << "'... overwriting existing object.");
        }

        m_sharedPolygons[poly->getId()] = poly;
    }
void EnvironmentMgr::addPath(const std::shared_ptr<EnvironmentNode> pNode)
{
    auto retVal = m_nodeIds.insert({pNode->getId(), pNode });
    if (!retVal.second)
    {
        throw (ParseException("Attempted to insert duplicate path name " + pNode->getId() + " for node "));
    }
}
bool CImageReceiverWorker::tryLoadMat(
        const QByteArray& receiveStr,
        std::string& errString,
        std::shared_ptr<CMatWithTimeStamp> matPtr)
{
    if (CDeSerializer::load(*matPtr, receiveStr, errString, mBufferId, mLastId))
    {
        if (mpNet->getConnectionConfig().mIsTextBuffer)
        {
            CMainFunctions::doTextAlgo(mAlert);
            return true;
        }
        else
        {
            if (mLastId != static_cast<NTypes::tMatIdType>(-1) && matPtr->getId() < mLastId)
            {
                LOG_DEBUG << "server restart" << mBufferId << mpNet->getConnectionConfig();
                //TODO: test it
                //            mImageBuffer.clear(mBufferId);
                //            CMainFunctions::restartAlgo(mBufferId, mAlgorithms);
            }
            mLastId = matPtr->getId();
            if (!matPtr->getMat().empty())
            {
                CImageBuffer::getBufferInstance().push_back(mBufferId, matPtr);
                if (CConfig::getInstance().mRunStatus.mIsRunMotionAlgo)
                {
                    if (CConfig::getInstance().mIsAlgoRunAsync)
                    {
                        std::thread thread(
                                    CMainFunctions::doAlgoAsync,
                                    std::ref(mAlert),
                                    mBufferId,
                                    std::ref(mAlgorithms),
                                    std::ref(mAlgoMutex),
                                    "Net_" + mUrl);
                        thread.detach();
                    }
                    else
                    {
                        CMainFunctions::doAlgo(mAlert, mBufferId, mAlgorithms, "Net_" + mUrl);
                    }
                }
            }
            else
        {
            LOG_WARN << "empty image";
        }
        return true;
        }
    }
    return false;
}
Example #4
0
void CommunicationInterface::handleMessage(std::shared_ptr<Message> message)
{
  auto entity = message->getEntity();
  _log->info("Received Message with id '%v' from %v", std::to_string(message->getId()), entity->toString());
  entity->setActiveTimestamp();

  switch (message->getId())
  {
    case (SCMD_IDS_REQUEST):
      this->onRequestIds(entity);
      break;

    case (SCMD_IDS_RESPONSE):
    {
      entity->fuse(std::static_pointer_cast<IdMessage>(message)->getIds());
      entity->checkIce();
      break;
    }

    case (SCMD_ID_REQUEST):
        // TODO
      break;

    case (SCMD_ID_RESPONSE):
      // TODO
      break;

    case (SCMD_OFFERS_REQUEST):
      this->onRequestOffers(entity);
      break;

    case (SCMD_OFFERS_RESPONSE):
        entity->addOfferedInformation(std::static_pointer_cast<OffersMessage>(message)->getOfferes());
      break;

    case (SCMD_INFORMATION_REQUEST):
        this->onRequestInformation(entity, std::static_pointer_cast<RequestMessage>(message)->getRequests());
    break;

    case (SCMD_INFORMATION_RESPONSE):
        this->onInformation(entity, std::static_pointer_cast<InformationMessage>(message)->getInformations());
    break;

    default:
      _log->error("Unknown command '%v', message will be skipped", std::to_string(message->getId()));
      break;
  }
}
Example #5
0
void ShardRegistryData::_addShard(WithLock lk,
                                  std::shared_ptr<Shard> const& shard,
                                  bool useOriginalCS) {
    const ShardId shardId = shard->getId();

    const ConnectionString connString =
        useOriginalCS ? shard->originalConnString() : shard->getConnString();

    auto currentShard = _findByShardId(lk, shardId);
    if (currentShard) {
        auto oldConnString = currentShard->originalConnString();

        if (oldConnString.toString() != connString.toString()) {
            log() << "Updating ShardRegistry connection string for shard " << currentShard->getId()
                  << " from: " << oldConnString.toString() << " to: " << connString.toString();
        }

        for (const auto& host : oldConnString.getServers()) {
            _lookup.erase(host.toString());
            _hostLookup.erase(host);
        }
        _lookup.erase(oldConnString.toString());
    }

    _lookup[shard->getId()] = shard;

    LOG(3) << "Adding shard " << shard->getId() << ", with CS " << connString.toString();
    if (connString.type() == ConnectionString::SET) {
        _rsLookup[connString.getSetName()] = shard;
    } else if (connString.type() == ConnectionString::CUSTOM) {
        // CUSTOM connection strings (ie "$dummy:10000) become DBDirectClient connections which
        // always return "localhost" as their response to getServerAddress().  This is just for
        // making dbtest work.
        _lookup[ShardId("localhost")] = shard;
        _hostLookup[HostAndPort("localhost")] = shard;
    }

    // TODO: The only reason to have the shard host names in the lookup table is for the
    // setShardVersion call, which resolves the shard id from the shard address. This is
    // error-prone and will go away eventually when we switch all communications to go through
    // the remote command runner and all nodes are sharding aware by default.
    _lookup[connString.toString()] = shard;

    for (const HostAndPort& hostAndPort : connString.getServers()) {
        _lookup[hostAndPort.toString()] = shard;
        _hostLookup[hostAndPort] = shard;
    }
}
Example #6
0
bool UILogic::handle(const gearsbox::ViewEventParam & param, const std::shared_ptr<gearsbox::ViewGen> & view){
    if (nullptr == view){
        G_LOG_FC(LOG_ERROR, "handle event viewgen null");
        return false;
    }
    
    //G_LOG_FC(LOG_INFO, "handle event view:%s event:%d text:%s", view->getId().c_str(), param.type, param.text.c_str());
    
    if (ViewType::LABEL == view->getType()){
        
        if (m_input->getText().size() != 0)
            updateValueLabel(view->getId(), false);
        PlatformUtilityGen::instance()->getExcutor()->endEniting(true);
    }
    else if (ViewType::BASE == view->getType()){
        PlatformUtilityGen::instance()->getExcutor()->endEniting(true);
    }
    else if (ViewType::INPUT == view->getType()){
        if (view == m_input && param.text.size()>0){
            view->getText();
            m_value = atof(param.text.c_str());
            //UsnitGen::instance()->setInput(value);
            updateValueLabel("", true);
        }
    }
    
    return true;
}
	void sendCommand(std::shared_ptr<User> user, const std::string &message, Args... args)
	{
		std::string msg = Utils::format(message, args...);
		// Crop message if it's longer than 1024 bytes
		// Let's hope TeamSpeak won't complain if we destroy some unicode
		// Also, some characters are expanded to 2 bytes:
		static const std::string doubleChars = " \\/\n\r\f\t\v|";

		// Find out when the max length is reached
		std::string::size_type length = 0;
		std::string::size_type i = 0;
		for (; i < msg.length() && length < 1024; i++)
		{
			if (doubleChars.find(msg[i]) != std::string::npos)
				length += 2;
			else
				length++;
		}
		if (length > 1024 || i < msg.length() - 1)
		{
			// Something needs to be removed again because the last parsed
			// character takes 2 bytes
			if (length > 1024)
				i--;

			msg.erase(msg.begin() + i + 1, msg.end());
			// Append ...
			msg[i - 2] = '.';
			msg[i - 1] = '.';
			msg[i] = '.';
		}
		tsApi->handleTsError(tsApi->getFunctions().requestSendPrivateTextMsg(
			handlerId, msg.c_str(), user->getId(),
			nullptr));
	}
Example #8
0
std::list<std::shared_ptr<MediaObjectImpl>>
    MediaSet::getChildren (std::shared_ptr<MediaObjectImpl> obj)
{
  std::unique_lock <std::recursive_mutex> lock (recMutex);
  std::list<std::shared_ptr<MediaObjectImpl>> ret;

  try {
    for (auto it : childrenMap.at (obj->getId() ) ) {
      ret.push_back (it.second);
    }
  } catch (std::out_of_range) {
    GST_DEBUG ("Object %s has not children", obj->getId().c_str() );
  }

  return ret;
}
   void TransformFeedback::calculate(std::shared_ptr<GLBuffer> outBuffer, int vertexCount, GLenum primitiveType)
   {
      SCOPED_BIND(mProgramData);

      glEnable(GL_RASTERIZER_DISCARD);
      CHECK_GL_ERROR();
      glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, outBuffer->getId());
      CHECK_GL_ERROR();

      GLenum transformPrimitiveType = primitiveType;

      switch (primitiveType)
      {
      case GL_POINTS:
         transformPrimitiveType = GL_POINTS; break;
      case GL_LINES:
      case GL_LINE_LOOP:
      case GL_LINE_STRIP:
         transformPrimitiveType = GL_LINES; break;
      case GL_TRIANGLES:
      case GL_TRIANGLE_STRIP:
      case GL_TRIANGLE_FAN:
         transformPrimitiveType = GL_TRIANGLES; break;
      }

      glBeginTransformFeedback(transformPrimitiveType);
      CHECK_GL_ERROR();
      glDrawArrays(primitiveType, 0, vertexCount);
      CHECK_GL_ERROR();
      glEndTransformFeedback();
      CHECK_GL_ERROR();

      glDisable(GL_RASTERIZER_DISCARD);
      CHECK_GL_ERROR();
   }
Example #10
0
void GLModel::Draw(std::shared_ptr<GLUniform> fragment, GLuint program)
{
    GLint face_offset = 0;
    GLint vertex_offset = 0;
    glBindVertexArray(this->vao);

    bool texture, color;

    color = (fragment->getId() != UINT_MAX);

    if(color)
    {
        glBindBuffer(GL_UNIFORM_BUFFER, fragment->getId());
    }

    //Draw Model 
    for(size_t i=0; i< this->faces->size(); i++)
    {   

        texture = this->textures->at(this->mtlIndices.at(i)).first;
        if(texture)
            this->textures->at(this->mtlIndices.at(i)).second.Bind(GL_TEXTURE0);
        if(color)
        {
            glBufferSubData(GL_UNIFORM_BUFFER,
                        0,
                        sizeof(this->materials->at(this->mtlIndices.at(i)).second),
                        &(this->materials->at(this->mtlIndices.at(i)).second) );
        }

        if( (color && !texture) || (!color && texture) )
        {
            glDrawElementsBaseVertex(GL_TRIANGLES, 
                    this->faces->at(i).size(),
                    GL_UNSIGNED_INT,
                    (void*)(sizeof(GLuint) * face_offset),
                    vertex_offset);
        }

        face_offset += this->faces->at(i).size();
        vertex_offset += this->positions->at(i).size();
    }

    glBindBuffer(GL_UNIFORM_BUFFER, 0);
    glBindTexture(GL_TEXTURE_2D, 0);
    glBindVertexArray(0);
}
Example #11
0
static void
releaseTestSrc (std::shared_ptr<MediaElementImpl> &ep)
{
  std::string id = ep->getId();

  ep.reset();
  MediaSet::getMediaSet ()->release (id);
}
Example #12
0
static void
releaseRtpEndpoint (std::shared_ptr<RtpEndpointImpl> &ep)
{
  std::string id = ep->getId();

  ep.reset();
  MediaSet::getMediaSet ()->release (id);
}
Example #13
0
 virtual void erase (std::unique_lock <std::mutex>& guard, std::shared_ptr <Resource> resource) noexcept {
    assert (guard.mutex () == &m_mutex);
    
    resource_iterator ii = m_resources.find (resource->getId ());
    
    if (ii != resource_end ())
       m_resources.erase (ii);
 }
Example #14
0
void Cube::upload(std::shared_ptr<GLShader> &s) {
	shader = s;
	shader->bind();

	// VAO
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	// Positions
	glGenBuffers(1, &vbo[VERTEX_BUFFER]);
	glBindBuffer(GL_ARRAY_BUFFER, vbo[VERTEX_BUFFER]);
	glBufferData(GL_ARRAY_BUFFER, 3 * m_V.cols() * sizeof(GLfloat), (const uint8_t *)m_V.data(), GL_STREAM_DRAW);
	GLuint pp = glGetAttribLocation(s->getId(), glPositionName.c_str());
	glVertexAttribPointer(pp, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(pp);

	// UV
	if (m_UV.cols() > 0) {
		glGenBuffers(1, &vbo[TEXCOORD_BUFFER]);
		glBindBuffer(GL_ARRAY_BUFFER, vbo[TEXCOORD_BUFFER]);
		glBufferData(GL_ARRAY_BUFFER, 2 * m_V.cols() * sizeof(GLfloat), (const uint8_t *)m_UV.data(), GL_STATIC_DRAW);
		GLuint uvp = glGetAttribLocation(s->getId(), glTexName.c_str());
		glVertexAttribPointer(uvp, 2, GL_FLOAT, GL_FALSE, 0, 0);
		glEnableVertexAttribArray(uvp);
	}

	// Normals
	if (m_N.cols() > 0) {
		glGenBuffers(1, &vbo[NORMAL_BUFFER]);
		glBindBuffer(GL_ARRAY_BUFFER, vbo[NORMAL_BUFFER]);
		glBufferData(GL_ARRAY_BUFFER, 3 * m_V.cols() * sizeof(GLfloat), (const uint8_t *)m_N.data(), GL_STATIC_DRAW);
		GLuint np = glGetAttribLocation(s->getId(), glNormalName.c_str());
		glVertexAttribPointer(np, 3, GL_FLOAT, GL_FALSE, 0, 0);
		glEnableVertexAttribArray(np);
	}

	// Indices
	glGenBuffers(1, &vbo[INDEX_BUFFER]);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[INDEX_BUFFER]);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, 3 * m_F.cols() * sizeof(GLuint), (const uint8_t *)m_F.data(), GL_STATIC_DRAW);

	// Reset state
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindVertexArray(0);
}
void
ServerMethods::registerEventHandler (std::shared_ptr<MediaObjectImpl> obj,
                                     const std::string &sessionId,
                                     const  std::string &subscriptionId,
                                     std::shared_ptr<EventHandler> handler)
{
  MediaSet::getMediaSet()->addEventHandler (sessionId, obj->getId(),
      subscriptionId, handler);
}
Example #16
0
std::shared_ptr<Metadata> MetadataStream::import( MetadataStream& srcStream, std::shared_ptr< Metadata >& spMetadata, std::map< IdType, IdType >& mapIds, long long nTarFrameIndex, long long nSrcFrameIndex, long long nNumOfFrames )
{
    auto nSrcMetadataId = spMetadata->getId();

    // Check to make sure the metadata belongs to the source stream
    if( nSrcMetadataId < 0 || srcStream.getById( nSrcMetadataId ) != spMetadata )
    {
        VMF_EXCEPTION(IncorrectParamException, "The input metadata does not belong to the source stream!" );
    }

    // Skip if it has already been imported
    if( mapIds.find( nSrcMetadataId ) != mapIds.end() )
    {
        auto spNewMetadata = this->getById( mapIds[ nSrcMetadataId ] );
        if( spNewMetadata == nullptr )
        {
            VMF_EXCEPTION(InternalErrorException, "Unexpected exception!" );
        }

        return spNewMetadata;
    }

    // Make a deep copy, add to the new stream, and add to the map
    std::shared_ptr< Metadata > spNewMetadata( new Metadata( *spMetadata ));
    if( !spNewMetadata->shiftFrameIndex( nTarFrameIndex, nSrcFrameIndex, nNumOfFrames ))
    {
        return nullptr;
    }

    auto nNewMetadataId = this->add( spNewMetadata );
    mapIds[ nSrcMetadataId ] = nNewMetadataId;

    // Wire to the correct description
    auto spNewSchema = this->getSchema( spMetadata->getSchemaName() );
    auto spNewDescriptor = spNewSchema == nullptr ? nullptr : spNewSchema->findMetadataDesc( spMetadata->getName() );
    if( spNewDescriptor == nullptr )
    {
        VMF_EXCEPTION(InternalErrorException, "Metadata schema or description was not found!" );
    }
    spNewMetadata->setDescriptor( spNewDescriptor );

    // Import all references recursively
    spNewMetadata->removeAllReferences();
    auto vReferences = spMetadata->getAllReferences();
    std::for_each( vReferences.begin(), vReferences.end(), [&]( Reference& reference )
    {
        // Import the reference to the new stream
        std::shared_ptr<Metadata> md = reference.getReferenceMetadata().lock();
        auto spNewReference = import( srcStream, md, mapIds, nTarFrameIndex, nSrcFrameIndex, nNumOfFrames );

        // Add as reference
        if( spNewReference != nullptr )
            spNewMetadata->addReference( spNewReference );
    });

    return spNewMetadata;
}
Example #17
0
void Scheduler::finished(const std::shared_ptr<Coroutine>& coroutine)
{
    // Check for any joins on this coroutine, then push it onto the finished
    // coroutine list
    coroutineDone(coroutine);
    DEBUG("Putting coroutine %d in the finish list", coroutine->getId());
    printFinishedQueue();
    m_finishedCoroutines.push_back(coroutine);
}
Example #18
0
/*
 * 決定的最大値行動更新ルール
 */
void BestStrategyRule::runRule(
		const std::shared_ptr<Player>& player,
		const AllPlayer& allPlayers,
		const spd::param::Parameter& param,
		int step) {

	// 戦略更新周期でなければ、何もしない
	if (step % param.getRuntimeParameter()->getStrategyUpdateCycle() != 0) {
		return;
	}

	// 近傍の設定
	auto phase = NeighborhoodType::STRATEGY;
	auto neighbors = player->getNeighbors(phase);
	if (neighbors == nullptr) {
		neighbors = std::move(param.getNeighborhoodParameter()->getTopology()->getNeighbors(
				allPlayers,
				player->getId(),
				param.getNeighborhoodParameter()->getNeiborhoodRadius(phase)));
	}

	// 最大値は自身ので初期化
	double maxScore = player->getPreScore();
	// 最大戦略のID
	int maxStrategyId = player->getPreStrategy()->getId();

	// 自身と比べる必要はないので1から。
	for (int r = 1, rMax = neighbors->size(); r < rMax; ++r) {
		for (auto& opponentWP : *(neighbors->at(r))) {

			auto opponent = opponentWP.lock();

			if (opponent == nullptr) {
				// 近傍がいない場合終了
				throw std::runtime_error("Could not find a neighbor of a player.");
			}

			if (maxScore < opponent->getPreScore()) {
				// 対戦相手の戦略が高い場合、その戦略を記憶
				maxStrategyId = opponent->getPreStrategy()->getId();
				maxScore = opponent->getPreScore();
			} else if ((maxScore == opponent->getPreScore())
					&& (player->getPreStrategy()->getId() == opponent->getPreStrategy()->getId())) {
				// 利得が同じなら、戦略を維持する
				maxStrategyId = opponent->getPreStrategy()->getId();
			}
		}
	}

	// 最大の戦略を設定
	player->setStrategy(param.getStrategyList().at(maxStrategyId).first);

	// 利得を0にする
	player->setScore(0.0);
}
Example #19
0
void ParallelSortClusteredCursor::setupVersionAndHandleSlaveOk(
    OperationContext* txn,
    PCStatePtr state,
    const ShardId& shardId,
    std::shared_ptr<Shard> primary,
    const NamespaceString& ns,
    const string& vinfo,
    std::shared_ptr<ChunkManager> manager) {
    if (manager) {
        state->manager = manager;
    } else if (primary) {
        state->primary = primary;
    }

    verify(!primary || shardId == primary->getId());

    // Setup conn
    if (!state->conn) {
        const auto shard = grid.shardRegistry()->getShard(txn, shardId);
        state->conn.reset(new ShardConnection(shard->getConnString(), ns.ns(), manager));
    }

    const DBClientBase* rawConn = state->conn->getRawConn();
    bool allowShardVersionFailure = rawConn->type() == ConnectionString::SET &&
        DBClientReplicaSet::isSecondaryQuery(_qSpec.ns(), _qSpec.query(), _qSpec.options());
    bool connIsDown = rawConn->isFailed();
    if (allowShardVersionFailure && !connIsDown) {
        // If the replica set connection believes that it has a valid primary that is up,
        // confirm that the replica set monitor agrees that the suspected primary is indeed up.
        const DBClientReplicaSet* replConn = dynamic_cast<const DBClientReplicaSet*>(rawConn);
        invariant(replConn);
        ReplicaSetMonitorPtr rsMonitor = ReplicaSetMonitor::get(replConn->getSetName());
        if (!rsMonitor->isHostUp(replConn->getSuspectedPrimaryHostAndPort())) {
            connIsDown = true;
        }
    }

    if (allowShardVersionFailure && connIsDown) {
        // If we're doing a secondary-allowed query and the primary is down, don't attempt to
        // set the shard version.

        state->conn->donotCheckVersion();

        // A side effect of this short circuiting is the mongos will not be able figure out that
        // the primary is now up on it's own and has to rely on other threads to refresh node
        // states.

        OCCASIONALLY {
            const DBClientReplicaSet* repl = dynamic_cast<const DBClientReplicaSet*>(rawConn);
            dassert(repl);
            warning() << "Primary for " << repl->getServerAddress()
                      << " was down before, bypassing setShardVersion."
                      << " The local replica set view and targeting may be stale.";
        }
    } else {
Example #20
0
	void Image::loadTexture(std::shared_ptr<Texture> texture, size_t width, size_t height, ImageChannels channels)
	{
		this->width = width;
		this->height = height;
		this->channels = channels;
		GLRUN(glBindTexture(GL_TEXTURE_2D, texture->getId()));
		int pixSize = channels == ImageChannels::ImageRGB ? 3 : 4;
		GLenum format = channels == ImageChannels::ImageRGB ? GL_RGB : GL_RGBA;
		this->data = std::vector<unsigned char>(width * height * pixSize);
		GLRUN(glGetTexImage(GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, this->data.data()));
	}
Example #21
0
void
MediaSet::ref (const std::string &sessionId,
               std::shared_ptr<MediaObjectImpl> mediaObject)
{
  std::unique_lock <std::recursive_mutex> lock (recMutex);

  if (objectsMap.find (mediaObject->getId() ) == objectsMap.end() ) {
    throw KurentoException (MEDIA_OBJECT_NOT_FOUND,
                            "Cannot register media object, it was not created by MediaSet");
  }

  keepAliveSession (sessionId, true);

  if (mediaObject->getParent() ) {
    ref (sessionId,
         std::dynamic_pointer_cast<MediaObjectImpl> (mediaObject->getParent() ) );
  }

  sessionMap[sessionId][mediaObject->getId()] = mediaObject;
  reverseSessionMap[mediaObject->getId()].insert (sessionId);
}
Example #22
0
void Scheduler::start(const std::shared_ptr<Coroutine>& coroutine)
{
    DEBUG("Starting coroutine %d...", coroutine->getId());

    // Ensure that this coroutine is not already scheduled
    if(m_readyCoroutines.find(coroutine) == m_readyCoroutines.end()
            && m_unstartedCoroutines.find(coroutine) == m_unstartedCoroutines.end())
    {
        // Insert the coroutine into the unstarted coroutine list
        m_unstartedCoroutines.insert(coroutine);
    }
}
	void TypeCollection::addType( std::shared_ptr< TypeMetainfoImpl_I > type )
	{
		auto it = std::find_if( mTypes.begin(), mTypes.end(), TypeByName( type->getId()->getName() ) );
		if ( it != mTypes.end() )
		{
			std::ostringstream msg;
			msg << "type " << type->getId()->getName() << " already exists" << std::endl;
			throw AlreadyExists( msg.str() );
		}

		if ( !type->isBasicType() )
		{
			auto custom = std::static_pointer_cast< const CustomTypeMetainfoImpl >( type );
			auto connection = custom->registerToDestroyed( std::bind( &TypeCollection::typeDestroyed, this, std::placeholders::_1 ) );
			mTypes.push_back( std::make_pair( connection, type ) );
		}
		else
		{
			mTypes.push_back( std::make_pair( Connection(), type ) );
		}
	}
Example #24
0
void ParallelSortClusteredCursor::setupVersionAndHandleSlaveOk(
    OperationContext* txn,
    PCStatePtr state,
    const ShardId& shardId,
    std::shared_ptr<Shard> primary,
    const NamespaceString& ns,
    const string& vinfo,
    std::shared_ptr<ChunkManager> manager) {
    if (manager) {
        state->manager = manager;
    } else if (primary) {
        state->primary = primary;
    }

    verify(!primary || shardId == primary->getId());

    // Setup conn
    if (!state->conn) {
        const auto shard = uassertStatusOK(Grid::get(txn)->shardRegistry()->getShard(txn, shardId));
        state->conn.reset(new ShardConnection(shard->getConnString(), ns.ns(), manager));
    }

    const DBClientBase* rawConn = state->conn->getRawConn();
    bool allowShardVersionFailure = rawConn->type() == ConnectionString::SET &&
        DBClientReplicaSet::isSecondaryQuery(_qSpec.ns(), _qSpec.query(), _qSpec.options());

    // Skip shard version checking if primary is known to be down.
    if (allowShardVersionFailure) {
        const DBClientReplicaSet* replConn = dynamic_cast<const DBClientReplicaSet*>(rawConn);
        invariant(replConn);
        ReplicaSetMonitorPtr rsMonitor = ReplicaSetMonitor::get(replConn->getSetName());
        uassert(16388,
                str::stream() << "cannot access unknown replica set: " << replConn->getSetName(),
                rsMonitor != nullptr);
        if (!rsMonitor->isKnownToHaveGoodPrimary()) {
            state->conn->donotCheckVersion();

            // A side effect of this short circuiting is the mongos will not be able figure out
            // that the primary is now up on it's own and has to rely on other threads to refresh
            // node states.

            OCCASIONALLY {
                const DBClientReplicaSet* repl = dynamic_cast<const DBClientReplicaSet*>(rawConn);
                dassert(repl);
                warning() << "Primary for " << repl->getServerAddress()
                          << " was down before, bypassing setShardVersion."
                          << " The local replica set view and targeting may be stale.";
            }

            return;
        }
    }
Example #25
0
void TcpServer::writeOrRemove(std::shared_ptr<ClientContext> cc,
		const std::string& datagram) {
	auto id = cc->getId();
	boost::asio::async_write(cc->getTcpSocket(), boost::asio::buffer(datagram),
			[this, id](boost::system::error_code ec, std::size_t transferred) {
				if (ec) {
					INFO(ec);
					controller.removeClient(id);
				} else {
					LOG("Datagram sent to client, id: " + _(id));
				}
			});
}
Example #26
0
/*
 * 平均利得の対戦を行う
 */
void AverageGameRule::runRule(
		const std::shared_ptr<Player>& player,
		const AllPlayer& allPlayers,
		const spd::param::Parameter& param,
		int step) {

	// 近傍の設定
	auto phase = NeighborhoodType::GAME;
	auto neighbors = player->getNeighbors(phase);
	if (neighbors == nullptr) {
		neighbors = std::move(param.getNeighborhoodParameter()->getTopology()->getNeighbors(
				allPlayers,
				player->getId(),
				param.getNeighborhoodParameter()->getNeiborhoodRadius(phase)));
	}

	double payoffSum = 0.0;

	int neighborsCount = 0;

	// 自身の利得行を取得
	auto payoffRow = param.getRuntimeParameter()->getPayoffRow(player->getAction());

	int startRadius = 0;
	// 自己対戦がないなら、半径1から
	if (!param.getRuntimeParameter()->isSelfInteraction()) {
		startRadius++;
	}
	// 近傍対戦
	for (int r = startRadius, rMax = neighbors->size(); r < rMax; ++r) {
		for (auto& opponentWP : *(neighbors->at(r))) {

			auto opponent = opponentWP.lock();

			if (opponent == nullptr) {
				// 近傍がいない場合終了
				throw std::runtime_error("Could not find a neighbor of a player.");
			}

			// 対戦者の数を追加
			neighborsCount++;

			payoffSum += payoffRow[static_cast<int>(opponent->getAction())];
		}
	}

	double payoffAve = payoffSum / neighborsCount;

	// 利得を加える
	player->addScore(payoffAve);
}
Example #27
0
void CSerializer::save(
        const std::shared_ptr<CMatWithTimeStamp> mat,
        ImageType::EType type,
        CNetProtocol::ANSVER ansver,
        NTypes::tIdType imageQuality,
        QByteArray& outArray,
        const QString& infoStr)
{
    outArray.clear();
    static_assert(ImageType::MAX_VALUE == 6, "Change ImageType enum");
    {
        QDataStream stream(&outArray, QIODevice::ReadWrite);

        stream.setVersion(CNetValues::sDataStreamVersion);
        stream << CNetValues::sVersion;
        stream << infoStr;
        stream << static_cast<NTypes::tAnsver>(ansver);  //TODO: in server (actual??)

        if (ansver == CNetProtocol::ANSVER::IMAGE_ID)
        {
            std::vector<int> compressionParams;
            compressionParams.push_back(CV_IMWRITE_JPEG_QUALITY);
            compressionParams.push_back(imageQuality);

            std::vector<uchar> buff;
            cv::imencode(".jpg", mat->getMat(type), buff, compressionParams);
            NTypes::tBuffSizeTmp buffSize = buff.size(); //fix fail compile on gcc-4.9
            const char* charArray =  reinterpret_cast<const char*>(&buff.at(0));

            stream <<  mat->getId();
            stream << mat->getDateTimeCreation();
            stream << buffSize;

            stream.writeRawData(charArray, buff.size());
            stream << CMemoryUssage::processMemoryUssage();

            CHashFunctions::writeHash(outArray, stream);
        }
        else if (ansver == CNetProtocol::ANSVER::TEXT_BUFFER)
        {
            stream <<  NText::CTextBuffer::getInstance().getMap();
            CHashFunctions::writeHash(outArray, stream);
        }
        else
        {
            CHashFunctions::writeHash(outArray, stream);
        }
    }
}
Example #28
0
    void ChunkRenderer::activateTileAndSetTileUniforms(
        std::shared_ptr<LayeredTextureShaderUniformIdHandler> uniformIdHandler,
        LayeredTextures::TextureCategory textureCategory,
        LayeredTextureShaderUniformIdHandler::BlendLayerSuffixes blendLayerSuffix,
        size_t layerIndex,
        ghoul::opengl::TextureUnit& texUnit,
        const TileAndTransform& tileAndTransform)
    {

        // Blend tile with two parents
        // The texture needs a unit to sample from
        texUnit.activate();
        tileAndTransform.tile.texture->bind();

        uniformIdHandler->programObject().setUniform(
            uniformIdHandler->getId(
                textureCategory,
                blendLayerSuffix,
                layerIndex,
                LayeredTextureShaderUniformIdHandler::GlslTileDataId::textureSampler),
            texUnit);
        uniformIdHandler->programObject().setUniform(
            uniformIdHandler->getId(
                textureCategory,
                blendLayerSuffix,
                layerIndex,
                LayeredTextureShaderUniformIdHandler::GlslTileDataId::uvTransform_uvScale),
            tileAndTransform.uvTransform.uvScale);
        uniformIdHandler->programObject().setUniform(
            uniformIdHandler->getId(
                textureCategory,
                blendLayerSuffix,
                layerIndex,
                LayeredTextureShaderUniformIdHandler::GlslTileDataId::uvTransform_uvOffset),
            tileAndTransform.uvTransform.uvOffset);
    }
Example #29
0
    void ChunkRenderer::setDepthTransformUniforms(
        std::shared_ptr<LayeredTextureShaderUniformIdHandler> uniformIdHandler,
        LayeredTextures::TextureCategory textureCategory,
        LayeredTextureShaderUniformIdHandler::BlendLayerSuffixes blendLayerSuffix,
        size_t layerIndex,
        const TileDepthTransform& tileDepthTransform)
    {   
        uniformIdHandler->programObject().setUniform(
            uniformIdHandler->getId(
                textureCategory,
                blendLayerSuffix,
                layerIndex,
                LayeredTextureShaderUniformIdHandler::GlslTileDataId::depthTransform_depthScale),
            tileDepthTransform.depthScale);

        uniformIdHandler->programObject().setUniform(
            uniformIdHandler->getId(
                textureCategory,
                blendLayerSuffix,
                layerIndex,
                LayeredTextureShaderUniformIdHandler::GlslTileDataId::depthTransform_depthOffset),
            tileDepthTransform.depthOffset);

    }
Example #30
0
SimulateTrafficDialog::SimulateTrafficDialog(std::shared_ptr<Router> r, std::shared_ptr<IController> editor, QMainWindow *widget)
: QDialog(widget)
{
    nodesEditor = editor;
    id = r->getId();
    router = r;
    router->attach(this);
    view = widget;
    repopulateFecList();
    this->setAttribute(Qt::WA_DeleteOnClose);
    mainLayout = new QVBoxLayout;
    mainLayout->setSizeConstraint(QLayout::SetFixedSize);
    QHBoxLayout *firstLayout = new QHBoxLayout;
    QHBoxLayout *secondLayout = new QHBoxLayout;
    QHBoxLayout *thirdLayout = new QHBoxLayout;
    setLayout(mainLayout);
    mainLayout->addLayout(firstLayout);
    mainLayout->addLayout(secondLayout);
    mainLayout->addLayout(thirdLayout);

    fecComboBox = new QComboBox;
    fillFecComboBox(fecComboBox);
    firstLayout->addWidget(fecComboBox);

    startButton = new QPushButton(tr("Start"));
    stopButton = new QPushButton(tr("Stop"));
    secondLayout->addWidget(startButton);
    secondLayout->addWidget(stopButton);

    prevButton = new QPushButton(tr("Prev"));
    nextButton = new QPushButton(tr("Next"));
    thirdLayout->addWidget(prevButton);
    thirdLayout->addWidget(nextButton);

    connect(startButton, SIGNAL(pressed()),
                         this, SLOT(handleStartButton()));
    connect(stopButton, SIGNAL(pressed()),
                         this, SLOT(handleStopButton()));
    connect(prevButton, SIGNAL(pressed()),
                         this, SLOT(handlePrevButton()));
    connect(nextButton, SIGNAL(pressed()),
                         this, SLOT(handleNextButton()));

    stopButton->setEnabled(false);
    prevButton->setEnabled(false);
    nextButton->setEnabled(false);
    this->setWindowTitle("Trafiic simulation");
}