nsresult nsBaseChannel::Redirect(nsIChannel *newChannel, uint32_t redirectFlags, bool openNewChannel) { SUSPEND_PUMP_FOR_SCOPE(); // Transfer properties newChannel->SetLoadGroup(mLoadGroup); newChannel->SetNotificationCallbacks(mCallbacks); newChannel->SetLoadFlags(mLoadFlags | LOAD_REPLACE); // make a copy of the loadinfo, append to the redirectchain // and set it on the new channel if (mLoadInfo) { nsCOMPtr<nsILoadInfo> newLoadInfo = static_cast<mozilla::LoadInfo*>(mLoadInfo.get())->Clone(); nsCOMPtr<nsIPrincipal> uriPrincipal; nsIScriptSecurityManager *sm = nsContentUtils::GetSecurityManager(); sm->GetChannelURIPrincipal(this, getter_AddRefs(uriPrincipal)); bool isInternalRedirect = (redirectFlags & (nsIChannelEventSink::REDIRECT_INTERNAL | nsIChannelEventSink::REDIRECT_STS_UPGRADE)); newLoadInfo->AppendRedirectedPrincipal(uriPrincipal, isInternalRedirect); newChannel->SetLoadInfo(newLoadInfo); } else { // the newChannel was created with a dummy loadInfo, we should clear // it in case the original channel does not have a loadInfo newChannel->SetLoadInfo(nullptr); } // Preserve the privacy bit if it has been overridden if (mPrivateBrowsingOverriden) { nsCOMPtr<nsIPrivateBrowsingChannel> newPBChannel = do_QueryInterface(newChannel); if (newPBChannel) { newPBChannel->SetPrivate(mPrivateBrowsing); } } nsCOMPtr<nsIWritablePropertyBag> bag = ::do_QueryInterface(newChannel); if (bag) { for (auto iter = mPropertyHash.Iter(); !iter.Done(); iter.Next()) { bag->SetProperty(iter.Key(), iter.UserData()); } } // Notify consumer, giving chance to cancel redirect. For backwards compat, // we support nsIHttpEventSink if we are an HTTP channel and if this is not // an internal redirect. RefPtr<nsAsyncRedirectVerifyHelper> redirectCallbackHelper = new nsAsyncRedirectVerifyHelper(); bool checkRedirectSynchronously = !openNewChannel; mRedirectChannel = newChannel; mRedirectFlags = redirectFlags; mOpenRedirectChannel = openNewChannel; nsresult rv = redirectCallbackHelper->Init(this, newChannel, redirectFlags, checkRedirectSynchronously); if (NS_FAILED(rv)) return rv; if (checkRedirectSynchronously && NS_FAILED(mStatus)) return mStatus; return NS_OK; }
void IDBDatabase::AbortTransactions(bool aShouldWarn) { AssertIsOnOwningThread(); class MOZ_STACK_CLASS Helper final { typedef nsAutoTArray<RefPtr<IDBTransaction>, 20> StrongTransactionArray; typedef nsAutoTArray<IDBTransaction*, 20> WeakTransactionArray; public: static void AbortTransactions(IDBDatabase* aDatabase, const bool aShouldWarn) { MOZ_ASSERT(aDatabase); aDatabase->AssertIsOnOwningThread(); nsTHashtable<nsPtrHashKey<IDBTransaction>>& transactionTable = aDatabase->mTransactions; if (!transactionTable.Count()) { return; } StrongTransactionArray transactionsToAbort; transactionsToAbort.SetCapacity(transactionTable.Count()); for (auto iter = transactionTable.Iter(); !iter.Done(); iter.Next()) { IDBTransaction* transaction = iter.Get()->GetKey(); MOZ_ASSERT(transaction); transaction->AssertIsOnOwningThread(); // Transactions that are already done can simply be ignored. Otherwise // there is a race here and it's possible that the transaction has not // been successfully committed yet so we will warn the user. if (!transaction->IsDone()) { transactionsToAbort.AppendElement(transaction); } } MOZ_ASSERT(transactionsToAbort.Length() <= transactionTable.Count()); if (transactionsToAbort.IsEmpty()) { return; } // We want to abort transactions as soon as possible so we iterate the // transactions once and abort them all first, collecting the transactions // that need to have a warning issued along the way. Those that need a // warning will be a subset of those that are aborted, so we don't need // additional strong references here. WeakTransactionArray transactionsThatNeedWarning; for (RefPtr<IDBTransaction>& transaction : transactionsToAbort) { MOZ_ASSERT(transaction); MOZ_ASSERT(!transaction->IsDone()); if (aShouldWarn) { switch (transaction->GetMode()) { // We ignore transactions that could not have written any data. case IDBTransaction::READ_ONLY: break; // We warn for any transactions that could have written data. case IDBTransaction::READ_WRITE: case IDBTransaction::READ_WRITE_FLUSH: case IDBTransaction::VERSION_CHANGE: transactionsThatNeedWarning.AppendElement(transaction); break; default: MOZ_CRASH("Unknown mode!"); } } transaction->Abort(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR); } static const char kWarningMessage[] = "IndexedDBTransactionAbortNavigation"; for (IDBTransaction* transaction : transactionsThatNeedWarning) { MOZ_ASSERT(transaction); nsString filename; uint32_t lineNo, column; transaction->GetCallerLocation(filename, &lineNo, &column); aDatabase->LogWarning(kWarningMessage, filename, lineNo, column); } }
SurfaceFormat UploadImageDataToTexture(GLContext* gl, unsigned char* aData, int32_t aStride, SurfaceFormat aFormat, const nsIntRegion& aDstRegion, GLuint aTexture, const gfx::IntSize& aSize, size_t* aOutUploadSize, bool aNeedInit, GLenum aTextureUnit, GLenum aTextureTarget) { gl->MakeCurrent(); gl->fActiveTexture(aTextureUnit); gl->fBindTexture(aTextureTarget, aTexture); GLenum format = 0; GLenum internalFormat = 0; GLenum type = 0; int32_t pixelSize = BytesPerPixel(aFormat); SurfaceFormat surfaceFormat = gfx::SurfaceFormat::UNKNOWN; MOZ_ASSERT(gl->GetPreferredARGB32Format() == LOCAL_GL_BGRA || gl->GetPreferredARGB32Format() == LOCAL_GL_RGBA); switch (aFormat) { case SurfaceFormat::B8G8R8A8: if (gl->GetPreferredARGB32Format() == LOCAL_GL_BGRA) { format = LOCAL_GL_BGRA; surfaceFormat = SurfaceFormat::R8G8B8A8; type = LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV; } else { format = LOCAL_GL_RGBA; surfaceFormat = SurfaceFormat::B8G8R8A8; type = LOCAL_GL_UNSIGNED_BYTE; } internalFormat = LOCAL_GL_RGBA; break; case SurfaceFormat::B8G8R8X8: // Treat BGRX surfaces as BGRA except for the surface // format used. if (gl->GetPreferredARGB32Format() == LOCAL_GL_BGRA) { format = LOCAL_GL_BGRA; surfaceFormat = SurfaceFormat::R8G8B8X8; type = LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV; } else { format = LOCAL_GL_RGBA; surfaceFormat = SurfaceFormat::B8G8R8X8; type = LOCAL_GL_UNSIGNED_BYTE; } internalFormat = LOCAL_GL_RGBA; break; case SurfaceFormat::R8G8B8A8: if (gl->GetPreferredARGB32Format() == LOCAL_GL_BGRA) { // Upload our RGBA as BGRA, but store that the uploaded format is // BGRA. (sample from R to get B) format = LOCAL_GL_BGRA; type = LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV; surfaceFormat = SurfaceFormat::B8G8R8A8; } else { format = LOCAL_GL_RGBA; type = LOCAL_GL_UNSIGNED_BYTE; surfaceFormat = SurfaceFormat::R8G8B8A8; } internalFormat = LOCAL_GL_RGBA; break; case SurfaceFormat::R8G8B8X8: // Treat RGBX surfaces as RGBA except for the surface // format used. if (gl->GetPreferredARGB32Format() == LOCAL_GL_BGRA) { format = LOCAL_GL_BGRA; type = LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV; surfaceFormat = SurfaceFormat::B8G8R8X8; } else { format = LOCAL_GL_RGBA; type = LOCAL_GL_UNSIGNED_BYTE; surfaceFormat = SurfaceFormat::R8G8B8X8; } internalFormat = LOCAL_GL_RGBA; break; case SurfaceFormat::R5G6B5_UINT16: internalFormat = format = LOCAL_GL_RGB; type = LOCAL_GL_UNSIGNED_SHORT_5_6_5; surfaceFormat = SurfaceFormat::R5G6B5_UINT16; break; case SurfaceFormat::A8: internalFormat = format = LOCAL_GL_LUMINANCE; type = LOCAL_GL_UNSIGNED_BYTE; // We don't have a specific luminance shader surfaceFormat = SurfaceFormat::A8; break; default: NS_ASSERTION(false, "Unhandled image surface format!"); } if (aOutUploadSize) { *aOutUploadSize = 0; } if (aNeedInit || !CanUploadSubTextures(gl)) { // If the texture needs initialized, or we are unable to // upload sub textures, then initialize and upload the entire // texture. TexImage2DHelper(gl, aTextureTarget, 0, internalFormat, aSize.width, aSize.height, aStride, pixelSize, 0, format, type, aData); if (aOutUploadSize && aNeedInit) { uint32_t texelSize = GetBytesPerTexel(internalFormat, type); size_t numTexels = size_t(aSize.width) * size_t(aSize.height); *aOutUploadSize += texelSize * numTexels; } } else { // Upload each rect in the region to the texture for (auto iter = aDstRegion.RectIter(); !iter.Done(); iter.Next()) { const IntRect& rect = iter.Get(); const unsigned char* rectData = aData + DataOffset(rect.TopLeft(), aStride, aFormat); TexSubImage2DHelper(gl, aTextureTarget, 0, rect.x, rect.y, rect.Width(), rect.Height(), aStride, pixelSize, format, type, rectData); } } return surfaceFormat; }
nsRect nsRegion::GetLargestRectangle (const nsRect& aContainingRect) const { nsRect bestRect; if (GetNumRects() <= 1) { bestRect = GetBounds(); return bestRect; } AxisPartition xaxis, yaxis; // Step 1: Calculate the grid lines for (auto iter = RectIter(); !iter.Done(); iter.Next()) { const nsRect& rect = iter.Get(); xaxis.InsertCoord(rect.x); xaxis.InsertCoord(rect.XMost()); yaxis.InsertCoord(rect.y); yaxis.InsertCoord(rect.YMost()); } if (!aContainingRect.IsEmpty()) { xaxis.InsertCoord(aContainingRect.x); xaxis.InsertCoord(aContainingRect.XMost()); yaxis.InsertCoord(aContainingRect.y); yaxis.InsertCoord(aContainingRect.YMost()); } // Step 2: Fill out the grid with the areas // Note: due to the ordering of rectangles in the region, it is not always // possible to combine steps 2 and 3 so we don't try to be clever. int32_t matrixHeight = yaxis.GetNumStops() - 1; int32_t matrixWidth = xaxis.GetNumStops() - 1; int32_t matrixSize = matrixHeight * matrixWidth; nsTArray<SizePair> areas(matrixSize); areas.SetLength(matrixSize); for (auto iter = RectIter(); !iter.Done(); iter.Next()) { const nsRect& rect = iter.Get(); int32_t xstart = xaxis.IndexOf(rect.x); int32_t xend = xaxis.IndexOf(rect.XMost()); int32_t y = yaxis.IndexOf(rect.y); int32_t yend = yaxis.IndexOf(rect.YMost()); for (; y < yend; y++) { nscoord height = yaxis.StopSize(y); for (int32_t x = xstart; x < xend; x++) { nscoord width = xaxis.StopSize(x); int64_t size = width*int64_t(height); if (rect.Intersects(aContainingRect)) { areas[y*matrixWidth+x].mSizeContainingRect = size; } areas[y*matrixWidth+x].mSize = size; } } } // Step 3: Find the maximum submatrix sum that does not contain a rectangle { // First get the prefix sum array int32_t m = matrixHeight + 1; int32_t n = matrixWidth + 1; nsTArray<SizePair> pareas(m*n); pareas.SetLength(m*n); for (int32_t y = 1; y < m; y++) { for (int32_t x = 1; x < n; x++) { SizePair area = areas[(y-1)*matrixWidth+x-1]; if (!area.mSize) { area = SizePair::VeryLargeNegative(); } area = area + pareas[ y*n+x-1] + pareas[(y-1)*n+x ] - pareas[(y-1)*n+x-1]; pareas[y*n+x] = area; } } // No longer need the grid areas.SetLength(0); SizePair bestArea; struct { int32_t left, top, right, bottom; } bestRectIndices = { 0, 0, 0, 0 }; for (int32_t m1 = 0; m1 < m; m1++) { for (int32_t m2 = m1+1; m2 < m; m2++) { nsTArray<SizePair> B; B.SetLength(n); for (int32_t i = 0; i < n; i++) { B[i] = pareas[m2*n+i] - pareas[m1*n+i]; } int32_t minIdx, maxIdx; SizePair area = MaxSum1D(B, n, &minIdx, &maxIdx); if (area > bestArea) { bestRectIndices.left = minIdx; bestRectIndices.top = m1; bestRectIndices.right = maxIdx; bestRectIndices.bottom = m2; bestArea = area; } } } bestRect.MoveTo(xaxis.StopAt(bestRectIndices.left), yaxis.StopAt(bestRectIndices.top)); bestRect.SizeTo(xaxis.StopAt(bestRectIndices.right) - bestRect.x, yaxis.StopAt(bestRectIndices.bottom) - bestRect.y); } return bestRect; }
void cStructLoader::Load(bool reload) { if(SL_TSTFLAG(SL_DISABLED) || (reload && !SL_TSTFLAG(SL_WATCH))) return; FILE *f=fopen(path,"r"); if(f) { PreLoad(); int curr_mtime=MTime(true); ListLock(true); bool doload=false; if(!reload) { Clear(); Modified(false); mtime=curr_mtime; doload=true; } else if(mtime<curr_mtime) { PRINTF(L_CORE_LOAD,"detected change of %s",path); if(IsModified()) PRINTF(L_CORE_LOAD,"discarding in-memory changes"); for(cStructItem *a=First(); a; a=Next(a)) DelItem(a); Modified(false); mtime=curr_mtime; doload=true; } if(doload) { SL_SETFLAG(SL_LOADED); PRINTF(L_GEN_INFO,"loading %s from %s",type,path); CheckAccess(); int lineNum=0, num=0; char buff[4096]; while(fgets(buff,sizeof(buff),f)) { lineNum++; if(!index(buff,'\n') && !feof(f)) { PRINTF(L_GEN_ERROR,"file %s readbuffer overflow line#%d",path,lineNum); SL_CLRFLAG(SL_LOADED); break; } strreplace(buff,'\n',0); strreplace(buff,'\r',0); // chomp bool hasContent=false; char *ls; for(ls=buff; *ls; ls++) { if(*ls==';' || *ls=='#') { // comment if(hasContent) while(ls>buff && ls[-1]<=' ') ls--; // search back to non-whitespace break; } if(*ls>' ') hasContent=true; // line contains something usefull } cStructItem *it=0; if(hasContent) { char save=*ls; *ls=0; it=ParseLine(skipspace(buff)); *ls=save; if(!it) { PRINTF(L_GEN_ERROR,"file %s has error in line #%d",path,lineNum); ls=buff; } else num++; } else ls=buff; if(!it) it=new cCommentItem; if(it) { it->SetComment(ls); Add(it); } else { PRINTF(L_GEN_ERROR,"out of memory loading file %s",path); SL_CLRFLAG(SL_LOADED); break; } } ListUnlock(); PRINTF(L_CORE_LOAD,"loaded %d %s from %s",num,type,path); PostLoad(); } else ListUnlock(); fclose(f); LoadFinished(); } else OpenFailed(); }
TxId DatabaseHelper::txLoad(TxId txIndex, DbTransaction& dbTx, std::vector<DbTransactionOutput>* outputs, std::vector<DbTransactionBlock>* blocks) { auto buffer = bufferTLS.get(); if (buffer == NULL) { bufferTLS.reset(buffer = new std::string()); } bool loadedTransaction = false; char searchKey2[1 + sizeof(TxId)]; searchKey2[0] = (uint8_t)DatabaseKeyHeader::Tx; *((TxId*)&searchKey2[1]) = swapByteOrder(txIndex); auto searchKeySlice = leveldb::Slice((const char*)searchKey2, sizeof(searchKey2)); if (outputs == NULL && blocks == NULL) { if (!db->Get(leveldb::ReadOptions(), searchKeySlice, buffer).ok()) return 0; } else { // Slower path to get outputs and/or blocks using iterators auto it = std::unique_ptr<leveldb::Iterator>(db->NewIterator(leveldb::ReadOptions())); it->Seek(searchKeySlice); if (!it->Valid() || it->key() != searchKeySlice) return false; buffer->assign(it->value().data(), it->value().size()); // Read outputs it->Next(); for (; it->Valid(); it->Next()) { auto key = it->key(); if (key.size() < searchKeySlice.size() || memcmp(key.data(), searchKeySlice.data(), searchKeySlice.size()) != 0) break; auto keyType = key.data()[1 + sizeof(TxId)]; if (keyType == 0x02) { if (outputs != NULL) { auto& transactionOutput = *(DbTransactionOutput*)&key.data()[1 + sizeof(TxId) + 1]; outputs->push_back(transactionOutput); } } else if (keyType == 0x03 && blocks != NULL) { if (blocks != NULL) { auto& transactionBlock = *(DbTransactionBlock*) &key.data()[1 + sizeof(TxId) + 1]; blocks->push_back(transactionBlock); } } else { break; } } } Deserialize(*buffer, dbTx); return txIndex; }
/* <1bcf96> ../cstrike/dlls/vehicle.cpp:179 */ void CFuncVehicle::__MAKE_VHOOK(Use)(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) { float delta = value; if (useType != USE_SET) { if (ShouldToggle(useType, pev->speed != 0)) { if (pev->speed == 0) { pev->speed = m_dir * m_speed; Next(); } else { pev->speed = 0; pev->velocity = g_vecZero; pev->avelocity = g_vecZero; StopSound(); SetThink(NULL); } } return; } if (delta < 10) { if (delta < 0) { if (pev->speed > 145) { StopSound(); } } float_precision flSpeedRatio = delta; if (delta > 0) { flSpeedRatio = (float)(pev->speed / m_speed); if (pev->speed < 0) flSpeedRatio = m_acceleration * 0.0005 + flSpeedRatio + VEHICLE_SPEED0_ACCELERATION; else if (pev->speed < 10) flSpeedRatio = m_acceleration * 0.0006 + flSpeedRatio + VEHICLE_SPEED1_ACCELERATION; else if (pev->speed < 20) flSpeedRatio = m_acceleration * 0.0007 + flSpeedRatio + VEHICLE_SPEED2_ACCELERATION; else if (pev->speed < 30) flSpeedRatio = m_acceleration * 0.0007 + flSpeedRatio + VEHICLE_SPEED3_ACCELERATION; else if (pev->speed < 45) flSpeedRatio = m_acceleration * 0.0007 + flSpeedRatio + VEHICLE_SPEED4_ACCELERATION; else if (pev->speed < 60) flSpeedRatio = m_acceleration * 0.0008 + flSpeedRatio + VEHICLE_SPEED5_ACCELERATION; else if (pev->speed < 80) flSpeedRatio = m_acceleration * 0.0008 + flSpeedRatio + VEHICLE_SPEED6_ACCELERATION; else if (pev->speed < 100) flSpeedRatio = m_acceleration * 0.0009 + flSpeedRatio + VEHICLE_SPEED7_ACCELERATION; else if (pev->speed < 150) flSpeedRatio = m_acceleration * 0.0008 + flSpeedRatio + VEHICLE_SPEED8_ACCELERATION; else if (pev->speed < 225) flSpeedRatio = m_acceleration * 0.0007 + flSpeedRatio + VEHICLE_SPEED9_ACCELERATION; else if (pev->speed < 300) flSpeedRatio = m_acceleration * 0.0006 + flSpeedRatio + VEHICLE_SPEED10_ACCELERATION; else if (pev->speed < 400) flSpeedRatio = m_acceleration * 0.0005 + flSpeedRatio + VEHICLE_SPEED11_ACCELERATION; else if (pev->speed < 550) flSpeedRatio = m_acceleration * 0.0005 + flSpeedRatio + VEHICLE_SPEED12_ACCELERATION; else if (pev->speed < 800) flSpeedRatio = m_acceleration * 0.0005 + flSpeedRatio + VEHICLE_SPEED13_ACCELERATION; } else if (delta < 0) { flSpeedRatio = pev->speed / m_speed; // TODO: fix float for test demo if (flSpeedRatio > 0) flSpeedRatio = (float)flSpeedRatio - 0.0125; else if (flSpeedRatio <= 0 && flSpeedRatio > -0.05) flSpeedRatio = (float)flSpeedRatio - 0.0075; else if (flSpeedRatio <= 0.05 && flSpeedRatio > -0.1) flSpeedRatio = (float)flSpeedRatio - 0.01; else if (flSpeedRatio <= 0.15 && flSpeedRatio > -0.15) flSpeedRatio = (float)flSpeedRatio - 0.0125; else if (flSpeedRatio <= 0.15 && flSpeedRatio > -0.22) flSpeedRatio = (float)flSpeedRatio - 0.01375; else if (flSpeedRatio <= 0.22 && flSpeedRatio > -0.3) flSpeedRatio = (float)flSpeedRatio - 0.0175; else if (flSpeedRatio <= 0.3) flSpeedRatio = (float)flSpeedRatio - 0.0125; } if (flSpeedRatio > 1) { flSpeedRatio = 1; } else if (flSpeedRatio < -0.35) { flSpeedRatio = -0.35; } pev->speed = flSpeedRatio * m_speed; Next(); m_flAcceleratorDecay = gpGlobals->time + 0.25; } else if (m_flCanTurnNow < gpGlobals->time) { if (delta == 20) { m_iTurnAngle++; m_flSteeringWheelDecay = gpGlobals->time + 0.075; if (m_iTurnAngle > 8) { m_iTurnAngle = 8; } } else if (delta == 30) { m_iTurnAngle--; m_flSteeringWheelDecay = gpGlobals->time + 0.075; if (m_iTurnAngle < -8) { m_iTurnAngle = -8; } } m_flCanTurnNow = gpGlobals->time + 0.05; } }
/* [caml_fl_merge_block] returns the head pointer of the next block after [bp], because merging blocks may change the size of [bp]. */ char *caml_fl_merge_block (char *bp) { char *prev, *cur, *adj; header_t hd = Hd_bp (bp); mlsize_t prev_wosz; caml_fl_cur_size += Whsize_hd (hd); #ifdef DEBUG caml_set_fields (bp, 0, Debug_free_major); #endif prev = caml_fl_merge; cur = Next (prev); /* The sweep code makes sure that this is the right place to insert this block: */ Assert (prev < bp || prev == Fl_head); Assert (cur > bp || cur == NULL); if (policy == Policy_first_fit) truncate_flp (prev); /* If [last_fragment] and [bp] are adjacent, merge them. */ if (last_fragment == Hp_bp (bp)){ mlsize_t bp_whsz = Whsize_bp (bp); if (bp_whsz <= Max_wosize){ hd = Make_header (bp_whsz, 0, Caml_white); bp = last_fragment; Hd_bp (bp) = hd; caml_fl_cur_size += Whsize_wosize (0); } } /* If [bp] and [cur] are adjacent, remove [cur] from the free-list and merge them. */ adj = bp + Bosize_hd (hd); if (adj == Hp_bp (cur)){ char *next_cur = Next (cur); mlsize_t cur_whsz = Whsize_bp (cur); if (Wosize_hd (hd) + cur_whsz <= Max_wosize){ Next (prev) = next_cur; if (policy == Policy_next_fit && fl_prev == cur) fl_prev = prev; hd = Make_header (Wosize_hd (hd) + cur_whsz, 0, Caml_blue); Hd_bp (bp) = hd; adj = bp + Bosize_hd (hd); #ifdef DEBUG fl_last = NULL; Next (cur) = (char *) Debug_free_major; Hd_bp (cur) = Debug_free_major; #endif cur = next_cur; } } /* If [prev] and [bp] are adjacent merge them, else insert [bp] into the free-list if it is big enough. */ prev_wosz = Wosize_bp (prev); if (prev + Bsize_wsize (prev_wosz) == Hp_bp (bp) && prev_wosz + Whsize_hd (hd) < Max_wosize){ Hd_bp (prev) = Make_header (prev_wosz + Whsize_hd (hd), 0,Caml_blue); #ifdef DEBUG Hd_bp (bp) = Debug_free_major; #endif Assert (caml_fl_merge == prev); }else if (Wosize_hd (hd) != 0){ Hd_bp (bp) = Bluehd_hd (hd); Next (bp) = cur; Next (prev) = bp; caml_fl_merge = bp; }else{ /* This is a fragment. Leave it in white but remember it for eventual merging with the next block. */ last_fragment = bp; caml_fl_cur_size -= Whsize_wosize (0); } return adj; }
void CMessageLoop::Last() { while(Next()); }
/*------------------------------------------------------------ pdr_ns_supg_time_integration - time integration driver ------------------------------------------------------------*/ void pdr_ns_supg_time_integration( char* Work_dir, FILE *Interactive_input, FILE *Interactive_output ) { int mesh_id; int field_ns_supg_id; int solver_ns_supg_id; double sol_norm_uk_ns_supg, sol_norm_un_ns_supg; char autodump_filename[300]; int iadapt = 0; char solver_ns_supg_filename[300]; int nr_iter, nonl_iter; double conv_meas, conv_rate; int i, iaux; double cfl_min=1000000, cfl_max=0, cfl_ave=0.0, daux; /* Navier_Stokes problem parameters */ pdt_ns_supg_problem *problem_ns_supg = &pdv_ns_supg_problem; pdt_ns_supg_ctrls *ctrl_ns_supg = &pdv_ns_supg_problem.ctrl; pdt_ns_supg_times *time_ns_supg = &pdv_ns_supg_problem.time; pdt_ns_supg_nonls *nonl_ns_supg = &pdv_ns_supg_problem.nonl; pdt_ns_supg_linss *lins_ns_supg = &pdv_ns_supg_problem.lins; pdt_ns_supg_adpts *adpt_ns_supg = &pdv_ns_supg_problem.adpt; /* time step length adaptation based on specified CFL number */ int cfl_control = time_ns_supg->CFL_control; double cfl_limit = time_ns_supg->CFL_limit; //double reference_time_step_length = time_ns_supg->reference_time_step_length; double time_step_length_mult = time_ns_supg->time_step_length_mult; /*++++++++++++++++ executable statements ++++++++++++++++*/ pdv_ns_supg_current_problem_id = PDC_NS_SUPG_ID; // get mesh and field parameters i = 2; mesh_id = pdr_ctrl_i_params(pdv_ns_supg_current_problem_id,i); field_ns_supg_id = pdr_ctrl_i_params(pdv_ns_supg_current_problem_id,3); #ifdef TURBULENTFLOW int intStep=0; SetMesh(mesh_id); SetField(field_ns_supg_id); //SetTurbModel(pdv_settings->chlength); SetTurbModel(pdv_ns_supg_current_problem_id); #endif //TURBULENTFLOW // when finished time loop reset interactively time integration parameters if (time_ns_supg->cur_time >= time_ns_supg->final_time) { fprintf(Interactive_output, "\nCurrent time: %lf is bigger than final time: %lf.\n\n", time_ns_supg->cur_time, time_ns_supg->final_time); fprintf(Interactive_output, "\nCurrent time-step: %d, current time step length: %lf.\n\n", time_ns_supg->cur_step, time_ns_supg->cur_dtime); if(Interactive_input == stdin){ #ifdef PARALLEL if (pcr_my_proc_id() == pcr_print_master()) { #endif printf("How many steps to perform?\n"); scanf("%d",&iaux); #ifdef PARALLEL } pcr_bcast_int(pcr_print_master(), 1, &iaux); #endif #ifdef PARALLEL if (pcr_my_proc_id() == pcr_print_master()) { #endif printf("Set new time step length (or CFL limit if < 0):\n"); scanf("%lf",&daux); #ifdef PARALLEL } pcr_bcast_double(pcr_print_master(), 1, &daux); #endif if(daux>0){ time_ns_supg->CFL_control = 0; time_ns_supg->CFL_limit = 1.e10; time_ns_supg->time_step_length_mult = 1.0; //time_ns_supg->reference_time_step_length = daux; //cfl_control = 0; //cfl_limit = 1.e10; //time_step_length_mult = 1.0; time_ns_supg->cur_dtime = daux; } else{ time_ns_supg->CFL_control = 1; time_ns_supg->CFL_limit = -daux; //time_ns_supg->reference_time_step_length = time_ns_supg->cur_dtime; //cfl_control = 1; //cfl_limit = -daux; #ifdef PARALLEL if (pcr_my_proc_id() == pcr_print_master()) { #endif printf("Set new time step length multiplier:\n"); scanf("%lf",&daux); #ifdef PARALLEL } pcr_bcast_double(pcr_print_master(), 1, &daux); #endif time_ns_supg->time_step_length_mult = daux; //time_step_length_mult = daux; } } else{ fprintf(Interactive_output, "\nExiting!\n\n"); exit(0);; } time_ns_supg->final_step = time_ns_supg->cur_step + iaux; time_ns_supg->final_time = time_ns_supg->cur_time + iaux*time_ns_supg->cur_dtime; } if (time_ns_supg->cur_step >= time_ns_supg->final_step) { fprintf(Interactive_output, "\nCurrent time-step: %d is bigger than final step: %d\n\n", time_ns_supg->cur_step, time_ns_supg->final_step); fprintf(Interactive_output, "\nCurrent time: %lf, current time step length: %lf.\n\n", time_ns_supg->cur_time, time_ns_supg->cur_dtime); if(Interactive_input == stdin){ #ifdef PARALLEL if (pcr_my_proc_id() == pcr_print_master()) { #endif printf("How many steps to perform?\n"); scanf("%d",&iaux); #ifdef PARALLEL } pcr_bcast_int(pcr_print_master(), 1, &iaux); #endif #ifdef PARALLEL if (pcr_my_proc_id() == pcr_print_master()) { #endif printf("Set new time step length (or CFL limit if < 0):\n"); scanf("%lf",&daux); #ifdef PARALLEL } pcr_bcast_double(pcr_print_master(), 1, &daux); #endif if(daux>0){ time_ns_supg->CFL_control = 0; time_ns_supg->CFL_limit = 1.e10; time_ns_supg->time_step_length_mult = 1.0; //time_ns_supg->reference_time_step_length = daux; //cfl_control = 0; //cfl_limit = 1.e10; //time_step_length_mult = 1.0; time_ns_supg->cur_dtime = daux; } else{ time_ns_supg->CFL_control = 1; time_ns_supg->CFL_limit = -daux; //time_ns_supg->reference_time_step_length = time_ns_supg->cur_dtime; //cfl_control = 1; //cfl_limit = -daux; #ifdef PARALLEL if (pcr_my_proc_id() == pcr_print_master()) { #endif printf("Set new time step length multiplier:\n"); scanf("%lf",&daux); #ifdef PARALLEL } pcr_bcast_double(pcr_print_master(), 1, &daux); #endif time_ns_supg->time_step_length_mult = daux; //time_step_length_mult = daux; } } else{ fprintf(Interactive_output, "\nExiting!\n\n"); exit(0);; } time_ns_supg->final_step = time_ns_supg->cur_step + iaux; time_ns_supg->final_time = time_ns_supg->cur_time + iaux*time_ns_supg->cur_dtime; } /* print some info */ fprintf(Interactive_output, "\nTime integration will stop whichever comes first:\n"); fprintf(Interactive_output, "final_time: %lf\n", time_ns_supg->final_time); fprintf(Interactive_output, "final_timestep: %d\n", time_ns_supg->final_step); fprintf(Interactive_output, "error less than time_integration_tolerance: %lf\n\n", time_ns_supg->conv_meas); #ifndef PARALLEL if(Interactive_input == stdin) { printf("Type [Ctrl-C] to manually break time integration.\n"); } #endif sprintf(solver_ns_supg_filename, "%s/%s", ctrl_ns_supg->work_dir, ctrl_ns_supg->solver_filename); if(pdr_lins_i_params(PDC_NS_SUPG_ID, 1) > 0){ // iterative solver #ifndef PARALLEL pdv_ns_supg_current_problem_id = PDC_NS_SUPG_ID; // ns_supg problem int problem_id = pdv_ns_supg_current_problem_id; solver_ns_supg_id = sir_init(SIC_SEQUENTIAL, solver_ns_supg_filename, pdr_lins_i_params(problem_id, 2), // max_iter pdr_lins_i_params(problem_id, 3), // error_type pdr_lins_d_params(problem_id, 4), // error_tolerance pdr_lins_i_params(problem_id, 5) // monitoring level ); ctrl_ns_supg->solver_id = solver_ns_supg_id; fprintf(Interactive_output, "Assigned solver ID: %d for NS_SUPG\n", solver_ns_supg_id); #endif #ifdef PARALLEL pdv_ns_supg_current_problem_id = PDC_NS_SUPG_ID; // ns_supg problem int problem_id = pdv_ns_supg_current_problem_id; solver_ns_supg_id = sir_init(SIC_PARALLEL, solver_ns_supg_filename, pdr_lins_i_params(problem_id, 2), // max_iter pdr_lins_i_params(problem_id, 3), // error_type pdr_lins_d_params(problem_id, 4), // error_tolerance pdr_lins_i_params(problem_id, 5) // monitoring level ); ctrl_ns_supg->solver_id = solver_ns_supg_id; fprintf(Interactive_output, "Assigned solver ID: %d for NS_SUPG\n", solver_ns_supg_id); #endif } /* set parameter indicating new mesh */ iadapt = 1; /* start loop over time steps */ while (utv_SIGINT_not_caught) { /* update time step and current time */ ++(time_ns_supg->cur_step); time_ns_supg->prev_dtime = time_ns_supg->cur_dtime; // here possible time step length adaptations !!! // compute maximal, minimal and average CFL number for ns_supg_problem if(time_ns_supg->CFL_control == 1){ cfl_limit = time_ns_supg->CFL_limit; time_step_length_mult = time_ns_supg->time_step_length_mult; fprintf(Interactive_output, "\nCFL numbers before time step length control:\n"); pdr_ns_supg_compute_CFL(PDC_NS_SUPG_ID, &cfl_min, &cfl_max, &cfl_ave); //fprintf(Interactive_output, // "CFL_min = %lf, CFL_max = %lf, CFL_average = %lf\n", // cfl_min,cfl_max,cfl_ave); #ifdef PARALLEL { double cfl_max_new = cfl_max; pcr_allreduce_max_double(1,&cfl_max,&cfl_max_new); cfl_max = cfl_max_new; } #endif fprintf(Interactive_output, "CFL_min = %lf, CFL_max = %lf, CFL_average = %lf\n", cfl_min,cfl_max,cfl_ave); // check whether CFL is not too big if(cfl_max > cfl_limit){ time_ns_supg->cur_dtime = time_ns_supg->cur_dtime/time_step_length_mult; } // check whether CFL is not too small if(cfl_max < cfl_limit/(time_step_length_mult) ){ if(cfl_max > 1.e-3){ // to exclude pure diffusion problems time_ns_supg->cur_dtime=time_ns_supg->cur_dtime*time_step_length_mult; } } } time_ns_supg->cur_time += time_ns_supg->cur_dtime; fprintf(Interactive_output, "\n\nSolving time step %d (cur_dtime: %lf, cur_time (t^(n+1)): %lf)\n", time_ns_supg->cur_step, time_ns_supg->cur_dtime, time_ns_supg->cur_time); // compute maximal, minimal and average CFL number for ns_supg_problem pdr_ns_supg_compute_CFL(PDC_NS_SUPG_ID, &cfl_min, &cfl_max, &cfl_ave); #ifdef PARALLEL { double cfl_max_new = cfl_max; pcr_allreduce_max_double(1,&cfl_max,&cfl_max_new); cfl_max = cfl_max_new; } #endif fprintf(Interactive_output, "CFL_min = %lf, CFL_max = %lf, CFL_average = %lf\n", cfl_min,cfl_max,cfl_ave); // compute maximal, minimal and average CFL number // rewrite solution: // current from previous time step becomes previous for current time step // soldofs_1 are the most recent solution dofs // at the beginning of time step they are rewritten to soldofs_3 // that holds the solution from the previous time step apr_rewr_sol(field_ns_supg_id, 1, 3); //rewrite current -> u_n (3) /* update time dependent boundary conditions for NS problem*/ pdv_ns_supg_current_problem_id = PDC_NS_SUPG_ID; pdr_ns_supg_update_timedep_bc(&problem_ns_supg->bc, time_ns_supg->cur_time); nonl_iter = 0; do { fprintf(Interactive_output, "\nSolving for nonlin. (nonl. iter step %d) convergence (time step %d).\n", nonl_iter+1, time_ns_supg->cur_step); // when forming linear system - soldofs_1 are equal to soldofs_2 // after solving the system soldofs_1 are different than soldofs_2 // before starting new solution soldofs_1 are rewritten to soldofs_2 // simply: soldofs_1 are u_k+1, soldofs_2 are u_k and soldofs_3 are u_n apr_rewr_sol(field_ns_supg_id, 1, 2); //rewrite current -> u_k (2) if (iadapt == 1) { #ifdef PARALLEL const int ione = 1; /* initiate exchange tables for DOFs - for two fields, one level */ appr_init_exchange_tables(pcr_nr_proc(), pcr_my_proc_id(), 1, &ione); #endif if(pdr_lins_i_params(PDC_NS_SUPG_ID, 1) > 0){ // iterative solver sir_create(solver_ns_supg_id, PDC_NS_SUPG_ID); } iadapt = 0; } if(pdr_lins_i_params(PDC_NS_SUPG_ID, 1) > 0){ // iterative solver int ini_guess = 1; // get initial guess from data structure nr_iter = pdr_lins_i_params(PDC_NS_SUPG_ID, 2); conv_meas = pdr_lins_d_params(PDC_NS_SUPG_ID, 4); int monitor = pdr_lins_i_params(PDC_NS_SUPG_ID, 5); /*------------ CALLING ITERATIVE SOLVER ------------------*/ sir_solve(solver_ns_supg_id, SIC_SOLVE, ini_guess, monitor, &nr_iter, &conv_meas, &conv_rate); fprintf(Interactive_output, "\nAfter %d iterations of linear solver for ns_supg problem\n", nr_iter); fprintf(Interactive_output, "Convergence measure: %lf, convergence rate %lf\n", conv_meas, conv_rate); } else { #ifdef PARALLEL if(pcv_nr_proc > 1) { mf_log_err("Shared memory PARDISO called for solving in distributed memory computations!"); } #endif sir_direct_solve_lin_sys(PDC_NS_SUPG_ID, SIC_SEQUENTIAL, solver_ns_supg_filename); } /* post-process solution using slope limiter */ //if(slope) { // iaux=pdr_slope_limit(problem_id); // pdr_slope_limit for DG is archived in pdd_conv_diff/approx_dg/..._util.c // if(iaux<0) { printf("\nError in slope!\n");getchar();} //} pdr_ns_supg_sol_diff_norm(1,2,&sol_norm_uk_ns_supg); fprintf(Interactive_output, "\nNorm for ns_supg(u_k, prev. u_k): %lf\n", sol_norm_uk_ns_supg); ++nonl_iter; if (nonl_iter >= nonl_ns_supg->max_iter) { fprintf(Interactive_output, "\nMax nonlinear iterations reached - breaking.\n"); #ifdef TURBULENTFLOW fprintf(Interactive_output, "test_tstart"); if (intStep>0) { //RevStep(); } intStep=intStep+1; int jturb; for (jturb=0;jturb<1;jturb++) { Next(time_ns_supg->cur_time); } fprintf(Interactive_output, "test_tstop"); // ConfStep(); #endif //TURBULENTFLOW break; } } while (sol_norm_uk_ns_supg > nonl_ns_supg->conv_meas ); pdr_ns_supg_sol_diff_norm(1,3,&sol_norm_un_ns_supg); fprintf(Interactive_output, "\nNorm ns_supg (u_n, prev. u_n): %lf\n", sol_norm_un_ns_supg); /* graphics data dumps */ if (time_ns_supg->intv_graph > 0 && time_ns_supg->cur_step % time_ns_supg->intv_graph == 0) { fprintf(Interactive_output, "(Writing field to disk (graphics)...)\n"); /* sprintf(autodump_filename, "%s/%s_g%d.dmp", ctrl_ns_supg->work_dir, ctrl_ns_supg->field_dmp_filepattern, time_ns_supg->cur_step); */ /* if (apr_write_field(field_id, PDC_NREQ, 1, time_ns_supg->intv_graph_accu, autodump_filename) < 0) */ /* fprintf(Interactive_output, "Error in writing field data!\n"); */ #ifdef TURBULENTFLOW DumpParaviewC(time_ns_supg->cur_step); #endif pdr_ns_supg_write_paraview(Work_dir, Interactive_input, Interactive_output); } /* full data dumps (for restarting) */ if (time_ns_supg->intv_dumpout > 0 && time_ns_supg->cur_step % time_ns_supg->intv_dumpout == 0) { fprintf(Interactive_output, "\n(Writing field to disk - not implemented)\n"); /* sprintf(autodump_filename, "%s/%s_f.dmp", ctrl_ns_supg->work_dir, ctrl_ns_supg->field_dmp_filepattern); */ /* if (apr_write_field(field_id, PDC_NREQ, 0, 0, autodump_filename) < 0) */ /* fprintf(Interactive_output, "Error in writing field data!\n"); */ } /* check for stop conditions */ /* stop when final time reached */ if (time_ns_supg->cur_time >= time_ns_supg->final_time) { fprintf(Interactive_output, "\nFinal time reached. Stopping.\n"); break; } /* cur_dtime could change through simulation (time step adaptation) */ /* thus we need to check also if cur_step not bigger than final_step */ if (time_ns_supg->cur_step >= time_ns_supg->final_step) { fprintf(Interactive_output, "\nFinal step reached. Stopping.\n"); break; } /* stop if convergence reached (for stationary problems) */ if (sol_norm_un_ns_supg < time_ns_supg->conv_meas) { fprintf(Interactive_output, "\nNorm ns_supg (u_n, prev. u_n) below n_epsilon: %lf. Stopping.\n", time_ns_supg->conv_meas); break; } // when time for adaptation if( adpt_ns_supg->type>0 && adpt_ns_supg->interval>0 && (time_ns_supg->cur_step+1)%adpt_ns_supg->interval==0 ) { #ifdef PARALLEL /* free exchange tables for DOFs */ appr_free_exchange_tables(1); #endif if(pdr_lins_i_params(PDC_NS_SUPG_ID, 1) > 0){ // iterative solver /* free solver data structures */ sir_free(solver_ns_supg_id); } pdr_ns_supg_adapt(Work_dir, Interactive_input, Interactive_output); /* indicate to recreate block structure */ iadapt=1; } //// check if user want to break time_integration //if(Interactive_input == stdin) { // int sec=0; // char c=getc(stdin); // fflush(stdout); // if(c == 'q') { // printf("\nPress [q] again to finalize current step and exit to menu: "); // c=0; // c=getchar(); // if(c == 'q') { // printf("\nBreaking time integration (user input)!"); // break; // } //} //} } //end loop over timesteps if (iadapt == 0) { #ifdef PARALLEL /* free exchange tables for DOFs */ appr_free_exchange_tables(1); #endif if(pdr_lins_i_params(PDC_NS_SUPG_ID, 1) > 0){ // iterative solver sir_free(solver_ns_supg_id); } } if(pdr_lins_i_params(PDC_NS_SUPG_ID, 1) > 0){ // iterative solver sir_destroy(solver_ns_supg_id); } return; }
/* [caml_fl_allocate] does not set the header of the newly allocated block. The calling function must do it before any GC function gets called. [caml_fl_allocate] returns a head pointer. */ char *caml_fl_allocate (mlsize_t wo_sz) { char *cur = NULL, *prev, *result; int i; mlsize_t sz, prevsz; Assert (sizeof (char *) == sizeof (value)); Assert (wo_sz >= 1); switch (policy){ case Policy_next_fit: Assert (fl_prev != NULL); /* Search from [fl_prev] to the end of the list. */ prev = fl_prev; cur = Next (prev); while (cur != NULL){ Assert (Is_in_heap (cur)); if (Wosize_bp (cur) >= wo_sz){ return allocate_block (Whsize_wosize (wo_sz), 0, prev, cur); } prev = cur; cur = Next (prev); } fl_last = prev; /* Search from the start of the list to [fl_prev]. */ prev = Fl_head; cur = Next (prev); while (prev != fl_prev){ if (Wosize_bp (cur) >= wo_sz){ return allocate_block (Whsize_wosize (wo_sz), 0, prev, cur); } prev = cur; cur = Next (prev); } /* No suitable block was found. */ return NULL; break; case Policy_first_fit: { /* Search in the flp array. */ for (i = 0; i < flp_size; i++){ sz = Wosize_bp (Next (flp[i])); if (sz >= wo_sz){ #if FREELIST_DEBUG if (i > 5) fprintf (stderr, "FLP: found at %d size=%d\n", i, wo_sz); #endif result = allocate_block (Whsize_wosize (wo_sz), i, flp[i], Next(flp[i])); goto update_flp; } } /* Extend the flp array. */ if (flp_size == 0){ prev = Fl_head; prevsz = 0; }else{ prev = Next (flp[flp_size - 1]); prevsz = Wosize_bp (prev); if (beyond != NULL) prev = beyond; } while (flp_size < FLP_MAX){ cur = Next (prev); if (cur == NULL){ fl_last = prev; beyond = (prev == Fl_head) ? NULL : prev; return NULL; }else{ sz = Wosize_bp (cur); if (sz > prevsz){ flp[flp_size] = prev; ++ flp_size; if (sz >= wo_sz){ beyond = cur; i = flp_size - 1; #if FREELIST_DEBUG if (flp_size > 5){ fprintf (stderr, "FLP: extended to %d\n", flp_size); } #endif result = allocate_block (Whsize_wosize (wo_sz), flp_size - 1, prev, cur); goto update_flp; } prevsz = sz; } } prev = cur; } beyond = cur; /* The flp table is full. Do a slow first-fit search. */ #if FREELIST_DEBUG fprintf (stderr, "FLP: table is full -- slow first-fit\n"); #endif if (beyond != NULL){ prev = beyond; }else{ prev = flp[flp_size - 1]; } prevsz = Wosize_bp (Next (flp[FLP_MAX-1])); Assert (prevsz < wo_sz); cur = Next (prev); while (cur != NULL){ Assert (Is_in_heap (cur)); sz = Wosize_bp (cur); if (sz < prevsz){ beyond = cur; }else if (sz >= wo_sz){ return allocate_block (Whsize_wosize (wo_sz), flp_size, prev, cur); } prev = cur; cur = Next (prev); } fl_last = prev; return NULL; update_flp: /* (i, sz) */ /* The block at [i] was removed or reduced. Update the table. */ Assert (0 <= i && i < flp_size + 1); if (i < flp_size){ if (i > 0){ prevsz = Wosize_bp (Next (flp[i-1])); }else{ prevsz = 0; } if (i == flp_size - 1){ if (Wosize_bp (Next (flp[i])) <= prevsz){ beyond = Next (flp[i]); -- flp_size; }else{ beyond = NULL; } }else{ char *buf [FLP_MAX]; int j = 0; mlsize_t oldsz = sz; prev = flp[i]; while (prev != flp[i+1]){ cur = Next (prev); sz = Wosize_bp (cur); if (sz > prevsz){ buf[j++] = prev; prevsz = sz; if (sz >= oldsz){ Assert (sz == oldsz); break; } } prev = cur; } #if FREELIST_DEBUG if (j > 2) fprintf (stderr, "FLP: update; buf size = %d\n", j); #endif if (FLP_MAX >= flp_size + j - 1){ if (j != 1){ memmove (&flp[i+j], &flp[i+1], sizeof (block *) * (flp_size-i-1)); } if (j > 0) memmove (&flp[i], &buf[0], sizeof (block *) * j); flp_size += j - 1; }else{ if (FLP_MAX > i + j){ if (j != 1){ memmove (&flp[i+j], &flp[i+1], sizeof (block *) * (FLP_MAX-i-j)); } if (j > 0) memmove (&flp[i], &buf[0], sizeof (block *) * j); }else{ if (i != FLP_MAX){ memmove (&flp[i], &buf[0], sizeof (block *) * (FLP_MAX - i)); } } flp_size = FLP_MAX - 1; beyond = Next (flp[FLP_MAX - 1]); } } } return result; } break; default: Assert (0); /* unknown policy */ break; } return NULL; /* NOT REACHED */ }
gListNode *gListNode::FindNode( gListNode *l ) { // objects can be duped on the list -> first one wins... for( gListNode *n=First(); !isEmpty() && n != 0; n= Next(n) ) if( n == l ) return n; return 0; }
gListNode *gListNode::Find( void *o ) { // objects can be duped on the list -> first one wins... for( gListNode *n=First(); !isEmpty() && n != 0; n= Next(n) ) if( n->obj == o ) return n; return 0; }
int AverageSSSP::getAverageSSSP() { try { double** dist; double MAX = 10000000; int paircount = 0; double distance = 0; sae::io::MappedGraph* g = sae::io::MappedGraph::Open(graphFile.c_str()); dist = new double*[g->VertexCount()]; for(int i = 0; i < g->VertexCount(); i++) { dist[i] = new double[g -> VertexCount()]; for(int j = 0; j < g->VertexCount(); j++) { dist[i][j] = MAX; } } for (auto v = g->Vertices(); v->Alive(); v->Next()) { for(auto e = v->OutEdges(); e->Alive(); e->Next()) { dist[v->GlobalId()][e->Source()->GlobalId()] = sae::serialization::convert_from_string<EData>(e->Data()).attribute[0]; } } int maxIter = g->VertexCount() / 1000; int lastIter = -10; for(int k = 0; k < g->VertexCount() / 1000; k++) { if (k * 100 / maxIter >= lastIter + 10) { lastIter = k * 100 / maxIter; printf("Processing %d%%...\n", lastIter); } for(int i = 0; i < g->VertexCount(); i++) { for(int j = 0; j < g->VertexCount(); j++) { if(dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } for(int i = 0; i < g->VertexCount(); i++) { for(int j = 0; j < g->VertexCount(); j++) { if(dist[i][j] < MAX) { paircount ++; distance += dist[i][j]; } } } if(paircount > 0) { cout<<"Average SSSP: " << distance / paircount << endl; } else { cout<<"Average SSSP: " << 0 << endl; } } catch(...) { cout<<"AverageSSSP parameter error"<<endl; return -1; } return 0; }
GlobalShortcuts::GlobalShortcuts(QWidget* parent) : QWidget(parent), gnome_backend_(nullptr), system_backend_(nullptr), use_gnome_(false), rating_signals_mapper_(new QSignalMapper(this)) { settings_.beginGroup(kSettingsGroup); // Create actions AddShortcut("play", tr("Play"), SIGNAL(Play())); AddShortcut("pause", tr("Pause"), SIGNAL(Pause())); AddShortcut("play_pause", tr("Play/Pause"), SIGNAL(PlayPause()), QKeySequence(Qt::Key_MediaPlay)); AddShortcut("stop", tr("Stop"), SIGNAL(Stop()), QKeySequence(Qt::Key_MediaStop)); AddShortcut("stop_after", tr("Stop playing after current track"), SIGNAL(StopAfter())); AddShortcut("next_track", tr("Next track"), SIGNAL(Next()), QKeySequence(Qt::Key_MediaNext)); AddShortcut("prev_track", tr("Previous track"), SIGNAL(Previous()), QKeySequence(Qt::Key_MediaPrevious)); AddShortcut("inc_volume", tr("Increase volume"), SIGNAL(IncVolume())); AddShortcut("dec_volume", tr("Decrease volume"), SIGNAL(DecVolume())); AddShortcut("mute", tr("Mute"), SIGNAL(Mute())); AddShortcut("seek_forward", tr("Seek forward"), SIGNAL(SeekForward())); AddShortcut("seek_backward", tr("Seek backward"), SIGNAL(SeekBackward())); AddShortcut("show_hide", tr("Show/Hide"), SIGNAL(ShowHide())); AddShortcut("show_osd", tr("Show OSD"), SIGNAL(ShowOSD())); AddShortcut( "toggle_pretty_osd", tr("Toggle Pretty OSD"), SIGNAL(TogglePrettyOSD())); // Toggling possible only for pretty OSD AddShortcut("shuffle_mode", tr("Change shuffle mode"), SIGNAL(CycleShuffleMode())); AddShortcut("repeat_mode", tr("Change repeat mode"), SIGNAL(CycleRepeatMode())); AddShortcut("toggle_last_fm_scrobbling", tr("Enable/disable Last.fm scrobbling"), SIGNAL(ToggleScrobbling())); AddShortcut("love_last_fm_scrobbling", tr("Love (Last.fm scrobbling)"), SIGNAL(Love())); AddShortcut("ban_last_fm_scrobbling", tr("Ban (Last.fm scrobbling)"), SIGNAL(Ban())); AddRatingShortcut("rate_zero_star", tr("Rate the current song 0 stars"), rating_signals_mapper_, 0); AddRatingShortcut("rate_one_star", tr("Rate the current song 1 star"), rating_signals_mapper_, 1); AddRatingShortcut("rate_two_star", tr("Rate the current song 2 stars"), rating_signals_mapper_, 2); AddRatingShortcut("rate_three_star", tr("Rate the current song 3 stars"), rating_signals_mapper_, 3); AddRatingShortcut("rate_four_star", tr("Rate the current song 4 stars"), rating_signals_mapper_, 4); AddRatingShortcut("rate_five_star", tr("Rate the current song 5 stars"), rating_signals_mapper_, 5); connect(rating_signals_mapper_, SIGNAL(mapped(int)), SIGNAL(RateCurrentSong(int))); // Create backends - these do the actual shortcut registration gnome_backend_ = new GnomeGlobalShortcutBackend(this); #ifndef Q_OS_DARWIN system_backend_ = new QxtGlobalShortcutBackend(this); #else system_backend_ = new MacGlobalShortcutBackend(this); #endif ReloadSettings(); }
Node* Parser::IterationStmt() { if(oper == KEYWORD_FOR) { Next(); if(oper != ROUND_LEFT_BRACKET) throw ParserException(currentToken, "Iteration statement without '('"); Next(); Node *forInit = Expression(); if(oper != SEMICOLON) throw ParserException(currentToken, "Iteration statement without separator in condition"); Next(); Node *forCond = Expression(); if(oper != SEMICOLON) throw ParserException(currentToken, "Iteration statement without separator in condition"); Next(); Node *forIter = Expression(); if(oper != ROUND_RIGHT_BRACKET) throw ParserException(currentToken, "Iteration statement without ')'"); Next(); Node *stmt = Statement(); return new NodeIterationFor(forInit, forCond, forIter, stmt); } if(oper == KEYWORD_WHILE) { Next(); if(oper != ROUND_LEFT_BRACKET) throw ParserException(currentToken, "Iteration statement without '('"); Next(); Node *expr = Expression(); if(expr == NULL) throw ParserException(currentToken, "Iteration statement without expression"); if(oper != ROUND_RIGHT_BRACKET) throw ParserException(currentToken, "Iteration statement without ')'"); Next(); Node *stmt = Statement(); return new NodeIterationWhile(expr, stmt); } if(oper == KEYWORD_DO) { Next(); Node *stmt = Statement(); if(oper == KEYWORD_WHILE) { Next(); if(oper != ROUND_LEFT_BRACKET) throw ParserException(currentToken, "Iteration statement without '('"); Next(); Node *expr = Expression(); if(expr == NULL) throw ParserException(currentToken, "Iteration statement without expression"); if(oper != ROUND_RIGHT_BRACKET) throw ParserException(currentToken, "Iteration statement without ')'"); Next(); return new NodeIterationDo(expr, stmt); } else throw ParserException(currentToken, "Iteration statement without condition"); } return NULL; }
void MP3Player::HandleController(int analogX, int analogY, int btn) { if (btn == PSP_CTRL_CROSS) { if (analogY > (img_back_panel->imageHeight - 30) && !Controller::IsLastInputPressed) { // software button pressed if (analogX < 36) { Previous(); lcd->PrintMessage("Previous song"); } if (analogX > 34 && analogX < 67 && Playback) { lcd->PrintMessage("Stop"); Stop(); } if (analogX > 65 && analogX < 98 && !Paused && Playback) { lcd->PrintMessage("Pause"); Pause(); } if (analogX > 96 && analogX < 129 && !Paused && !Playback) { Play(); lcd->PrintMessage("Play"); } if (analogX > 96 && analogX < 129 && Paused) { lcd->PrintMessage("Play"); Resume(); } if (analogX > 127 && analogX < 160) { lcd->PrintMessage("Next song"); Next(); } if (analogX > 170) { pllWndHnd->Enabled = !pllWndHnd->Enabled; } } } if ((btn == PSP_CTRL_TRIANGLE || Controller::LastInputRemote == PSP_HPRM_PLAYPAUSE) && !Playback) { Play(); lcd->PrintMessage("Play"); } if ((btn == PSP_CTRL_TRIANGLE || Controller::LastInputRemote == PSP_HPRM_PLAYPAUSE) && Paused) { lcd->PrintMessage("Play"); Resume(); } if ((btn == PSP_CTRL_CIRCLE || Controller::LastInputRemote == PSP_HPRM_PLAYPAUSE) && !Paused && Playback) { lcd->PrintMessage("Pause"); Pause(); } if ((btn == PSP_CTRL_RTRIGGER || Controller::LastInputRemote == PSP_HPRM_FORWARD) && !Controller::IsLastInputPressed) { lcd->PrintMessage("Next song"); Next(); } if ((btn == PSP_CTRL_LTRIGGER || Controller::LastInputRemote == PSP_HPRM_BACK) && !Controller::IsLastInputPressed) { Previous(); lcd->PrintMessage("Previous song"); } if (PlayBackMP3::EndOfFile()) Next(); }
BOOL COutputPage::OnSetActive() { SetWizardButtons( PSWIZB_BACK | PSWIZB_NEXT ); GET_PAGE( CWelcomePage, pWelcome ); if ( pWelcome->m_nType == 0 ) { GET_PAGE( CSinglePage, pSingle ); CString strFile = pSingle->m_sFileName; if ( LPCTSTR pszSlash = _tcsrchr( strFile, '\\' ) ) { m_sName = pszSlash + 1; m_sName += _T(".torrent"); if ( m_sFolder.IsEmpty() ) m_sFolder = strFile.Left( (int)( pszSlash - strFile ) ); } } else { GET_PAGE( CPackagePage, pPackage ); CString sName = pPackage->m_wndList.GetItemText( 0, 0 ); // Get same part of first and last files int nCount = pPackage->m_wndList.GetItemCount(); if ( nCount > 1 ) { CString sName2 = pPackage->m_wndList.GetItemText( nCount - 1, 0 ); LPCTSTR pszName1 = sName; LPCTSTR pszName2 = sName2; for ( int i = 0; *pszName1 && *pszName2; ++pszName1, ++pszName2, ++i ) { if ( *pszName1 != *pszName2 ) { sName = sName.Left( i + 1 ); break; } } } // Use parent folder name as torrent name int nSlash = sName.ReverseFind( _T('\\') ); if ( nSlash != -1 ) { sName = sName.Left( nSlash ); nSlash = sName.ReverseFind( _T('\\') ); if ( nSlash != -1 ) { m_sName = sName.Mid( nSlash + 1 ) + _T(".torrent"); } } if ( m_sFolder.IsEmpty() ) m_sFolder = theApp.GetProfileString( _T("Folders"), _T("Last") ); if ( ! m_sFolder.IsEmpty() && m_sName.IsEmpty() ) { m_sName = PathFindFileName( m_sFolder ); m_sName += _T(".torrent"); } } if ( ! theApp.m_sCommandLineDestination.IsEmpty() ) { m_sFolder = theApp.m_sCommandLineDestination; theApp.m_sCommandLineDestination.Empty(); Next(); } UpdateData( FALSE ); return CWizardPage::OnSetActive(); }
bool PhysicalNestLoopJoin::Next(SegmentExecStatus *const exec_status, BlockStreamBase *block) { /** * @brief it describes the sequence of the nestloop join. As the intermediate * result of the left child has been stored in the dynamic block buffer in the * open function. in this next function, it get the intermediate result of the * right child operator, one block after one block. Within each block, it gets * each tuple in the block and joins with each tuple in the dynamic block * buffer * when traversing them. * Method description : * @param * @ return * @details (additional) */ RETURN_IF_CANCELLED(exec_status); void *tuple_from_buffer_child = NULL; void *tuple_from_right_child = NULL; void *result_tuple = NULL; bool pass = false; BlockStreamBase *buffer_block = NULL; NestLoopJoinContext *jtc = reinterpret_cast<NestLoopJoinContext *>(GetContext()); while (1) { RETURN_IF_CANCELLED(exec_status); while (NULL != (tuple_from_right_child = jtc->block_stream_iterator_->currentTuple())) { while (1) { while (NULL != (tuple_from_buffer_child = jtc->buffer_stream_iterator_->currentTuple())) { pass = join_condi_process_(tuple_from_buffer_child, tuple_from_right_child, jtc); if (pass) { if (NULL != (result_tuple = block->allocateTuple( state_.output_schema_->getTupleMaxSize()))) { const unsigned copyed_bytes = state_.input_schema_left_->copyTuple(tuple_from_buffer_child, result_tuple); state_.input_schema_right_->copyTuple( tuple_from_right_child, reinterpret_cast<char *>(result_tuple + copyed_bytes)); } else { // LOG(INFO) << "[NestloopJoin]: [a block of the // result // is full of " // "the nest loop join result ]" << // std::endl; return true; } } jtc->buffer_stream_iterator_->increase_cur_(); } // jtc->buffer_stream_iterator_->~BlockStreamTraverseIterator(); if (jtc->buffer_stream_iterator_ != NULL) { delete jtc->buffer_stream_iterator_; jtc->buffer_stream_iterator_ = NULL; } if (NULL != (buffer_block = jtc->buffer_iterator_.nextBlock())) { jtc->buffer_stream_iterator_ = buffer_block->createIterator(); } else { break; } } jtc->buffer_iterator_.ResetCur(); if (NULL == (buffer_block = jtc->buffer_iterator_.nextBlock())) { LOG(ERROR) << "[NestloopJoin]: this block shouldn't be NULL in nest " "loop join!"; assert( false && "[NestloopJoin]: this block shouldn't be NULL in nest loop join!"); } if (jtc->buffer_stream_iterator_ != NULL) { delete jtc->buffer_stream_iterator_; jtc->buffer_stream_iterator_ = NULL; } jtc->buffer_stream_iterator_ = buffer_block->createIterator(); jtc->block_stream_iterator_->increase_cur_(); } // if buffer is empty, return false directly jtc->buffer_iterator_.ResetCur(); if (NULL == (buffer_block = jtc->buffer_iterator_.nextBlock())) { LOG(WARNING) << "[NestloopJoin]: the buffer is empty in nest loop join!"; // for getting all right child's data jtc->block_for_asking_->setEmpty(); while (state_.child_right_->Next(exec_status, jtc->block_for_asking_)) { jtc->block_for_asking_->setEmpty(); } return false; } if (jtc->buffer_stream_iterator_ != NULL) { delete jtc->buffer_stream_iterator_; jtc->buffer_stream_iterator_ = NULL; } jtc->buffer_stream_iterator_ = buffer_block->createIterator(); // ask block from right child jtc->block_for_asking_->setEmpty(); if (false == state_.child_right_->Next(exec_status, jtc->block_for_asking_)) { if (true == block->Empty()) { LOG(WARNING) << "[NestloopJoin]: [no join result is stored in the " "block after traverse the right child operator]" << std::endl; return false; } else { LOG(INFO) << "[NestloopJoin]: get a new block from right child " << std::endl; return true; } } if (jtc->block_stream_iterator_ != NULL) { delete jtc->block_stream_iterator_; jtc->block_stream_iterator_ = NULL; } jtc->block_stream_iterator_ = jtc->block_for_asking_->createIterator(); } return Next(exec_status, block); }
void nsGenConList::Insert(nsGenConNode* aNode) { // Check for append. if (mList.isEmpty() || NodeAfter(aNode, mList.getLast())) { mList.insertBack(aNode); } else { // Binary search. // the range of indices at which |aNode| could end up. // (We already know it can't be at index mSize.) uint32_t first = 0, last = mSize - 1; // A cursor to avoid walking more than the length of the list. nsGenConNode* curNode = mList.getLast(); uint32_t curIndex = mSize - 1; while (first != last) { uint32_t test = (first + last) / 2; if (last == curIndex) { for ( ; curIndex != test; --curIndex) curNode = Prev(curNode); } else { for ( ; curIndex != test; ++curIndex) curNode = Next(curNode); } if (NodeAfter(aNode, curNode)) { first = test + 1; // if we exit the loop, we need curNode to be right ++curIndex; curNode = Next(curNode); } else { last = test; } } curNode->setPrevious(aNode); } ++mSize; // Set the mapping only if it is the first node of the frame. // The DEBUG blocks below are for ensuring the invariant required by // nsGenConList::DestroyNodesFor. See comment there. if (IsFirst(aNode) || Prev(aNode)->mPseudoFrame != aNode->mPseudoFrame) { #ifdef DEBUG if (nsGenConNode* oldFrameFirstNode = mNodes.Get(aNode->mPseudoFrame)) { MOZ_ASSERT(Next(aNode) == oldFrameFirstNode, "oldFrameFirstNode should now be immediately after " "the newly-inserted one."); } else { // If the node is not the only node in the list. if (!IsFirst(aNode) || !IsLast(aNode)) { nsGenConNode* nextNode = Next(aNode); MOZ_ASSERT(!nextNode || nextNode->mPseudoFrame != aNode->mPseudoFrame, "There shouldn't exist any node for this frame."); // If the node is neither the first nor the last node if (!IsFirst(aNode) && !IsLast(aNode)) { MOZ_ASSERT(Prev(aNode)->mPseudoFrame != nextNode->mPseudoFrame, "New node should not break contiguity of nodes of " "the same frame."); } } } #endif mNodes.Put(aNode->mPseudoFrame, aNode); } else { #ifdef DEBUG nsGenConNode* frameFirstNode = mNodes.Get(aNode->mPseudoFrame); MOZ_ASSERT(frameFirstNode, "There should exist node map for the frame."); for (nsGenConNode* curNode = Prev(aNode); curNode != frameFirstNode; curNode = Prev(curNode)) { MOZ_ASSERT(curNode->mPseudoFrame == aNode->mPseudoFrame, "Every node between frameFirstNode and the new node inserted " "should refer to the same frame."); MOZ_ASSERT(!IsFirst(curNode), "The newly-inserted node should be in a contiguous run after " "frameFirstNode, thus frameFirstNode should be reached before " "the first node of mList."); } #endif } NS_ASSERTION(IsFirst(aNode) || NodeAfter(aNode, Prev(aNode)), "sorting error"); NS_ASSERTION(IsLast(aNode) || NodeAfter(Next(aNode), aNode), "sorting error"); }
void ClientSingleTiledLayerBuffer::PaintThebes(const nsIntRegion& aNewValidRegion, const nsIntRegion& aPaintRegion, const nsIntRegion& aDirtyRegion, LayerManager::DrawPaintedLayerCallback aCallback, void* aCallbackData, bool aIsProgressive) { mWasLastPaintProgressive = aIsProgressive; // Compare layer valid region size to current backbuffer size, discard if not matching. gfx::IntSize size = aNewValidRegion.GetBounds().Size(); gfx::IntPoint origin = aNewValidRegion.GetBounds().TopLeft(); nsIntRegion paintRegion = aPaintRegion; RefPtr<TextureClient> discardedFrontBuffer = nullptr; RefPtr<TextureClient> discardedFrontBufferOnWhite = nullptr; nsIntRegion discardedValidRegion; if (mSize != size || mTilingOrigin != origin) { discardedFrontBuffer = mTile.mFrontBuffer; discardedFrontBufferOnWhite = mTile.mFrontBufferOnWhite; discardedValidRegion = mValidRegion; TILING_LOG("TILING %p: Single-tile valid region changed. Discarding buffers.\n", &mPaintedLayer) ; ResetPaintedAndValidState(); mSize = size; mTilingOrigin = origin; paintRegion = aNewValidRegion; } SurfaceMode mode; gfxContentType content = GetContentType(&mode); mFormat = gfxPlatform::GetPlatform()->OptimalFormatForContent(content); if (mTile.IsPlaceholderTile()) { mTile.SetTextureAllocator(this); } // The dirty region relative to the top-left of the tile. nsIntRegion tileDirtyRegion = paintRegion.MovedBy(-mTilingOrigin); nsIntRegion extraPainted; RefPtr<TextureClient> backBufferOnWhite; RefPtr<TextureClient> backBuffer = mTile.GetBackBuffer(mCompositableClient, tileDirtyRegion, content, mode, extraPainted, &backBufferOnWhite); mTile.mUpdateRect = tileDirtyRegion.GetBounds().Union(extraPainted.GetBounds()); extraPainted.MoveBy(mTilingOrigin); extraPainted.And(extraPainted, aNewValidRegion); mPaintedRegion.OrWith(paintRegion); mPaintedRegion.OrWith(extraPainted); if (!backBuffer) { return; } RefPtr<gfx::DrawTarget> dt = backBuffer->BorrowDrawTarget(); RefPtr<gfx::DrawTarget> dtOnWhite; if (backBufferOnWhite) { dtOnWhite = backBufferOnWhite->BorrowDrawTarget(); } if (mode != SurfaceMode::SURFACE_OPAQUE) { for (auto iter = tileDirtyRegion.RectIter(); !iter.Done(); iter.Next()) { const gfx::IntRect& rect = iter.Get(); if (dtOnWhite) { dt->FillRect(gfx::Rect(rect.x, rect.y, rect.width, rect.height), gfx::ColorPattern(gfx::Color(0.0, 0.0, 0.0, 1.0))); dtOnWhite->FillRect(gfx::Rect(rect.x, rect.y, rect.width, rect.height), gfx::ColorPattern(gfx::Color(1.0, 1.0, 1.0, 1.0))); } else { dt->ClearRect(gfx::Rect(rect.x, rect.y, rect.width, rect.height)); } } } // If the old frontbuffer was discarded then attempt to copy what we // can from it to the new backbuffer. if (discardedFrontBuffer) { nsIntRegion copyableRegion; copyableRegion.And(aNewValidRegion, discardedValidRegion); copyableRegion.SubOut(aDirtyRegion); if (!copyableRegion.IsEmpty()) { TextureClientAutoLock frontLock(discardedFrontBuffer, OpenMode::OPEN_READ); if (frontLock.Succeeded()) { for (auto iter = copyableRegion.RectIter(); !iter.Done(); iter.Next()) { const gfx::IntRect rect = iter.Get() - discardedValidRegion.GetBounds().TopLeft(); const gfx::IntPoint dest = iter.Get().TopLeft() - mTilingOrigin; discardedFrontBuffer->CopyToTextureClient(backBuffer, &rect, &dest); } } if (discardedFrontBufferOnWhite && backBufferOnWhite) { TextureClientAutoLock frontOnWhiteLock(discardedFrontBufferOnWhite, OpenMode::OPEN_READ); if (frontOnWhiteLock.Succeeded()) { for (auto iter = copyableRegion.RectIter(); !iter.Done(); iter.Next()) { const gfx::IntRect rect = iter.Get() - discardedValidRegion.GetBounds().TopLeft(); const gfx::IntPoint dest = iter.Get().TopLeft() - mTilingOrigin; discardedFrontBufferOnWhite->CopyToTextureClient(backBufferOnWhite, &rect, &dest); } } } TILING_LOG("TILING %p: Region copied from discarded frontbuffer %s\n", &mPaintedLayer, Stringify(copyableRegion).c_str()); // We don't need to repaint valid content that was just copied. paintRegion.SubOut(copyableRegion); } } if (dtOnWhite) { dt = gfx::Factory::CreateDualDrawTarget(dt, dtOnWhite); dtOnWhite = nullptr; } { RefPtr<gfxContext> ctx = gfxContext::CreateOrNull(dt); if (!ctx) { gfxDevCrash(gfx::LogReason::InvalidContext) << "SingleTiledContextClient context problem " << gfx::hexa(dt); return; } ctx->SetMatrix(ctx->CurrentMatrix().Translate(-mTilingOrigin.x, -mTilingOrigin.y)); aCallback(&mPaintedLayer, ctx, paintRegion, paintRegion, DrawRegionClip::DRAW, nsIntRegion(), aCallbackData); } // Mark the area we just drew into the back buffer as invalid in the front buffer as they're // now out of sync. mTile.mInvalidFront.OrWith(tileDirtyRegion); // The new buffer is now validated, remove the dirty region from it. mTile.mInvalidBack.SubOut(tileDirtyRegion); dt = nullptr; mTile.Flip(); UnlockTile(mTile); if (backBuffer->HasIntermediateBuffer()) { // If our new buffer has an internal buffer, we don't want to keep another // TextureClient around unnecessarily, so discard the back-buffer. mTile.DiscardBackBuffer(); } mValidRegion = aNewValidRegion; mLastPaintSurfaceMode = mode; mLastPaintContentType = content; }
void Attribute_Type_Array::Clear (void) { for (Attribute_Type *at_ptr = First (); at_ptr; at_ptr = Next ()) { at_ptr->Clear (); } }
cStructItem *cStructLoader::NextValid(cStructItem *it) const { while(it && !it->Valid()) it=Next(it); return it; }
void ClientSingleTiledLayerBuffer::PaintThebes(const nsIntRegion& aNewValidRegion, const nsIntRegion& aPaintRegion, const nsIntRegion& aDirtyRegion, LayerManager::DrawPaintedLayerCallback aCallback, void* aCallbackData) { // Compare layer valid region size to current backbuffer size, discard if not matching. gfx::IntSize size = aNewValidRegion.GetBounds().Size(); gfx::IntPoint origin = aNewValidRegion.GetBounds().TopLeft(); nsIntRegion paintRegion = aPaintRegion; if (mSize != size || mTilingOrigin != origin) { ResetPaintedAndValidState(); mSize = size; mTilingOrigin = origin; paintRegion = aNewValidRegion; } SurfaceMode mode; gfxContentType content = GetContentType(&mode); mFormat = gfxPlatform::GetPlatform()->OptimalFormatForContent(content); if (mTile.IsPlaceholderTile()) { mTile.SetLayerManager(mManager); mTile.SetTextureAllocator(this); } mTile.SetCompositableClient(mCompositableClient); // The dirty region relative to the top-left of the tile. nsIntRegion tileDirtyRegion = paintRegion.MovedBy(-mTilingOrigin); nsIntRegion extraPainted; RefPtr<TextureClient> backBufferOnWhite; RefPtr<TextureClient> backBuffer = mTile.GetBackBuffer(tileDirtyRegion, content, mode, extraPainted, &backBufferOnWhite); mTile.mUpdateRect = tileDirtyRegion.GetBounds().Union(extraPainted.GetBounds()); extraPainted.MoveBy(mTilingOrigin); extraPainted.And(extraPainted, aNewValidRegion); mPaintedRegion.OrWith(paintRegion); mPaintedRegion.OrWith(extraPainted); if (!backBuffer) { return; } RefPtr<gfx::DrawTarget> dt = backBuffer->BorrowDrawTarget(); RefPtr<gfx::DrawTarget> dtOnWhite; if (backBufferOnWhite) { dtOnWhite = backBufferOnWhite->BorrowDrawTarget(); } if (mode != SurfaceMode::SURFACE_OPAQUE) { for (auto iter = tileDirtyRegion.RectIter(); !iter.Done(); iter.Next()) { const gfx::IntRect& rect = iter.Get(); if (dtOnWhite) { dt->FillRect(gfx::Rect(rect.x, rect.y, rect.width, rect.height), gfx::ColorPattern(gfx::Color(0.0, 0.0, 0.0, 1.0))); dtOnWhite->FillRect(gfx::Rect(rect.x, rect.y, rect.width, rect.height), gfx::ColorPattern(gfx::Color(1.0, 1.0, 1.0, 1.0))); } else { dt->ClearRect(gfx::Rect(rect.x, rect.y, rect.width, rect.height)); } } } if (dtOnWhite) { dt = gfx::Factory::CreateDualDrawTarget(dt, dtOnWhite); dtOnWhite = nullptr; } { RefPtr<gfxContext> ctx = new gfxContext(dt); ctx->SetMatrix(ctx->CurrentMatrix().Translate(-mTilingOrigin.x, -mTilingOrigin.y)); aCallback(mPaintedLayer, ctx, paintRegion, paintRegion, DrawRegionClip::DRAW, nsIntRegion(), aCallbackData); } // Mark the area we just drew into the back buffer as invalid in the front buffer as they're // now out of sync. mTile.mInvalidFront.OrWith(tileDirtyRegion); // The new buffer is now validated, remove the dirty region from it. mTile.mInvalidBack.SubOut(tileDirtyRegion); dt = nullptr; mTile.Flip(); UnlockTile(mTile); if (backBuffer->HasInternalBuffer()) { // If our new buffer has an internal buffer, we don't want to keep another // TextureClient around unnecessarily, so discard the back-buffer. mTile.DiscardBackBuffer(); } mValidRegion = aNewValidRegion; mLastPaintSurfaceMode = mode; mLastPaintContentType = content; }
/** We can easily allow a prefix operator++. Postfix would be a stack management nightmare. **/ LuaStackTableIterator& LuaStackTableIterator::operator++() { Next(); return *this; }
bool ResultIterator::Next(PageIteratorLevel level) { if (it_->block() == NULL) return false; // already at end! switch (level) { case RIL_BLOCK: // explicit fall-through case RIL_PARA: // explicit fall-through case RIL_TEXTLINE: if (!PageIterator::Next(level)) return false; if (IsWithinFirstTextlineOfParagraph()) { // if we've advanced to a new paragraph, // recalculate current_paragraph_is_ltr_ current_paragraph_is_ltr_ = CurrentParagraphIsLtr(); } in_minor_direction_ = false; MoveToLogicalStartOfTextline(); return it_->block() != NULL; case RIL_SYMBOL: { GenericVector<int> blob_order; CalculateBlobOrder(&blob_order); int next_blob = 0; while (next_blob < blob_order.size() && blob_index_ != blob_order[next_blob]) next_blob++; next_blob++; if (next_blob < blob_order.size()) { // we're in the same word; simply advance one blob. BeginWord(blob_order[next_blob]); at_beginning_of_minor_run_ = false; return true; } level = RIL_WORD; // we've fallen through to the next word. } case RIL_WORD: { // explicit fall-through. if (it_->word() == NULL) return Next(RIL_BLOCK); GenericVectorEqEq<int> word_indices; int this_word_index = LTRWordIndex(); CalculateTextlineOrder(current_paragraph_is_ltr_, *this, &word_indices); int final_real_index = word_indices.size() - 1; while (final_real_index > 0 && word_indices[final_real_index] < 0) final_real_index--; for (int i = 0; i < final_real_index; i++) { if (word_indices[i] == this_word_index) { int j = i + 1; for (; j < final_real_index && word_indices[j] < 0; j++) { if (word_indices[j] == kMinorRunStart) in_minor_direction_ = true; if (word_indices[j] == kMinorRunEnd) in_minor_direction_ = false; } at_beginning_of_minor_run_ = (word_indices[j - 1] == kMinorRunStart); // awesome, we move to word_indices[j] if (BidiDebug(3)) { tprintf("Next(RIL_WORD): %d -> %d\n", this_word_index, word_indices[j]); } PageIterator::RestartRow(); for (int k = 0; k < word_indices[j]; k++) { PageIterator::Next(RIL_WORD); } MoveToLogicalStartOfWord(); return true; } } if (BidiDebug(3)) { tprintf("Next(RIL_WORD): %d -> EOL\n", this_word_index); } // we're going off the end of the text line. return Next(RIL_TEXTLINE); } } ASSERT_HOST(false); // shouldn't happen. return false; }
void ThreadedInorderIterator::Inorder() { for (char *ch = Next(); ch; ch = Next()) cout << *ch << endl; }
void ServoRestyleManager::ProcessPendingRestyles() { MOZ_ASSERT(PresContext()->Document(), "No document? Pshaw!"); MOZ_ASSERT(!nsContentUtils::IsSafeToRunScript(), "Missing a script blocker!"); if (MOZ_UNLIKELY(!PresContext()->PresShell()->DidInitialize())) { // PresShell::FlushPendingNotifications doesn't early-return in the case // where the PreShell hasn't yet been initialized (and therefore we haven't // yet done the initial style traversal of the DOM tree). We should arguably // fix up the callers and assert against this case, but we just detect and // handle it for now. return; } if (!HasPendingRestyles()) { return; } ServoStyleSet* styleSet = StyleSet(); nsIDocument* doc = PresContext()->Document(); Element* root = doc->GetRootElement(); if (root) { for (auto iter = mModifiedElements.Iter(); !iter.Done(); iter.Next()) { ServoElementSnapshot* snapshot = iter.UserData(); Element* element = iter.Key(); // TODO: avoid the ComputeRestyleHint call if we already have the highest // explicit restyle hint? nsRestyleHint hint = styleSet->ComputeRestyleHint(element, snapshot); hint |= snapshot->ExplicitRestyleHint(); if (hint) { NoteRestyleHint(element, hint); } } if (root->IsDirtyForServo() || root->HasDirtyDescendantsForServo()) { mInStyleRefresh = true; styleSet->StyleDocument(/* aLeaveDirtyBits = */ true); // First do any queued-up frame creation. (see bugs 827239 and 997506). // // XXXEmilio I'm calling this to avoid random behavior changes, since we // delay frame construction after styling we should re-check once our // model is more stable whether we can skip this call. // // Note this has to be *after* restyling, because otherwise frame // construction will find unstyled nodes, and that's not funny. PresContext()->FrameConstructor()->CreateNeededFrames(); nsStyleChangeList changeList; RecreateStyleContexts(root, nullptr, styleSet, changeList); ProcessRestyledFrames(changeList); mInStyleRefresh = false; } } MOZ_ASSERT(!doc->IsDirtyForServo()); doc->UnsetHasDirtyDescendantsForServo(); mModifiedElements.Clear(); IncrementRestyleGeneration(); }
eOSState cMenuBrowseFiles::Open(bool ForceOpen, bool Queue, bool Rewind) { if (!GetCurrent()) { return osContinue; } /* parent directory */ if (!strcmp("..", GetCurrent()->Name())) { m_CurrentDir = ParentDir(m_CurrentDir); Set(); return osContinue; /* directory */ } else if (GetCurrent()->IsDir()) { if (!ForceOpen && GetCurrent()->IsDvd()) { /* play dvd */ cPlayerFactory::Launch(m_Dev, pmAudioVideo, cPlaylist::BuildMrl("dvd", *m_CurrentDir, "/", GetCurrent()->Name()), NULL, true); return osEnd; } if (!ForceOpen && GetCurrent()->IsBluRay()) { cString bd_path = cString::sprintf("%s/%s/", *m_CurrentDir, GetCurrent()->Name()); if (BlurayMenuSupported(bd_path)) { AddSubMenu(new cMenuBluray(m_Dev, bd_path)); return osContinue; } /* play BluRay disc/image */ cPlayerFactory::Launch(m_Dev, pmAudioVideo, cPlaylist::BuildMrl("bluray", *m_CurrentDir, "/", GetCurrent()->Name(), "/"), NULL, true); return osEnd; } if (ForceOpen && GetCurrent()->IsDir() && !GetCurrent()->IsDvd() && !GetCurrent()->IsBluRay()) { /* play all files */ if (m_Mode != ShowImages) { if (m_OnlyQueue && !Queue) return osContinue; cString f = cString::sprintf("%s/%s/", *m_CurrentDir, GetCurrent()->Name()); if (!Queue || !cPlayerFactory::IsOpen()) cControl::Shutdown(); if (Queue) cPlayerFactory::Queue(m_Dev, f); else cPlayerFactory::Launch(m_Dev, m_Mode == ShowFiles ? pmAudioVideo : pmAudioOnly, f, NULL, true); return Queue ? osContinue : osEnd; } else { // TODO: show all images } } /* go to directory */ const char *d = GetCurrent()->Name(); char *buffer = NULL; if (asprintf(&buffer, "%s/%s", *m_CurrentDir, d) >= 0) { while (buffer[0] == '/' && buffer[1] == '/') memmove(buffer, buffer+1, strlen(buffer)); m_CurrentDir = cString(buffer, true); } Set(); return osContinue; /* regular file */ } else { cString f = cString::sprintf("%s/%s", *m_CurrentDir, GetCurrent()->Name()); strn0cpy(m_ConfigLastDir, f, sizeof(xc.browse_files_dir)); StoreConfig(); if (m_Mode != ShowImages) { /* video/audio */ if (m_OnlyQueue && !Queue) return osContinue; if (!Queue || !cPlayerFactory::IsOpen()) cControl::Shutdown(); if (Queue) cPlayerFactory::Queue(m_Dev, f); if (!cPlayerFactory::IsOpen()) { if (Rewind) unlink(cString::sprintf("%s.resume", *f)); if (GetCurrent()->IsBluRay()) { AddSubMenu(new cMenuBluray(m_Dev, f)); return osContinue; } if (GetCurrent()->IsDvd()) cPlayerFactory::Launch(m_Dev, pmAudioVideo, cPlaylist::BuildMrl("dvd", f), NULL, true); else cPlayerFactory::Launch(m_Dev, m_Mode == ShowFiles ? pmAudioVideo : pmAudioOnly, f, GetCurrent()->SubFile(), true); } if (Queue) return osContinue; } else { /* image */ cPlaylist *Playlist = new cPlaylist(); for (cFileListItem *it = (cFileListItem*)First(); it; it=(cFileListItem*)Next(it)) { if (!it->IsDir()) Playlist->Read(cString::sprintf("%s/%s", *m_CurrentDir, it->Name())); if (it == Get(Current())) Playlist->SetCurrent(Playlist->Last()); } cPlayerFactory::Launch(m_Dev, pmVideoOnly, Playlist, true); } return osEnd; } return osContinue; }
void AnnotatedDataLayer<Dtype>::load_batch(Batch<Dtype>* batch) { CPUTimer batch_timer; batch_timer.Start(); double read_time = 0; double trans_time = 0; CPUTimer timer; CHECK(batch->data_.count()); CHECK(this->transformed_data_.count()); // Reshape according to the first anno_datum of each batch // on single input batches allows for inputs of varying dimension. const int batch_size = this->layer_param_.data_param().batch_size(); const AnnotatedDataParameter& anno_data_param = this->layer_param_.annotated_data_param(); const TransformationParameter& transform_param = this->layer_param_.transform_param(); AnnotatedDatum anno_datum; //AnnotatedDatum& anno_datum = *(reader_.full().peek()); // Use data_transformer to infer the expected blob shape from anno_datum. //vector<int> top_shape = // this->data_transformer_->InferBlobShape(anno_datum.datum()); //this->transformed_data_.Reshape(top_shape); // Reshape batch according to the batch_size. //top_shape[0] = batch_size; //batch->data_.Reshape(top_shape); //Dtype* top_data = batch->data_.mutable_cpu_data(); //Dtype* top_label = NULL; // suppress warnings about uninitialized variables //if (this->output_labels_ && !has_anno_type_) { // top_label = batch->label_.mutable_cpu_data(); //} // Store transformed annotation. map<int, vector<AnnotationGroup> > all_anno; int num_bboxes = 0; for (int item_id = 0; item_id < batch_size; ++item_id) { timer.Start(); // get a anno_datum //AnnotatedDatum& anno_datum = *(reader_.full().pop("Waiting for data")); while (Skip()) { Next(); } anno_datum.ParseFromString(cursor_->value()); read_time += timer.MicroSeconds(); //timer.Start(); if (item_id == 0) { // Reshape according to the first datum of each batch // on single input batches allows for inputs of varying dimension. // Use data_transformer to infer the expected blob shape from datum. vector<int> top_shape = this->data_transformer_->InferBlobShape(anno_datum.datum()); this->transformed_data_.Reshape(top_shape); // Reshape batch according to the batch_size. top_shape[0] = batch_size; batch->data_.Reshape(top_shape); } AnnotatedDatum distort_datum; AnnotatedDatum* expand_datum = NULL; if (transform_param.has_distort_param()) { distort_datum.CopyFrom(anno_datum); this->data_transformer_->DistortImage(anno_datum.datum(), distort_datum.mutable_datum()); if (transform_param.has_expand_param()) { expand_datum = new AnnotatedDatum(); this->data_transformer_->ExpandImage(distort_datum, expand_datum); } else { expand_datum = &distort_datum; } } else { if (transform_param.has_expand_param()) { expand_datum = new AnnotatedDatum(); this->data_transformer_->ExpandImage(anno_datum, expand_datum); } else { expand_datum = &anno_datum; } } AnnotatedDatum* sampled_datum = NULL; bool has_sampled = false; if (batch_samplers_.size() > 0) { // Generate sampled bboxes from expand_datum. vector<NormalizedBBox> sampled_bboxes; GenerateBatchSamples(*expand_datum, batch_samplers_, &sampled_bboxes); if (sampled_bboxes.size() > 0) { // Randomly pick a sampled bbox and crop the expand_datum. int rand_idx = caffe_rng_rand() % sampled_bboxes.size(); sampled_datum = new AnnotatedDatum(); this->data_transformer_->CropImage(*expand_datum, sampled_bboxes[rand_idx], sampled_datum); has_sampled = true; } else { sampled_datum = expand_datum; } } else { sampled_datum = expand_datum; } CHECK(sampled_datum != NULL); timer.Start(); vector<int> top_shape = this->data_transformer_->InferBlobShape(anno_datum.datum()); vector<int> shape = this->data_transformer_->InferBlobShape(sampled_datum->datum()); if (transform_param.has_resize_param()) { if (transform_param.resize_param().resize_mode() == ResizeParameter_Resize_mode_FIT_SMALL_SIZE) { this->transformed_data_.Reshape(shape); batch->data_.Reshape(shape); //top_data = batch->data_.mutable_cpu_data(); } else { CHECK(std::equal(top_shape.begin() + 1, top_shape.begin() + 4, shape.begin() + 1)); } } else { CHECK(std::equal(top_shape.begin() + 1, top_shape.begin() + 4, shape.begin() + 1)); } // Apply data transformations (mirror, scale, crop...) timer.Start(); int offset = batch->data_.offset(item_id); Dtype* top_data = batch->data_.mutable_cpu_data(); this->transformed_data_.set_cpu_data(top_data + offset); vector<AnnotationGroup> transformed_anno_vec; if (this->output_labels_) { if (has_anno_type_) { // Make sure all data have same annotation type. CHECK(sampled_datum->has_type()) << "Some datum misses AnnotationType."; if (anno_data_param.has_anno_type()) { sampled_datum->set_type(anno_type_); } else { CHECK_EQ(anno_type_, sampled_datum->type()) << "Different AnnotationType."; } // Transform datum and annotation_group at the same time transformed_anno_vec.clear(); this->data_transformer_->Transform(*sampled_datum, &(this->transformed_data_), &transformed_anno_vec); if (anno_type_ == AnnotatedDatum_AnnotationType_BBOX) { // Count the number of bboxes. for (int g = 0; g < transformed_anno_vec.size(); ++g) { num_bboxes += transformed_anno_vec[g].annotation_size(); } } else { LOG(FATAL) << "Unknown annotation type."; } all_anno[item_id] = transformed_anno_vec; } else { this->data_transformer_->Transform(sampled_datum->datum(), &(this->transformed_data_)); // Otherwise, store the label from datum. CHECK(sampled_datum->datum().has_label()) << "Cannot find any label."; Dtype* top_label = batch->label_.mutable_cpu_data(); top_label[item_id] = sampled_datum->datum().label(); } } else { this->data_transformer_->Transform(sampled_datum->datum(), &(this->transformed_data_)); } // clear memory if (has_sampled) { delete sampled_datum; } if (transform_param.has_expand_param()) { delete expand_datum; } trans_time += timer.MicroSeconds(); //reader_.free().push(const_cast<AnnotatedDatum*>(&anno_datum)); Next(); } // Store "rich" annotation if needed. if (this->output_labels_ && has_anno_type_) { vector<int> label_shape(4); if (anno_type_ == AnnotatedDatum_AnnotationType_BBOX) { label_shape[0] = 1; label_shape[1] = 1; label_shape[3] = 8; if (num_bboxes == 0) { // Store all -1 in the label. label_shape[2] = 1; batch->label_.Reshape(label_shape); caffe_set<Dtype>(8, -1, batch->label_.mutable_cpu_data()); } else { // Reshape the label and store the annotation. label_shape[2] = num_bboxes; batch->label_.Reshape(label_shape); Dtype* top_label = batch->label_.mutable_cpu_data(); int idx = 0; for (int item_id = 0; item_id < batch_size; ++item_id) { const vector<AnnotationGroup>& anno_vec = all_anno[item_id]; for (int g = 0; g < anno_vec.size(); ++g) { const AnnotationGroup& anno_group = anno_vec[g]; for (int a = 0; a < anno_group.annotation_size(); ++a) { const Annotation& anno = anno_group.annotation(a); const NormalizedBBox& bbox = anno.bbox(); top_label[idx++] = item_id; top_label[idx++] = anno_group.group_label(); top_label[idx++] = anno.instance_id(); top_label[idx++] = bbox.xmin(); top_label[idx++] = bbox.ymin(); top_label[idx++] = bbox.xmax(); top_label[idx++] = bbox.ymax(); top_label[idx++] = bbox.difficult(); } } } } } else { LOG(FATAL) << "Unknown annotation type."; } } timer.Stop(); batch_timer.Stop(); DLOG(INFO) << "Prefetch batch: " << batch_timer.MilliSeconds() << " ms."; DLOG(INFO) << " Read time: " << read_time / 1000 << " ms."; DLOG(INFO) << "Transform time: " << trans_time / 1000 << " ms."; }