Result RSS14Reader::decodeRow(int rowNumber, const BitArray& row_, std::unique_ptr<DecodingState>& state) const { RSS14DecodingState* prevState = nullptr; if (state == nullptr) { state.reset(prevState = new RSS14DecodingState); } else { #if !defined(ZX_HAVE_CONFIG) #error "You need to include ZXConfig.h" #elif !defined(ZX_NO_RTTI) prevState = dynamic_cast<RSS14DecodingState*>(state.get()); #else prevState = static_cast<RSS14DecodingState*>(state.get()); #endif } if (prevState == nullptr) { throw std::runtime_error("Invalid state"); } BitArray row = row_.copy(); AddOrTally(prevState->possibleLeftPairs, DecodePair(row, false, rowNumber)); row.reverse(); AddOrTally(prevState->possibleRightPairs, DecodePair(row, true, rowNumber)); // row.reverse(); for (const auto& left : prevState->possibleLeftPairs) { if (left.count() > 1) { for (const auto& right : prevState->possibleRightPairs) { if (right.count() > 1) { if (CheckChecksum(left, right)) { return ConstructResult(left, right); } } } } } return Result(DecodeStatus::NotFound); }
void cSlotAreaCrafting::ShiftClickedResult(cPlayer & a_Player) { cItem Result(*GetSlot(0, a_Player)); if (Result.IsEmpty()) { return; } cItem * PlayerSlots = GetPlayerSlots(a_Player) + 1; for (;;) { // Try distributing the result. If it fails, bail out: cItem ResultCopy(Result); m_ParentWindow.DistributeStack(ResultCopy, a_Player, this, false); if (!ResultCopy.IsEmpty()) { // Couldn't distribute all of it. Bail out return; } // Distribute the result, this time for real: ResultCopy = Result; m_ParentWindow.DistributeStack(ResultCopy, a_Player, this, true); // Remove the ingredients from the crafting grid and update the recipe: cCraftingRecipe & Recipe = GetRecipeForPlayer(a_Player); cCraftingGrid Grid(PlayerSlots, m_GridSize, m_GridSize); Recipe.ConsumeIngredients(Grid); Grid.CopyToItems(PlayerSlots); UpdateRecipe(a_Player); // Broadcast the window, we sometimes move items to different locations than Vanilla, causing needless desyncs: m_ParentWindow.BroadcastWholeWindow(); // If the recipe has changed, bail out: if (!Recipe.GetResult().IsEqual(Result)) { return; } } }
void CBaseDialog::OnComputeStoreHash() { HRESULT hRes = S_OK; CEditor MyStoreEID( this, IDS_COMPUTESTOREHASH, IDS_COMPUTESTOREHASHPROMPT, 4, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); MyStoreEID.InitPane(0, CreateSingleLinePane(IDS_STOREEID, NULL, false)); MyStoreEID.InitPane(1, CreateCheckPane(IDS_EIDBASE64ENCODED, false, false)); MyStoreEID.InitPane(2, CreateSingleLinePane(IDS_FILENAME, NULL, false)); MyStoreEID.InitPane(3, CreateCheckPane(IDS_PUBLICFOLDERSTORE, false, false)); WC_H(MyStoreEID.DisplayDialog()); if (S_OK != hRes) return; // Get the entry ID as a binary LPENTRYID lpEntryID = NULL; size_t cbBin = NULL; EC_H(MyStoreEID.GetEntryID(0, MyStoreEID.GetCheck(1), &cbBin, &lpEntryID)); DWORD dwHash = ComputeStoreHash((ULONG)cbBin, (LPBYTE)lpEntryID, NULL, MyStoreEID.GetStringW(2), MyStoreEID.GetCheck(3)); CString szHash; szHash.FormatMessage(IDS_STOREHASHVAL, dwHash); CEditor Result( this, IDS_STOREHASH, NULL, (ULONG)0, CEDITOR_BUTTON_OK); Result.SetPromptPostFix(szHash); (void)Result.DisplayDialog(); delete[] lpEntryID; } // CBaseDialog::OnComputeStoreHash
Recordinfo API::createIndex(sqlcommand& sql, bool flag){ std::string tablename=sql.createIndexInfo[1]; std::string indexname=sql.createIndexInfo[0]; std::string attrname=sql.createIndexInfo[2]; // if(catalogmanager->attrname) // 保证index一定会在unique上面创建,primary key // if(!catalogmanager->isUnique(tablename, attrname) && !catalogmanager->isPK(tablename, attrname) ){ Recordinfo result=Recordinfo(false, "You can only create an index on unique/primary attribute!", Result(), 0); return result; } int attrtype=catalogmanager->getAttrType(tablename, sql.createIndexInfo[2]); catalogmanager->insertIndex(sql); int valuecharlen=0; if(attrtype>0) valuecharlen=catalogmanager->getCharLength(tablename, sql.createIndexInfo[2]); indexmanager->CreateIndex(indexname, attrtype, std::vector<Value>(), std::vector<slot>(), valuecharlen); // insert all records to index sqlcommand tempsql=sqlcommand(); tempsql.sqlType=0; tempsql.selectInfo=std::vector<std::string>(); tempsql.selectInfo.push_back(sql.createIndexInfo[2]); tempsql.tablename=tablename; tempsql.conditions=std::vector<std::vector<std::string> >(); Table temptable=catalogmanager->getTable(tablename); std::vector<slot> tempslot=std::vector<slot>(); Recordinfo result=recordmanager->Select_Record(tempsql, temptable, 0, tempslot); for(int i=0;i<tempslot.size();i++){ Value v; switch(attrtype){ case 0:v=Value(attrtype, std::stoi(result.res.rows[i+1].cols[0]));break; case 1:v=Value(attrtype, result.res.rows[i+1].cols[0]);break; case -1:v=Value(attrtype, std::stof(result.res.rows[i+1].cols[0]));break; } indexmanager->_insert(indexname, v, tempslot[i]); } return Recordinfo(1, "", Result(), 0); // further improve }
void ObjectMgr::LoadItemTemplates() { QueryResult Result(sDatabase.Query("SELECT * FROM `item_template`")); ItemTemplate* pTemplate; while (Result->next()) { pTemplate = new ItemTemplate; pTemplate->ItemID = Result->getUInt64 (1); pTemplate->Class = Result->getUInt (2); pTemplate->SubClass = Result->getUInt (3); pTemplate->Name = Result->getString (4); pTemplate->DisplayInfoID = Result->getUInt (5); pTemplate->InventoryType = Result->getUInt (6); pTemplate->ContainerSlots = Result->getUInt (7); pTemplate->Description = Result->getString (8); ItemTemplates[pTemplate->ItemID] = pTemplate; } }
void ObjectMgr::LoadSpellTemplates() { QueryResult Result(WorldDB->Query("SELECT * FROM `spell_template`")); SpellTemplate* pTemplate; while (Result->next()) { pTemplate = new SpellTemplate; pTemplate->Entry = Result->getUInt (1); pTemplate->Name = Result->getString (2); pTemplate->Tileset = Result->getString (3); pTemplate->TextureX = Result->getUInt (4); pTemplate->TextureY = Result->getUInt (5); pTemplate->Flag = Result->getUInt (6); pTemplate->BaseValue = Result->getUInt (7); pTemplate->BaseCost = Result->getUInt (8); SpellTemplates[pTemplate->Entry] = pTemplate; } }
status_t PrintServerMessenger::SendRequest() { fThreadCompleted = create_sem(0, "print_server_messenger_sem"); if (fThreadCompleted < B_OK) return B_ERROR; thread_id id = spawn_thread(MessengerThread, "async_request", B_NORMAL_PRIORITY, this); if (id <= 0 || resume_thread(id) != B_OK) return B_ERROR; // Get the originating window, if it exists BWindow* window = dynamic_cast<BWindow*>( BLooper::LooperForThread(find_thread(NULL))); if (window != NULL) { status_t err; while (true) { do { err = acquire_sem_etc(fThreadCompleted, 1, B_RELATIVE_TIMEOUT, 50000); // We've (probably) had our time slice taken away from us } while (err == B_INTERRUPTED); // Semaphore was finally nuked in SetResult(BMessage *) if (err == B_BAD_SEM_ID) break; window->UpdateIfNeeded(); } } else { // No window to update, so just hang out until we're done. while (acquire_sem(fThreadCompleted) == B_INTERRUPTED); } status_t status; wait_for_thread(id, &status); return Result() != NULL ? B_OK : B_ERROR; }
static Result ConstructResult(const RSS::Pair& leftPair, const RSS::Pair& rightPair) { int64_t symbolValue = 4537077 * static_cast<int64_t>(leftPair.value()) + rightPair.value(); std::wstringstream buffer; buffer << std::setw(13) << std::setfill(L'0') << symbolValue; int checkDigit = 0; for (int i = 0; i < 13; i++) { int digit = buffer.get() - '0'; checkDigit += (i & 0x01) == 0 ? 3 * digit : digit; } checkDigit = 10 - (checkDigit % 10); if (checkDigit == 10) { checkDigit = 0; } buffer.put((wchar_t)(checkDigit + '0')); auto& leftPoints = leftPair.finderPattern().points(); auto& rightPoints = rightPair.finderPattern().points(); return Result(buffer.str(), ByteArray(), { leftPoints[0], leftPoints[1], rightPoints[0], rightPoints[1] }, BarcodeFormat::RSS_14); }
FunctionAnalysisManagerCGSCCProxy::Result FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG) { // Collect the FunctionAnalysisManager from the Module layer and use that to // build the proxy result. // // This allows us to rely on the FunctionAnalysisMangaerModuleProxy to // invalidate the function analyses. auto &MAM = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG).getManager(); Module &M = *C.begin()->getFunction().getParent(); auto *FAMProxy = MAM.getCachedResult<FunctionAnalysisManagerModuleProxy>(M); assert(FAMProxy && "The CGSCC pass manager requires that the FAM module " "proxy is run on the module prior to entering the CGSCC " "walk."); // Note that we special-case invalidation handling of this proxy in the CGSCC // analysis manager's Module proxy. This avoids the need to do anything // special here to recompute all of this if ever the FAM's module proxy goes // away. return Result(FAMProxy->getManager()); }
glm::mat4 Camera::GetViewMatrix(glm::vec3 _eye, glm::vec3 _center, glm::vec3 up ){ centre = eye + direction; glm::vec3 dir = glm::normalize(_center - eye); glm::vec3 tup = glm::normalize(up); glm::vec3 s = glm::normalize(glm::cross(dir, tup)); tup = glm::cross(s, dir); glm::mat4x4 Result(1); Result[0][0] = s.x; Result[1][0] = s.y; Result[2][0] = s.z; Result[0][1] = tup.x; Result[1][1] = tup.y; Result[2][1] = tup.z; Result[0][2] =-dir.x; Result[1][2] =-dir.y; Result[2][2] =-dir.z; return glm::translate(Result, -eye); }
//--------------------------------------------------------------------------- UnicodeString FmtLoadStr(intptr_t Id, ...) { UnicodeString Result(64, 0); wchar_t Format[1024]; HINSTANCE hInstance = GetGlobalFunctions()->GetInstanceHandle(); intptr_t Length = ::LoadString(hInstance, static_cast<UINT>(Id), Format, static_cast<int>(sizeof(Format))); if (!Length) { DEBUG_PRINTF(L"Unknown resource string id: %d\n", Id); } else { va_list Args; va_start(Args, Id); intptr_t Len = _vscwprintf(Format, Args); Result.SetLength(Len + sizeof(wchar_t)); vswprintf_s(&Result[1], Result.Length(), Format, Args); va_end(Args); } return Result; }
int main() { uint64_t EndTarget = 24; std::vector<uint64_t> Result(EndTarget); Result[0] = 1; for (uint64_t i = 0; i < EndTarget - 1; i++) { uint64_t Summation = 0; for (uint64_t j = 0; j <= i; j++) Summation += Result[j] * NChooseK(i, j); Result[i + 1] = Result[i] + Summation; } for (size_t i = 0; i < EndTarget; i++) { std::cout << Result[i] << std::endl; } std::cout << std::endl; for (size_t i = 0; i < EndTarget; i++) { std::bitset<64> x(Result[i]); std::cout << x << std::endl; } std::cout << std::endl; for (size_t i = 0; i < EndTarget; i++) { std::cout << float(Result[i]) << std::endl; } }
//----------------------------------------------------------------- void tStreamReceiveFile::ProcessError(QDataStream &) { enabled=false; int num_error=1; QString error="Error in command 1"; QString detail="File name: "+file_name+"\nFile size: "+QString::number(file_size); QString client_detail="Ошибка на стороне клиента \n"+error_reason; QByteArray block; QDataStream in(&block, QIODevice::WriteOnly); in << tr("Error"); in << num_error; in << error; in << detail; in << client_detail; emit Result(block); emit EndCommand(); }
FBox FKSphylElem::CalcAABB(const FTransform& BoneTM, float Scale) const { FTransform ElemTM = GetTransform(); ElemTM.ScaleTranslation( FVector(Scale) ); ElemTM *= BoneTM; const FVector SphylCenter = ElemTM.GetLocation(); // Get sphyl axis direction const FVector Axis = ElemTM.GetScaledAxis( EAxis::Z ); // Get abs of that vector const FVector AbsAxis(FMath::Abs(Axis.X), FMath::Abs(Axis.Y), FMath::Abs(Axis.Z)); // Scale by length of sphyl const FVector AbsDist = (Scale * 0.5f * Length) * AbsAxis; const FVector MaxPos = SphylCenter + AbsDist; const FVector MinPos = SphylCenter - AbsDist; const FVector Extent(Scale * Radius); FBox Result(MinPos - Extent, MaxPos + Extent); return Result; }
void ObjectMgr::LoadCreatureTemplates() { QueryResult Result(WorldDB->Query("SELECT * FROM `creature_template`")); CreatureTemplate* pTemplate; while(Result->next()) { pTemplate = new CreatureTemplate; pTemplate->Entry = Result->getUInt (1); pTemplate->Name = Result->getString (2); pTemplate->Tileset = Result->getString (3); pTemplate->TextureX = Result->getUInt (4); pTemplate->TextureY = Result->getUInt (5); pTemplate->Flag = Result->getUInt (6); pTemplate->MaxHealth = Result->getUInt (7); pTemplate->MaxPower = Result->getUInt (8); pTemplate->ScriptName = Result->getString (9); CreatureTemplates[pTemplate->Entry] = pTemplate; } }
void ObjectMgr::LoadItemTemplates() { QueryResult Result(WorldDB->Query("SELECT * FROM `item_template`")); ItemTemplate* pTemplate; while (Result->next()) { pTemplate = new ItemTemplate; pTemplate->Entry = Result->getUInt (1); pTemplate->Name = Result->getString (2); pTemplate->Class = Result->getUInt (3); pTemplate->Tileset = Result->getString (4); pTemplate->TextureX = Result->getUInt (5); pTemplate->TextureY = Result->getUInt (6); pTemplate->InventoryType = Result->getUInt (7); pTemplate->ContainerSlots = Result->getUInt (8); pTemplate->Description = Result->getString (9); ItemTemplates[pTemplate->Entry] = pTemplate; } }
int main(int argc, char ** argv) { MPI::Init(argc, argv); const int rank = MPI::COMM_WORLD.Get_rank(); const int SLAVE_COUNT = MPI::COMM_WORLD.Get_size(); //unit::Matrix<double> A, B, C; unit::Matrix<double> A(), B(); unit::Matrix<double> Result(); //std::printf("Hello world!\n"); MPI::Finalize(); if(rank == 0) { std::fflush(stdout); } return 0; }
WorkCoord DocCoord::ToLogical(Spread* pSpread, View *pView) { // Check that we have not been fed garbage ENSURE( pSpread!=NULL, "DocCoord::ToLogical was passed a NULL spread" ); // Find the chapter Chapter* pChapter = (Chapter*) pSpread->FindParent(); ENSURE( pChapter!=NULL, "DocCoord::ToLogical. Spread did not have a parent chapter" ); ENSURE( pChapter->IsKindOf(CC_RUNTIME_CLASS(Chapter)), "DocCoord::ToLogical. Chapter is not a chapter" ); // Find out about the chapter DocRect ChapterRect = pChapter->GetPasteboardRect(TRUE, pView); XLONG ChapterDepth = pChapter->GetChapterDepth(); // Build the logical coord from the doccoord WorkCoord Result( MakeXLong(x), MakeXLong(y) ); Result.x = Result.x - ChapterRect.lo.x; Result.y = Result.y - ChapterRect.hi.y; Result.y = Result.y - ChapterDepth; // return the coord return Result; }
TCString VariablesEscape(TCString Str) { if (!Str.GetLen()) { return _T(""); } enum eState { ST_TEXT, ST_QUOTE }; eState State = ST_QUOTE; TCString Result(_T("`")); const TCHAR *p = Str; while (*p) { if (*p == '`') { if (State == ST_TEXT) { Result += _T("````"); State = ST_QUOTE; } else { Result += _T("``"); } } else { Result += *p; State = ST_TEXT; } p++; } if (State == ST_QUOTE) { Result.GetBuffer()[Result.GetLen() - 1] = '\0'; Result.ReleaseBuffer(); } else { Result += '`'; } return Result; }
std::vector< Result > ElementPresentValidator::VerifyElementPresent( const QName &element_qname, const std::vector< QName > &possible_parents, const xc::DOMDocument &document ) { xc::DOMNodeList *matching_elements = document.getElementsByTagNameNS( toX( element_qname.namespace_name ), toX( element_qname.local_name ) ); std::vector< Result > results; if ( matching_elements->getLength() < 1 ) { xc::DOMNode* parent = xe::GetFirstAvailableElement( possible_parents, document ); Result result = parent != NULL ? ResultWithNodeLocation( ERROR_XML_ELEMENT_NOT_PRESENT, *parent ) : Result( ERROR_XML_ELEMENT_NOT_PRESENT ); result.AddMessageArgument( element_qname.local_name ); results.push_back( result ); } return results; }
Result Context::createErrorResultv(const char *fmt, va_list args) { if (fmt == NULL) return Result::out_of_memory; char *s = PR_vsmprintf(fmt, args); if (s == NULL) return Result::out_of_memory; int len = strlen(s); char *p = (char *) pool_malloc(pool, len + 1); if (p == NULL) { PR_Free(s); return Result::out_of_memory; } memcpy(p, s, len); p[len] = '\0'; PR_Free(s); return Result(RESULT_ERROR, PR_FALSE, -1, pool, p, len); }
CString CMail::MPAddressSpec(const CString& iStr, int& curPos){ /* addr-spec = local-part "@" domain ; global address */ #ifdef M_DEBUG cout << "MPAddressSpec() - " << curPos << endl; #endif if (curPos < iStr.StrLength()) { FUser = MPLocalPart(iStr, curPos); if (!FUser.StrLength()) return ""; if (iStr[curPos] == '@') { int workingPos = curPos+1; FDomain = MPDomain(iStr, workingPos); if (!FDomain.StrLength()) return ""; CString Result(FUser); Result+='@'; Result+=FDomain; curPos = workingPos; return Result; } else return ""; } else return ""; }
void cSlotAreaCrafting::ShiftClickedResult(cPlayer & a_Player) { cItem Result(*GetSlot(0, a_Player)); if (Result.IsEmpty()) { return; } cItem * PlayerSlots = GetPlayerSlots(a_Player) + 1; do { // Try distributing the result. If it fails, bail out: cItem ResultCopy(Result); m_ParentWindow.DistributeStack(ResultCopy, a_Player, this, false); if (!ResultCopy.IsEmpty()) { // Couldn't distribute all of it. Bail out return; } // Distribute the result, this time for real: ResultCopy = Result; m_ParentWindow.DistributeStack(ResultCopy, a_Player, this, true); // Remove the ingredients from the crafting grid and update the recipe: cCraftingRecipe & Recipe = GetRecipeForPlayer(a_Player); cCraftingGrid Grid(PlayerSlots, m_GridSize, m_GridSize); Recipe.ConsumeIngredients(Grid); Grid.CopyToItems(PlayerSlots); UpdateRecipe(a_Player); if (!Recipe.GetResult().IsEqual(Result)) { // The recipe has changed, bail out return; } } while (true); }
void BucketHandler::performSetCurrentState(BucketId bucketId, storage::spi::BucketInfo::ActiveState newState, IGenericResultHandler *resultHandler) { if (!_nodeUp) { Result result(Result::TRANSIENT_ERROR, "Cannot set bucket active state when node is down"); resultHandler->handle(result); return; } bool active = (newState == storage::spi::BucketInfo::ACTIVE); LOG(debug, "performSetCurrentState(%s, %s)", bucketId.toString().c_str(), (active ? "ACTIVE" : "NOT_ACTIVE")); _ready->setBucketState(bucketId, active); if (!_changedHandlers.empty()) { typedef std::vector<IBucketStateChangedHandler *> Chv; Chv &chs(_changedHandlers); for (Chv::const_iterator itr = chs.begin(); itr != chs.end(); ++itr) { (*itr)->notifyBucketStateChanged(bucketId, newState); } } resultHandler->handle(Result()); }
Result doOr(Result arg1, Result arg2, Result_Type ResultT) { switch(ResultT) { case s8: case u8: return Result(u8, arg1.convert<Result_type2type<u8>::type >() | arg2.convert< Result_type2type<u8>::type >()); case s16: case u16: return Result(u16, arg1.convert<Result_type2type<u16>::type >() | arg2.convert< Result_type2type<u16>::type >()); case s32: case u32: return Result(u32, arg1.convert<Result_type2type<u32>::type >() | arg2.convert< Result_type2type<u32>::type >()); case s48: case u48: return Result(u48, arg1.convert<Result_type2type<u48>::type >() | arg2.convert< Result_type2type<u48>::type >()); case s64: case u64: return Result(u64, arg1.convert<Result_type2type<u64>::type >() | arg2.convert< Result_type2type<u64>::type >()); /*case sp_float: return Result(ResultT, arg1.convert<Result_type2type<sp_float>::type >() + arg2.convert< Result_type2type<sp_float>::type >()); case dp_float: return Result(ResultT, arg1.convert<Result_type2type<dp_float>::type >() + arg2.convert< Result_type2type<dp_float>::type >());*/ case bit_flag: return Result(ResultT, arg1.convert<Result_type2type<bit_flag>::type >() | arg2.convert< Result_type2type<bit_flag>::type >()); default: // m512 and dbl128 not implemented yet... return Result(ResultT); } }
TSharedPtr<FExtender> STileMapEditorViewport::GetExtenders() const { TSharedPtr<FExtender> Result(MakeShareable(new FExtender)); return Result; }
PointTD* ProjectionComplexDD::Rotate3D(PointTD pPointTD) { PointTD Result(pPointTD.fX, pPointTD.fY, 0, pPointTD.iAction, pPointTD.iType, pPointTD.sText); return new PointTD(Result); }
std::string createSHLVertexProg(void) { std::string Result(""); return Result; }
Status createCollectionForApplyOps(OperationContext* opCtx, const std::string& dbName, const BSONElement& ui, const BSONObj& cmdObj, const BSONObj& idIndex) { invariant(opCtx->lockState()->isDbLockedForMode(dbName, MODE_X)); auto db = dbHolder().get(opCtx, dbName); const NamespaceString newCollName(Command::parseNsCollectionRequired(dbName, cmdObj)); auto newCmd = cmdObj; // If a UUID is given, see if we need to rename a collection out of the way, and whether the // collection already exists under a different name. If so, rename it into place. As this is // done during replay of the oplog, the operations do not need to be atomic, just idempotent. // We need to do the renaming part in a separate transaction, as we cannot transactionally // create a database on MMAPv1, which could result in createCollection failing if the database // does not yet exist. if (ui.ok()) { // Return an optional, indicating whether we need to early return (if the collection already // exists, or in case of an error). using Result = boost::optional<Status>; auto result = writeConflictRetry(opCtx, "createCollectionForApplyOps", newCollName.ns(), [&] { WriteUnitOfWork wunit(opCtx); // Options need the field to be named "uuid", so parse/recreate. auto uuid = uassertStatusOK(UUID::parse(ui)); uassert(ErrorCodes::InvalidUUID, "Invalid UUID in applyOps create command: " + uuid.toString(), uuid.isRFC4122v4()); auto& catalog = UUIDCatalog::get(opCtx); auto currentName = catalog.lookupNSSByUUID(uuid); OpObserver* opObserver = getGlobalServiceContext()->getOpObserver(); if (currentName == newCollName) return Result(Status::OK()); // In the case of oplog replay, a future command may have created or renamed a // collection with that same name. In that case, renaming this future collection to // a random temporary name is correct: once all entries are replayed no temporary // names will remain. On MMAPv1 the rename can result in index names that are too // long. However this should only happen for initial sync and "resync collection" // for rollback, so we can let the error propagate resulting in an abort and restart // of the initial sync or result in rollback to fassert, requiring a resync of that // node. const bool stayTemp = true; if (auto futureColl = db ? db->getCollection(opCtx, newCollName) : nullptr) { auto tmpNameResult = db->makeUniqueCollectionNamespace(opCtx, "tmp%%%%%"); if (!tmpNameResult.isOK()) { return Result(Status(tmpNameResult.getStatus().code(), str::stream() << "Cannot generate temporary " "collection namespace for applyOps " "create command: collection: " << newCollName.ns() << ". error: " << tmpNameResult.getStatus().reason())); } const auto& tmpName = tmpNameResult.getValue(); Status status = db->renameCollection(opCtx, newCollName.ns(), tmpName.ns(), stayTemp); if (!status.isOK()) return Result(status); opObserver->onRenameCollection(opCtx, newCollName, tmpName, futureColl->uuid(), /*dropTarget*/ false, /*dropTargetUUID*/ {}, stayTemp); } // If the collection with the requested UUID already exists, but with a different // name, just rename it to 'newCollName'. if (catalog.lookupCollectionByUUID(uuid)) { Status status = db->renameCollection(opCtx, currentName.ns(), newCollName.ns(), stayTemp); if (!status.isOK()) return Result(status); opObserver->onRenameCollection(opCtx, currentName, newCollName, uuid, /*dropTarget*/ false, /*dropTargetUUID*/ {}, stayTemp); wunit.commit(); return Result(Status::OK()); } // A new collection with the specific UUID must be created, so add the UUID to the // creation options. Regular user collection creation commands cannot do this. auto uuidObj = uuid.toBSON(); newCmd = cmdObj.addField(uuidObj.firstElement()); wunit.commit(); return Result(boost::none); }); if (result) { return *result; } } return createCollection( opCtx, newCollName, newCmd, idIndex, CollectionOptions::parseForStorage); }
PlanStage::StageState S2NearStage::addResultToQueue(WorkingSetID* out) { PlanStage::StageState state = _child->work(out); // All done reading from _child. if (PlanStage::IS_EOF == state) { _child.reset(); _keyGeoFilter.reset(); // Adjust the annulus size depending on how many results we got. if (_results.empty()) { _radiusIncrement *= 2; } else if (_results.size() < 300) { _radiusIncrement *= 2; } else if (_results.size() > 600) { _radiusIncrement /= 2; } // Make a new ixscan next time. return PlanStage::NEED_TIME; } // Nothing to do unless we advance. if (PlanStage::ADVANCED != state) { return state; } WorkingSetMember* member = _ws->get(*out); // Must have an object in order to get geometry out of it. verify(member->hasObj()); // The scans we use don't dedup so we must dedup them ourselves. We only put locs into here // if we know for sure whether or not we'll return them in this annulus. if (member->hasLoc()) { if (_seenInScan.end() != _seenInScan.find(member->loc)) { return PlanStage::NEED_TIME; } } // Get all the fields with that name from the document. BSONElementSet geom; member->obj.getFieldsDotted(_params.nearQuery.field, geom, false); if (geom.empty()) { return PlanStage::NEED_TIME; } // Some value that any distance we can calculate will be less than. double minDistance = numeric_limits<double>::max(); BSONObj minDistanceObj; for (BSONElementSet::iterator git = geom.begin(); git != geom.end(); ++git) { if (!git->isABSONObj()) { mongoutils::str::stream ss; ss << "s2near stage read invalid geometry element " << *git << " from child"; Status status(ErrorCodes::InternalError, ss); *out = WorkingSetCommon::allocateStatusMember( _ws, status); return PlanStage::FAILURE; } BSONObj obj = git->Obj(); double distToObj; if (S2SearchUtil::distanceBetween(_params.nearQuery.centroid.point, obj, &distToObj)) { if (distToObj < minDistance) { minDistance = distToObj; minDistanceObj = obj; } } else { warning() << "unknown geometry: " << obj.toString(); } } // If we're here we'll either include the doc in this annulus or reject it. It's safe to // ignore it if it pops up again in this annulus. if (member->hasLoc()) { _seenInScan.insert(member->loc); } // If the distance to the doc satisfies our distance criteria, add it to our buffered // results. if (minDistance >= _innerRadius && (_outerRadiusInclusive ? minDistance <= _outerRadius : minDistance < _outerRadius)) { _results.push(Result(*out, minDistance)); if (_params.addDistMeta) { // FLAT implies the output distances are in radians. Convert to meters. if (FLAT == _params.nearQuery.centroid.crs) { member->addComputed(new GeoDistanceComputedData(minDistance / kRadiusOfEarthInMeters)); } else { member->addComputed(new GeoDistanceComputedData(minDistance)); } } if (_params.addPointMeta) { member->addComputed(new GeoNearPointComputedData(minDistanceObj)); } if (member->hasLoc()) { _invalidationMap[member->loc] = *out; } } return PlanStage::NEED_TIME; }