コード例 #1
0
bool KinematicIntegerBands::cd_future_traj(Detection3D* det, double B, double T, bool trajdir, double t,
    const TrafficState& ownship, const TrafficState& ac) const {
  if (t > T || B > T) return false;
  std::pair<Vect3,Velocity> sovot = trajectory(ownship,t,trajdir);
  Vect3 sot = sovot.first;
  Velocity vot = sovot.second;
  Vect3 si = ac.get_s();
  Velocity vi = ac.get_v();
  Vect3 sit = vi.ScalAdd(t,si);
  if (B > t) {
    return conflict(det, sot, vot, sit, vi, B-t, T-t);
  }
  return conflict(det, sot, vot, sit, vi, 0, T-t);
}
コード例 #2
0
ファイル: grequal.c プロジェクト: Distrotech/icmake
ESTRUC_ *gr_equal (ESTRUC_ *lval, ESTRUC_ *rval)
{
    btoi(lval);                             /* convert boolean to i */
    btoi(rval);

    if (conflict(lval, rval, op_greq))      /* test type conflict */
        return(lval);

    if ((lval->type & rval->type & (size_t)~ALLTYPES) == e_const)
    {
        if (test_type(lval, e_int))
            lval->evalue = (lval->evalue >= rval->evalue);
        else
        {
            lval->evalue =
                      (
                        strcmp
                        (
                            stringtab[lval->evalue].string,
                            stringtab[rval->evalue].string
                        )
                      ) >= 0;
            set_type(lval, e_int | e_const);
        }
    }
    else
        defcode(lval, rval, op_greq);

    return (lval);                          /* return new expression */
}
コード例 #3
0
// Pre-condition: perm stores a permutation of queens from index 0 to location-1
//                that is valid for a set of location number of non-conflicting
//                queens. location represents the column we are placing the next
//                queen, and usedList keeps track of the rows in which queens
//                have already been placed.
void solveItRec(int perm[], int location, int usedList[]) {

    int i;

    // We've found a solution to the problem, so print it!
    if (location == SIZE) {
        printSol(perm);
    }

    // Loop through possible locations for the next queen to place.
    for (i=0; i<SIZE; i++) {
        // Only try this row if it hasn't already been used.
        if (usedList[i] == 0) {
            // We can actually place this particular queen without conflict!
            if (!conflict(perm, location, i)) {
                // Place the new queen!
                perm[location] = i;
                // We've used this row now, so mark that.
                usedList[i] = 1;
                // Recursively solve this board.
                solveItRec(perm, location+1, usedList);
                // Unselect this square, so that we can continue trying to
                // fill it with the next possible choice.
                usedList[i] = 0;
            }
        }
    }
}
コード例 #4
0
ファイル: locks.c プロジェクト: Lakshmipathi/Linux-historic
int fcntl_getlk(unsigned int fd, struct flock *l)
{
	int error;
	struct flock flock;
	struct file *filp;
	struct file_lock *fl,file_lock;

	if (fd >= NR_OPEN || !(filp = current->files->fd[fd]))
		return -EBADF;
	error = verify_area(VERIFY_WRITE,l, sizeof(*l));
	if (error)
		return error;
	memcpy_fromfs(&flock, l, sizeof(flock));
	if (flock.l_type == F_UNLCK)
		return -EINVAL;
	if (!copy_flock(filp, &file_lock, &flock, fd))
		return -EINVAL;

	for (fl = filp->f_inode->i_flock; fl != NULL; fl = fl->fl_next) {
		if (conflict(&file_lock, fl)) {
			flock.l_pid = fl->fl_owner->pid;
			flock.l_start = fl->fl_start;
			flock.l_len = fl->fl_end == OFFSET_MAX ? 0 :
				fl->fl_end - fl->fl_start + 1;
			flock.l_whence = fl->fl_whence;
			flock.l_type = fl->fl_type;
			memcpy_tofs(l, &flock, sizeof(flock));
			return 0;
		}
	}

	flock.l_type = F_UNLCK;			/* no conflict found */
	memcpy_tofs(l, &flock, sizeof(flock));
	return 0;
}
コード例 #5
0
ファイル: quiddiards.cpp プロジェクト: silencious/Quiddiards
void Quiddiards::initObjects(){
	ground = new Ground({ 0, 0, 0 }, MAXRANGE, WAVEHGT);
	//float desktop = table.getRugHgt();
	float desktop = WAVEHGT / 2;
	table.setCenter({ 0, 0, 0 });

	// init balls and stick
	cueball.setCenter({ 0, 0, desktop + cueball.getR() });
	balls.clear();
	balls.push_back(&cueball);

	float l = cuebroom.getStickLen();
	cuebroom.setAim(cueball.getCenter());
	cuebroom.setCenter(cueball.getCenter() + QVector3D({ l, l / 3, l / 3 }));

	float boundX = COURTRANGE - 1, boundY = COURTRANGE - 1;
	for (unsigned i = 0; i < QUAFNUM; i++){
		do{
			quaffles[i].setCenter({ randf(-boundX, boundX), randf(-boundY, boundY), desktop + quaffles[i].getR() });
		} while (conflict(quaffles[i]));
		balls.push_back(&quaffles[i]);
	}

	float sB = bludgers[0].getSpeed(), sS = snitch.getSpeed();
	for (unsigned i = 0; i < BLUGNUM; i++){
		do{
			bludgers[i].setCenter({ randf(-boundX, boundX), randf(-boundY, boundY), desktop + bludgers[i].getR() });
		} while (conflict(bludgers[i]));
		bludgers[i].setVelocity({ randf(-sB, sB), randf(-sB, sB), 0.0f });
		balls.push_back(&bludgers[i]);
	}
	do{
		snitch.setCenter({ randf(-boundX, boundX), randf(-boundY, boundY), desktop + snitch.getR() + 5.0f });
	} while (conflict(snitch));
	snitch.setVelocity({ randf(-sS, sS), randf(-sS, sS), 0 });
	balls.push_back(&snitch);

	// init flag
	wind = { 1.0f, 1.0f };
	flags[0] = Flag({ COURTRANGE, COURTRANGE, FLAGHGT }, Flag::GRYFFINDOR);
	flags[1] = Flag({ -COURTRANGE, COURTRANGE, FLAGHGT }, Flag::SLYTHERIN);
	flags[2] = Flag({ -COURTRANGE, -COURTRANGE, FLAGHGT }, Flag::RAVENCLAW);
	flags[3] = Flag({ COURTRANGE, -COURTRANGE, FLAGHGT }, Flag::HUFFLEPUFF);
}
コード例 #6
0
ファイル: collective_teams.cpp プロジェクト: miki151/keeperrl
void CollectiveTeams::setTeamOrder(TeamId id, const Creature* c, TeamOrder order, bool state) {
  CHECK(exists(id));
  if (state) {
    teamInfo.at(id).teamOrders.insert(order);
    for (auto order2 : ENUM_ALL(TeamOrder))
      if (order != order2 && conflict(order, order2))
        teamInfo.at(id).teamOrders.erase(order2);
  } else
    teamInfo.at(id).teamOrders.erase(order);
}
コード例 #7
0
ファイル: 11926.cpp プロジェクト: a5216652166/coding
int main(void){
	while(scanf("%d %d", &n, &m) == 2 && (m | n)){
		for(int i = 0; i < n; ++i) scanf("%d %d", l + i, r + i);
		for(int i = 0; i < m; ++i){
			scanf("%d %d %d", b + i, d + i, p + i);
			d[i] -= b[i];
		}
		puts("NO CONFLICT" + 3 * conflict());
	}
	return 0;
}
コード例 #8
0
int main (){
  Any a2 = Int(1);
  Any a3 = Int(2);
  Any a4 = Tuple( a2, a3);
  Any a8 = Int(1);
  Any a9 = Int(2);
  Any a6 = conflict ( a4, a8, a9 );
  Any a5 = a6;
  Any a13 = a5;
  println ( a13 );
  Any a16 = Int(3);
  Any a17 = Int(4);
  Any a14 = conflict ( a4, a16, a17 );
  a5 = a14;
  Any a21 = a5;
  println ( a21 );
  Any a24 = Int(1);
  Any a25 = Int(4);
  Any a22 = conflict ( a4, a24, a25 );
  a5 = a22;
  Any a29 = a5;
  println ( a29 );
  Any a32 = Int(3);
  Any a33 = Int(2);
  Any a30 = conflict ( a4, a32, a33 );
  a5 = a30;
  Any a37 = a5;
  println ( a37 );
  Any a40 = Int(3);
  Any a41 = Int(3);
  Any a38 = conflict ( a4, a40, a41 );
  a5 = a38;
  Any a45 = a5;
  println ( a45 );
  return 0;
}
コード例 #9
0
//Used to find the next new row and corresponding column that is 
//suitable for the arrangement and then return its new row index
//and the new suitable column which will be stored in stack;
int backtrack(int* stack, int top, int n)
{
    while(true)
    {
        while(top > -1 && stack[top]+1 == n) top--; // if the current row reached its final column, search for its previous row;
        if(top == -1) //if row index reaches its end, return -1;
            return top;
        int col = stack[top] + 1; // test next column for the suitable row;
        while(col < n) // test all the remained columns of the row until it's okay with the current arrangement, if not go back to select another row in the previous section;
        {
            stack[top] = col;
            if(conflict(stack, top-1, n, col))
                col++;
            else
                return top;
        }
    }
}
コード例 #10
0
ファイル: n_queens.c プロジェクト: Core055/leetcode
int totalNQueens(int n) {
    int row = 0, col = 0, sum = 0, cap = 1;
    int *stack = malloc(n * sizeof(int));
    for (row = 0; row < n; row++) {
        stack[row] = -1;
    }

    if (n == 1) {
        return 1;
    }

    for (; ;) {
        for (; row < n; row++) {
            while (col < n) {
                if (conflict(stack, row, col)) {
                    while (col == n - 1) {
                        /* No other positions in this row and therefore backtracking */
                        if (--row < 0) {
                            /* All solution provided */
                            free(stack);
                            return sum;
                        }
                        col = pop(stack, row);
                    }
                    col++;
                } else {
                    push(stack, row, col);
                    break;
                }
            }
            col = 0;
        }

        /* Full stack, a new complete solution */
        row = top(stack, n);
        if (row == n - 1) {
            sum++;
        }

        /* Move on to find if there are still other solutions */
        col = pop(stack, row);
        col++;
    }    
}
コード例 #11
0
ファイル: kpk.c プロジェクト: kervinck/pfkpk
int kpkSelfCheck(void)
{
        int counts[] = {                // As given by Steven J. Edwards (1996):
                163328 / 2, 168024 / 2, // - Legal positions per side
                124960 / 2, 97604  / 2  // - Non-draw positions per side
        };
        for (int ix=0; ix<arrayLen(kpkTable[0]); ix++) {
                int wKing = wKingSquare(ix), wPawn = wPawnSquare(ix);
                for (int bKing=0; bKing<boardSize; bKing++) {
                        if (!inPawnZone(wPawn) || conflict(wKing, wPawn, bKing))
                                continue;
                        counts[0] -= !bInCheck(wKing, wPawn, bKing);
                        counts[1] -= !wInCheck(wKing, wPawn, bKing);
                        counts[2] -= !bInCheck(wKing, wPawn, bKing) && ((kpkTable[white][ix] >> bKing) & 1);
                        counts[3] -= !wInCheck(wKing, wPawn, bKing) && ((kpkTable[black][ix] >> bKing) & 1);
                }
        }
        return !counts[0] && !counts[1] && !counts[2] && !counts[3];
}
コード例 #12
0
ファイル: fe_config.cpp プロジェクト: Cucurbitace/attract
bool FeScriptConfigMenu::on_option_select(
		FeConfigContext &ctx, FeBaseConfigMenu *& submenu )
{
	FeMenuOpt &o = ctx.curr_opt();

	if ( o.opaque == 1 )
	{
		std::string res;
		FeInputMap::Command conflict( FeInputMap::LAST_COMMAND );
		ctx.input_map_dialog( "Press Input", res, conflict );

		if (( conflict == FeInputMap::ExitMenu )
			|| ( conflict == FeInputMap::ExitNoMenu ))
		{
			// Clear the mapping if the user pushed an exit button
			res.clear();
		}

		o.set_value( res );
		ctx.save_req = true;
	}
	else if (( o.opaque == 2 ) && ( m_configurable ))
	{
		save( ctx );

		ctx.fe_settings.set_present_state( m_state );
		FePresent *fep = FePresent::script_get_fep();
		if ( fep )
			fep->set_script_id( m_script_id );

		FeVM::script_run_config_function(
				*m_configurable,
				m_file_path,
				m_file_name,
				o.opaque_str,
				ctx.help_msg );
	}
	return true;
}
コード例 #13
0
ファイル: main.cpp プロジェクト: zJoyceLee/DataStructure
TEST(Hash, testConstruct) {
    std::vector<std::pair<int, bool>> myvec;
    for(std::size_t i = 0; i < 11; ++i) {
        myvec.push_back({0, false});
    }; // initialization
    std::vector<int> mykeys = {22,41,53,46,30,13,1,67};

    double countFindPosition = double(mykeys.size()); // ASL

    for(std::size_t index = 0; index < mykeys.size(); ++index) {
        int key = mykeys[index]; // index is increasing
        std::size_t position = myHash(key);
        std::size_t rePosition = myvec.size();
        if(myvec[position].second == false) {
            myvec[position] = {key, true};
        } else {
            std::size_t i = 1;
            do {
                if(i == 11)
                    break;
                rePosition = conflict(key, 11, i);
                ++i;
            } while(myvec[rePosition].second == true);
            myvec[rePosition] = {key, true};
            countFindPosition += double(i - 1); // ASL
        }
    } // (1) construct

    std::cout << "ASL(success): " << countFindPosition / mykeys.size() << ". should be: " << 17./8 << std::endl;
    EXPECT_EQ(countFindPosition / mykeys.size(), 17./8); // ASL

    ///{{22,true},{67,true},{41,true},{30,true},{0, false},{53,true},{46,true},{0, false},{13,true},{0, false},{1,true}}
    std::vector<int> resultVec;
    for(std::size_t i = 0; i < myvec.size(); ++i) {
        resultVec.push_back(myvec[i].first);
    }
    assert_eq_vector({ 22, 67, 41, 30,  0, 53, 46,  0, 13,  0,  1}, resultVec);
}
コード例 #14
0
ファイル: oscene.cpp プロジェクト: mifark/everything
void OScene::lifeperiod()
{
    int count;
    int bufferpoint[FSIZE][FSIZE];
    for(int i=1;i<FSIZE-1;++i)
    {
        for(int j=1;j<FSIZE-1;++j)
        {
            count = conflict(i,j);
            if(count<2 || count>3)
                bufferpoint[i][j] = FREE;
            else if(count==3)
                bufferpoint[i][j] = ACTIVE;
            else
                bufferpoint[i][j] = point[i][j];

        }
    }
    for(int i=1;i<FSIZE-1;++i)
        for(int j=1;j<FSIZE-1;++j)
            point[i][j] = bufferpoint[i][j];
    this->updateGL();
}
コード例 #15
0
ファイル: main.cpp プロジェクト: zJoyceLee/DataStructure
TEST(Hash, testSearchFailureASL) {
    std::vector<std::pair<int, bool>> myvec;
    for(std::size_t i = 0; i < 11; ++i) {
        myvec.push_back({0, false});
    }; // initialization
    std::vector<int> mykeys = {22,41,53,46,30,13,1,67};

    for(std::size_t index = 0; index < mykeys.size(); ++index) {
        int key = mykeys[index]; // index is increasing
        std::size_t position = myHash(key);
        std::size_t rePosition = myvec.size();
        if(myvec[position].second == false) {
            myvec[position] = {key, true};
        } else {
            std::size_t i = 1;
            do {
                rePosition = conflict(key, 11, i);
                ++i;
            } while(myvec[rePosition].second == true);
            myvec[rePosition] = {key, true};
        }
    } // (1) construct

    // --------------------------------------------------------

    // (2) test search failure ASL

    // for each bucket (aka position)
    std::size_t bucketSize = 11;
    double sumUp = 0.;
    for(std::size_t bucketIndex = 0; bucketIndex < bucketSize; ++bucketIndex) {
        double currentBucketAverageSteps = calculateAverageStepsForBucket(myvec, bucketIndex, bucketSize);
        sumUp += currentBucketAverageSteps;
    }
    printf("Search Failed ASL: %lf\n", sumUp/bucketSize);
}
コード例 #16
0
ファイル: jsondbobject.cpp プロジェクト: Distrotech/qtjsondb
/*!
 * \brief JsonDbObject::updateVersionReplicating implements a replicatedWrite
 * \param other the (remote) object to include into this one.
 * \return if the passed object was a valid replication
 */
bool JsonDbObject::updateVersionReplicating(const JsonDbObject &other)
{
    // these two will be the final _meta content
    QJsonArray history;
    QJsonArray conflicts;

    // let's go thru all version, i.e. this, this._conflicts, other, and other._conflicts
    {
        // thanks to the operator <, documents will sort and remove duplicates
        // the value is just for show, QSet is based on QHash, which does not sort
        QMap<JsonDbObject,bool> documents;

        QUuid id;
        if (!isEmpty()) {
            id = uuid();
            populateMerge(&documents, id, *this);
        } else {
            id = other.uuid();
        }
        if (!populateMerge(&documents, id, other, true))
            return false;

        // now we have all versions sorted and duplicates removed
        // let's figure out what to keep, what to toss
        // this is O(n^2) but should be fine in real world situations
        for (QMap<JsonDbObject,bool>::const_iterator ii = documents.begin(); ii != documents.end(); ii++) {
            bool alive = !ii.key().isDeleted();
            for (QMap<JsonDbObject,bool>::const_iterator jj = ii + 1; alive && jj != documents.end(); jj++)
                if (ii.key().isAncestorOf(jj.key()))
                    alive = false;

            if (ii+1 == documents.end()) {
                // last element, so found the winner,
                // assigning to *this, which is head
                *this = ii.key();
                populateHistory(&history, *this, false);
            } else if (alive) {
                // this is a conflict, strip _meta and keep it
                JsonDbObject conflict(ii.key());
                conflict.remove(JsonDbString::kMetaStr);
                conflicts.append(conflict);
            } else {
                // this version was replaced, just keep history
                populateHistory(&history, ii.key(), true);
            }
        }
    }

    // let's write a new _meta into head
    if (history.size() || conflicts.size()) {
        QJsonObject meta;
        if (history.size())
            meta.insert(QStringLiteral("history"), history);
        if (conflicts.size())
            meta.insert(JsonDbString::kConflictsStr, conflicts);
        insert(JsonDbString::kMetaStr, meta);
    } else {
        // this is really just for sanity reason, but it feels better to have it
        // aka: this branch should never be reached in real world situations
        remove(JsonDbString::kMetaStr);
    }

    return true;
}
コード例 #17
0
ファイル: jsondbobject.cpp プロジェクト: Distrotech/qtjsondb
/*!
 * \brief JsonDbObject::updateVersionOptimistic implement an optimisticWrite
 * \param other the object containing the update to be written. Do NOT call computeVersion()
 *        on the other object before passing it in! other._meta.history is assumed untrusted.
 * \param versionWritten contains the version string of the write upon return
 * \param trackHistory whether version history should be tracked or not. Defaults to true.
 * \return true if the passed object is a valid write. As this version can operate
 *         on conflicts too, version() and versionWritten can differ.
 */
bool JsonDbObject::updateVersionOptimistic(const JsonDbObject &other, QString *versionWrittenOut, bool trackHistory)
{
    QString versionWritten;
    // this is trusted and expected to contain a _meta object with book keeping info
    QJsonObject meta = value(JsonDbString::kMetaStr).toObject();

    // an array of all versions this object has replaced
    QJsonArray history = meta.value(QStringLiteral("history")).toArray();

    // all known conflicts
    QJsonArray conflicts = meta.value(JsonDbString::kConflictsStr).toArray();

    // check for in-object override of history tracking
    if (trackHistory && value(JsonDbString::kLocalStr).toBool())
        trackHistory = false;

    QString replacedVersion = other.version();

    int replacedCount;
    QString replacedHash = tokenizeVersion(replacedVersion, &replacedCount);

    int updateCount = replacedCount;
    QString hash = replacedHash;

    // we don't trust other._meta.history, so other._version must be replacedVersion
    // if other.computeVersion() was called before updateVersionOptimistic(), other can at max be a replay
    // as we lost which version other is replacing.
    bool isReplay = !other.computeVersion(replacedCount, replacedHash, &updateCount, &hash);

    bool isValidWrite = false;

    // first we check if this version can eliminate a conflict
    for (QJsonArray::const_iterator ii = conflicts.begin(); ii < conflicts.end(); ii++) {

        JsonDbObject conflict((*ii).toObject());
        if (conflict.version() == replacedVersion) {
            if (!isReplay)
                conflicts.removeAt(ii.i);
            if (!isValidWrite) {
                addAncestor(&history, updateCount, hash);
                versionWritten = versionAsString(updateCount, hash);
            }
            isValidWrite = true;
        }
    }

    // now we check if this version can progress the head
    if (version().isEmpty() || version() == replacedVersion) {
        if (!isReplay)
            *this = other;
        if (!isValidWrite)
            versionWritten = versionAsString(updateCount, hash);
        insert(JsonDbString::kVersionStr, versionWritten);
        isValidWrite = true;
    }

    // make sure we can resurrect a tombstone
    // Issue: Recreating a _uuid must have a updateCount higher than the tombstone
    //        otherwise it is considered a conflict.
    if (!isValidWrite && isDeleted()) {
        if (!isReplay) {
            addAncestor(&history, replacedCount, replacedHash);
        }

        replacedHash = tokenizeVersion(version(), &replacedCount);
        updateCount = replacedCount + 1;
        versionWritten = versionAsString(updateCount, hash);

        *this = other;
        insert(JsonDbString::kVersionStr, versionWritten);
        isValidWrite = true;
    }

    // update the book keeping of what versions we have replaced in this version branch
    if (isValidWrite && !isReplay) {
        addAncestor(&history, replacedCount, replacedHash);

        meta = QJsonObject();

        if (trackHistory && history.size())
            meta.insert(QStringLiteral("history"), history);
        if (conflicts.size())
            meta.insert(JsonDbString::kConflictsStr, history);

        if (!meta.isEmpty())
            insert(JsonDbString::kMetaStr, meta);
        else
            insert(JsonDbString::kMetaStr, QJsonValue::Undefined);
    }

    // last chance for a valid write: other is a replay from history
    if (!isValidWrite && isAncestorOf(history, updateCount, hash)) {
        isValidWrite = true;
        versionWritten = versionAsString(updateCount, hash);
    }

    if (versionWrittenOut)
        *versionWrittenOut = versionWritten;

    return isValidWrite;
}
コード例 #18
0
ファイル: arp.cpp プロジェクト: stbuehler/nut
	void ARPProbe::gotProbe(const libnutcommon::MacAddress &mac) {
		if (mac.zero()) return;
		m_state = CONFLICT;
		finish();
		emit conflict(m_ip, mac);
	}
コード例 #19
0
ファイル: arp.cpp プロジェクト: stbuehler/nut
	void ARPWatch::gotPacket(const libnutcommon::MacAddress &mac) {
		if (m_arp) m_arp->m_watches.remove(m_ip);
		m_arp = 0;
		emit conflict(m_ip, mac);
		deleteLater();
	}
コード例 #20
0
// Reader/writer locks, static or dynamic working sets.
bool LockTableRWTxnManager::RunTxn(const std::vector<OpDescription> &operations,
        std::vector<string> *get_results, ThreadStats *stats) {
    // DYNAMIC KEY SET 
    // Deadlock detection and txn termination after undoing effects 
    if (dynamic) {
        bool abort = true;
        string result;

        while (abort) {
            set<long> keys;
            unordered_map<long, string> old_values;
            abort = false;
            LockMode requestMode;

            for (const OpDescription &op : operations) {
                if (op.type == GET) {
                    requestMode = READ;
                } 
                else {
                    requestMode = WRITE;
                }

                if (keys.count(op.key) == 0) {
                    lock_timed(&tableMutex, stats);
                    if (lockTable.count(op.key) == 0) {
                        Lock *l = &lockTable[op.key]; // Creates lock object
                        l->mode = requestMode;

                        if (requestMode == READ) {
                            l->num_readers = 1;
                        } else {
                            l->num_readers = 0;
                        }

                        TIME_CODE(stats, unique_lock<mutex> lk(l->mutex));
                        tableMutex.unlock();
                    } 
                    else {
                        Lock *l = &lockTable[op.key];
                        tableMutex.unlock();

                        TIME_CODE(stats, unique_lock<mutex> lk(l->mutex));

                        thread::id id = this_thread::get_id();
                        l->q.push(id);
                        int wakeups = 0;

                        while (l->q.front() != id || conflict(requestMode, l->mode)) {
                            TIME_CODE(stats, l->cv.wait_for(lk, chrono::milliseconds(10)));
                            wakeups++;
                            if (wakeups > 2) {
                                // Remove this thread from the queue of waiting threads.
                                queue<thread::id> q;
                                while (l->q.size() > 0) {
                                    thread::id i = l->q.front();
                                    l->q.pop();
                                    if (i != id) {
                                        q.push(i);
                                    }
                                }

                                l->q.swap(q);
                                abort = true;
                                if (get_results != NULL) {
                                    get_results->clear();
                                }
                                break;
                            }
                        }

                        if (abort) {
                            break;
                        }

                        if (requestMode == READ) {
                            assert(l->mode != WRITE);
                            l->mode = READ;
                            l->num_readers++;
                        } 
                        else {
                            assert(l->mode == FREE && l->num_readers == 0);
                            l->mode = WRITE;
                        }
                        l->q.pop();
                    }
                    keys.insert(op.key);
                }

                // Run this op.
                ExecuteTxnOp(op, &result);

                if (op.type == GET) {
                    if (get_results != NULL) {
                        get_results->push_back(result);
                    }
                } 
                else if (old_values.count(op.key) == 0) {
                    old_values[op.key] = result;
                }
            }

            // Roll back changes if we aborted.
            if (abort) {
                OpDescription op;
                op.type = INSERT;

                for (auto it = old_values.begin(); it != old_values.end(); it++) {
                    op.key = it->first;
                    op.value = it->second;
                    ExecuteTxnOp(op);
                }
            }

            // Unlock all keys in reverse order.
            for (auto rit = keys.rbegin(); rit != keys.rend(); ++rit) {
                lock_timed(&tableMutex, stats);
                Lock *l = &lockTable[*rit];
                tableMutex.unlock();

                {
                    TimedLockGuard guard(&l->mutex, stats);
                    if (l->mode == READ) {
                        assert(l->num_readers > 0);
                        l->num_readers--;
                        if (l->num_readers == 0) {
                            l->mode = FREE;
                        }
                    } else {
                        assert(l->num_readers == 0);
                        l->mode = FREE;
                    }
                }

                l->cv.notify_all();
            }
        }
    } 
    // STATIC KEY SET
    else {
        // Construct an ordered set of keys to lock, mapped to the type of lock we
        // need to grab.
        map<long, LockMode> keys;
        for (const OpDescription &op : operations) {
            if (keys.count(op.key) == 1) {
                if (op.type != GET) {
                    keys[op.key] = WRITE;
                }
            } 
            else {
                if (op.type == GET) {
                    keys[op.key] = READ;
                } else {
                    keys[op.key] = WRITE;
                }
            }
        }

        //std::cout << keys.size() << " ";

        // Lock keys in order.
        for (const pair<long, LockMode> &p : keys) {
            long key = p.first;
            LockMode requestMode = p.second;

            Lock *l = &lockTable[key];

            TIME_CODE(stats, unique_lock<mutex> lk(l->mutex));
            thread::id id = this_thread::get_id();
            l->q.push(id);

            while (l->q.front() != id || conflict(requestMode, l->mode)) {
                //while (conflict(requestMode, l->mode)) {
                TIME_CODE(stats, l->cv.wait(lk));
            }

            if (requestMode == READ) {
                assert(l->mode != WRITE);
                l->mode = READ;
                l->num_readers++;
                //if (l->num_readers > 3) {
                //std::cout << l->num_readers << "\n";
                //}
            } 
            else {
                assert(l->mode == FREE && l->num_readers == 0);
                l->mode = WRITE;
            }

            l->q.pop();
            }

            // Do transaction.
            ExecuteTxnOps(operations, get_results);

            // Unlock all keys in reverse order.
            for (auto rit = keys.rbegin(); rit != keys.rend(); ++rit) {
                Lock *l = &lockTable[rit->first];
                bool notify = false;
                {
                    TimedLockGuard guard(&l->mutex, stats);
                    if (l->mode == READ) {
                        assert(l->num_readers > 0);
                        l->num_readers--;
                        if (l->num_readers == 0) {
                            l->mode = FREE;
                            notify = true;
                        }
                    } else {
                        assert(l->num_readers == 0);
                        assert(rit->second == WRITE);
                        l->mode = FREE;
                        notify = true;
                    }
                }
                if (notify) {
                    l->cv.notify_all();
                }
            }
        }
        return true;
    }
コード例 #21
0
ファイル: fe_config.cpp プロジェクト: Cucurbitace/attract
bool FeEmulatorEditMenu::on_option_select(
		FeConfigContext &ctx, FeBaseConfigMenu *& submenu )
{
	FeMenuOpt &o = ctx.curr_opt();

	if ( !m_emulator )
		return true;

	switch ( o.opaque )
	{
	case 1: //	 Edit artwork
		m_art_menu.set_art( m_emulator, o.setting );
		submenu = &m_art_menu;
		break;

	case 2: //	 Add new artwork
		m_art_menu.set_art( m_emulator, "" );
		submenu = &m_art_menu;
		break;

	case 3: // Generate Romlist
		{
			// Make sure m_emulator is set with all the configured info
			//
			for ( int i=0; i < FeEmulatorInfo::LAST_INDEX; i++ )
				m_emulator->set_info( (FeEmulatorInfo::Index)i,
					ctx.opt_list[i].get_value() );

			// Do some checks and confirmation before launching the Generator
			//
			std::vector<std::string> paths = m_emulator->get_paths();

			for ( std::vector<std::string>::const_iterator itr = paths.begin();
					itr != paths.end(); ++itr )
			{
				std::string rom_path = clean_path( *itr );
				if ( !directory_exists( rom_path ) )
				{
					if ( ctx.confirm_dialog( "Rom path '$1' not found, proceed anyways?",
										rom_path ) == false )
						return false;
					else
						break; // only bug the user once if there are multiple paths configured
				}
			}

			std::string emu_name = m_emulator->get_info( FeEmulatorInfo::Name );

			if ( m_romlist_exists )
			{
				if ( ctx.confirm_dialog( "Overwrite existing '$1' list?",
									emu_name ) == false )
					return false;
			}

			FePresent *fep = FePresent::script_get_fep();
			if ( fep )
				fep->set_video_play_state( false );

			ctx.fe_settings.build_romlist( emu_name, gen_ui_update, &ctx,
								ctx.help_msg );

			if ( fep )
				fep->set_video_play_state(
					fep->get_video_toggle() );

			//
			// If we don't have a display configured for this romlist,
			// configure one now
			//
			if ( !ctx.fe_settings.check_romlist_configured( emu_name ) )
			{
				FeDisplayInfo *new_disp = ctx.fe_settings.create_display( emu_name );
				new_disp->set_info( FeDisplayInfo::Romlist, emu_name );
			}

			ctx.save_req = true;
			m_parent_save = true;
		}
		break;
	case 4: // Scrape Artwork
		{
			FePresent *fep = FePresent::script_get_fep();
			if ( fep )
				fep->set_video_play_state( false );

			std::string emu_name = m_emulator->get_info( FeEmulatorInfo::Name );
			ctx.fe_settings.scrape_artwork( emu_name, scrape_ui_update, &ctx, ctx.help_msg );

			if ( fep )
				fep->set_video_play_state(
					fep->get_video_toggle() );
		}
		break;
	case 5: // Delete this Emulator
		{
			std::string name = m_emulator->get_info(FeEmulatorInfo::Name);

			if ( ctx.confirm_dialog( "Delete emulator '$1'?", name ) == false )
				return false;

			ctx.fe_settings.delete_emulator(
					m_emulator->get_info(FeEmulatorInfo::Name) );
		}
		break;

	case 100: // Hotkey input
		{
			std::string res;
			FeInputMap::Command conflict( FeInputMap::LAST_COMMAND );
			ctx.input_map_dialog( "Press Exit Hotkey", res, conflict );

			bool save=false;
			if ( o.get_value().compare( res ) != 0 )
				save = true;
			else
			{
				if ( ctx.confirm_dialog( "Clear Exit Hotkey?", res ))
				{
					res.clear();
					save = true;
				}
			}

			if ( save )
			{
				o.set_value( res );
				ctx.save_req = true;
			}
		}
		break;

	default:
		break;
	}

	return true;
}
コード例 #22
0
ファイル: fe_config.cpp プロジェクト: Cucurbitace/attract
bool FeInputEditMenu::on_option_select(
		FeConfigContext &ctx, FeBaseConfigMenu *& submenu )
{
	FeMenuOpt &o = ctx.curr_opt();
	if (!m_mapping)
		return true;

	switch ( o.opaque )
	{
	case 0:
		{
			if (( m_mapping->input_list.size() <= 1 ) && (
					( m_mapping->command == FeInputMap::Select )
					|| ( m_mapping->command == FeInputMap::Up )
					|| ( m_mapping->command == FeInputMap::Down ) ) )
			{
				// We don't let the user unmap all "Up", "Down" or "Select" controls.
				// Doing so would prevent them from further navigating configure mode.
				break;
			}

			std::vector< std::string >::iterator it;
			for ( it=m_mapping->input_list.begin();
					it<m_mapping->input_list.end(); ++it )
			{
				if ( (*it).compare( o.get_value() ) == 0 )
				{
					// User selected to remove this mapping
					//
					m_mapping->input_list.erase( it );
					ctx.save_req = true;
					break;
				}
			}
		}
		break;

	case 1:
		{
			std::string res;
			FeInputMap::Command conflict( FeInputMap::LAST_COMMAND );
			ctx.input_map_dialog( "Press Input", res, conflict );

			bool save=true;
			if (( conflict != FeInputMap::LAST_COMMAND )
				&& ( conflict != m_mapping->command ))
			{
				std::string command_str;
				ctx.fe_settings.get_resource( FeInputMap::commandDispStrings[ conflict ], command_str );
				save = ctx.confirm_dialog(
					"This will overwrite an existing mapping ($1).  Proceed?", command_str  );
			}

			if ( save )
			{
				m_mapping->input_list.push_back( res );
				ctx.save_req = true;
			}
		}
		break;

	default:
		break;
	}

	return true;
}
コード例 #23
0
ファイル: state.c プロジェクト: qb1/curseofwar
void state_init(struct state *s, struct basic_options *op, struct multi_options *mop){
 
  s->speed = op->speed;
  s->prev_speed = s->speed;
  s->dif = op->dif;
  s->map_seed = op->map_seed;
  s->conditions = op->conditions;
  s->inequality = op->inequality;
  s->winlosecondition = 0;
  s->time = (1850 + rand()%100) * 360 + rand()%360;

  /* player controlled from the keyboard */
  s->controlled = 1;
  /* int players[] = {7, 2, 3, 5}; */
  /* int players[] = {2, 3, 4, 5, 6, 7}; */

  int all_players[] = {1, 2, 3, 4, 5, 6, 7};
  int comp_players[MAX_PLAYER]; 
  int comp_players_num = 7 - mop->clients_num;
 
  s->kings_num = comp_players_num;
  int ui_players[MAX_PLAYER];
  int ui_players_num = mop->clients_num;
  int i;
  for (i=0; i<7; ++i) {
    if (i<mop->clients_num)
      ui_players[i] = all_players[i];
    else {
      int j = i - mop->clients_num; /* computer player index / king's index */
      comp_players[j] = all_players[i];
      switch (i){
        case 1:
          king_init (&s->king[j], i+1, opportunist, &s->grid, s->dif); 
          break;
        case 2:
          king_init (&s->king[j], i+1, one_greedy, &s->grid, s->dif);
          break;
        case 3:
          king_init (&s->king[j], i+1, none, &s->grid, s->dif);
          break;
        case 4:
          king_init (&s->king[j], i+1, aggr_greedy, &s->grid, s->dif);
          break;
        case 5:
          king_init (&s->king[j], i+1, noble, &s->grid, s->dif);
          break;
        case 6:
          king_init (&s->king[j], i+1, persistent_greedy, &s->grid, s->dif);
          break;
      }
    }
  }

  /* Initialize map generation with the map_seed */
  srand(s->map_seed);

  /* Map generation starts */
  {
    int conflict_code = 0;
    do {
      grid_init(&s->grid, op->w, op->h);
  
      /* starting locations arrays */
      struct loc loc_arr[MAX_AVLBL_LOC];
      int available_loc_num = 0;
      int d = 2;
      apply_stencil(op->shape, &s->grid, d, loc_arr, &available_loc_num);
     
      /* conflict mode */
      conflict_code = 0;
      if (!op->keep_random_flag) 
        conflict_code = conflict(&s->grid, loc_arr, available_loc_num, 
            comp_players, comp_players_num, op->loc_num, ui_players, ui_players_num, s->conditions, s->inequality);
    } while(conflict_code != 0 || !is_connected(&s->grid));
  }
  /* Map is ready */

  int p;
  for(p = 0; p<MAX_PLAYER; ++p) {
    flag_grid_init(&s->fg[p], op->w, op->h);
    s->country[p].gold = 0;
  }

  /* kings evaluate the map */
  for(p = 0; p < s->kings_num; ++p) {
    king_evaluate_map(&s->king[p], &s->grid, s->dif);
  }

  /* Zero timeline */
  s->show_timeline = op->timeline_flag;
  s->timeline.mark = -1;
  for(i=0; i<MAX_TIMELINE_MARK; ++i) {
    s->timeline.time[i] = s->time;
    for(p=0; p<MAX_PLAYER; ++p) {
      s->timeline.data[p][i] = 0.0;
    }
  }

  /* init turn by turn */
  for(p=0; p<mop->clients_num; ++p) {
	s->turn_validated[p] = 0;
  }
}
コード例 #24
0
ファイル: applylog.c プロジェクト: npe9/harvey
void
main(int argc, char **argv)
{ 
	char *f[10], *local, *name, *remote, *s, *t, verb;
	int fd, havedb, havelocal, i, k, n, nf, resolve1, skip;
	int checkedmatch1, checkedmatch2, 
		checkedmatch3, checkedmatch4;
	ulong now;
	Biobuf bin;
	Dir dbd, ld, nd, rd;
	Avlwalk *w;
	Entry *e;

	membogus(argv);
	quotefmtinstall();
	ARGBEGIN{
	case 's':
	case 'c':
		i = ARGC();
		addresolve(i, EARGF(usage()));
		break;
	case 'n':
		donothing = 1;
		verbose = 1;
		break;
	case 'S':
		safeinstall = 0;
		break;
	case 'T':
		timefile = EARGF(usage());
		break;
	case 't':
		tempspool = 0;
		break;
	case 'u':
		douid = 1;
		break;
	case 'v':
		verbose++;
		break;
	default:
		usage();
	}ARGEND

	if(argc < 3)
		usage();

	if(timefile)
		readtimefile();

	lroot = argv[1];
	if(!isdir(lroot))
		sysfatal("bad local root directory");
	rroot = argv[2];
	if(!isdir(rroot))
		sysfatal("bad remote root directory");

	match = argv+3;
	nmatch = argc-3;
	for(i=0; i<nmatch; i++)
		if(match[i][0] == '/')
			match[i]++;

	if((clientdb = opendb(argv[0])) == nil)
		sysfatal("opendb %q: %r", argv[2]);
	
	copyerr = opendb(nil);

	skip = 0;
	Binit(&bin, 0, OREAD);
	for(; s=Brdstr(&bin, '\n', 1); free(s)){
		t = estrdup(s);
		nf = tokenize(s, f, nelem(f));
		if(nf != 10 || strlen(f[2]) != 1){
			skip = 1;
			fprint(2, "warning: skipping bad log entry <%s>\n", t);
			free(t);
			continue;
		}
		free(t);
		now = strtoul(f[0], 0, 0);
		n = atoi(f[1]);
		verb = f[2][0];
		name = f[3];
		if(now < maxnow || (now==maxnow && n <= maxn))
			continue;
		local = mkname(localbuf, sizeof localbuf, lroot, name);
		if(strcmp(f[4], "-") == 0)
			f[4] = f[3];
		remote = mkname(remotebuf, sizeof remotebuf, rroot, f[4]);
		rd.name = f[4];
		rd.mode = strtoul(f[5], 0, 8);
		rd.uid = f[6];
		rd.gid = f[7];
		rd.mtime = strtoul(f[8], 0, 10);
		rd.length = strtoll(f[9], 0, 10);
		havedb = finddb(clientdb, name, &dbd)>=0;
		havelocal = localdirstat(local, &ld)>=0;

		resolve1 = resolve(name);

		/*
		 * if(!ismatch(name)){
		 *	skip = 1;
		 *	continue;
		 * }
		 * 
		 * This check used to be right here, but we want
		 * the time to be able to move forward past entries
		 * that don't match and have already been applied.
		 * So now every path below must checked !ismatch(name)
		 * before making any changes to the local file
		 * system.  The fake variable checkedmatch
		 * tracks whether !ismatch(name) has been checked.
		 * If the compiler doesn't produce any used/set
		 * warnings, then all the paths should be okay.
		 * Even so, we have the asserts to fall back on.
		 */
		switch(verb){
		case 'd':	/* delete file */
			delce(local);
			if(!havelocal)	/* doesn't exist; who cares? */
				break;
			if(access(remote, AEXIST) >= 0)	/* got recreated! */
				break;
			if(!ismatch(name)){
				skip = prstopped(skip, name);
				continue;
			}
			SET(checkedmatch1);
			if(!havedb){
				if(resolve1 == 's')
					goto DoRemove;
				else if(resolve1 == 'c')
					goto DoRemoveDb;
				conflict(name, "locally created; will not remove");
				skip = 1;
				continue;
			}
			assert(havelocal && havedb);
			if(dbd.mtime > rd.mtime)		/* we have a newer file than what was deleted */
				break;
			if(samecontents(local, remote) > 0){	/* going to get recreated */
				chat("= %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
				break;
			}
			if(!(dbd.mode&DMDIR) && (dbd.mtime != ld.mtime || dbd.length != ld.length)){	/* locally modified since we downloaded it */
				if(resolve1 == 's')
					goto DoRemove;
				else if(resolve1 == 'c')
					break;
				conflict(name, "locally modified; will not remove");
				skip = 1;
				continue;
			}
		    DoRemove:
			USED(checkedmatch1);
			assert(ismatch(name));
			chat("d %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
			if(donothing)
				break;
			if(remove(local) < 0){
				error("removing %q: %r", name);
				skip = 1;
				continue;
			}
		    DoRemoveDb:
			USED(checkedmatch1);
			assert(ismatch(name));
			removedb(clientdb, name);
			break;

		case 'a':	/* add file */
			if(!havedb){
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch2);
				if(!havelocal)
					goto DoCreate;
				if((ld.mode&DMDIR) && (rd.mode&DMDIR))
					break;
				if(samecontents(local, remote) > 0){
					chat("= %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
					goto DoCreateDb;
				}
				if(resolve1 == 's')
					goto DoCreate;
				else if(resolve1 == 'c')
					goto DoCreateDb;
				conflict(name, "locally created; will not overwrite");
				skip = 1;
				continue;
			}
			assert(havedb);
			if(dbd.mtime >= rd.mtime)	/* already created this file; ignore */
				break;
			if(havelocal){
				if((ld.mode&DMDIR) && (rd.mode&DMDIR))
					break;
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch2);
				if(samecontents(local, remote) > 0){
					chat("= %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
					goto DoCreateDb;
				}
				if(dbd.mtime==ld.mtime && dbd.length==ld.length)
					goto DoCreate;
				if(resolve1=='s')
					goto DoCreate;
				else if(resolve1 == 'c')
					goto DoCreateDb;
				conflict(name, "locally modified; will not overwrite");
				skip = 1;
				continue;
			}
			if(!ismatch(name)){
				skip = prstopped(skip, name);
				continue;
			}
			SET(checkedmatch2);
		    DoCreate:
			USED(checkedmatch2);
			assert(ismatch(name));
			if(notexists(remote)){
				addce(local);
				/* no skip=1 */
				break;;
			}
			chat("a %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
			if(donothing)
				break;
			if(rd.mode&DMDIR){
				fd = create(local, OREAD, DMDIR);
				if(fd < 0 && isdir(local))
					fd = open(local, OREAD);
				if(fd  < 0){
					error("mkdir %q: %r", name);
					skip = 1;
					continue;
				}
				nulldir(&nd);
				nd.mode = rd.mode;
				if(dirfwstat(fd, &nd) < 0)
					fprint(2, "warning: cannot set mode on %q\n", local);
				nulldir(&nd);
				nd.gid = rd.gid;
				if(dirfwstat(fd, &nd) < 0)
					fprint(2, "warning: cannot set gid on %q\n", local);
				if(douid){
					nulldir(&nd);
					nd.uid = rd.uid;
					if(dirfwstat(fd, &nd) < 0)
						fprint(2, "warning: cannot set uid on %q\n", local);
				}
				close(fd);
				rd.mtime = now;
			}else{
				if(copyfile(local, remote, name, &rd, 1, &k) < 0){
					if(k)
						addce(local);
					skip = 1;
					continue;
				}
			}
		    DoCreateDb:
			USED(checkedmatch2);
			assert(ismatch(name));
			insertdb(clientdb, name, &rd);
			break;
			
		case 'c':	/* change contents */
			if(!havedb){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch3);
				if(resolve1 == 's')
					goto DoCopy;
				else if(resolve1=='c')
					goto DoCopyDb;
				if(samecontents(local, remote) > 0){
					chat("= %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
					goto DoCopyDb;
				}
				if(havelocal)
					conflict(name, "locally created; will not update");
				else
					conflict(name, "not replicated; will not update");
				skip = 1;
				continue;
			}
			if(dbd.mtime >= rd.mtime)		/* already have/had this version; ignore */
				break;
			if(!ismatch(name)){
				skip = prstopped(skip, name);
				continue;
			}
			SET(checkedmatch3);
			if(!havelocal){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(resolve1 == 's')
					goto DoCopy;
				else if(resolve1 == 'c')
					break;
				conflict(name, "locally removed; will not update");
				skip = 1;
				continue;
			}
			assert(havedb && havelocal);
			if(dbd.mtime != ld.mtime || dbd.length != ld.length){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(samecontents(local, remote) > 0){
					chat("= %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
					goto DoCopyDb;
				}
				if(resolve1 == 's')
					goto DoCopy;
				else if(resolve1 == 'c')
					goto DoCopyDb;
				conflict(name, "locally modified; will not update [%llud %lud -> %llud %lud]", dbd.length, dbd.mtime, ld.length, ld.mtime);
				skip = 1;
				continue;
			}
		    DoCopy:
			USED(checkedmatch3);
			assert(ismatch(name));
			if(notexists(remote)){
				addce(local);
				/* no skip=1 */
				break;
			}
			chat("c %q\n", name);
			if(donothing)
				break;
			if(copyfile(local, remote, name, &rd, 0, &k) < 0){
				if(k)
					addce(local);
				skip = 1;
				continue;
			}
		    DoCopyDb:
			USED(checkedmatch3);
			assert(ismatch(name));
			if(!havedb){
				if(havelocal)
					dbd = ld;
				else
					dbd = rd;
			}
			dbd.mtime = rd.mtime;
			dbd.length = rd.length;
			insertdb(clientdb, name, &dbd);
			break;			

		case 'm':	/* change metadata */
			if(!havedb){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch4);
				if(resolve1 == 's'){
					USED(checkedmatch4);
					SET(checkedmatch2);
					goto DoCreate;
				}
				else if(resolve1 == 'c')
					goto DoMetaDb;
				if(havelocal)
					conflict(name, "locally created; will not update metadata");
				else
					conflict(name, "not replicated; will not update metadata");
				skip = 1;
				continue;
			}
			if(!(dbd.mode&DMDIR) && dbd.mtime > rd.mtime)		/* have newer version; ignore */
				break;
			if((dbd.mode&DMDIR) && dbd.mtime > now)
				break;
			if(havelocal && (!douid || strcmp(ld.uid, rd.uid)==0) && strcmp(ld.gid, rd.gid)==0 && ld.mode==rd.mode)
				break;
			if(!havelocal){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch4);
				if(resolve1 == 's'){
					USED(checkedmatch4);
					SET(checkedmatch2);
					goto DoCreate;
				}
				else if(resolve1 == 'c')
					break;
				conflict(name, "locally removed; will not update metadata");
				skip = 1;
				continue;
			}
			if(!(dbd.mode&DMDIR) && (dbd.mtime != ld.mtime || dbd.length != ld.length)){	/* this check might be overkill */
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch4);
				if(resolve1 == 's' || samecontents(local, remote) > 0)
					goto DoMeta;
				else if(resolve1 == 'c')
					break;
				conflict(name, "contents locally modified (%s); will not update metadata to %s %s %luo",
					dbd.mtime != ld.mtime ? "mtime" :
					dbd.length != ld.length ? "length" : 
					"unknown",
					rd.uid, rd.gid, rd.mode);
				skip = 1;
				continue;
			}
			if((douid && strcmp(ld.uid, dbd.uid)!=0) || strcmp(ld.gid, dbd.gid)!=0 || ld.mode!=dbd.mode){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch4);
				if(resolve1 == 's')
					goto DoMeta;
				else if(resolve1 == 'c')
					break;
				conflict(name, "metadata locally changed; will not update metadata to %s %s %luo", rd.uid, rd.gid, rd.mode);
				skip = 1;
				continue;
			}
			if(!ismatch(name)){
				skip = prstopped(skip, name);
				continue;
			}
			SET(checkedmatch4);
		    DoMeta:
			USED(checkedmatch4);
			assert(ismatch(name));
			if(notexists(remote)){
				addce(local);
				/* no skip=1 */
				break;
			}
			chat("m %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
			if(donothing)
				break;
			nulldir(&nd);
			nd.gid = rd.gid;
			nd.mode = rd.mode;
			if(douid)
				nd.uid = rd.uid;
			if(dirwstat(local, &nd) < 0){
				error("dirwstat %q: %r", name);
				skip = 1;
				continue;
			}
		    DoMetaDb:
			USED(checkedmatch4);
			assert(ismatch(name));
			if(!havedb){
				if(havelocal)
					dbd = ld;
				else
					dbd = rd;
			}
			if(dbd.mode&DMDIR)
				dbd.mtime = now;
			dbd.gid = rd.gid;
			dbd.mode = rd.mode;
			if(douid)
				dbd.uid = rd.uid;
			insertdb(clientdb, name, &dbd);
			break;
		}
		if(!skip && !donothing){
			maxnow = now;
			maxn = n;
		}
	}

	w = avlwalk(copyerr->avl);
	while(e = (Entry*)avlnext(w))
		error("copying %q: %s\n", e->name, e->d.name);

	if(timefile)
		writetimefile();
	if(nconf)
		exits("conflicts");

	if(errors)
		exits("errors");
	exits(nil);
}
コード例 #25
0
ファイル: balesh.adventure.c プロジェクト: balesh2/OS1-HW2
int main() {
  //======Declare all Variables======
  int i;
  int j;
  int pid;
  int con;
  int counter;
  int room;
  char* tmp;
  int connections[7][6];
  char* dir;
  char* rooms[7];
  char* path;
  FILE* file;
  //=================================

  //======Malloc Everything==========
  dir = malloc(sizeof(char)*18);
  for(i=0; i<7; i++) {
    rooms[i] = malloc(sizeof(char)*8);
  }
  path = malloc(sizeof(char)*29);
  tmp = malloc(sizeof(char));
  //=================================

  //seed rand
  srand(time(NULL));

  //init connections matrix
  for(i=0; i<7; i++){
    for(j=0; j<6; j++){
      connections[i][j] = 9;
    }
  }

  //get pid
  pid = getpid();
  //add pid to dir name
  sprintf(dir, "balesh.rooms.%d", pid);

  //make list of room names
  rooms[0] = "Darkroom";
  rooms[1] = "Ballroom";
  rooms[2] = "Mailroom";
  rooms[3] = "Coatroom";
  rooms[4] = "Newsroom";
  rooms[5] = "Restroom";
  rooms[6] = "Entryway";

  //make the dir
  mkdir(dir, 0777);

  //create all the connections in an array
  for(i=0; i<7; i++){
    //get the number of connections for that room
    con = (rand()%4) + 3;
    for(j=0; j<con; j++) {
      //only add a new connection if that connection has not already been filled
      if(connections[i][j] == 9){
        //do this while the room was already a connection
        do {
          //do this while the room was the current room
          do{
            //pick a random room
            room = rand()%7;
          }while(room == i);
        }while(conflict(connections[i], j, room));

        //save the accepted connection
        connections[i][j] = room;
        //saves to connection in the randomly chosen room
        //into the first open position in the array
        for(counter=0; counter<6; counter++){
          if(connections[room][counter] == 9) {
            connections[room][counter] = i;
            break;
          }
        }
      }
    }

  }

  //for testing
  //prints the array of connections
  /*
  for(i=0; i<7; i++){
    printf("room %d\n", i);
    for(j=0; j<6; j++){
      if(connections[i][j] != 9) {
        printf("%s\n", rooms[connections[i][j]]);
      }
      else{
        printf("9\n");
      }
    }
  }
  */


  //puts the connections from the array to the files
  for(i=0; i<7; i++){
    //cats the dir and file name to the path
    sprintf(path, "./%s/%s", dir, rooms[i]);
    //opens the file with write priveledges
    file = fopen(path, "w");
    //puts the room name in the file
    fputs("ROOM NAME: ", file);
    fputs(rooms[i], file);
    fputs("\n", file);
    //puts the connections in the file
    for(j=0; j<6; j++){
      if(connections[i][j] != 9){
        //puts the connection number in a temp string var
        sprintf(tmp, "%d", (j+1));
        //prints the connections to the file
        fputs("CONNECTION ", file);
        fputs(tmp, file);
        fputs(": ", file);
        fputs(rooms[connections[i][j]], file);
        fputs("\n", file);
      }
    }
    //puts the room type at the end of the file
    fputs("ROOM TYPE: ", file);
    //if the file open is Restroom, put end type
    if(i == 5) {
      fputs("END_ROOM", file);
    }
    //if the file open is Entryway, put start type
    else if(i == 6) {
      fputs("START_ROOM", file);
    }
    //otherwise put mid type
    else {
      fputs("MID_ROOM", file);
    }
    fputs("\n", file);
    //close the file
    fclose(file);
    file = NULL;
  }

  //play the game
  play(rooms, dir);

  //=========Free Everything=========
  free(dir);
  free(path);
  //=================================

  return(0);

}
コード例 #26
0
/**
 * Returns true if loss last more than thr in seconds
 */
bool LossData::conflict(double thr) const {
	return conflict() && (time_out - time_in >= thr);
}
コード例 #27
0
ファイル: locks.c プロジェクト: Lakshmipathi/Linux-historic
int fcntl_setlk(unsigned int fd, unsigned int cmd, struct flock *l)
{
	int error;
	struct file *filp;
	struct file_lock *fl,file_lock;
	struct flock flock;

	/*
	 * Get arguments and validate them ...
	 */

	if (fd >= NR_OPEN || !(filp = current->files->fd[fd]))
		return -EBADF;
	error = verify_area(VERIFY_READ, l, sizeof(*l));
	if (error)
		return error;
	memcpy_fromfs(&flock, l, sizeof(flock));
	if (!copy_flock(filp, &file_lock, &flock, fd))
		return -EINVAL;
	switch (file_lock.fl_type) {
	case F_RDLCK :
		if (!(filp->f_mode & 1))
			return -EBADF;
		break;
	case F_WRLCK :
		if (!(filp->f_mode & 2))
			return -EBADF;
		break;
	case F_SHLCK :
		if (!(filp->f_mode & 3))
			return -EBADF;
		file_lock.fl_type = F_RDLCK;
		break;
	case F_EXLCK :
		if (!(filp->f_mode & 3))
			return -EBADF;
		file_lock.fl_type = F_WRLCK;
		break;
	case F_UNLCK :
		break;
	}

  	/*
  	 * Scan for a conflicting lock ...
  	 */
  
	if (file_lock.fl_type != F_UNLCK) {
repeat:
		for (fl = filp->f_inode->i_flock; fl != NULL; fl = fl->fl_next) {
			if (!conflict(&file_lock, fl))
				continue;
			/*
			 * File is locked by another process. If this is
			 * F_SETLKW wait for the lock to be released.
			 */
			if (cmd == F_SETLKW) {
				if (current->signal & ~current->blocked)
					return -ERESTARTSYS;
#ifdef DEADLOCK_DETECTION
				if (locks_deadlocked(file_lock.fl_owner->pid,fl->fl_owner->pid)) return -EDEADLOCK;
#endif
				interruptible_sleep_on(&fl->fl_wait);
				if (current->signal & ~current->blocked)
					return -ERESTARTSYS;
				goto repeat;
			}
			return -EAGAIN;
  		}
  	}

	/*
	 * Lock doesn't conflict with any other lock ...
	 */

	return lock_it(filp, &file_lock, fd);
}
コード例 #28
0
ファイル: topolTest.cpp プロジェクト: phborba/QGIS
ErrorList topolTest::checkDuplicates( QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent )
{
  Q_UNUSED( layer2 );
  //TODO: multilines - check all separate pieces
  int i = 0;
  ErrorList errorList;

  QList<QgsFeatureId> duplicateIds;

  QgsSpatialIndex *index = mLayerIndexes[layer1->id()];

  QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( qgsInterface->mapCanvas()->extent().asWktPolygon() );

  QMap<QgsFeatureId, FeatureLayer>::const_iterator it;
  for ( it = mFeatureMap2.constBegin(); it != mFeatureMap2.constEnd(); ++it )
  {
    if ( !( ++i % 100 ) )
      emit progress( i );

    QgsFeatureId currentId = it->feature.id();

    if ( duplicateIds.contains( currentId ) )
    {
      //is already a duplicate geometry..skip..
      continue;
    }

    if ( testCanceled() )
      break;

    QgsGeometry g1 = it->feature.geometry();
    QgsRectangle bb = g1.boundingBox();

    QList<QgsFeatureId> crossingIds;
    crossingIds = index->intersects( bb );

    QList<QgsFeatureId>::ConstIterator cit = crossingIds.constBegin();
    QList<QgsFeatureId>::ConstIterator crossingIdsEnd = crossingIds.constEnd();

    bool duplicate = false;

    for ( ; cit != crossingIdsEnd; ++cit )
    {
      duplicate = false;
      // skip itself
      if ( mFeatureMap2[*cit].feature.id() == it->feature.id() )
        continue;

      QgsGeometry g2 = mFeatureMap2[*cit].feature.geometry();
      if ( g2.isNull() )
      {
        QgsMessageLog::logMessage( tr( "Invalid second geometry in duplicate geometry test." ), tr( "Topology plugin" ) );
        continue;
      }

      if ( !_canExportToGeos( g2 ) )
      {
        QgsMessageLog::logMessage( tr( "Failed to import second geometry into GEOS in duplicate geometry test." ), tr( "Topology plugin" ) );
        continue;
      }

      if ( g1.isGeosEqual( g2 ) )
      {
        duplicate = true;
        duplicateIds.append( mFeatureMap2[*cit].feature.id() );
      }

      if ( duplicate )
      {


        QList<FeatureLayer> fls;
        fls << *it << *it;
        QgsGeometry conflict( g1 );

        if ( isExtent )
        {
          if ( canvasExtentPoly.disjoint( conflict ) )
          {
            continue;
          }
          if ( canvasExtentPoly.crosses( conflict ) )
          {
            conflict = conflict.intersection( canvasExtentPoly );
          }
        }

        TopolErrorDuplicates *err = new TopolErrorDuplicates( bb, conflict, fls );

        errorList << err;
      }

    }

  }
  return errorList;
}
コード例 #29
0
 void dfs(int x,int y,int c){
     // 如果找到了最理想结果,则不必继续搜索
     if(flag) return ;
     pii temp[N];
     // expt表示比赛(x,y)预计要安排到的轮次数
     int expt = c / tmpn;
     // sum表示当前的方差和
     int sum = 0;
     for(int i = 1; i <= cntn; i++)
         sum += differ(hash[i]);
     if(sum > TMP+EPS) return;
     // 此处是一个剪枝,如果继续搜索没有当前结果好,则舍弃
     if(y == ANS[x].size()) x ++, y = 0;
     if(x == len) {
         // 搜索到终点
         if(sum == TMP) {
             flag = 1;
         }
         // 如果当前结果比最优结果好,那么记录当前结果
         if(sum < best ) {
             // 按照之前的要求,某行的轮空不超过1
             for(int i = 1; i <= base; i++)
                 if(chk_zero(hash[i]) > 1)
                     return ;
             best = sum;
             memcpy(last_ans,ans,sizeof(ans));
             memcpy(myconf,conf,sizeof(conf));
         }
         return;
     }
     //p是当前比赛
     pii p = ANS[x][y];
     int a =p.first, b = p.second;
     for(int i =  0; i < coln; i++)
         temp[i] = make_pair(use[i],i);
     // 数组use是赛道的使用频率
     sort(temp,temp+coln);
     // 先从使用频率最小的赛道开始检查
     for(int  q = 0; q < coln; q++){
         int j = temp[q].second;
         hash[a][j]++;
         hash[b][j]++;
         use[j] ++;
         // 假设选择赛道j,更新hash && use 数组
         // dif是能容忍的hash值最大的最大最小值的差
         int dif = coln <= 4 ? 3 : 2;
         if(differ(hash[a]) <= dif && differ(hash[b]) <= dif) {
             int i = expt,cost = 0;
             if(ans[i][j] == zero && !_vis[a][i] && !_vis[b][i]) 
                 // tight_col是代表列数 <=2
                 if(tight_col || i == 0 || !conflict(ans[i-1][j],a,b)){
                     _vis[a][i] = 1;
                     _vis[b][i] = 1;
                     ans[i][j] = p;
                     dfs(x,y+1,c+1);
                     if(flag) return ;
                     _vis[a][i] = 0;
                     _vis[b][i] = 0;
                     ans[i][j] = zero;
                 }
         }
         // 搜索结束,回溯
         use[j]--;
         hash[a][j]--;
         hash[b][j]--;
     }
 }
コード例 #30
0
ファイル: row_mvcc.cpp プロジェクト: rharding6373/ddbms
RC Row_mvcc::access(TxnManager * txn, TsType type, row_t * row) {
	RC rc = RCOK;
	ts_t ts = txn->get_timestamp();
	uint64_t starttime = get_sys_clock();

	if (g_central_man)
		glob_manager.lock_row(_row);
	else
		pthread_mutex_lock( latch );
  if (type == R_REQ) {
		// figure out if ts is in interval(prewrite(x))
		bool conf = conflict(type, ts);
		if ( conf && rreq_len < g_max_read_req) {
			rc = WAIT;
      //txn->wait_starttime = get_sys_clock();
        DEBUG("buf R_REQ %ld %ld\n",txn->get_txn_id(),_row->get_primary_key());
			buffer_req(R_REQ, txn);
			txn->ts_ready = false;
		} else if (conf) { 
			rc = Abort;
			printf("\nshould never happen. rreq_len=%ld", rreq_len);
		} else {
			// return results immediately.
			rc = RCOK;
			MVHisEntry * whis = writehis;
			while (whis != NULL && whis->ts > ts) 
				whis = whis->next;
			row_t * ret = (whis == NULL)? 
				_row : whis->row;
			txn->cur_row = ret;
			insert_history(ts, NULL);
			assert(strstr(_row->get_table_name(), ret->get_table_name()));
		}
	} else if (type == P_REQ) {
		if ( conflict(type, ts) ) {
			rc = Abort;
		} else if (preq_len < g_max_pre_req){
        DEBUG("buf P_REQ %ld %ld\n",txn->get_txn_id(),_row->get_primary_key());
			buffer_req(P_REQ, txn);
			rc = RCOK;
		} else  {
			rc = Abort;
		}
	} else if (type == W_REQ) {
		rc = RCOK;
		// the corresponding prewrite request is debuffered.
		insert_history(ts, row);
        DEBUG("debuf %ld %ld\n",txn->get_txn_id(),_row->get_primary_key());
		MVReqEntry * req = debuffer_req(P_REQ, txn);
		assert(req != NULL);
		return_req_entry(req);
		update_buffer(txn);
	} else if (type == XP_REQ) {
        DEBUG("debuf %ld %ld\n",txn->get_txn_id(),_row->get_primary_key());
		MVReqEntry * req = debuffer_req(P_REQ, txn);
		assert (req != NULL);
		return_req_entry(req);
		update_buffer(txn);
	} else 
		assert(false);
	
	if (rc == RCOK) {
		if (whis_len > g_his_recycle_len || rhis_len > g_his_recycle_len) {
			ts_t t_th = glob_manager.get_min_ts(txn->get_thd_id());
			if (readhistail && readhistail->ts < t_th)
				clear_history(R_REQ, t_th);
			// Here is a tricky bug. The oldest transaction might be 
			// reading an even older version whose timestamp < t_th.
			// But we cannot recycle that version because it is still being used.
			// So the HACK here is to make sure that the first version older than
			// t_th not be recycled.
			if (whis_len > 1 && 
				writehistail->prev->ts < t_th) {
				row_t * latest_row = clear_history(W_REQ, t_th);
				if (latest_row != NULL) {
					assert(_row != latest_row);
					_row->copy(latest_row);
				}
			}
		}
	}
	
	uint64_t timespan = get_sys_clock() - starttime;
	txn->txn_stats.cc_time += timespan;
	txn->txn_stats.cc_time_short += timespan;

	if (g_central_man)
		glob_manager.release_row(_row);
	else
		pthread_mutex_unlock( latch );	
		
	return rc;
}