Example #1
0
// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
void Scouter::InitAI(Global* GLI){
	G = GLI;
	for(vector<float3>::iterator kj = G->M->hotspot.begin(); kj != G->M->hotspot.end(); ++kj){
		mexes.push_back(*kj);
	}
	TdfParser cq(G);
	cq.LoadFile("script.txt");
	int nd=0;
	cq.GetDef(nd,"0","GAME\\NumTeams");
	TdfParser MP(G);
	MP.LoadFile(string("maps\\")+string(G->cb->GetMapName()).substr(0,string(G->cb->GetMapName()).find('.'))+".smd");
	vector<string> sections = MP.GetSectionList("MAP\\");
	for(int n=0; n<nd; n++){
    	char c[8];
    	//itoa(n,c,10);// something to do with ANSI standards and 64 bit compatability
		sprintf(c,"%i",n);
		float3 pos= UpVector;
    	MP.GetDef(pos.x, "-1", string("MAP\\TEAM") + string(c) + "\\StartPosX");
    	MP.GetDef(pos.z, "-1", string("MAP\\TEAM") + string(c) + "\\StartPosZ");
		if(G->Map->CheckFloat3(pos)==true){
			start_pos.push_back(pos);
			G->Actions->AddPoint(pos);
		}
    }
}
Example #2
0
// static
StatusWith<std::unique_ptr<CanonicalQuery>> CanonicalQuery::canonicalize(
    const CanonicalQuery& baseQuery,
    MatchExpression* root,
    const MatchExpressionParser::WhereCallback& whereCallback) {
    // TODO: we should be passing the filter corresponding to 'root' to the LPQ rather than the base
    // query's filter, baseQuery.getParsed().getFilter().
    BSONObj emptyObj;
    auto lpqStatus = LiteParsedQuery::makeAsOpQuery(baseQuery.nss(),
                                                    0,  // ntoskip
                                                    0,  // ntoreturn
                                                    0,  // queryOptions
                                                    baseQuery.getParsed().getFilter(),
                                                    baseQuery.getParsed().getProj(),
                                                    baseQuery.getParsed().getSort(),
                                                    emptyObj,  // hint
                                                    emptyObj,  // min
                                                    emptyObj,  // max
                                                    false,     // snapshot
                                                    baseQuery.getParsed().isExplain());
    if (!lpqStatus.isOK()) {
        return lpqStatus.getStatus();
    }

    // Make the CQ we'll hopefully return.
    std::unique_ptr<CanonicalQuery> cq(new CanonicalQuery());
    Status initStatus =
        cq->init(lpqStatus.getValue().release(), whereCallback, root->shallowClone().release());

    if (!initStatus.isOK()) {
        return initStatus;
    }
    return std::move(cq);
}
Example #3
0
// static
StatusWith<std::unique_ptr<CanonicalQuery>> CanonicalQuery::canonicalize(
    OperationContext* opCtx, const CanonicalQuery& baseQuery, MatchExpression* root) {
    auto qr = stdx::make_unique<QueryRequest>(baseQuery.nss());
    BSONObjBuilder builder;
    root->serialize(&builder);
    qr->setFilter(builder.obj());
    qr->setProj(baseQuery.getQueryRequest().getProj());
    qr->setSort(baseQuery.getQueryRequest().getSort());
    qr->setCollation(baseQuery.getQueryRequest().getCollation());
    qr->setExplain(baseQuery.getQueryRequest().isExplain());
    auto qrStatus = qr->validate();
    if (!qrStatus.isOK()) {
        return qrStatus;
    }

    std::unique_ptr<CollatorInterface> collator;
    if (baseQuery.getCollator()) {
        collator = baseQuery.getCollator()->clone();
    }

    // Make the CQ we'll hopefully return.
    std::unique_ptr<CanonicalQuery> cq(new CanonicalQuery());
    Status initStatus = cq->init(opCtx,
                                 std::move(qr),
                                 baseQuery.canHaveNoopMatchNodes(),
                                 root->shallowClone(),
                                 std::move(collator));

    if (!initStatus.isOK()) {
        return initStatus;
    }
    return std::move(cq);
}
Example #4
0
texture_2d color_quantization(const texture_2d& img,
                              int nbins,
                              float phi_q,
                              int filter)
{
    texture_2d dst(img.clone_format());
    texture_2d tmp(img.clone_format());

    glsl_program cq("color_quantization_fs.glsl");
    cq.use();
    cq.bind_sampler("img", img);
    cq.set_uniform_1i("nbins", nbins);
    cq.set_uniform_1f("phi_q", phi_q);
    cq.set_uniform_2f("img_size", (float)dst.get_width(), (float)dst.get_height());
    cq.draw(&tmp);

    if (filter) {
        glsl_program gauss((filter == 1)? "gauss3x3_fs.glsl" : "gauss5x5_fs.glsl");
        gauss.use();
        gauss.bind_sampler("img", tmp);
        gauss.set_uniform_2f("img_size", (float)dst.get_width(), (float)dst.get_height());
        gauss.draw(&dst);                  
    } else {
        dst = tmp;
    }

    return dst;
}
Example #5
0
TEST(CircularQueue, QUEUE_MAINTAINS_CORRECT_ORDER_EVEN_WITH_LOTS_OF_DATA) {
    CircularQueue<int> cq(5);
    for(int i = 0; i < 10; i++){
        cq.push(i);
    }
    return cq.front() == 5 && cq.back() == 9;
}
        void run() {
            OldClientWriteContext ctx(&_txn, ns());
            addIndex(BSON("a" << "2d" << "b" << 1));
            addIndex(BSON("a" << "2d"));

            BSONObj query = fromjson("{$or: [{a: {$geoWithin: {$centerSphere: [[0,0],10]}}},"
                                            "{a: {$geoWithin: {$centerSphere: [[1,1],10]}}}]}");

            CanonicalQuery* rawCq;
            ASSERT_OK(CanonicalQuery::canonicalize(ns(), query, &rawCq));
            boost::scoped_ptr<CanonicalQuery> cq(rawCq);

            Collection* collection = ctx.getCollection();

            // Get planner params.
            QueryPlannerParams plannerParams;
            fillOutPlannerParams(&_txn, collection, cq.get(), &plannerParams);

            WorkingSet ws;
            boost::scoped_ptr<SubplanStage> subplan(new SubplanStage(&_txn, collection, &ws,
                                                                     plannerParams, cq.get()));

            // Plan selection should succeed due to falling back on regular planning.
            PlanYieldPolicy yieldPolicy(NULL, PlanExecutor::YIELD_MANUAL);
            ASSERT_OK(subplan->pickBestPlan(&yieldPolicy));
        }
Example #7
0
// static
StatusWith<std::unique_ptr<CanonicalQuery>> CanonicalQuery::canonicalize(
    OperationContext* opCtx,
    const CanonicalQuery& baseQuery,
    MatchExpression* root,
    const ExtensionsCallback& extensionsCallback) {
    // TODO: we should be passing the filter corresponding to 'root' to the QR rather than the base
    // query's filter, baseQuery.getQueryRequest().getFilter().
    auto qr = stdx::make_unique<QueryRequest>(baseQuery.nss());
    qr->setFilter(baseQuery.getQueryRequest().getFilter());
    qr->setProj(baseQuery.getQueryRequest().getProj());
    qr->setSort(baseQuery.getQueryRequest().getSort());
    qr->setCollation(baseQuery.getQueryRequest().getCollation());
    qr->setExplain(baseQuery.getQueryRequest().isExplain());
    auto qrStatus = qr->validate();
    if (!qrStatus.isOK()) {
        return qrStatus;
    }

    std::unique_ptr<CollatorInterface> collator;
    if (baseQuery.getCollator()) {
        collator = baseQuery.getCollator()->clone();
    }

    // Make the CQ we'll hopefully return.
    std::unique_ptr<CanonicalQuery> cq(new CanonicalQuery());
    Status initStatus = cq->init(
        std::move(qr), extensionsCallback, root->shallowClone().release(), std::move(collator));

    if (!initStatus.isOK()) {
        return initStatus;
    }
    return std::move(cq);
}
Example #8
0
    // static
    Status CanonicalQuery::canonicalize(const CanonicalQuery& baseQuery,
                                        MatchExpression* root,
                                        CanonicalQuery** out,
                                        const MatchExpressionParser::WhereCallback& whereCallback) {

        LiteParsedQuery* lpq;

        // Pass empty sort and projection.
        BSONObj emptyObj;
        // 0, 0, 0 is 'ntoskip', 'ntoreturn', and 'queryoptions'
        // false, false is 'snapshot' and 'explain'
        Status parseStatus = LiteParsedQuery::make(baseQuery.ns(),
                                                   0, 0, 0,
                                                   baseQuery.getParsed().getFilter(),
                                                   baseQuery.getParsed().getProj(),
                                                   baseQuery.getParsed().getSort(),
                                                   emptyObj, emptyObj, emptyObj,
                                                   false, false, &lpq);
        if (!parseStatus.isOK()) {
            return parseStatus;
        }

        // Make the CQ we'll hopefully return.
        std::auto_ptr<CanonicalQuery> cq(new CanonicalQuery());
        Status initStatus = cq->init(lpq, whereCallback, root->shallowClone());

        if (!initStatus.isOK()) { return initStatus; }
        *out = cq.release();
        return Status::OK();
    }
Example #9
0
    Status FindCmd::explain(OperationContext* txn,
                             const std::string& dbname,
                             const BSONObj& cmdObj,
                             ExplainCommon::Verbosity verbosity,
                             BSONObjBuilder* out) const {
        const string fullns = parseNs(dbname, cmdObj);

        // Parse the command BSON to a LiteParsedQuery.
        LiteParsedQuery* rawLpq;
        bool isExplain = true;
        Status lpqStatus = LiteParsedQuery::make(fullns, cmdObj, isExplain, &rawLpq);
        if (!lpqStatus.isOK()) {
            return lpqStatus;
        }
        auto_ptr<LiteParsedQuery> lpq(rawLpq);

        const NamespaceString nss(fullns);

        // Finish the parsing step by using the LiteParsedQuery to create a CanonicalQuery.
        // This requires a lock on the collection in case we're parsing $where: where-specific
        // parsing code assumes we have a lock and creates execution machinery that requires it.
        CanonicalQuery* rawCq;
        WhereCallbackReal whereCallback(txn, nss.db());
        Status canonStatus = CanonicalQuery::canonicalize(lpq.release(), &rawCq, whereCallback);
        if (!canonStatus.isOK()) {
            return canonStatus;
        }
        auto_ptr<CanonicalQuery> cq(rawCq);

        AutoGetCollectionForRead ctx(txn, nss);
        // The collection may be NULL. If so, getExecutor() should handle it by returning
        // an execution tree with an EOFStage.
        Collection* collection = ctx.getCollection();

        // We have a parsed query. Time to get the execution plan for it.
        PlanExecutor* rawExec;
        Status execStatus = Status::OK();
        if (cq->getParsed().getOptions().oplogReplay) {
            execStatus = getOplogStartHack(txn, collection, cq.release(), &rawExec);
        }
        else {
            size_t options = QueryPlannerParams::DEFAULT;
            if (shardingState.needCollectionMetadata(cq->getParsed().ns())) {
                options |= QueryPlannerParams::INCLUDE_SHARD_FILTER;
            }

            execStatus = getExecutor(txn, collection, cq.release(), &rawExec, options);
        }

        if (!execStatus.isOK()) {
            return execStatus;
        }

        scoped_ptr<PlanExecutor> exec(rawExec);
        exec->setYieldPolicy(PlanExecutor::YIELD_AUTO);

        // Got the execution tree. Explain it.
        return Explain::explainStages(exec.get(), verbosity, out);
    }
void RTreeAssemblyAdapter::addReads(U2DbiIterator<U2AssemblyRead>* it, U2AssemblyReadsImportInfo& ii, U2OpStatus& os) {
    static QString q1 = "INSERT INTO %1(name, flags, mq, data) VALUES (?1, ?2, ?3, ?4)";
    static QString q2 = "INSERT INTO %1(id, gstart, gend, prow1, prow2) VALUES (?1, ?2, ?3, ?4, ?5)";

    SQLiteTransaction t(db, os);
    SQLiteWriteQuery insertRQ(q1.arg(readsTable), db, os);
    SQLiteWriteQuery insertIQ(q2.arg(indexTable), db, os);

    while (it->hasNext()) {
        U2AssemblyRead read = it->next();

        bool dnaExt = false; //TODO
        qint64 flags = read->flags;
        flags = flags | (dnaExt ? DnaExtAlphabet : 0);

        int readLen = read->readSequence.length();
        int effectiveReadLength = readLen + U2AssemblyUtils::getCigarExtraLength(read->cigar);
        read->effectiveLen = effectiveReadLength;

        int hash = qHash(read->name);
        insertRQ.reset();
        insertRQ.bindInt64(1, hash);
        insertRQ.bindInt64(2, flags);
        insertRQ.bindInt32(3, read->mappingQuality);
        QByteArray packedData = SQLiteAssemblyUtils::packData(SQLiteAssemblyDataMethod_NSCQ, read, os);
        insertRQ.bindBlob(4, packedData, false);

        insertRQ.insert();

        if (os.hasError()) {
            break;
        }
        insertIQ.reset();
        insertIQ.bindDataId(1, read->id);
        insertIQ.bindInt64(2, read->leftmostPos);
        insertIQ.bindInt64(3, read->leftmostPos + read->effectiveLen);
        insertIQ.bindInt64(4, read->packedViewRow);
        insertIQ.bindInt64(5, read->packedViewRow);

        insertIQ.execute();

        SQLiteAssemblyUtils::addToCoverage(ii.coverageInfo, read);

        ii.nReads++;

//#define U2_SQLITE_CHECK_RTREE_
#ifdef U2_SQLITE_CHECK_RTREE_
// Consistency check. To be removed after all known rtree issues are resolved
        qint64 dbId = U2DbiUtils::toDbiId(read->id);
        SQLiteQuery cq("SELECT gstart, gend FROM " + indexTable + " WHERE id = " + QString::number(dbId), db, os);
        cq.step();
        qint64 cstart =  cq.getInt64(0);
        qint64 cend =  cq.getInt64(1);
        assert(cstart == read->leftmostPos);
        assert(cend == read->leftmostPos + read->effectiveLen);
#endif
    }
}
Example #11
0
 Status UpdateDriver::populateDocumentWithQueryFields(const BSONObj& query,
                                                      mutablebson::Document& doc) const {
     CanonicalQuery* rawCG;
     // We canonicalize the query to collapse $and/$or, and the first arg (ns) is not needed
     Status s = CanonicalQuery::canonicalize("", query, &rawCG);
     if (!s.isOK())
         return s;
     scoped_ptr<CanonicalQuery> cq(rawCG);
     return populateDocumentWithQueryFields(rawCG, doc);
 }
Example #12
0
    void run() {
        // Run the update.
        {
            Client::WriteContext ctx(&_txn, ns());
            Client& c = cc();
            CurOp& curOp = *c.curop();
            OpDebug* opDebug = &curOp.debug();
            UpdateDriver driver( (UpdateDriver::Options()) );
            Database* db = ctx.ctx().db();

            // Collection should be empty.
            ASSERT_EQUALS(0U, count(BSONObj()));

            UpdateRequest request(&_txn, nsString());
            UpdateLifecycleImpl updateLifecycle(false, nsString());
            request.setLifecycle(&updateLifecycle);

            // Update is the upsert {_id: 0, x: 1}, {$set: {y: 2}}.
            BSONObj query = fromjson("{_id: 0, x: 1}");
            BSONObj updates = fromjson("{$set: {y: 2}}");

            request.setUpsert();
            request.setQuery(query);
            request.setUpdates(updates);

            ASSERT_OK(driver.parse(request.getUpdates(), request.isMulti()));

            // Setup update params.
            UpdateStageParams params(&request, &driver, opDebug);
            scoped_ptr<CanonicalQuery> cq(canonicalize(query));
            params.canonicalQuery = cq.get();

            scoped_ptr<WorkingSet> ws(new WorkingSet());
            auto_ptr<EOFStage> eofStage(new EOFStage());

            scoped_ptr<UpdateStage> updateStage(
                new UpdateStage(params, ws.get(), db, eofStage.release()));

            runUpdate(updateStage.get());
            ctx.commit();
        }

        // Verify the contents of the resulting collection.
        {
            Client::ReadContext ctx(&_txn, ns());
            Collection* collection = ctx.ctx().db()->getCollection(&_txn, ns());

            vector<BSONObj> objs;
            getCollContents(collection, &objs);

            // Expect a single document, {_id: 0, x: 1, y: 2}.
            ASSERT_EQUALS(1U, objs.size());
            ASSERT_EQUALS(objs[0], fromjson("{_id: 0, x: 1, y: 2}"));
        }
    }
Example #13
0
void TfrmRetrieveMain::createBoxes( const LCDbCryoJob & job, const LPDbBoxType & boxType ) {
	struct Box {
		LPDbBoxName record;
		std::set<int> projects;
	} current;
	std::map<short,Box> boxes;
	short size = boxType.getCapacity();
	if( size < 1 ) {
		size = 100;		// assume MVE boxes
	}
	// work out which projects each box belong to
	progress->Position = 0;
	for( const GridEntry & ge : rows ) {
		short boxNumber = (ge.new_pos-1) / size;
		boxes[ boxNumber ].projects.insert( ge.pid );
	}
	for( auto & entry : boxes ) {
		const std::set<int> & projList = entry.second.projects;
		int projID = projList.size() == 1 ? *projList.begin() : 0;
		entry.second.record.setProjectCID( projID );
	}
	// create records in central and project databases
	LQuery cq( LIMSDatabase::getCentralDb( ) );
	for( auto & entry : boxes ) {
		const std::set<int> & projList = entry.second.projects;
		auto pi = projList.begin();
		LQuery pq1( LIMSDatabase::getProjectDb( *pi ) );
		LPDbBoxName & box = entry.second.record;
		if( !box.create( boxType, job.getBoxSet( ), pq1, cq ) ) {
			throw Exception( "Cannot create destination box" );
		}
		while( ++pi != projList.end() ) {
			LQuery pq( LIMSDatabase::getProjectDb( *pi ) );
			if( !box.saveRecord( pq, cq ) ) {
				throw Exception( "Cannot copy destination box" );
			}
		}
	}
	// mark the cryovials for removal into the new boxes
	progress->Max = rows.size( );
	StoreDAO dao;
	for( const GridEntry & ge : rows ) {
		short boxNumber = (ge.new_pos-1) / size;
		const LPDbBoxName & box = boxes[ boxNumber ].record;
		short position = ge.new_pos - (boxNumber * size);
		LQuery pq( LIMSDatabase::getProjectDb( ge.pid ) );
		if( dao.addToRetrieval( job.getID( ), ge.cid, ge.pid, box.getID(), position ) ) {
			progress->StepIt( );
		} else {
			throw Exception( "Cannot add cryovial(s)" );
		}
	}
}
/*! return rotational matrix made of quaternion */
inline dgemat3 q2m(const dquater& q)
{VERBOSE_REPORT;
  dquater cq( conj(q) );
  dquater X( dquater(+q(3),+q(2),-q(1),-q(0))*cq );
  dquater Y( dquater(-q(2),+q(3),+q(0),-q(1))*cq );
  dquater Z( dquater(+q(1),-q(0),+q(3),-q(2))*cq );
  dgemat3 mat;
  mat(0,0)=X(0); mat(0,1)=Y(0); mat(0,2)=Z(0);
  mat(1,0)=X(1); mat(1,1)=Y(1); mat(1,2)=Z(1);
  mat(2,0)=X(2); mat(2,1)=Y(2); mat(2,2)=Z(2);
  return mat;
}
Example #15
0
 Status UpdateDriver::populateDocumentWithQueryFields(const BSONObj& query,
                                                      mutablebson::Document& doc) const {
     CanonicalQuery* rawCG;
     // We canonicalize the query to collapse $and/$or, and the first arg (ns) is not needed
     // Also, because this is for the upsert case, where we insert a new document if one was
     // not found, the $where clause does not make sense, hence empty WhereCallback.
     Status s = CanonicalQuery::canonicalize("", query, &rawCG, WhereCallbackNoop());
     if (!s.isOK())
         return s;
     scoped_ptr<CanonicalQuery> cq(rawCG);
     return populateDocumentWithQueryFields(rawCG, doc);
 }
Example #16
0
    // static
    Status CanonicalQuery::canonicalize(const QueryMessage& qm, CanonicalQuery** out) {
        LiteParsedQuery* lpq;
        Status parseStatus = LiteParsedQuery::make(qm, &lpq);
        if (!parseStatus.isOK()) { return parseStatus; }

        auto_ptr<CanonicalQuery> cq(new CanonicalQuery());
        Status initStatus = cq->init(lpq);
        if (!initStatus.isOK()) { return initStatus; }

        *out = cq.release();
        return Status::OK();
    }
Example #17
0
// static
StatusWith<std::unique_ptr<CanonicalQuery>> CanonicalQuery::canonicalize(
    const std::string& ns,
    const BSONObj& query,
    const BSONObj& sort,
    const BSONObj& proj,
    long long skip,
    long long limit,
    const BSONObj& hint,
    const BSONObj& minObj,
    const BSONObj& maxObj,
    bool snapshot,
    bool explain,
    const MatchExpressionParser::WhereCallback& whereCallback) {
    // Pass empty sort and projection.
    BSONObj emptyObj;

    auto lpqStatus = LiteParsedQuery::makeAsOpQuery(NamespaceString(ns),
                                                    skip,
                                                    limit,
                                                    0,
                                                    query,
                                                    proj,
                                                    sort,
                                                    hint,
                                                    minObj,
                                                    maxObj,
                                                    snapshot,
                                                    explain);
    if (!lpqStatus.isOK()) {
        return lpqStatus.getStatus();
    }

    auto& lpq = lpqStatus.getValue();

    // Build a parse tree from the BSONObj in the parsed query.
    StatusWithMatchExpression statusWithMatcher =
        MatchExpressionParser::parse(lpq->getFilter(), whereCallback);
    if (!statusWithMatcher.isOK()) {
        return statusWithMatcher.getStatus();
    }
    std::unique_ptr<MatchExpression> me = std::move(statusWithMatcher.getValue());

    // Make the CQ we'll hopefully return.
    std::unique_ptr<CanonicalQuery> cq(new CanonicalQuery());
    Status initStatus = cq->init(lpq.release(), whereCallback, me.release());

    if (!initStatus.isOK()) {
        return initStatus;
    }
    return std::move(cq);
}
Example #18
0
// static
StatusWith<std::unique_ptr<CanonicalQuery>> CanonicalQuery::canonicalize(
    OperationContext* opCtx,
    std::unique_ptr<QueryRequest> qr,
    const boost::intrusive_ptr<ExpressionContext>& expCtx,
    const ExtensionsCallback& extensionsCallback,
    MatchExpressionParser::AllowedFeatureSet allowedFeatures) {
    auto qrStatus = qr->validate();
    if (!qrStatus.isOK()) {
        return qrStatus;
    }

    std::unique_ptr<CollatorInterface> collator;
    if (!qr->getCollation().isEmpty()) {
        auto statusWithCollator = CollatorFactoryInterface::get(opCtx->getServiceContext())
                                      ->makeFromBSON(qr->getCollation());
        if (!statusWithCollator.isOK()) {
            return statusWithCollator.getStatus();
        }
        collator = std::move(statusWithCollator.getValue());
    }

    // Make MatchExpression.
    boost::intrusive_ptr<ExpressionContext> newExpCtx;
    if (!expCtx.get()) {
        newExpCtx.reset(new ExpressionContext(opCtx, collator.get()));
    } else {
        newExpCtx = expCtx;
        invariant(CollatorInterface::collatorsMatch(collator.get(), expCtx->getCollator()));
    }
    StatusWithMatchExpression statusWithMatcher = MatchExpressionParser::parse(
        qr->getFilter(), newExpCtx, extensionsCallback, allowedFeatures);
    if (!statusWithMatcher.isOK()) {
        return statusWithMatcher.getStatus();
    }
    std::unique_ptr<MatchExpression> me = std::move(statusWithMatcher.getValue());

    // Make the CQ we'll hopefully return.
    std::unique_ptr<CanonicalQuery> cq(new CanonicalQuery());

    Status initStatus =
        cq->init(opCtx,
                 std::move(qr),
                 parsingCanProduceNoopMatchNodes(extensionsCallback, allowedFeatures),
                 std::move(me),
                 std::move(collator));

    if (!initStatus.isOK()) {
        return initStatus;
    }
    return std::move(cq);
}
Example #19
0
TEST_F(FSMCallerTest, sanity) {
    system("rm -rf ./data");
    scoped_ptr<braft::ConfigurationManager> cm(
                                new braft::ConfigurationManager);
    scoped_ptr<braft::SegmentLogStorage> storage(
                                new braft::SegmentLogStorage("./data"));
    scoped_ptr<braft::LogManager> lm(new braft::LogManager());
    braft::LogManagerOptions log_opt;
    log_opt.log_storage = storage.get();
    log_opt.configuration_manager = cm.get();
    ASSERT_EQ(0, lm->init(log_opt));

    braft::ClosureQueue cq(false);

    OrderedStateMachine fsm;
    fsm._expected_next = 0;

    braft::FSMCallerOptions opt;
    opt.log_manager = lm.get();
    opt.after_shutdown = NULL;
    opt.fsm = &fsm;
    opt.closure_queue = &cq;

    braft::FSMCaller caller;
    ASSERT_EQ(0, caller.init(opt));

    const size_t N = 1000;

    for (size_t i = 0; i < N; ++i) {
        std::vector<braft::LogEntry*> entries;
        braft::LogEntry* entry = new braft::LogEntry;
        entry->AddRef();
        entry->type = braft::ENTRY_TYPE_DATA;
        std::string buf;
        butil::string_printf(&buf, "hello_%lu", i);
        entry->data.append(buf);
        entry->id.index = i + 1;
        entry->id.term = i;
        entries.push_back(entry);
        SyncClosure c;
        lm->append_entries(&entries, &c);
        c.join();
        ASSERT_TRUE(c.status().ok()) << c.status();
    }
    ASSERT_EQ(0, caller.on_committed(N));
    ASSERT_EQ(0, caller.shutdown());
    fsm.join();
    ASSERT_EQ(fsm._expected_next, N);
}
Example #20
0
    // static
    Status CanonicalQuery::canonicalize(const string& ns, const BSONObj& query,
                                        CanonicalQuery** out) {
        LiteParsedQuery* lpq;
        // Pass empty sort and projection.
        BSONObj emptyObj;
        Status parseStatus = LiteParsedQuery::make(ns, 0, 0, 0, query, emptyObj, emptyObj, &lpq);
        if (!parseStatus.isOK()) { return parseStatus; }

        auto_ptr<CanonicalQuery> cq(new CanonicalQuery());
        Status initStatus = cq->init(lpq);
        if (!initStatus.isOK()) { return initStatus; }

        *out = cq.release();
        return Status::OK();
    }
Example #21
0
LPDbBoxType * TfrmRetrieveMain::getBoxType( ) {
	std::set < int > aliquots, boxes, projects, tubes;
	for( const GridEntry & ge : rows ) {
		aliquots.insert( ge.aid );
		boxes.insert( ge.bid );
		projects.insert( ge.pid );
	}
	if( aliquots.size( ) > 3 ) {
		throw Exception( "Cannot include more than three aliquot types" );
	}

	LQuery cq( LIMSDatabase::getCentralDb( ) );
	LPDbBoxNames boxList;
	for( int boxID : boxes ) {
		const LPDbBoxName * box = boxList.readRecord( cq, boxID );
		int tubeSizeID = 0;
		if( box != NULL ) {
			const LCDbBoxSize * size = box->getLayout( );
			if( size != NULL ) {
				tubeSizeID = size->getTubeType( );
			}
		}
		tubes.insert( tubeSizeID );
	}
	if( tubes.size( ) != 1 || tubes.count( 0 ) == 1 ) {
		throw Exception( "Tubes must all be the same size" );
	}

	LPDbBoxType *boxType = NULL;
	frmNewBoxType->init( aliquots, *tubes.begin( ) );
	if( frmNewBoxType->ShowModal( ) == mrOk ) {
		boxType = frmNewBoxType->getDetails( );
	}
	if( boxType != NULL ) {
		if( projects.size( ) > 1 ) {
			boxType->setProjectCID( 0 );
		} else if( boxType->getID( ) == 0 ) {
			boxType->setProjectCID( *projects.begin( ) );
		}
		for( int projID : projects ) {
			LQuery pq( LIMSDatabase::getProjectDb( projID ) );
			if( !boxType->saveRecord( pq, cq ) ) {
				throw Exception( "Cannot create selected box type" );
			}
		}
	}
	return boxType;
}
Example #22
0
TEST(CircularQueue, SIZE_ALWAYS_CORRECT_FOR_GIVEN_DATA) {
    CircularQueue<int> cq(5);
    
    bool condition = false;
    cq.push(1); cq.push(1);
    
    condition = cq.size() == 2;
    
    for(int i = 0; i < 10; i++){
        cq.push(i);
    }
    
    condition = condition && cq.size() == 5;
    
    return condition;
}
Example #23
0
    Status CanonicalQuery::canonicalize(const string& ns, const BSONObj& query,
                                        CanonicalQuery** out) {
        auto_ptr<CanonicalQuery> cq(new CanonicalQuery());

        LiteParsedQuery* lpq;
        Status parseStatus = LiteParsedQuery::make(ns, 0, 0, 0, query, &lpq);
        if (!parseStatus.isOK()) { return parseStatus; }
        cq->_pq.reset(lpq);

        StatusWithMatchExpression swme = MatchExpressionParser::parse(cq->_pq->getFilter());
        if (!swme.isOK()) { return swme.getStatus(); }

        cq->_root.reset(swme.getValue());
        *out = cq.release();
        return Status::OK();
    }
Example #24
0
//计算可行组合数
void cq(int i)
{
	for(int j=1; j <= N; j++)
		if(bSafe(i, j))
		{
			flag[i]=j;
			if (i < N)
				cq(1+i);
			else
			{	
				count++;
				printboard();
				break;
			}
		}
}
Example #25
0
    // static
    Status CanonicalQuery::canonicalize(const QueryMessage& qm, CanonicalQuery** out) {
        auto_ptr<CanonicalQuery> cq(new CanonicalQuery());

        // Parse the query.
        LiteParsedQuery* lpq;
        Status parseStatus = LiteParsedQuery::make(qm, &lpq);
        if (!parseStatus.isOK()) { return parseStatus; }
        cq->_pq.reset(lpq);

        // Build a parse tree from the BSONObj in the parsed query.
        StatusWithMatchExpression swme = MatchExpressionParser::parse(cq->_pq->getFilter());
        if (!swme.isOK()) { return swme.getStatus(); }

        cq->_root.reset(swme.getValue());
        *out = cq.release();
        return Status::OK();
    }
        void run() {
            OldClientWriteContext ctx(&_txn, ns());

            addIndex(BSON("a" << 1 << "b" << 1));
            addIndex(BSON("a" << 1 << "c" << 1));

            for (int i = 0; i < 10; i++) {
                insert(BSON("a" << 1 << "b" << i << "c" << i));
            }

            // This query should result in a plan cache entry for the first branch. The second
            // branch should tie, meaning that nothing is inserted into the plan cache.
            BSONObj query = fromjson("{$or: [{a: 1, b: 3}, {a: 1}]}");

            Collection* collection = ctx.getCollection();

            CanonicalQuery* rawCq;
            ASSERT_OK(CanonicalQuery::canonicalize(ns(), query, &rawCq));
            boost::scoped_ptr<CanonicalQuery> cq(rawCq);

            // Get planner params.
            QueryPlannerParams plannerParams;
            fillOutPlannerParams(&_txn, collection, cq.get(), &plannerParams);

            WorkingSet ws;
            boost::scoped_ptr<SubplanStage> subplan(new SubplanStage(&_txn, collection, &ws,
                                                                     plannerParams, cq.get()));

            PlanYieldPolicy yieldPolicy(NULL, PlanExecutor::YIELD_MANUAL);
            ASSERT_OK(subplan->pickBestPlan(&yieldPolicy));

            // Nothing is in the cache yet, so neither branch should have been planned from
            // the plan cache.
            ASSERT_FALSE(subplan->branchPlannedFromCache(0));
            ASSERT_FALSE(subplan->branchPlannedFromCache(1));

            // If we repeat the same query, then the first branch should come from the cache,
            // but the second is re-planned due to tying on the first run.
            ws.clear();
            subplan.reset(new SubplanStage(&_txn, collection, &ws, plannerParams, cq.get()));

            ASSERT_OK(subplan->pickBestPlan(&yieldPolicy));

            ASSERT_TRUE(subplan->branchPlannedFromCache(0));
            ASSERT_FALSE(subplan->branchPlannedFromCache(1));
        }
Example #27
0
TEST_F(FSMCallerTest, on_leader_start_and_stop) {
    scoped_ptr<braft::LogManager> lm(new braft::LogManager());
    OrderedStateMachine fsm;
    fsm._expected_next = 0;
    braft::ClosureQueue cq(false);
    braft::FSMCallerOptions opt;
    opt.log_manager = lm.get();
    opt.after_shutdown = NULL;
    opt.fsm = &fsm;
    opt.closure_queue = &cq;
    braft::FSMCaller caller;
    ASSERT_EQ(0, caller.init(opt));
    butil::Status status;
    caller.on_leader_stop(status);
    caller.shutdown();
    fsm.join();
    ASSERT_EQ(0, fsm._on_leader_start_times);
    ASSERT_EQ(1, fsm._on_leader_stop_times);
}
/**
@brief		print a REQ_ACK

Prints a snapshot of the status of the @b @@dev circular queue when AP sends or
receives an REQ_ACK.

@param mld	the pointer to a mem_link_device instance
@param mst	the pointer to a mem_snapshot instance
@param dev	the pointer to a mem_ipc_device instance (IPC_FMT, etc.)
@param dir	the direction of communication (TX or RX)
*/
void print_req_ack(struct mem_link_device *mld, struct mem_snapshot *mst,
		   struct mem_ipc_device *dev, enum direction dir)
{
#ifdef DEBUG_MODEM_IF_FLOW_CTRL
	struct link_device *ld = &mld->link_dev;
	struct modem_ctl *mc = ld->mc;
	enum dev_format id = dev->id;
	unsigned int qsize = get_size(cq(dev, dir));
	unsigned int in = mst->head[id][dir];
	unsigned int out = mst->tail[id][dir];
	unsigned int usage = circ_get_usage(qsize, in, out);
	unsigned int space = circ_get_space(qsize, in, out);

	mif_info("REQ_ACK: %s%s%s: %s_%s.%d "
		"{in:%u out:%u usage:%u space:%u}\n",
		ld->name, arrow(dir), mc->name, dev->name, q_dir(dir),
		dev->req_ack_cnt[dir], in, out, usage, space);
#endif
}
Example #29
0
    // static
    Status CanonicalQuery::canonicalize(const string& ns, const BSONObj& query,
                                        const BSONObj& sort, const BSONObj& proj,
                                        long long skip, long long limit,
                                        const BSONObj& hint,
                                        const BSONObj& minObj, const BSONObj& maxObj,
                                        bool snapshot, CanonicalQuery** out) {
        LiteParsedQuery* lpq;
        // Pass empty sort and projection.
        BSONObj emptyObj;
        Status parseStatus = LiteParsedQuery::make(ns, skip, limit, 0, query, proj, sort,
                                                   hint, minObj, maxObj, snapshot, &lpq);
        if (!parseStatus.isOK()) { return parseStatus; }

        auto_ptr<CanonicalQuery> cq(new CanonicalQuery());
        Status initStatus = cq->init(lpq);
        if (!initStatus.isOK()) { return initStatus; }

        *out = cq.release();
        return Status::OK();
    }
Example #30
0
    // static
    Status CanonicalQuery::canonicalize(LiteParsedQuery* lpq,
                                        CanonicalQuery** out,
                                        const MatchExpressionParser::WhereCallback& whereCallback) {
        std::auto_ptr<LiteParsedQuery> autoLpq(lpq);

        // Make MatchExpression.
        StatusWithMatchExpression swme = MatchExpressionParser::parse(autoLpq->getFilter(),
                                                                      whereCallback);
        if (!swme.isOK()) {
            return swme.getStatus();
        }

        // Make the CQ we'll hopefully return.
        std::auto_ptr<CanonicalQuery> cq(new CanonicalQuery());
        // Takes ownership of lpq and the MatchExpression* in swme.
        Status initStatus = cq->init(autoLpq.release(), whereCallback, swme.getValue());

        if (!initStatus.isOK()) { return initStatus; }
        *out = cq.release();
        return Status::OK();
    }