bool VisualViewport::magnifyScaleAroundAnchor(float magnifyDelta, const FloatPoint& anchor) { const float oldPageScale = scale(); const float newPageScale = frameHost().chromeClient().clampPageScaleFactorToLimits( magnifyDelta * oldPageScale); if (newPageScale == oldPageScale) return false; if (!mainFrame() || !mainFrame()->view()) return false; // Keep the center-of-pinch anchor in a stable position over the course // of the magnify. FloatPoint anchorAtOldScale = anchor.scaledBy(1.f / oldPageScale); FloatPoint anchorAtNewScale = anchor.scaledBy(1.f / newPageScale); FloatSize anchorDelta = anchorAtOldScale - anchorAtNewScale; // First try to use the anchor's delta to scroll the FrameView. FloatSize anchorDeltaUnusedByScroll = anchorDelta; if (!frameHost().settings().invertViewportScrollOrder()) { FrameView* view = mainFrame()->view(); DoublePoint oldPosition = view->scrollPositionDouble(); view->scrollBy(DoubleSize(anchorDelta.width(), anchorDelta.height()), UserScroll); DoublePoint newPosition = view->scrollPositionDouble(); anchorDeltaUnusedByScroll -= toFloatSize(newPosition - oldPosition); } // Manually bubble any remaining anchor delta up to the visual viewport. FloatPoint newLocation(location() + anchorDeltaUnusedByScroll); setScaleAndLocation(newPageScale, newLocation); return true; }
void BulletCharacterObject::postTick(const Time& t) { LocationInfo& locinfo = mParent->info(mID); btTransform worldTrans = mGhostObject->getWorldTransform(); btVector3 pos = worldTrans.getOrigin(); TimedMotionVector3f newLocation(t, MotionVector3f(Vector3f(pos.x(), pos.y(), pos.z()), locinfo.props.location().velocity())); btQuaternion rot = worldTrans.getRotation(); TimedMotionQuaternion newOrientation( t, MotionQuaternion( Quaternion(rot.x(), rot.y(), rot.z(), rot.w()), locinfo.props.orientation().velocity() ) ); // Only update and report a change if it's big enough. This allows us to // stop sending updates if the object ends up essentially still. float32 pos_diff = (mParent->location(mID).position(t)-newLocation.position(t)).lengthSquared(); // This test is easy, but also conservative... float32 angle1, angle2; Vector3f axis1, axis2; mParent->orientation(mID).position(t).toAngleAxis(angle1, axis1); newOrientation.position(t).toAngleAxis(angle2, axis2); // FIXME what should this really be? This approach doesn't seem to really // work because we sometimes get 0 vectors and the constants seem odd... bool orient_changed = (axis1.dot(axis2) < 0.9) || (fabs(angle1-angle2) > 3.14159/180); if (pos_diff > 0.001 || orient_changed) { mParent->setLocation(mID, newLocation); mParent->setOrientation(mID, newOrientation); mParent->addUpdate(mID); } }
std::shared_ptr<HeightMap> HeightGrid::map(int latitude, int longitude) { auto findCoordinate = [](int current, int newPoint) -> int { return newPoint > current ? newPoint - 1 : newPoint; }; std::shared_ptr<Grid> grid = std::atomic_load_explicit(&grid_, std::memory_order_consume); auto heightMap = getMap(grid, latitude, longitude); if (!heightMap) { auto& location = grid->first; Point2D<int> newLocation(findCoordinate(location.x(), longitude), findCoordinate(location.y(), latitude)); auto newGrid = std::make_shared<Grid>(newLocation, Grid::second_type()); auto& newData = newGrid->second; for (int row = 0; row < newData.size(); row++) { for (int col = 0; col < newData[row].size(); col++) newData[row][col] = getMap(grid, newLocation.y() + row, newLocation.x() + col); } heightMap = createMap(latitude, longitude); newData[latitude - newLocation.y()][longitude - newLocation.x()] = heightMap; std::atomic_store_explicit(&grid_, std::move(newGrid), std::memory_order_release); } return heightMap; }
bool VisualViewport::magnifyScaleAroundAnchor(float magnifyDelta, const FloatPoint& anchor) { const float oldPageScale = scale(); const float newPageScale = frameHost().chromeClient().clampPageScaleFactorToLimits(magnifyDelta * oldPageScale); if (newPageScale == oldPageScale) return false; if (!mainFrame() || !mainFrame()->view()) return false; // Keep the center-of-pinch anchor in a stable position over the course // of the magnify. FloatPoint anchorAtOldScale = anchor.scaledBy(1.f / oldPageScale); FloatPoint anchorAtNewScale = anchor.scaledBy(1.f / newPageScale); FloatSize anchorDelta = anchorAtOldScale - anchorAtNewScale; // First try to use the anchor's delta to scroll the FrameView. FloatSize anchorDeltaUnusedByScroll = anchorDelta; // Manually bubble any remaining anchor delta up to the visual viewport. FloatPoint newLocation(FloatPoint(getScrollOffset()) + anchorDeltaUnusedByScroll); setScaleAndLocation(newPageScale, newLocation); return true; }
void BulletRigidBodyObject::updateObjectFromBullet(const btTransform& worldTrans) { assert(mFixed == false); LocationInfo& locinfo = mParent->info(mID); btVector3 pos = worldTrans.getOrigin(); btVector3 vel = mObjRigidBody->getLinearVelocity(); TimedMotionVector3f newLocation(mParent->context()->simTime(), MotionVector3f(Vector3f(pos.x(), pos.y(), pos.z()), Vector3f(vel.x(), vel.y(), vel.z()))); mParent->setLocation(mID, newLocation); BULLETLOG(insane, "Updating " << mID << " to velocity " << vel.x() << " " << vel.y() << " " << vel.z()); btQuaternion rot = worldTrans.getRotation(); btVector3 angvel = mObjRigidBody->getAngularVelocity(); Vector3f angvel_siri(angvel.x(), angvel.y(), angvel.z()); float angvel_angle = angvel_siri.normalizeThis(); TimedMotionQuaternion newOrientation( mParent->context()->simTime(), MotionQuaternion( Quaternion(rot.x(), rot.y(), rot.z(), rot.w()), Quaternion(angvel_siri, angvel_angle) ) ); mParent->setOrientation(mID, newOrientation); mParent->addUpdate(mID); }
int main(void) { int i, j; int found_src, found_dest; char src_name[MAXNAME + 1]; char dest_name[MAXNAME + 1]; int distance; while (scanf("%s to %s = %d", src_name, dest_name, &distance) != EOF) { found_src = found_dest = 0; min_distance += distance; for (i = 0; i < size; i++) { if (!strcmp(src_name, locations[i].name)) { found_src = 1; break; } } for (j = 0; j < size; j++) { if (!strcmp(dest_name, locations[j].name)) { found_dest = 1; break; } } if (!found_src) { i = newLocation(src_name); } if (!found_dest) { j = newLocation(dest_name); } addConnection(&locations[i], &locations[j], distance); } for(i = 0; i < size; i++) tryPath(locations + i, 0, 0); printf("Minimum path: %d\n", min_distance); printPath(min_path, size); printf("Maximum path: %d\n", max_distance); printPath(max_path, size); return 0; }
void AbstractPiece::Move(int incCol, int incRow, int incDep) { VoxelLocation newLocation(location); newLocation.col += incCol; newLocation.row += incRow; newLocation.dep += incDep; location = newLocation; }
void LayoutRect::uniteEvenIfEmpty(const LayoutRect& other) { LayoutPoint newLocation(std::min(x(), other.x()), std::min(y(), other.y())); LayoutPoint newMaxPoint(std::max(maxX(), other.maxX()), std::max(maxY(), other.maxY())); m_location = newLocation; m_size = newMaxPoint - newLocation; }
void LayoutRect::intersect(const LayoutRect& other) { LayoutPoint newLocation(std::max(x(), other.x()), std::max(y(), other.y())); LayoutPoint newMaxPoint(std::min(maxX(), other.maxX()), std::min(maxY(), other.maxY())); // Return a clean empty rectangle for non-intersecting cases. if (newLocation.x() >= newMaxPoint.x() || newLocation.y() >= newMaxPoint.y()) { newLocation = LayoutPoint(0, 0); newMaxPoint = LayoutPoint(0, 0); } m_location = newLocation; m_size = newMaxPoint - newLocation; }
bool LayoutRect::inclusiveIntersect(const LayoutRect& other) { LayoutPoint newLocation(std::max(x(), other.x()), std::max(y(), other.y())); LayoutPoint newMaxPoint(std::min(maxX(), other.maxX()), std::min(maxY(), other.maxY())); if (newLocation.x() > newMaxPoint.x() || newLocation.y() > newMaxPoint.y()) { *this = LayoutRect(); return false; } m_location = newLocation; m_size = newMaxPoint - newLocation; return true; }
//! Pick a random place on the screen to move the dialog. This is supposed to work on multiple monitors //! but I've only been able to test it with two. void PoppyUpper::moveItSomewhere() { // get the desktop object so we can get geometry to figure out where this will land QDesktopWidget *theDesktop = QApplication::desktop(); // Pick from any number of screens! unsigned int screens = theDesktop->screenCount(); unsigned int whichScreen = Randoid::getRand(0, screens - 1); // screens start at zero const QRect screenGeometry = theDesktop->availableGeometry(whichScreen); const QRect dialogGeometry = this->geometry(); bool positioned = false; //! Pick a random point on the screen QRect newRect; Randoid screenRandThingX(screenGeometry.topLeft().x(), screenGeometry.topRight().x()); Randoid screenRandThingY(screenGeometry.topLeft().y(), screenGeometry.bottomLeft().y()); //! \todo This loop can probably be eliminated and replaced with some calculation that would choose random coordinates //! such that the dialog doesn't get clipped by an edge of the screen do { // pick a point on the screen... this will be the top left point QPoint newLocation(screenRandThingX.getRand(), screenRandThingY.getRand()); qDebug() << "newLocation " << newLocation; // Now figure out the bottom right point for the new QRect QPoint bottomRight(newLocation.x() + dialogGeometry.width() - 1, newLocation.y() + dialogGeometry.height() - 1); // Now create a QRect that represents the dialog at this position newRect = QRect(newLocation, bottomRight); qDebug() << "newRect " << newRect; // Now, if this new rectangle is completely contained within the screen geometry, we're done! positioned = screenGeometry.contains(newRect, true); // If not, we try again } while (!positioned); qDebug() << "Old location: " << dialogGeometry; qDebug() << "New location: " << newRect; setGeometry(newRect); }
void LayoutRect::uniteIfNonZero(const LayoutRect& other) { // Handle empty special cases first. if (!other.width() && !other.height()) return; if (!width() && !height()) { *this = other; return; } LayoutPoint newLocation(std::min(x(), other.x()), std::min(y(), other.y())); LayoutPoint newMaxPoint(std::max(maxX(), other.maxX()), std::max(maxY(), other.maxY())); m_location = newLocation; m_size = newMaxPoint - newLocation; }
void LayoutRect::unite(const LayoutRect& other) { // Handle empty special cases first. if (other.isEmpty()) return; if (isEmpty()) { *this = other; return; } LayoutPoint newLocation(std::min(x(), other.x()), std::min(y(), other.y())); LayoutPoint newMaxPoint(std::max(maxX(), other.maxX()), std::max(maxY(), other.maxY())); m_location = newLocation; m_size = newMaxPoint - newLocation; }
void PropertyTreeViewer::import() { QString filePath = QFileDialog::getOpenFileName(); QFileInfo fileInfo(filePath); if(!fileInfo.exists()) return; QString fileName = fileInfo.fileName(); QString newLocation(m_loader->projectDir() + "/" + fileName); if(QFileInfo(newLocation).exists()) { // TODO AM add check. Some dialog or smth like that. } QFile::copy(filePath, newLocation); auto rSide = m_loader->getOrCreateRightSide(m_leftSideTreeId, fileName); addOneRSide(rSide->id()); }
int PicInputHandler::HandleMouseEvent(int x, int y, const sf::Mouse::Button btn, const sf::Event::EventType event) { sf::Vector2f mousePos = app->convertCoords(sf::Vector2i(x, y)); sf::Vector2i newLocation( (mousePos.x - game->PixOffsetX()) / game->CellLength(), (mousePos.y - game->PixOffsetY()) / game->CellLength()); int op = OP_NONE; /* only handle mouse events in game board area */ if (!game->IsInBounds(newLocation)) { return OP_NONE; } switch (event) { case sf::Event::MouseButtonPressed: if (btn == sf::Mouse::Left) { op = (game->GetStateAt(newLocation) == BOARD_CLEAN) ? OP_FORCE_HIT : OP_FORCE_HIT2CLEAR; } else if (btn == sf::Mouse::Right) { op = (game->GetStateAt(newLocation) == BOARD_CLEAN) ? OP_FORCE_MARK : OP_FORCE_MARK2CLEAR; } dragHelper.begin(newLocation, btn, op); break; case sf::Event::MouseMoved: if (btn == sf::Mouse::Left || btn == sf::Mouse::Right) { /* only run drag logic if a mousebutton is pressed, otherwise only set location */ newLocation = dragHelper.update(newLocation); if (dragHelper.nothingTobeDone()) { return OP_NONE; } } break; default: break; } game->TrySetLocation(newLocation); if (btn == sf::Mouse::Left || btn == sf::Mouse::Right) { return dragHelper.getOperation(); } return OP_NONE; }
/** * moveToPoint function, is called by the json service functions and the old deprecated service functions. * * @param x destination x-coordinate * @param y destination y-coordinate * @param z destination z-coordinate * @param maxAcceleration maximum acceleration * * @return false if the path is illegal, true if the motion is executed succesfully. **/ bool stewartGoughNodeNamespace::StewartGoughNode::moveToPoint(rexos_stewart_gough::StewartGoughLocation to, double maxAcceleration){ if(maxAcceleration > 20){ maxAcceleration = 20; } REXOS_INFO_STREAM("moveTo rotation: " << to.rotationX << " " << to.rotationY << " " << to.rotationZ << std::endl); rexos_stewart_gough::StewartGoughLocation oldLocation(stewartGough->getEffectorLocation()); rexos_stewart_gough::StewartGoughLocation newLocation(to); try { stewartGough->moveTo(newLocation, maxAcceleration); return true; } catch(std::out_of_range& ex){ REXOS_INFO_STREAM(ex.what()); return false; } }
// ----------------------------------------------------------------------------- // CLandmarksEditDialog::SaveFormDataL // // (other items were commented in a header). // ----------------------------------------------------------------------------- // TBool CLandmarksEditDialog::SaveFormDataL() { CEikEdwin* editor = NULL; // Fetch name TBuf<KPosLmMaxTextFieldLength> name; editor = static_cast <CEikEdwin*> (Control(ELandmarkNameField)); editor->GetText(name); // Fetch description HBufC* descBuf = HBufC::NewLC(KPosLmMaxDescriptionLength); TPtr desc = descBuf->Des(); editor = static_cast <CEikEdwin*> (Control(ELandmarkDescField)); editor->GetText(desc); // Fetch existing location TLocality existingLocation; TBool locationExists = (iLandmark->GetPosition(existingLocation) == KErrNone); TRealX floatFieldValue; // Fetch Latitude TReal latitude = existingLocation.Latitude(); if (iIsRealValueEdited[ELatitudeEditor] || !locationExists) { FetchFloatL(floatFieldValue, ELandmarkLatitudeField, R_LMREFAPP_LATITUDE_ERROR); floatFieldValue.GetTReal(latitude); } // Fetch Longitude TReal longitude = existingLocation.Longitude(); if (iIsRealValueEdited[ELongitudeEditor] || !locationExists) { FetchFloatL(floatFieldValue, ELandmarkLongitudeField, R_LMREFAPP_LONGITUDE_ERROR); floatFieldValue.GetTReal(longitude); } // Fetch Altitude TReal32 altitude = existingLocation.Altitude(); if (iIsRealValueEdited[EAltitudeEditor] || !locationExists) { FetchFloatL(floatFieldValue, ELandmarkAltitudeField, R_LMREFAPP_ALTITUDE_ERROR); floatFieldValue.GetTReal(altitude); } // Fetch horizontal accuracy TReal32 horAcc = existingLocation.HorizontalAccuracy(); if (iIsRealValueEdited[EHorizontalAccEditor] || !locationExists) { FetchFloatL(floatFieldValue, ELandmarkHorAccField, R_LMREFAPP_HOR_ACC_ERROR); floatFieldValue.GetTReal(horAcc); } // Fetch vertical accuracy TReal32 verAcc = existingLocation.VerticalAccuracy(); if (iIsRealValueEdited[EVerticalAccEditor] || !locationExists) { FetchFloatL(floatFieldValue, ELandmarkVerAccField, R_LMREFAPP_VER_ACC_ERROR); floatFieldValue.GetTReal(verAcc); } // Fetch Coverage Radius TReal32 radius; TInt radiusExists = (iLandmark->GetCoverageRadius(radius) == KErrNone); if (iIsRealValueEdited[ERadiusEditor] || !radiusExists) { FetchFloatL(floatFieldValue, ELandmarkRadiusField, R_LMREFAPP_RADIUS_ERROR); floatFieldValue.GetTReal(radius); } // Fetch street TBuf<KPosLmMaxTextFieldLength> street; editor = static_cast <CEikEdwin*> (Control(ELandmarkStreetField)); editor->GetText(street); // Fetch postal code TBuf<KPosLmMaxTextFieldLength> postalCode; editor = static_cast <CEikEdwin*> (Control(ELandmarkPostalField)); editor->GetText(postalCode); // Fetch city TBuf<KPosLmMaxTextFieldLength> city; editor = static_cast <CEikEdwin*> (Control(ELandmarkCityField)); editor->GetText(city); // Fetch country TBuf<KPosLmMaxTextFieldLength> country; editor = static_cast <CEikEdwin*> (Control(ELandmarkCountryField)); editor->GetText(country); // Update category iLandmark->RemoveLandmarkAttributes(CPosLandmark::ECategoryInfo); for (TInt i = 0; i < iCategoryIds.Count(); i++) { iLandmark->AddCategoryL(iCategoryIds[i]); } // Check that at least some data is entered if (!name.Length() && !desc.Length() && !street.Length() && !city.Length() && !country.Length() && !postalCode.Length() && !iCategoryIds.Count() && Math::IsNaN(latitude) && Math::IsNaN(longitude) && Math::IsNaN(altitude) && Math::IsNaN(radius) && Math::IsNaN(horAcc) && Math::IsNaN(verAcc)) { NotifyErrorToUserL(R_LMREFAPP_EMPTY_LANDMARK); } // Update name iLandmark->SetLandmarkNameL(name); // Update description iLandmark->SetLandmarkDescriptionL(desc); CleanupStack::PopAndDestroy(descBuf); // Update coverage radius if (!Math::IsNaN(radius) && radius < 0) { NotifyErrorToUserL(R_LMREFAPP_RADIUS_ERROR); } iLandmark->SetCoverageRadius(radius); // Update street iLandmark->SetPositionFieldL(EPositionFieldStreet, street); // Update postal code iLandmark->SetPositionFieldL(EPositionFieldPostalCode, postalCode); // Update city iLandmark->SetPositionFieldL(EPositionFieldCity, city); // Update country iLandmark->SetPositionFieldL(EPositionFieldCountry, country); // Update location. There are some rules specified by TLocality and // TCoordinate how to update a location. These rules are taken into // account below when validating the location data. if (Math::IsNaN(latitude) && Math::IsNaN(longitude)) { // If lat long are undefined, then alt and hAcc // must be undefined if (!Math::IsNaN(horAcc)) { NotifyErrorToUserL(R_LMREFAPP_HACC_LAT_LONG_ERROR); } else if (!Math::IsNaN(altitude)) { NotifyErrorToUserL(R_LMREFAPP_ALT_LAT_LONG_ERROR); } else if (!Math::IsNaN(verAcc)) { NotifyErrorToUserL(R_LMREFAPP_VACC_ALT_ERROR); } else { // None position fields are set, Remove position info. iLandmark->RemoveLandmarkAttributes(CPosLandmark::EPosition); } } else if (!Math::IsNaN(latitude) && !Math::IsNaN(longitude)) { // If lat long are defined, hAcc must be positive if defined if (!Math::IsNaN(horAcc) && horAcc < 0) { NotifyErrorToUserL(R_LMREFAPP_HOR_ACC_ERROR); } // if altitude is undefined, then vertical accuracy // must be undefined if (Math::IsNaN(altitude) && !Math::IsNaN(verAcc)) { NotifyErrorToUserL(R_LMREFAPP_VACC_ALT_ERROR); } // vertical accuracy must be positive if defined if (!Math::IsNaN(verAcc) && verAcc < 0) { NotifyErrorToUserL(R_LMREFAPP_VER_ACC_ERROR); } // We are allowed to set the new locality TCoordinate coordinate(latitude, longitude, altitude); TLocality newLocation(coordinate, horAcc, verAcc); iLandmark->SetPositionL(newLocation); } else { // Inform user that no valid lat/long has been entered NotifyErrorToUserL(R_LMREFAPP_LAT_LONG_ERROR); } iEdited = ETrue; return ETrue; }
bool PlayerCharacterEntity::goToNearestEmptyTile(int fromX, int fromY) { // set an immediate GO_TO instruction if a suitable empty tile is found set<coord> searched; list<coord> toSearch; toSearch.push_front(coord(fromX, fromY)); while (!toSearch.empty()) { // get head of toSearch coord currentLocation = toSearch.front(); toSearch.pop_front(); // is this an empty tile we want? if (!staticEntityAtLocation(currentLocation.first, currentLocation.second)) { // it is, set GO_TO instruction and be happy AIInstruction * ins = new AIInstruction(AIInstruction::GO_TO, 0, getType(), currentLocation.first, currentLocation.second); m_insList.push_front(ins); return true; } else { // there is a static entity here, add valid adjoining tiles to toSearch list searched.insert(currentLocation); Map * staticMap = Map::getInstance(); for (int i = 0; i < 4; ++i) { int x, y; x = currentLocation.first; y = currentLocation.second; switch (i) { case 0: x++; break; case 1: x--; break; case 2: y++; break; case 3: y--; break; } if (staticMap->staticTileAt(x, y) == Map::EMPTY) { coord newLocation(x, y); // check searched set if (searched.find(newLocation) == searched.end()) { toSearch.push_back(newLocation); } } } // end for 0..3 } // end else static entry found } // end while toSearch not-empty return false; }
/****************************************************************************** * Class LInfoWindow :: LInfoWindow - Constructor for the information window * * given an employee. * * * * Define yourself as an IFrameWindow * * Create title * * Create notebook * * Create help window * * Store pointer to container object * * Store query flag * ******************************************************************************/ LInfoWindow::LInfoWindow ( unsigned long windowId, IWindow* parent, IWindow* owner, IPoint bottomLeft, LCnrObject* object, LEmployeeData& employee, bool isQuery ) :IFrameWindow ( windowId, parent, owner, IRectangle(), classDefaultStyle | dialogBackground | dialogBorder ), title ( this ), notebook ( this, this, employee, isQuery ), help ( ID_HELP_TABLE3, this ), pObject ( object ), isAQuery ( isQuery ) { /*----------------------------------------------------------------------------- | If this window was launched from a cnr object, | | - set as open | | - increment usage count | -----------------------------------------------------------------------------*/ if ( pObject ) { pObject->setOpen(); pObject->incrementUsage(); } /*----------------------------------------------------------------------------- | Attempt to load the help file | -----------------------------------------------------------------------------*/ try { help.addLibraries( "lanchelp.hlp" ); help.setTitle( STR_HELP_TITLE ); } catch( ... ) {} /*----------------------------------------------------------------------------- | Handle command events for this frame window | -----------------------------------------------------------------------------*/ ICommandHandler::handleEventsFor( this ); /*----------------------------------------------------------------------------- | Determine the title for this frame window | -----------------------------------------------------------------------------*/ if ( isQuery ) title.setTitleText( STR_MAIN_TITLE, STR_QUERY_INFO_WINDOW ); else if ( ! employee.employeeNumber().length() ) title.setTitleText( STR_MAIN_TITLE, STR_NEW_INFO_WINDOW ); else title.setTitleText( IApplication::current().userResourceLibrary(). loadString( STR_MAIN_TITLE ), IString( employee.lastName() + ", " + employee.firstName() ) ); /*----------------------------------------------------------------------------- | Set the frame's icon | | Set the frame's client to be the notebook | -----------------------------------------------------------------------------*/ setIcon( ID_ICON_PERSON4 ); setClient( ¬ebook ); /*----------------------------------------------------------------------------- | Resize the window based on the minimum size of the notebook | -----------------------------------------------------------------------------*/ moveSizeToClient( IRectangle( bottomLeft, notebook.minimumSize() ) ); /*----------------------------------------------------------------------------- | Move the frame window to the best location for the display size | | Set the focus to the frame | | Show the frame | -----------------------------------------------------------------------------*/ IPoint newLocation( LFrameWindow::bestFit( this ) ); moveTo( newLocation ); if ( ( ! newLocation.x() ) || ( !newLocation.y() ) ) maximize(); setFocus().show(); }
/****************************************************************************** * Class LInfoWindow :: LInfoWindow - Constructor for the information window * * given a query string. * * * * Define yourself as an IFrameWindow * * Create title * * Create notebook * * Create help window * * Store pointer to container object * * Store query flag * ******************************************************************************/ LInfoWindow::LInfoWindow ( unsigned long windowId, IWindow* parent, IWindow* owner, IPoint bottomLeft, LMainCnr* cnr, LCnrObject* object, IString queryName ) :IFrameWindow ( windowId, parent, owner, IRectangle(), classDefaultStyle | dialogBackground | dialogBorder ), title ( this ), notebook ( this, this, cnr, queryName ), help ( ID_HELP_TABLE3, this ), pObject ( object ), isAQuery ( true ) { /*----------------------------------------------------------------------------- | If this window was launched from a valid cnr object, | | - set as open | | - increment usage count | -----------------------------------------------------------------------------*/ if ( pObject ) { pObject->setOpen(); pObject->incrementUsage(); } /*----------------------------------------------------------------------------- | Attempt to load the help file | -----------------------------------------------------------------------------*/ try { help.addLibraries( "lanchelp.hlp" ); help.setTitle( STR_HELP_TITLE ); } catch( ... ) {} /*----------------------------------------------------------------------------- | Handle command events for this frame window | -----------------------------------------------------------------------------*/ ICommandHandler::handleEventsFor( this ); /*----------------------------------------------------------------------------- | Set the title of this frame window to indicate a query | -----------------------------------------------------------------------------*/ title.setTitleText( STR_MAIN_TITLE, STR_QUERY_INFO_WINDOW ); /*----------------------------------------------------------------------------- | Set the frame's icon | | Set the frame's client to be the notebook | -----------------------------------------------------------------------------*/ setIcon( ID_ICON_PERSON4 ); setClient( ¬ebook ); /*----------------------------------------------------------------------------- | Resize the window based on the minimum size of the notebook | -----------------------------------------------------------------------------*/ moveSizeToClient( IRectangle( bottomLeft, notebook.minimumSize() ) ); /*----------------------------------------------------------------------------- | Move the frame window to the best location for the display size | | Set the focus to the frame | | Show the frame | -----------------------------------------------------------------------------*/ IPoint newLocation( LFrameWindow::bestFit( this ) ); moveTo( newLocation ); if ( ( !newLocation.x() ) || ( ! newLocation.y() ) ) maximize(); setFocus().show(); }
/* Updates computer model Uses estimated distance travled, angle, to calculate where robot is */ void updateModel(double phi) { globalLoc = newLocation(globalLoc, estDisTraveled, phi); }
bool PlayerCharacterEntity::goNumTilesAway(int numToMove) { // set an immediate GO_TO instruction if a suitable tile is found set<coord> searched; list<pair<int,coord> > toSearch; toSearch.push_front(pair<int, coord>(0, coord(getTileX(), getTileY()))); while (!toSearch.empty()) { // get head of toSearch pair<int, coord> currentLocation = toSearch.front(); toSearch.pop_front(); // is this the tile we want? if (currentLocation.first >= numToMove) { // it is, set GO_TO instruction and be happy AIInstruction * ins = new AIInstruction(AIInstruction::GO_TO, 0, getType(), currentLocation.second.first, currentLocation.second.second); m_insList.push_front(ins); return true; } else { // add valid adjoining tiles to toSearch list searched.insert(currentLocation.second); Map * staticMap = Map::getInstance(); AIGameView * view = AIGameView::getInstance(); for (int i = 0; i < 4; ++i) { int x, y; x = currentLocation.second.first; y = currentLocation.second.second; switch (i) { case 0: x++; break; case 1: x--; break; case 2: y++; break; case 3: y--; break; } if (staticMap->staticTileAt(x, y) == Map::EMPTY) { // check for hostile mines bool badMineFound = false; vector<EntityInfo> info = view->getEntityInfoAtLocation(x, y); vector<EntityInfo>::iterator it; for (it = info.begin(); it != info.end(); ++it) { if (it->type == MINE && it->team != getTeam()) { badMineFound = true; break; } } if (badMineFound) { continue; } coord newCoord(x, y); pair<int, coord> newLocation(currentLocation.first + 1, newCoord); // check searched set if (searched.find(newCoord) == searched.end()) { toSearch.push_back(newLocation); } } } // end for 0..3 } // end else static entry found } // end while toSearch not-empty return false; }
int Caller::loadEntries( const std::string path) { std::string nextLine; std::string key; std::string chr; std::string refBase; int readDepth; int pos; // Open the sample file std::ifstream inputFile( path.c_str()); if( !inputFile.is_open()) { perror( "Error opening input readcount file"); exit( 1); } // For each line in the sample file (which will correspond to a genomic location) while( std::getline( inputFile, nextLine)) { // Split the line into tokens separated by whitespace (for columns, since this is a tab delimited file) std::istringstream strStream( nextLine); std::istream_iterator<std::string> begin( strStream), end; std::vector<std::string> stringTokens( begin, end); // Get all main fields chr = stringTokens[0]; pos = atoi( stringTokens[1].c_str()); refBase = stringTokens[2]; refBase[0] = toupper( refBase[0]); readDepth = atoi( stringTokens[3].c_str()); // Generate the key, (chr:pos) key = stringTokens[0] + ":" + stringTokens[1]; if( key == "") { std::cout << "Empty key" << std::endl; } // Create the base ReadcountEntry object ReadcountEntry nextReadcountEntry( refBase, readDepth); // Get all subfields for each allele, the 5th column (stringTokens[4]) is garbage due to a bug with the bam-readcount program, ignore it for( int i = 5; i < stringTokens.size(); i++) { std::vector<std::string> nextSubTokens = Common::split( stringTokens[i], ":", true); // Create the Allele objects and add them to the current ReadcountEntry object std::string base = nextSubTokens[0]; int count = atoi( nextSubTokens[1].c_str()); double avgMappingQuality = atof( nextSubTokens[2].c_str()); double avgBaseQuality = atof( nextSubTokens[3].c_str()); double avgSEMappingQuality = atof( nextSubTokens[4].c_str()); int numPlusStrand = atoi( nextSubTokens[5].c_str()); int numMinusStrand = atoi( nextSubTokens[6].c_str()); double avgPosAsFraction = atof( nextSubTokens[7].c_str()); double avgNumMismatchesAsFraction = atof( nextSubTokens[8].c_str()); double avgSumMismatchQualities = atof( nextSubTokens[9].c_str()); int numQ2ContainingReads = atoi( nextSubTokens[10].c_str()); double avgDistanceToQ2StartInQ2Reads = atof( nextSubTokens[11].c_str()); double avgClippedLength = atof( nextSubTokens[12].c_str()); double avgDistanceToEffective3pEnd = atof( nextSubTokens[13].c_str()); bool variant = false; if( base != refBase) { variant = true; } double percentage; if( readDepth != 0) { percentage = ( double) count / ( double) readDepth * 100; } else { percentage = 0; } Allele nextAllele( base, count, avgMappingQuality, avgBaseQuality, avgSEMappingQuality, numPlusStrand, numMinusStrand, avgPosAsFraction, avgNumMismatchesAsFraction, avgSumMismatchQualities, numQ2ContainingReads, avgDistanceToQ2StartInQ2Reads, avgClippedLength, avgDistanceToEffective3pEnd, percentage, variant); nextReadcountEntry.addAllele( nextAllele); } // Now, the ReadcountEntry object is filled, so we can create the Sample object nextReadcountEntry.setMostFreqVariantAllele(); Sample nextSample( path, nextReadcountEntry); // Finally, add the Sample object to the Location object, // Check if the Location object with the current key exists in the hash table std::unordered_map<std::string, Location>::iterator iter = locationTable.find( key); if( iter == locationTable.end()) { // If it does not exist, create the Location object Location newLocation( chr, pos); // Add the new Sample to the Location object newLocation.addSample( nextSample); // Insert the new key-Location pair to the hash table std::pair<std::string, Location> newKeyPair( key, newLocation); locationTable.insert( newKeyPair); } else { bool sampleExists = false; std::vector<Sample> samples = ( iter->second).getSamples(); for( int j = 0; j < samples.size(); j++) { if( samples[j].getSampleName() == nextSample.getSampleName()) { sampleExists = true; } } if( !sampleExists) { ( iter->second).addSample( nextSample); } } } // Check if the file was read correctly if( inputFile.bad()) { perror( "Error reading input readcount file"); } // Close the input sample file inputFile.close(); }
PRBool nsEudoraWin32::GetMailboxNameHierarchy( const nsACString& pEudoraLocation, const char* pEudoraFilePath, nsCString& nameHierarchy) { if (pEudoraLocation.IsEmpty() || !pEudoraFilePath || !*pEudoraFilePath) return PR_FALSE; nsresult rv; nsCOMPtr <nsILocalFile> descMap = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID); rv = descMap->InitWithNativePath(pEudoraLocation); NS_ENSURE_SUCCESS(rv, PR_FALSE); rv = descMap->AppendNative(NS_LITERAL_CSTRING("descmap.pce")); NS_ENSURE_SUCCESS(rv, PR_FALSE); nsCOMPtr <nsIInputStream> inputStream; rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), descMap); NS_ENSURE_SUCCESS(rv, PR_FALSE); nsCOMPtr<nsILineInputStream> lineStream(do_QueryInterface(inputStream, &rv)); NS_ENSURE_SUCCESS(rv, PR_FALSE); PRInt32 pathLength; const char* backslash = strchr(pEudoraFilePath, '\\'); if (backslash) pathLength = backslash - pEudoraFilePath; else pathLength = strlen(pEudoraFilePath); PRBool more = PR_TRUE; nsCAutoString buf; while (more) { rv = lineStream->ReadLine(buf, &more); NS_ENSURE_SUCCESS(rv, PR_FALSE); PRInt32 iNameEnd = buf.FindChar(','); if (iNameEnd < 0) continue; const nsACString& name = Substring(buf, 0, iNameEnd); PRInt32 iPathEnd = buf.FindChar(',', iNameEnd + 1); if (iPathEnd < 0) continue; const nsACString& path = Substring(buf, iNameEnd + 1, iPathEnd - iNameEnd - 1); const char type = buf[iPathEnd + 1]; if (strnicmp(path.BeginReading(), pEudoraFilePath, pathLength) == 0 && path.Length() == pathLength) { nameHierarchy += "\\"; nameHierarchy += name; if (pEudoraFilePath[pathLength] == 0) return PR_TRUE; if (type != 'F') { // Something went wrong. We've matched a mailbox, but the // hierarchical name says we've got more folders to traverse. return PR_FALSE; } nsCString newLocation(pEudoraLocation); newLocation += '\\'; newLocation += path; return GetMailboxNameHierarchy(newLocation, pEudoraFilePath + pathLength + 1, nameHierarchy); } } return PR_FALSE; }