void c_AsyncFunctionWaitHandle::exitContext(context_idx_t ctx_idx) { assert(AsioSession::Get()->getContext(ctx_idx)); // stop before corrupting unioned data if (isFinished()) { decRefObj(this); return; } // not in a context being exited assert(getContextIdx() <= ctx_idx); if (getContextIdx() != ctx_idx) { decRefObj(this); return; } switch (getState()) { case STATE_BLOCKED: // we were already ran due to duplicit scheduling; the context will be // updated thru exitContext() call on the non-blocked wait handle we // recursively depend on decRefObj(this); break; case STATE_READY: // Recursively move all wait handles blocked by us. getParentChain().exitContext(ctx_idx); // Move us to the parent context. setContextIdx(getContextIdx() - 1); // Reschedule if still in a context. if (isInContext()) { if (isFastResumable()) { getContext()->scheduleFast(this); } else { getContext()->schedule(this); } } else { decRefObj(this); } break; default: assert(false); } }
void LoopAction::update(float dt){ if (!isFinished()){ actionList[currentIndex]->update(dt); if (actionList[currentIndex]->finished) currentIndex = currentIndex + 1; if (currentIndex == actionList.size()){ for (auto action : actionList){ action->init(); } currentIndex = 0; } } else { finished = true; } }
void LLLibraryOutfitsFetch::folderDone() { llinfos << "start" << llendl; LLInventoryModel::cat_array_t cat_array; LLInventoryModel::item_array_t wearable_array; gInventory.collectDescendents(mMyOutfitsID, cat_array, wearable_array, LLInventoryModel::EXCLUDE_TRASH); // Early out if we already have items in My Outfits // except the case when My Outfits contains just initial outfit if (cat_array.count() > 1) { mOutfitsPopulated = true; return; } mClothingID = gInventory.findCategoryUUIDForType(LLFolderType::FT_CLOTHING); mLibraryClothingID = gInventory.findCategoryUUIDForType(LLFolderType::FT_CLOTHING, false, true); // If Library->Clothing->Initial Outfits exists, use that. LLNameCategoryCollector matchFolderFunctor("Initial Outfits"); cat_array.clear(); gInventory.collectDescendentsIf(mLibraryClothingID, cat_array, wearable_array, LLInventoryModel::EXCLUDE_TRASH, matchFolderFunctor); if (cat_array.count() > 0) { const LLViewerInventoryCategory *cat = cat_array.get(0); mLibraryClothingID = cat->getUUID(); } mComplete.clear(); // Get the complete information on the items in the inventory. uuid_vec_t folders; folders.push_back(mClothingID); folders.push_back(mLibraryClothingID); setFetchIDs(folders); startFetch(); if (isFinished()) { done(); } }
void SequentialAnimation::animate(float const delta, Skeleton* skeleton) { for(Animation::Reference& animation : animations) { if(!animation->isFinished()) { animation->animate(delta, skeleton); if((loops == INFINITE_LOOPS || loop < loops) && animation->isFinished() && isFinished()) { loop += 1; resetAnimations(); } break; } } }
void LunarLander::updateState(VectorXd *p_action) { double rate = 0; decodeAction(p_action, rate); update(rate); _reward = 0; if (isFinished()) { cout<<"Final velocity: "<<_velocity; if (_velocity >= safe_velocity) { _reward = 10; cout<<"...good landing!\n"; } else { _reward = (_velocity - safe_velocity) / 20; cout<<"...you crashed!\n"; } } }
c_WaitableWaitHandle* c_WaitableWaitHandle::getChild() { assert(!isFinished()); switch (getKind()) { case Kind::Static: not_reached(); case Kind::AsyncFunction: return asAsyncFunction()->getChild(); case Kind::AsyncGenerator: return asAsyncGenerator()->getChild(); case Kind::GenArray: return asGenArray()->getChild(); case Kind::GenMap: return asGenMap()->getChild(); case Kind::GenVector: return asGenVector()->getChild(); case Kind::Reschedule: return nullptr; case Kind::Sleep: return nullptr; case Kind::ExternalThreadEvent: return nullptr; return nullptr; } not_reached(); }
void HHVM_METHOD(ConditionWaitHandle, fail, const Object& exception) { if (!exception->instanceof(SystemLib::s_ThrowableClass)) { SystemLib::throwInvalidArgumentExceptionObject( "Expected exception to be an instance of Throwable"); } auto obj = wait_handle<c_ConditionWaitHandle>(this_); if (obj->isFinished()) { failAlreadyFinished(); } assert(obj->getState() == c_ConditionWaitHandle::STATE_BLOCKED); auto parentChain = obj->getParentChain(); obj->setState(c_ConditionWaitHandle::STATE_FAILED); cellDup(make_tv<KindOfObject>(exception.get()), obj->m_resultOrException); parentChain.unblock(); }
IDBObjectStore* IDBTransaction::objectStore(const String& name, ExceptionState& exceptionState) { if (isFinished()) { exceptionState.throwDOMException( InvalidStateError, IDBDatabase::transactionFinishedErrorMessage); return nullptr; } IDBObjectStoreMap::iterator it = m_objectStoreMap.find(name); if (it != m_objectStoreMap.end()) return it->value; if (!isVersionChange() && !m_scope.contains(name)) { exceptionState.throwDOMException( NotFoundError, IDBDatabase::noSuchObjectStoreErrorMessage); return nullptr; } int64_t objectStoreId = m_database->findObjectStoreId(name); if (objectStoreId == IDBObjectStoreMetadata::InvalidId) { DCHECK(isVersionChange()); exceptionState.throwDOMException( NotFoundError, IDBDatabase::noSuchObjectStoreErrorMessage); return nullptr; } DCHECK(m_database->metadata().objectStores.contains(objectStoreId)); RefPtr<IDBObjectStoreMetadata> objectStoreMetadata = m_database->metadata().objectStores.get(objectStoreId); DCHECK(objectStoreMetadata.get()); IDBObjectStore* objectStore = IDBObjectStore::create(std::move(objectStoreMetadata), this); DCHECK(!m_objectStoreMap.contains(name)); m_objectStoreMap.set(name, objectStore); if (isVersionChange()) { DCHECK(!objectStore->isNewlyCreated()) << "Object store IDs are not assigned sequentially"; RefPtr<IDBObjectStoreMetadata> backupMetadata = objectStore->metadata().createCopy(); m_oldStoreMetadata.set(objectStore, std::move(backupMetadata)); } return objectStore; }
void SimulatedAnnealing::optimiseImplementation() { ++numberOfIterations_; bestParameter_ = initialParameter_; bestObjectiveValue_ = getObjectiveValue(initialParameter_); arma::Col<double> state = bestParameter_; while (!isFinished() && !isTerminated()) { ++numberOfIterations_; const arma::Col<double>& candidateParameter = getRandomNeighbour(bestParameter_, arma::zeros<arma::Col<double>>(numberOfDimensions_), maximalStepSize_); const double candidateObjectiveValue = getObjectiveValue(candidateParameter); if (updateBestParameter(candidateParameter, candidateObjectiveValue) || isAcceptableState(candidateObjectiveValue)) { state = candidateParameter; } } }
void FutureInterfaceBase::registerWatcher(FutureWatcher* watcher) { QMutexLocker locker(&_mutex); if(isStarted()) watcher->postCallOutEvent(FutureWatcher::CallOutEvent::Started, this); if(isResultSet()) watcher->postCallOutEvent(FutureWatcher::CallOutEvent::ResultReady, this); if(isCanceled()) watcher->postCallOutEvent(FutureWatcher::CallOutEvent::Canceled, this); if(isFinished()) watcher->postCallOutEvent(FutureWatcher::CallOutEvent::Finished, this); _watchers.push_back(watcher); }
void c_AwaitAllWaitHandle::blockOnCurrent() { auto child = m_children[m_cur]; assert(!child->isFinished()); try { if (isInContext()) { child->enterContext(getContextIdx()); } if (checkCycle) { detectCycle(child); } } catch (const Object& cycle_exception) { markAsFailed(cycle_exception); return; } blockOn(child); }
/** Update the particles after the transform, and then update the mesh node. */ void CC3ParticleEmitter::processUpdateAfterTransform( CC3NodeUpdatingVisitor* visitor ) { // If configured to update particles after the node is transformed, do so here. // For each particle, invoke the updateBeforeTransform: method. // Particles can also be removed during the update process. if ( m_shouldUpdateParticlesAfterTransform ) updateParticlesAfterTransform( visitor ); // If emission has stopped and all the particles have been killed off and the // emitter should be removed when finished, remove the emitter from its parent. if ( isFinished() && shouldRemoveOnFinish() ) { CC3_TRACE("[ptc]CC3ParticleEmitter is exhausted and is being removed"); visitor->requestRemovalOf( this ); } super::processUpdateAfterTransform( visitor ); }
//------------------------------- // Huffman decompressor //------------------------------- int DecompressorHuffman::unpack(Common::ReadStream *src, byte *dest, uint32 nPacked, uint32 nUnpacked) { init(src, dest, nPacked, nUnpacked); byte numnodes; int16 c; uint16 terminator; numnodes = _src->readByte(); terminator = _src->readByte() | 0x100; _nodes = new byte [numnodes << 1]; _src->read(_nodes, numnodes << 1); while ((c = getc2()) != terminator && (c >= 0) && !isFinished()) putByte(c); delete[] _nodes; return _dwWrote == _szUnpacked ? 0 : 1; }
void c_SetResultToRefWaitHandle::enterContext(context_idx_t ctx_idx) { assert(AsioSession::Get()->getContext(ctx_idx)); // stop before corrupting unioned data if (isFinished()) { return; } // already in the more specific context? if (LIKELY(getContextIdx() >= ctx_idx)) { return; } assert(getState() == STATE_BLOCKED); m_child->enterContext(ctx_idx); setContextIdx(ctx_idx); }
void c_RescheduleWaitHandle::enterContext(context_idx_t ctx_idx) { assert(AsioSession::Get()->getContext(ctx_idx)); // stop before corrupting unioned data if (isFinished()) { return; } // already in the more specific context? if (LIKELY(getContextIdx() >= ctx_idx)) { return; } assert(getState() == STATE_SCHEDULED); setContextIdx(ctx_idx); getContext()->schedule(this, m_queue, m_priority); }
void BaselinePattern::updateFeedback() { if (isFinished() && !stage->ground->isBlinking()) { for (int i = 0; i < stage->poppies.size(); ++i) stage->poppies[i]->setBaseColor(stage->poppies[i]->getBlinkColor()); if (player->numCorrect >= player->totalProblems) { player->updateSuccess(PLAYER_SUCCESS); player->score += player->level; stage->ground->setBlinkColor(FEEDBACK_COLOR_GOOD); //stage.positiveFeedback->Play(); } else { double correctness = getPlayerCorrectness(); player->updateSuccess(PLAYER_FAILURE); stage->ground->setBlinkColor(FEEDBACK_COLOR_BAD); //stage.negativeFeedback->Play(); } std::cout << "Is activating blink" << std::endl; stage->ground->activateBlink(); } double barWidth = Util::HP_BAR_WIDTH; if (player->numConsecutiveSuccess > 0) { barWidth *= player->numConsecutiveSuccess / (double)(player->levelUpCeiling); stage->barHP->setDimensions(barWidth, Util::HP_BAR_HEIGHT); if (player->numConsecutiveSuccess >= Player::levelUpCeiling) stage->barHP->setMaterialName("General/BaseBlue"); else stage->barHP->setMaterialName("General/BaseGreen"); } else { if (stage->ground->getBlinkColor() == FEEDBACK_COLOR_BAD) stage->barHP->setDimensions(barWidth, Util::HP_BAR_HEIGHT); else stage->barHP->setDimensions(0.0, Util::HP_BAR_HEIGHT); stage->barHP->setMaterialName("General/BaseRed"); } stage->label2->setCaption("Score: " + toStringInt(player->score)); }
PendingOperation *PendingChannelRequest::cancel() { if (isFinished()) { // CR has already succeeded or failed, so let's just fail here return new PendingFailure(TP_QT_DBUS_ERROR_UNKNOWN_METHOD, QLatin1String("ChannnelRequest already finished"), object()); } if (!mPriv->cancelOperation) { mPriv->cancelOperation = new PendingChannelRequestCancelOperation(); connect(mPriv->cancelOperation, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onCancelOperationFinished(Tp::PendingOperation*))); if (mPriv->channelRequest) { mPriv->cancelOperation->go(mPriv->channelRequest); } }
void ScriptStreamer::notifyFinishedToClient() { ASSERT(isMainThread()); // Usually, the loading will be finished first, and V8 will still need some // time to catch up. But the other way is possible too: if V8 detects a // parse error, the V8 side can complete before loading has finished. Send // the notification after both loading and V8 side operations have // completed. Here we also check that we have a client: it can happen that a // function calling notifyFinishedToClient was already scheduled in the task // queue and the upper layer decided that it's not interested in the script // and called removeClient. { MutexLocker locker(m_mutex); if (!isFinished()) return; } if (m_client) m_client->notifyFinished(m_resource); }
void ScriptJob::requestAbort() { QMutexLocker locker( m_mutex ); if ( m_quit || !m_engine ) { // Is already aborting/finished return; } m_quit = true; if ( m_eventLoop ) { QEventLoop *loop = m_eventLoop; m_eventLoop = 0; loop->quit(); } if ( !isFinished() && m_objects.network->hasRunningRequests() ) { m_objects.network->abortAllRequests(); } }
void QNetworkReplyWrapper::emitMetaDataChanged() { QueueLocker lock(m_queue); m_queue->push(&QNetworkReplyHandler::sendResponseIfNeeded); if (m_reply->bytesAvailable()) { m_responseContainsData = true; m_queue->push(&QNetworkReplyHandler::forwardData); } if (isFinished()) { m_queue->push(&QNetworkReplyHandler::finish); return; } // If not finished, connect to the slots that will be used from this point on. connect(m_reply, SIGNAL(readyRead()), this, SLOT(didReceiveReadyRead())); connect(m_reply, SIGNAL(finished()), this, SLOT(didReceiveFinished())); }
void c_ConditionWaitHandle::onUnblocked() { decRefObj(m_child); m_child = nullptr; // Unblocked after notification. if (LIKELY(isFinished())) { decRefObj(this); return; } auto parentChain = getParentChain(); setState(STATE_FAILED); tvCopy( make_tv<KindOfObject>(getNotNotifiedException().detach()), m_resultOrException ); parentChain.unblock(); decRefObj(this); }
bool Command::run() { if(!initialized) { initialize(); initialized = true; } bool finished = isFinished(); if(!finished) { execute(); } else { end(); } return finished; }
void AudioCdRecord::processOnOutput() { QStringList list = QString( p->process->readLine() ).split("\n",QString::SkipEmptyParts); for( int i=0 ; i<list.count() ; i++ ) { QString proc_str = list.at(i); QString tmp = proc_str.simplified(); tmp.replace( QRegExp("[0-9]| ") , "" ); if( tmp == QString("Track:ofMBwritten(fifo%)[buf%].x.") ) { if( p->timer->interval() != 1000 ) { p->timer->setInterval( 1000 ); // qDebug( "void AudioCdRecord::processOnOutput() : Timer Interval set to 1000 ms" ); } checkProgressLine( proc_str ); } else { if( p->timer->interval() != 25 ) { p->timer->setInterval( 25 ); // qDebug( "void AudioCdRecord::processOnOutput() : Timer Interval set to 25 ms" ); } checkItemicLog( proc_str ); p->log_str = p->log_str + '\n' + proc_str; emit logChanged( p->log_str ); } } if( isFinished() && list.isEmpty() ) { p->timer->stop(); p->clock->stop(); } }
void PendingStreamTubeConnection::onAcceptFinished(PendingOperation *op) { if (isFinished()) { return; } if (op->isError()) { warning().nospace() << "StreamTube.Accept failed with " << op->errorName() << ": " << op->errorMessage(); setFinishedWithError(op->errorName(), op->errorMessage()); return; } debug() << "StreamTube.Accept returned successfully"; PendingVariant *pv = qobject_cast<PendingVariant *>(op); // Build the address if (mPriv->type == SocketAddressTypeIPv4) { SocketAddressIPv4 addr = qdbus_cast<SocketAddressIPv4>(pv->result()); debug().nospace() << "Got address " << addr.address << ":" << addr.port; mPriv->hostAddress = QHostAddress(addr.address); mPriv->port = addr.port; } else if (mPriv->type == SocketAddressTypeIPv6) { SocketAddressIPv6 addr = qdbus_cast<SocketAddressIPv6>(pv->result()); debug().nospace() << "Got address " << addr.address << ":" << addr.port; mPriv->hostAddress = QHostAddress(addr.address); mPriv->port = addr.port; } else { // Unix socket mPriv->socketPath = QLatin1String(qdbus_cast<QByteArray>(pv->result())); debug() << "Got socket " << mPriv->socketPath; } // It might have been already opened - check if (mPriv->tube->state() == TubeChannelStateOpen) { onTubeStateChanged(mPriv->tube->state()); } else { // Wait until the tube gets opened on the other side connect(mPriv->tube.data(), SIGNAL(stateChanged(Tp::TubeChannelState)), this, SLOT(onTubeStateChanged(Tp::TubeChannelState))); } }
Object c_ConditionWaitHandle::ti_create(const Variant& child) { // Child not a WaitHandle? auto const child_wh = c_WaitHandle::fromCell(child.asCell()); if (UNLIKELY(!child_wh)) { SystemLib::throwInvalidArgumentExceptionObject( "Expected child to be an instance of WaitHandle"); } // Child finished before notification? if (UNLIKELY(child_wh->isFinished())) { throwNotNotifiedException(); } assert(child_wh->instanceof(c_WaitableWaitHandle::classof())); auto const child_wwh = static_cast<c_WaitableWaitHandle*>(child_wh); auto wh = req::make<c_ConditionWaitHandle>(); wh->initialize(child_wwh); return Object(std::move(wh)); }
void SyncManager::Release () { for (auto syncer : Syncer2Thread_.keys ()) { syncer->stop (); auto thread = Syncer2Thread_.value (syncer); thread->quit (); } for (auto syncer : Syncer2Thread_.keys ()) { syncer->stop (); auto thread = Syncer2Thread_.take (syncer); if (!thread->isFinished () && !thread->wait (3000)) thread->terminate (); syncer->deleteLater (); thread->deleteLater (); } }
void c_ConditionWaitHandle::t_fail(const Variant& exception) { auto const cell = exception.asCell(); if (UNLIKELY( cell->m_type != KindOfObject || !cell->m_data.pobj->instanceof(SystemLib::s_ExceptionClass) )) { SystemLib::throwInvalidArgumentExceptionObject( "Expected exception to be an instance of Exception"); } if (isFinished()) { failAlreadyFinished(); } assert(getState() == STATE_BLOCKED); auto parentChain = getParentChain(); setState(STATE_FAILED); cellDup(make_tv<KindOfObject>(cell->m_data.pobj), m_resultOrException); parentChain.unblock(); }
/* One of our subrequests has finished. Go to the next step. */ void FetchByIdRequestController::handleFinishedSubRequest(QContactAbstractRequest* subReq) { // It's possibly already finished if this function is called asynchronously and waitForFinished // had previously been called if (isFinished()) return; // For a FetchByIdRequest, we know that the only subrequest is a QContactFetchRequest. // The next step is simply to take the results and reformat it. // Take the results: QContactFetchRequest* qcfr = qobject_cast<QContactFetchRequest*>(subReq); QList<QContact> contacts = qcfr->contacts(); QContactManager::Error error = qcfr->error(); // Build an index into the results QHash<QContactLocalId, QContact> idMap; if (error == QContactManager::NoError) { foreach (const QContact& contact, contacts) { idMap.insert(contact.localId(), contact); }
void FutureInterfaceBase::setProgressValue(int value) { QMutexLocker locker(&_mutex); if(value == _progressValue) return; if(isCanceled() || isFinished()) return; _progressValue = value; if(_progressTime.isValid() && _progressValue != _progressMaximum) { if(_progressTime.elapsed() < (1000 / MaxProgressEmitsPerSecond)) { return; } } _progressTime.start(); sendCallOut(FutureWatcher::CallOutEvent::ProgressValue, _progressValue); }
void CFadeAnimation::update() { if (!fading) return; if (fadingMode == EMode::OUT) fadingCounter -= delta; else fadingCounter += delta; if (isFinished()) { fading = false; if (shouldFreeSurface) { SDL_FreeSurface(fadingSurface); fadingSurface = nullptr; } } }