Search Results

Search found 440 results on 18 pages for 'abs'.

Page 10/18 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • getting page info from a webpage while sharing facebook style

    - by user556167
    Hi all. I am writing an app to share a page to friends when browsing. To this end, I can get the url of the page to my app and display it on the screen. Could anyone tell me, how to improve this, to show the headline of the page and the picture of a page as it appears when a page is being shared to friends on facebook. Here is the code to get and display the url of the page: Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); String mNewLinkUrl=""; if (action != null && type != null && Intent.ACTION_SEND.equals(action) && "text/plain".equals(type)){ mNewLinkUrl = intent.getStringExtra(Intent.EXTRA_TEXT); } TextView ptext = (TextView) findViewById(R.id.pagetext); ptext.append("\n"+mNewLinkUrl); Any insight will be appreciated. //update 1 found a method: use Jsoup to download the html as a Document. And use Elements and Element to get the data. For eg, the following is the code to get the links in imports in the html page: Elements imports = doc.select("link[href]"); for (Element link : imports) { Log.d(TAG,"link.tagName()"+link.tagName()+"link.attr(abs:href)"+link.attr("abs:href") +"link.attr(rel)"+link.attr("rel")); } But I am not able to figure out what attributes facebook exactly gets. Can anyone help me in this? Thank you.

    Read the article

  • Storing multiple discarded datas in a single variable using a string accumulator

    - by dan
    For an assignment for my intro to python course, we are to write a program that generates 100 sets of x,y coordinates. X must be a float between -100.0 and 100.0 inclusive, but not 0. Y is Y = ((1/x) * 3070) but if the absolute value of Y is greater than 100, both numbers must be discarded (BUT STORED) and another set generated. The results must be displayed in a table, and then after the table, the discarded results must be shown. The teacher said we should use a "string accumulator" to store the discarded data. This is what I have so far, and I'm stuck at storing the discarded data. # import random.py import random # import math.py import math # define main def main(): x = random.uniform(-100.0, 100.0) while x == 0: x = random.uniform(-100.0, 100.0) y = ((1/x) * 3070) while math.fabs(y) > 100: xDiscarded = yDiscarded = y = ((1/x) * 3070) As you can see, I run into the problem of when abs(y) 100, I'm not too sure how to store the discarded data and let it accumulate every time abs(y) 100. I'm cool with the data being stored as "351.2, 231.1, 152.2" I just don't know how to turn the variable into a string and store it. We haven't learned arrays yet so I can't do that. Any help would be much appreciated. Thanks!

    Read the article

  • Centering Divisions Around Zero

    - by Mark
    I'm trying to create something that sort of resembles a histogram. I'm trying to create buckets from an array. Suppose I have a random array doubles between -10 and 10; this is very simplified. I then want to specify a center point, in this case 0 and the number of buckets. If I want 4 buckets the division would be -10 to -5, -5 to 0, 0 to 5 and 5 to 10. Not that complicated right. Now if I change the min and max to -12 and -9 and as for 4 divisions its more complicated. I either want a division at -3 and 3; it is centered around 0 ; or one at -6 to 0 and 0 to 6. Its not that hard to find the division size = Math.Ceiling((Abs(Max) + Abs(Min)) / Divisions) Then you would basically have an if statement to determine whether you want it centered on 0 or on an edge. You then iterate out from either 0 or DivisionSize/2 depending on the situation. You may not ALWAYS end up with the specified number of divisions but it will be close. Then you iterate through the array and increment the bin count. Does this seem like a good way to go about this? This method would surely work but it does not seem to be the most elegant. I'm curious as to whether the creation of the bins and the counting from the list could be done in a clever class with linq in a more elegant way? Something like creating the bins and then having each bin be a property {get;} that returns list.Count(x=> x >= Lower && x < Upper).

    Read the article

  • How to determine which enemy is hit and destroy it alone

    - by Jon Ferriter
    http://jsfiddle.net/5DB6K/ I have this game being made where you shoot enemies from the sides of the screen. I've got the bullets moving and being removed when they reach the end of the screen (if they didn't hit any enemy) and removing the enemy when they collide with it. //------------collision----------------// if(shot === true){ bulletY = $('.bullet').position().top + 2; bulletX = $('.bullet').position().left + 2; $('.enemy').each(function(){ if($('.enemy').hasClass('smallEnemy')){ enemyY = $(this).position().top + 7; enemyX = $(this).position().left + 7; if(Math.abs(bulletY - enemyY) <= 9 && Math.abs(bulletX - enemyX) <=9){ $(this).remove(); score = score + 40; bulletDestroy(); } } }); } However, the bullet destroys every enemy if the collision check is right which isn't what I want. I want to check if the enemy has the class of either smallEnemy, medEnemy, or lrgEnemy and then do the collision check which is what I thought I had but it doesn't seem to work. Also, the game starts to lag the more and more time goes on. Would anyone know the reason for that?

    Read the article

  • Android Can't get two virtual joysticks to move independently and at the same time

    - by Cole
    @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub float r = 70; float centerLx = (float) (screenWidth*.3425); float centerLy = (float) (screenHeight*.4958); float centerRx = (float) (screenWidth*.6538); float centerRy = (float) (screenHeight*.4917); float dx = 0; float dy = 0; float theta; float c; int action = event.getAction(); int actionCode = action & MotionEvent.ACTION_MASK; int pid = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; int fingerid = event.getPointerId(pid); int x = (int) event.getX(pid); int y = (int) event.getY(pid); c = FloatMath.sqrt(dx*dx + dy*dy); theta = (float) Math.atan(Math.abs(dy/dx)); switch (actionCode) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: //if touching down on left stick, set leftstick ID to this fingerid. if(x < screenWidth/2 && c<r*.8) { lsId = fingerid; dx = x-centerLx; dy = y-centerLy; touchingLs = true; } else if(x > screenWidth/2 && c<r*.8) { rsId = fingerid; dx = x-centerRx; dy = y-centerRy; touchingRs = true; } break; case MotionEvent.ACTION_MOVE: if (touchingLs && fingerid == lsId) { dx = x - centerLx; dy = y - centerLy; }else if (touchingRs && fingerid == rsId) { dx = x - centerRx; dy = y - centerRy; } c = FloatMath.sqrt(dx*dx + dy*dy); theta = (float) Math.atan(Math.abs(dy/dx)); //if touching outside left radius and moving left stick if(c >= r && touchingLs && fingerid == lsId) { if(dx>0 && dy<0) { //top right quadrant lsX = r * FloatMath.cos(theta); lsY = -(r * FloatMath.sin(theta)); Log.i("message", "top right"); } if(dx<0 && dy<0) { //top left quadrant lsX = -(r * FloatMath.cos(theta)); lsY = -(r * FloatMath.sin(theta)); Log.i("message", "top left"); } if(dx<0 && dy>0) { //bottom left quadrant lsX = -(r * FloatMath.cos(theta)); lsY = r * FloatMath.sin(theta); Log.i("message", "bottom left"); } else if(dx > 0 && dy > 0){ //bottom right quadrant lsX = r * FloatMath.cos(theta); lsY = r * FloatMath.sin(theta); Log.i("message", "bottom right"); } } if(c >= r && touchingRs && fingerid == rsId) { if(dx>0 && dy<0) { //top right quadrant rsX = r * FloatMath.cos(theta); rsY = -(r * FloatMath.sin(theta)); Log.i("message", "top right"); } if(dx<0 && dy<0) { //top left quadrant rsX = -(r * FloatMath.cos(theta)); rsY = -(r * FloatMath.sin(theta)); Log.i("message", "top left"); } if(dx<0 && dy>0) { //bottom left quadrant rsX = -(r * FloatMath.cos(theta)); rsY = r * FloatMath.sin(theta); Log.i("message", "bottom left"); } else if(dx > 0 && dy > 0) { rsX = r * FloatMath.cos(theta); rsY = r * FloatMath.sin(theta); Log.i("message", "bottom right"); } } else { if(c < r && touchingLs && fingerid == lsId) { lsX = dx; lsY = dy; } if(c < r && touchingRs && fingerid == rsId){ rsX = dx; rsY = dy; } } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: if (fingerid == lsId) { lsId = -1; lsX = 0; lsY = 0; touchingLs = false; } else if (fingerid == rsId) { rsId = -1; rsX = 0; rsY = 0; touchingRs = false; } break; } return true; } There's a left joystick and a right joystick. Right now only one will move at a time. If someone could set me on the right track I would be incredibly grateful cause I've been having nightmares about this problem.

    Read the article

  • Collision Detection, player correction

    - by DoomStone
    I am having some problems with collision detection, I have 2 types of objects excluding the player. Tiles and what I call MapObjects. The tiles are all 16x16, where the MapObjects can be any size, but in my case they are all 16x16. When my player runs along the mapobjects or tiles, it get verry jaggy. The player is unable to move right, and will get warped forward when moving left. I have found the problem, and that is my collision detection will move the player left/right if colliding the object from the side, and up/down if collision from up/down. Now imagine that my player is sitting on 2 tiles, at (10,12) and (11,12), and the player is mostly standing on the (11,12) tile. The collision detection will first run on then (10,12) tile, it calculates the collision depth, and finds that is is a collision from the side, and therefore move the object to the right. After, it will do the collision detection with (11,12) and it will move the character up. So the player will not fall down, but are unable to move right. And when moving left, the same problem will make the player warp forward. This problem have been bugging me for a few days now, and I just can't find a solution! Here is my code that does the collision detection. public void ApplyObjectCollision(IPhysicsObject obj, List<IComponent> mapObjects, TileMap map) { PhysicsVariables physicsVars = GetPhysicsVariables(); Rectangle bounds = ((IComponent)obj).GetBound(); int leftTile = (int)Math.Floor((float)bounds.Left / map.GetTileSize()); int rightTile = (int)Math.Ceiling(((float)bounds.Right / map.GetTileSize())) - 1; int topTile = (int)Math.Floor((float)bounds.Top / map.GetTileSize()); int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / map.GetTileSize())) - 1; // Reset flag to search for ground collision. obj.IsOnGround = false; // For each potentially colliding tile, for (int y = topTile; y <= bottomTile; ++y) { for (int x = leftTile; x <= rightTile; ++x) { IComponent tile = map.Get(x, y); if (tile != null) { bounds = HandelCollision(obj, tile, bounds, physicsVars); } } } // Handel collision for all Moving objects foreach (IComponent mo in mapObjects) { if (mo == obj) continue; if (mo.GetBound().Intersects(((IComponent)obj).GetBound())) { bounds = HandelCollision(obj, mo, bounds, physicsVars); } } } private Rectangle HandelCollision(IPhysicsObject obj, IComponent objb, Rectangle bounds, PhysicsVaraibales physicsVars) { // If this tile is collidable, SpriteCollision collision = ((IComponent)objb).GetCollisionType(); if (collision != SpriteCollision.Passable) { // Determine collision depth (with direction) and magnitude. Rectangle tileBounds = ((IComponent)objb).GetBound(); Vector2 depth = bounds.GetIntersectionDepth(tileBounds); if (depth != Vector2.Zero) { float absDepthX = Math.Abs(depth.X); float absDepthY = Math.Abs(depth.Y); // Resolve the collision along the shallow axis. if (absDepthY <= absDepthX || collision == SpriteCollision.Platform) { // If we crossed the top of a tile, we are on the ground. if (obj.PreviousBound.Bottom <= tileBounds.Top) obj.IsOnGround = true; // Ignore platforms, unless we are on the ground. if (collision == SpriteCollision.Impassable || obj.IsOnGround) { // Resolve the collision along the Y axis. ((IComponent)obj).Position = new Vector2(((IComponent)obj).Position.X, ((IComponent)obj).Position.Y + depth.Y); // If we hit something about us, remove all velosity upwards if (depth.Y > 0 && obj.IsJumping) { obj.Velocity = new Vector2(obj.Velocity.X, 0); obj.JumpTime = physicsVars.MaxJumpTime; } // Perform further collisions with the new bounds. return ((IComponent)obj).GetBound(); } } else if (collision == SpriteCollision.Impassable) // Ignore platforms. { // Resolve the collision along the X axis. ((IComponent)obj).Position = new Vector2(((IComponent)obj).Position.X + depth.X, ((IComponent)obj).Position.Y); // Perform further collisions with the new bounds. return ((IComponent)obj).GetBound(); } } } return bounds; } Update: I have uploaded the source code, if you want to look that through. I think that my general approach might be wrong when i am working with small tiles, I have also be unable to find any good information on physics and collision detection in Platform games. http://dl.dropbox.com/u/3181816/Sogaard.Games.SuperMario.rar

    Read the article

  • Which of these algorithms is best for my goal?

    - by JonathonG
    I have created a program that restricts the mouse to a certain region based on a black/white bitmap. The program is 100% functional as-is, but uses an inaccurate, albeit fast, algorithm for repositioning the mouse when it strays outside the area. Currently, when the mouse moves outside the area, basically what happens is this: A line is drawn between a pre-defined static point inside the region and the mouse's new position. The point where that line intersects the edge of the allowed area is found. The mouse is moved to that point. This works, but only works perfectly for a perfect circle with the pre-defined point set in the exact center. Unfortunately, this will never be the case. The application will be used with a variety of rectangles and irregular, amorphous shapes. On such shapes, the point where the line drawn intersects the edge will usually not be the closest point on the shape to the mouse. I need to create a new algorithm that finds the closest point to the mouse's new position on the edge of the allowed area. I have several ideas about this, but I am not sure of their validity, in that they may have far too much overhead. While I am not asking for code, it might help to know that I am using Objective C / Cocoa, developing for OS X, as I feel the language being used might affect the efficiency of potential methods. My ideas are: Using a bit of trigonometry to project lines would work, but that would require some kind of intense algorithm to test every point on every line until it found the edge of the region... That seems too resource intensive since there could be something like 200 lines that would have each have to have as many as 200 pixels checked for black/white.... Using something like an A* pathing algorithm to find the shortest path to a black pixel; however, A* seems resource intensive, even though I could probably restrict it to only checking roughly in one direction. It also seems like it will take more time and effort than I have available to spend on this small portion of the much larger project I am working on, correct me if I am wrong and it would not be a significant amount of code (100 lines or around there). Mapping the border of the region before the application begins running the event tap loop. I think I could accomplish this by using my current line-based algorithm to find an edge point and then initiating an algorithm that checks all 8 pixels around that pixel, finds the next border pixel in one direction, and continues to do this until it comes back to the starting pixel. I could then store that data in an array to be used for the entire duration of the program, and have the mouse re-positioning method check the array for the closest pixel on the border to the mouse target position. That last method would presumably execute it's initial border mapping fairly quickly. (It would only have to map between 2,000 and 8,000 pixels, which means 8,000 to 64,000 checked, and I could even permanently store the data to make launching faster.) However, I am uncertain as to how much overhead it would take to scan through that array for the shortest distance for every single mouse move event... I suppose there could be a shortcut to restrict the number of elements in the array that will be checked to a variable number starting with the intersecting point on the line (from my original algorithm), and raise/lower that number to experiment with the overhead/accuracy tradeoff. Please let me know if I am over thinking this and there is an easier way that will work just fine, or which of these methods would be able to execute something like 30 times per second to keep mouse movement smooth, or if you have a better/faster method. I've posted relevant parts of my code below for reference, and included an example of what the area might look like. (I check for color value against a loaded bitmap that is black/white.) // // This part of my code runs every single time the mouse moves. // CGPoint point = CGEventGetLocation(event); float tX = point.x; float tY = point.y; if( is_in_area(tX,tY, mouse_mask)){ // target is inside O.K. area, do nothing }else{ CGPoint target; //point inside restricted region: float iX = 600; // inside x float iY = 500; // inside y // delta to midpoint between iX,iY and tX,tY float dX; float dY; float accuracy = .5; //accuracy to loop until reached do { dX = (tX-iX)/2; dY = (tY-iY)/2; if(is_in_area((tX-dX),(tY-dY),mouse_mask)){ iX += dX; iY += dY; } else { tX -= dX; tY -= dY; } } while (abs(dX)>accuracy || abs(dY)>accuracy); target = CGPointMake(roundf(tX), roundf(tY)); CGDisplayMoveCursorToPoint(CGMainDisplayID(),target); } Here is "is_in_area(int x, int y)" : bool is_in_area(NSInteger x, NSInteger y, NSBitmapImageRep *mouse_mask){ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSUInteger pixel[4]; [mouse_mask getPixel:pixel atX:x y:y]; if(pixel[0]!= 0){ [pool release]; return false; } [pool release]; return true; }

    Read the article

  • Platformer Starter Kit - Collision Issues

    - by Cyral
    I'm having trouble with my game that is based off the XNA Platformer starter kit. My game uses smaller tiles (16x16) then the original (32x40) which I'm thinking may be having an effect on collision (Being it needs to be more precise). Standing on the edge of a tile and jumping causes the player to move off the the tile when he lands. And 80% of the time, when the player lands, he goes flying though SOLID tiles in a diagonal fashion. This is very annoying as it is almost impossible to test other features, when spawning and jumping will result in the player landing in another part of the level or falling off the edge completely. The code is as follows: /// <summary> /// Updates the player's velocity and position based on input, gravity, etc. /// </summary> public void ApplyPhysics(GameTime gameTime) { float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; Vector2 previousPosition = Position; // Base velocity is a combination of horizontal movement control and // acceleration downward due to gravity. velocity.X += movement * MoveAcceleration * elapsed; velocity.Y = MathHelper.Clamp(velocity.Y + GravityAcceleration * elapsed, -MaxFallSpeed, MaxFallSpeed); velocity.Y = DoJump(velocity.Y, gameTime); // Apply pseudo-drag horizontally. if (IsOnGround) velocity.X *= GroundDragFactor; else velocity.X *= AirDragFactor; // Prevent the player from running faster than his top speed. velocity.X = MathHelper.Clamp(velocity.X, -MaxMoveSpeed, MaxMoveSpeed); // Apply velocity. Position += velocity * elapsed; Position = new Vector2((float)Math.Round(Position.X), (float)Math.Round(Position.Y)); // If the player is now colliding with the level, separate them. HandleCollisions(); // If the collision stopped us from moving, reset the velocity to zero. if (Position.X == previousPosition.X) velocity.X = 0; if (Position.Y == previousPosition.Y) velocity.Y = 0; } /// <summary> /// Detects and resolves all collisions between the player and his neighboring /// tiles. When a collision is detected, the player is pushed away along one /// axis to prevent overlapping. There is some special logic for the Y axis to /// handle platforms which behave differently depending on direction of movement. /// </summary> private void HandleCollisions() { // Get the player's bounding rectangle and find neighboring tiles. Rectangle bounds = BoundingRectangle; int leftTile = (int)Math.Floor((float)bounds.Left / Tile.Width); int rightTile = (int)Math.Ceiling(((float)bounds.Right / Tile.Width)) - 1; int topTile = (int)Math.Floor((float)bounds.Top / Tile.Height); int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / Tile.Height)) - 1; // Reset flag to search for ground collision. isOnGround = false; // For each potentially colliding tile, for (int y = topTile; y <= bottomTile; ++y) { for (int x = leftTile; x <= rightTile; ++x) { // If this tile is collidable, ItemCollision collision = Level.GetCollision(x, y); if (collision != ItemCollision.Passable) { // Determine collision depth (with direction) and magnitude. Rectangle tileBounds = Level.GetBounds(x, y); Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds); if (depth != Vector2.Zero) { float absDepthX = Math.Abs(depth.X); float absDepthY = Math.Abs(depth.Y); // Resolve the collision along the shallow axis. if (absDepthY < absDepthX || collision == ItemCollision.Platform) { // If we crossed the top of a tile, we are on the ground. if (previousBottom <= tileBounds.Top) isOnGround = true; // Ignore platforms, unless we are on the ground. if (collision == ItemCollision.Impassable || IsOnGround) { // Resolve the collision along the Y axis. Position = new Vector2(Position.X, Position.Y + depth.Y); // Perform further collisions with the new bounds. bounds = BoundingRectangle; } } else if (collision == ItemCollision.Impassable) // Ignore platforms. { // Resolve the collision along the X axis. Position = new Vector2(Position.X + depth.X, Position.Y); // Perform further collisions with the new bounds. bounds = BoundingRectangle; } } } } } // Save the new bounds bottom. previousBottom = bounds.Bottom; } It also tends to jitter a little bit sometimes, I'm solved some of this with some fixes I found here on stackexchange, But Ive only seen one other case of the flying though blocks problem. This question seems to have a similar problem in the video, but mine is more crazy. Again this is a very annoying bug! Any help would be greatly appreciated! EDIT: Speed stuff // Constants for controling horizontal movement private const float MoveAcceleration = 13000.0f; private const float MaxMoveSpeed = 1750.0f; private const float GroundDragFactor = 0.48f; private const float AirDragFactor = 0.58f; // Constants for controlling vertical movement private const float MaxJumpTime = 0.35f; private const float JumpLaunchVelocity = -3500.0f; private const float GravityAcceleration = 3400.0f; private const float MaxFallSpeed = 550.0f; private const float JumpControlPower = 0.14f;

    Read the article

  • Continuous Movement of gun bullet

    - by Siddharth
    I was using box2d for the movement of the body. When I apply gravity (0,0) the bullet continuously move but when I change gravity to the earth the behavior was changed. I also try to apply continuous force to the bullet body but the behavior was not so good. So please provide any suggestion to continuously move bullet body in earth gravity. currentVelocity = bulletBody.getLinearVelocity(); if (currentVelocity.len() < speed|| currentVelocity.len() > speed + 0.25f) { velocityChange = Math.abs(speed - currentVelocity.len()); currentVelocity.set(currentVelocity.x* velocityChange, currentVelocity.y*velocityChange); bulletBody.applyLinearImpulse(currentVelocity,bulletBody.getWorldCenter()); } I apply above code for the continuous velocity of the body. And also I did not able to find any setGravityScale method in the library.

    Read the article

  • A*, Tile costs and heuristic; How to approach

    - by Kevin Toet
    I'm doing exercises in tile games and AI to improve my programming. I've written a highly unoptimised pathfinder that does the trick and a simple tile class. The first problem i ran into was that the heuristic was rounded to int's which resulted in very straight paths. Resorting a Euclidian Heuristic seemed to fixed it as opposed to use the Manhattan approach. The 2nd problem I ran into was when i tried added tile costs. I was hoping to use the value's of the flags that i set on the tiles but the value's were too small to make the pathfinder consider them a huge obstacle so i increased their value's but that breaks the flags a certain way and no paths were found anymore. So my questions, before posting the code, are: What am I doing wrong that the Manhatten heuristic isnt working? What ways can I store the tile costs? I was hoping to (ab)use the enum flags for this The path finder isnt considering the chance that no path is available, how do i check this? Any code optimisations are welcome as I'd love to improve my coding. public static List<Tile> FindPath( Tile startTile, Tile endTile, Tile[,] map ) { return FindPath( startTile, endTile, map, TileFlags.WALKABLE ); } public static List<Tile> FindPath( Tile startTile, Tile endTile, Tile[,] map, TileFlags acceptedFlags ) { List<Tile> open = new List<Tile>(); List<Tile> closed = new List<Tile>(); open.Add( startTile ); Tile tileToCheck; do { tileToCheck = open[0]; closed.Add( tileToCheck ); open.Remove( tileToCheck ); for( int i = 0; i < tileToCheck.neighbors.Count; i++ ) { Tile tile = tileToCheck.neighbors[ i ]; //has the node been processed if( !closed.Contains( tile ) && ( tile.flags & acceptedFlags ) != 0 ) { //Not in the open list? if( !open.Contains( tile ) ) { //Set G int G = 10; G += tileToCheck.G; //Set Parent tile.parentX = tileToCheck.x; tile.parentY = tileToCheck.y; tile.G = G; //tile.H = Math.Abs(endTile.x - tile.x ) + Math.Abs( endTile.y - tile.y ) * 10; //TODO omg wtf and other incredible stories tile.H = Vector2.Distance( new Vector2( tile.x, tile.y ), new Vector2(endTile.x, endTile.y) ); tile.Cost = tile.G + tile.H + (int)tile.flags; //Calculate H; Manhattan style open.Add( tile ); } //Update the cost if it is else { int G = 10;//cost of going to non-diagonal tiles G += map[ tile.parentX, tile.parentY ].G; //If this path is shorter (G cost is lower) then change //the parent cell, G cost and F cost. if ( G < tile.G ) //if G cost is less, { tile.parentX = tileToCheck.x; //change the square's parent tile.parentY = tileToCheck.y; tile.G = G;//change the G cost tile.Cost = tile.G + tile.H + (int)tile.flags; // add terrain cost } } } } //Sort costs open = open.OrderBy( o => o.Cost).ToList(); } while( tileToCheck != endTile ); closed.Reverse(); List<Tile> validRoute = new List<Tile>(); Tile currentTile = closed[ 0 ]; validRoute.Add( currentTile ); do { //Look up the parent of the current cell. currentTile = map[ currentTile.parentX, currentTile.parentY ]; currentTile.renderer.material.color = Color.green; //Add tile to list validRoute.Add( currentTile ); } while ( currentTile != startTile ); validRoute.Reverse(); return validRoute; } And my Tile class: [Flags] public enum TileFlags: int { NONE = 0, DIRT = 1, STONE = 2, WATER = 4, BUILDING = 8, //handy WALKABLE = DIRT | STONE | NONE, endofenum } public class Tile : MonoBehaviour { //Tile Properties public int x, y; public TileFlags flags = TileFlags.DIRT; public Transform cachedTransform; //A* properties public int parentX, parentY; public int G; public float Cost; public float H; public List<Tile> neighbors = new List<Tile>(); void Awake() { cachedTransform = transform; } }

    Read the article

  • How to Implement Single Sign-On between Websites

    - by hmloo
    Introduction Single sign-on (SSO) is a way to control access to multiple related but independent systems, a user only needs to log in once and gains access to all other systems. a lot of commercial systems that provide Single sign-on solution and you can also choose some open source solutions like Opensso, CAS etc. both of them use centralized authentication and provide more robust authentication mechanism, but if each system has its own authentication mechanism, how do we provide a seamless transition between them. Here I will show you the case. How it Works The method we’ll use is based on a secret key shared between the sites. Origin site has a method to build up a hashed authentication token with some other parameters and redirect the user to the target site. variables Status Description ssoEncode required hash(ssoSharedSecret + , + ssoTime + , + ssoUserName) ssoTime required timestamp with format YYYYMMDDHHMMSS used to prevent playback attacks ssoUserName required unique username; required when a user is logged in Note : The variables will be sent via POST for security reasons Building a Single Sign-On Solution Origin Site has function to 1. Create the URL for your Request. 2. Generate required authentication parameters 3. Redirect to target site. using System; using System.Web.Security; using System.Text; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string postbackUrl = "http://www.targetsite.com/sso.aspx"; string ssoTime = DateTime.Now.ToString("yyyyMMddHHmmss"); string ssoUserName = User.Identity.Name; string ssoSharedSecret = "58ag;ai76"; // get this from config or similar string ssoHash = FormsAuthentication.HashPasswordForStoringInConfigFile(string.Format("{0},{1},{2}", ssoSharedSecret, ssoTime, ssoUserName), "md5"); string value = string.Format("{0}:{1},{2}", ssoHash,ssoTime, ssoUserName); Response.Clear(); StringBuilder sb = new StringBuilder(); sb.Append("<html>"); sb.AppendFormat(@"<body onload='document.forms[""form""].submit()'>"); sb.AppendFormat("<form name='form' action='{0}' method='post'>", postbackUrl); sb.AppendFormat("<input type='hidden' name='t' value='{0}'>", value); sb.Append("</form>"); sb.Append("</body>"); sb.Append("</html>"); Response.Write(sb.ToString()); Response.End(); } } Target Site has function to 1. Get authentication parameters. 2. Validate the parameters with shared secret. 3. If the user is valid, then do authenticate and redirect to target page. 4. If the user is invalid, then show errors and return. using System; using System.Web.Security; using System.Text; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (User.Identity.IsAuthenticated) { Response.Redirect("~/Default.aspx"); } } if (Request.Params.Get("t") != null) { string ticket = Request.Params.Get("t"); char[] delimiters = new char[] { ':', ',' }; string[] ssoVariable = ticket.Split(delimiters, StringSplitOptions.None); string ssoHash = ssoVariable[0]; string ssoTime = ssoVariable[1]; string ssoUserName = ssoVariable[2]; DateTime appTime = DateTime.MinValue; int offsetTime = 60; // get this from config or similar try { appTime = DateTime.ParseExact(ssoTime, "yyyyMMddHHmmss", null); } catch { //show error return; } if (Math.Abs(appTime.Subtract(DateTime.Now).TotalSeconds) > offsetTime) { //show error return; } bool isValid = false; string ssoSharedSecret = "58ag;ai76"; // get this from config or similar string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(string.Format("{0},{1},{2}", ssoSharedSecret, ssoTime, ssoUserName), "md5"); if (string.Compare(ssoHash, hash, true) == 0) { if (Math.Abs(appTime.Subtract(DateTime.Now).TotalSeconds) > offsetTime) { //show error return; } else { isValid = true; } } if (isValid) { //Do authenticate; } else { //show error return; } } else { //show error } } } Summary This is a very simple and basic SSO solution, and its main advantage is its simplicity, only needs to add a single page to do SSO authentication, do not need to modify the existing system infrastructure.

    Read the article

  • C++: Checking if an object faces a point (within a certain range)

    - by bojoradarial
    I have been working on a shooter game in C++, and am trying to add a feature whereby missiles shot must be within 90 degrees (PI/2 radians) of the direction the ship is facing. The missiles will be shot towards the mouse. My idea is that the ship's angle of rotation is compared with the angle between the ship and the mouse (std::atan2(mouseY - shipY, mouseX - shipX)), and if the difference is less than PI/4 (45 degrees) then the missile can be fired. However, I can't seem to get this to work. The ship's angle of rotation is increased and decreased with the A and D keys, so it is possible that it isn't between 0 and 2*PI, hence the use of fmod() below. Code: float userRotation = std::fmod(user->Angle(), 6.28318f); if (std::abs(userRotation - missileAngle) > 0.78f) return; Any help would be appreciated. Thanks!

    Read the article

  • Leg animation not working

    - by Monacraft
    I am making a simple animation in XNA C# of a leg moving. This is the logic code for the thigh. It is meant to swing from 25' to 335'. However instead, it hits a point and then keeps on spinning in the other direction. Please help, here's the code: private void Thigh_method() { if (Legdata.Left == true) signvalue = -0.05f; else signvalue = 0.05f; if (Legdata.ToMid == true) Thighturn_ang += signvalue; if (Legdata.ToMid == false) Thighturn_ang -= signvalue; if (Thighturn_ang <= 25 || Thighturn_ang <= 335 && Thighturn_ang <= 180) Legdata.Left = true; if (Thighturn_ang >= 25 || Thighturn_ang >= 335 && Thighturn_ang >= 180) Legdata.Left = false; if (Thighturn_ang == 0) Legdata.ToMid = false; if (Math.Abs(Thighturn_ang) >= 25f) Legdata.ToMid = true; } Thanks in advance, Yours: Mona

    Read the article

  • Java Errors with jRuby on Rails on Google App Engine

    - by John Wang
    I followed all of the instructions so far from: http://code.google.com/p/appengine-jruby/wiki/RunningRails and http://gist.github.com/268192 Currently, I'm just trying to get to hello world. I'm getting these errors when I just run the dev_appserver.rb 238:hello-world jwang392$ dev_appserver.rb . => Booting DevAppServer => Press Ctrl-C to shutdown server => Generating configuration files 2010-04-08 09:16:51.961 java[411:1707] [Java CocoaComponent compatibility mode]: Enabled 2010-04-08 09:16:51.964 java[411:1707] [Java CocoaComponent compatibility mode]: Setting timeout for SWT to 0.100000 Apr 8, 2010 7:17:05 PM com.google.appengine.tools.development.ApiProxyLocalImpl log SEVERE: [1270754225387000] javax.servlet.ServletContext log: Warning: error application could not be initialized org.jruby.rack.RackInitializationException: no such file to load -- time from file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/booter.rb:25:in `boot!' from file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/boot/rack.rb:10 from file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/boot/rack.rb:1:in `load' from <script>:1 at org.jruby.rack.DefaultRackApplicationFactory $4.init(DefaultRackApplicationFactory.java:169) at org.jruby.rack.DefaultRackApplicationFactory.newErrorApplication(DefaultRac kApplicationFactory.java: 118) at org.jruby.rack.DefaultRackApplicationFactory.init(DefaultRackApplicationFac tory.java: 37) at org.jruby.rack.SharedRackApplicationFactory.init(SharedRackApplicationFacto ry.java: 26) at org.jruby.rack.RackServletContextListener.contextInitialized(RackServletCon textListener.java: 40) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java: 530) at org.mortbay.jetty.servlet.Context.startContext(Context.java:135) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java: 1218) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java: 500) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java: 448) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java: 40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java: 117) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java: 40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java: 117) at org.mortbay.jetty.Server.doStart(Server.java:217) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java: 40) at com.google.appengine.tools.development.JettyContainerService.startContainer (JettyContainerService.java: 188) at com.google.appengine.tools.development.AbstractContainerService.startup(Abs tractContainerService.java: 147) at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerI mpl.java: 219) at com.google.appengine.tools.development.DevAppServerMain $StartAction.apply(DevAppServerMain.java:162) at com.google.appengine.tools.util.Parser $ParseResult.applyArgs(Parser.java:48) at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServer Main.java: 113) at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMa in.java: 89) Caused by: org.jruby.exceptions.RaiseException: no such file to load -- time at (unknown).new(file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/booter.rb:25) at Kernel.require(file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/booter.rb:25) at JRuby::Rack::Booter.boot!(file:/Users/jwang392/hello-world/WEB-INF/ lib/jruby-rack-0.9.6.jar!/jruby/rack/boot/rack.rb:10) at (unknown).(unknown)(file:/Users/jwang392/hello-world/WEB-INF/lib/ jruby-rack-0.9.6.jar!/jruby/rack/boot/rack.rb:1) at (unknown).(unknown)(file:/Users/jwang392/Dhello-world/WEB-INF/lib/ jruby-rack-0.9.6.jar!/jruby/rack/boot/rack.rb:1) at Kernel.load(<script>:1) at (unknown).(unknown)(:1) Apr 8, 2010 7:17:05 PM com.google.appengine.tools.development.ApiProxyLocalImpl log SEVERE: [1270754225913000] javax.servlet.ServletContext log: unable to create shared application instance org.jruby.rack.RackInitializationException: no such file to load -- time from file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/booter.rb:25:in `boot!' from file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/boot/rack.rb:10 from file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/boot/rack.rb:1:in `load' from <script>:1 at org.jruby.rack.DefaultRackApplicationFactory $4.init(DefaultRackApplicationFactory.java:169) at org.jruby.rack.DefaultRackApplicationFactory.getApplication(DefaultRackAppl icationFactory.java: 51) at org.jruby.rack.SharedRackApplicationFactory.init(SharedRackApplicationFacto ry.java: 27) at org.jruby.rack.RackServletContextListener.contextInitialized(RackServletCon textListener.java: 40) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java: 530) at org.mortbay.jetty.servlet.Context.startContext(Context.java:135) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java: 1218) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java: 500) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java: 448) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java: 40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java: 117) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java: 40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java: 117) at org.mortbay.jetty.Server.doStart(Server.java:217) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java: 40) at com.google.appengine.tools.development.JettyContainerService.startContainer (JettyContainerService.java: 188) at com.google.appengine.tools.development.AbstractContainerService.startup(Abs tractContainerService.java: 147) at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerI mpl.java: 219) at com.google.appengine.tools.development.DevAppServerMain $StartAction.apply(DevAppServerMain.java:162) at com.google.appengine.tools.util.Parser $ParseResult.applyArgs(Parser.java:48) at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServer Main.java: 113) at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMa in.java: 89) Caused by: org.jruby.exceptions.RaiseException: no such file to load -- time at (unknown).new(file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/booter.rb:25) at Kernel.require(file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/booter.rb:25) at JRuby::Rack::Booter.boot!(file:/Users/jwang392/hello-world/WEB-INF/ lib/jruby-rack-0.9.6.jar!/jruby/rack/boot/rack.rb:10) at (unknown).(unknown)(file:/Users/jwang392/hello-world/WEB-INF/lib/ jruby-rack-0.9.6.jar!/jruby/rack/boot/rack.rb:1) at (unknown).(unknown)(file:/Users/jwang392/hello-world/WEB-INF/lib/ jruby-rack-0.9.6.jar!/jruby/rack/boot/rack.rb:1) at Kernel.load(<script>:1) at (unknown).(unknown)(:1) Apr 8, 2010 7:17:05 PM com.google.appengine.tools.development.ApiProxyLocalImpl log SEVERE: [1270754225915000] javax.servlet.ServletContext log: Error: application initialization failed org.jruby.rack.RackInitializationException: unable to create shared application instance at org.jruby.rack.SharedRackApplicationFactory.init(SharedRackApplicationFacto ry.java: 39) at org.jruby.rack.RackServletContextListener.contextInitialized(RackServletCon textListener.java: 40) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java: 530) at org.mortbay.jetty.servlet.Context.startContext(Context.java:135) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java: 1218) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java: 500) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java: 448) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java: 40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java: 117) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java: 40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java: 117) at org.mortbay.jetty.Server.doStart(Server.java:217) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java: 40) at com.google.appengine.tools.development.JettyContainerService.startContainer (JettyContainerService.java: 188) at com.google.appengine.tools.development.AbstractContainerService.startup(Abs tractContainerService.java: 147) at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerI mpl.java: 219) at com.google.appengine.tools.development.DevAppServerMain $StartAction.apply(DevAppServerMain.java:162) at com.google.appengine.tools.util.Parser $ParseResult.applyArgs(Parser.java:48) at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServer Main.java: 113) at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMa in.java: 89) Caused by: org.jruby.rack.RackInitializationException: no such file to load -- time from file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/booter.rb:25:in `boot!' from file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/boot/rack.rb:10 from file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/boot/rack.rb:1:in `load' from <script>:1 at org.jruby.rack.DefaultRackApplicationFactory $4.init(DefaultRackApplicationFactory.java:169) at org.jruby.rack.DefaultRackApplicationFactory.getApplication(DefaultRackAppl icationFactory.java: 51) at org.jruby.rack.SharedRackApplicationFactory.init(SharedRackApplicationFacto ry.java: 27) ... 19 more Caused by: org.jruby.exceptions.RaiseException: no such file to load -- time at (unknown).new(file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/booter.rb:25) at Kernel.require(file:/Users/jwang392/hello-world/WEB-INF/lib/jruby- rack-0.9.6.jar!/jruby/rack/booter.rb:25) at JRuby::Rack::Booter.boot!(file:/Users/jwang392/hello-world/WEB-INF/ lib/jruby-rack-0.9.6.jar!/jruby/rack/boot/rack.rb:10) at (unknown).(unknown)(file:/Users/jwang392/hello-world/WEB-INF/lib/ jruby-rack-0.9.6.jar!/jruby/rack/boot/rack.rb:1) at (unknown).(unknown)(file:/Users/jwang392/hello-world/WEB-INF/lib/ jruby-rack-0.9.6.jar!/jruby/rack/boot/rack.rb:1) at Kernel.load(<script>:1) at (unknown).(unknown)(:1) The server is running at http://localhost:8080/ I'm at a loss at what step I may have missed. I checked my ruby version (1.8.7) and rails version (2.3.5), gem version (1.3.6) and google-appengine-0.0.10.1 ran: sudo gem install google-appengine curl -O http://appengine-jruby.googlecode.com/hg/demos/rails2/rails2_appengine.rb ruby rails2_appengine.rb sudo gem install rails_dm_datastore sudo gem install activerecord-nulldb-adapter put this in my config.ru file: run lambda { |env| Rack::Response.new('Hello World!').finish } and finally ran $ dev_appserver.rb .

    Read the article

  • How to Solve N-Queens Problem in Scheme?

    - by Philip
    Hi, I'm stuck on the extended exercise 28.2 of How to Design Programs. Here is the link to the question: http://www.htdp.org/2003-09-26/Book/curriculum-Z-H-35.html#node_chap_28 I used a vector of true or false values to represent the board instead of using a list. This is what I've got which doesn't work: #lang Scheme (define-struct posn (i j)) ;takes in a position in i, j form and a board and returns a natural number that represents the position in index form ;example for board xxx ; xxx ; xxx ;(0, 1) - 1 ;(2, 1) - 7 (define (board-ref a-posn a-board) (+ (* (sqrt (vector-length a-board)) (posn-i a-posn)) (posn-j a-posn))) ;reverse of the above function ;1 - (0, 1) ;7 - (2, 1) (define (get-posn n a-board) (local ((define board-length (sqrt (vector-length a-board)))) (make-posn (floor (/ n board-length)) (remainder n board-length)))) ;determines if posn1 threatens posn2 ;true if they are on the same row/column/diagonal (define (threatened? posn1 posn2) (cond ((= (posn-i posn1) (posn-i posn2)) #t) ((= (posn-j posn1) (posn-j posn2)) #t) ((= (abs (- (posn-i posn1) (posn-i posn2))) (abs (- (posn-j posn1) (posn-j posn2)))) #t) (else #f))) ;returns a list of positions that are not threatened or occupied by queens ;basically any position with the value true (define (get-available-posn a-board) (local ((define (get-ava index) (cond ((= index (vector-length a-board)) '()) ((vector-ref a-board index) (cons index (get-ava (add1 index)))) (else (get-ava (add1 index)))))) (get-ava 0))) ;consume a position in the form of a natural number and a board ;returns a board after placing a queen on the position of the board (define (place n a-board) (local ((define (foo x) (cond ((not (board-ref (get-posn x a-board) a-board)) #f) ((threatened? (get-posn x a-board) (get-posn n a-board)) #f) (else #t)))) (build-vector (vector-length a-board) foo))) ;consume a list of positions in the form of natural number and consumes a board ;returns a list of boards after placing queens on each of the positions on the board (define (place/list alop a-board) (cond ((empty? alop) '()) (else (cons (place (first alop) a-board) (place/list (rest alop) a-board))))) ;returns a possible board after placing n queens on a-board ;returns false if impossible (define (placement n a-board) (cond ((zero? n) a-board) (else (local ((define available-posn (get-available-posn a-board))) (cond ((empty? available-posn) #f) (else (or (placement (sub1 n) (place (first available-posn) a-board)) (placement/list (sub1 n) (place/list (rest available-posn) a-board))))))))) ;returns a possible board after placing n queens on a list of boards ;returns false if all the boards are not valid (define (placement/list n boards) (cond ((empty? boards) #f) ((zero? n) (first boards)) ((not (boolean? (placement n (first boards)))) (first boards)) (else (placement/list n (rest boards)))))

    Read the article

  • Using selection sort in java to sort floats

    - by user334046
    Hey, I need to sort an array list of class house by a float field in a certain range. This is my code for the selection sort: public ArrayList<House> sortPrice(ArrayList<House> x,float y, float z){ ArrayList<House> xcopy = new ArrayList<House>(); for(int i = 0; i<x.size(); i++){ if(x.get(i).myPriceIsLessThanOrEqualTo(z) && x.get(i).myPriceIsGreaterThanOrEqualTo(y)){ xcopy.add(x.get(i)); } } ArrayList<House> price= new ArrayList<House>(); while(xcopy.size()>0){ House min = xcopy.get(0); for(int i = 1; i < xcopy.size();i++){ House current = xcopy.get(i); if (current.myPriceIsGreaterThanOrEqualTo(min.getPrice())){ min = current; } } price.add(min); xcopy.remove(min); } return price; } Here is what the house class looks like: public class House { private int numBedRs; private int sqft; private float numBathRs; private float price; private static int idNumOfMostRecentHouse = 0; private int id; public House(int bed,int ft, float bath, float price){ sqft = ft; numBathRs = bath; numBedRs = bed; this.price = price; idNumOfMostRecentHouse++; id = idNumOfMostRecentHouse; } public boolean myPriceIsLessThanOrEqualTo(float y){ if(Math.abs(price - y)<0.000001){ return true; } return false; } public boolean myPriceIsGreaterThanOrEqualTo(float b){ if(Math.abs(b-price)>0.0000001){ return true; } return false; } When i call looking for houses in range 260000.50 to 300000 I only get houses that are at the top of the range even though I have a lower value at 270000. Can someone help?

    Read the article

  • How to combine a relative top with an absolute bottom in CSS?

    - by ceving
    I need to define a div which must stay with the top at the normal position, which differs from the top of the surrounding element: position:relative top:0 and which grows in the height up to the size of the surrounding element: position:absolute bottom:0 I have no idea how to combine the both. Whenever I use a relative box I loose the absolute bottom and whenever I use an absolute box I loose the relative top. Can anybody help me how to do this in CSS? Here is an example: <html> <head> </head> <style type="text/css"> @media screen { body { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: 0; padding: 0; } #head { background-color: gray; } #rel { background-color: green; position: relative; top: 0; bottom: 0; float: left; } #abs { background-color: red; position: absolute; top: 0; bottom: 0; float: left; } } </style> <body> <div id="head"> <h1>Head</h1> </div> <div id="abs"> <h2>absolute</h2> </div> <div id="rel"> <h2>relative</h2> </div> </body> </html> "relative" does not grow at all and "absolute" grows too much.

    Read the article

  • Flash - Ease out scrolling moviclip, scrolled by sensor on each side

    - by webfac
    I am hoping someone can shed some light on this issue for me... I have a movieclip that is scrolled by means of a 'sensor' on each side of the stage. The clip scrolls fine in both directions, however here is my problem: When the users mouse leaves the stage, the movie clip stops dead in it's tracks, and this does not provide a noce smooth effect. Looking at the code below, is there any way I could tell the animation to ease out when the users mouse leaves the stage rather than simply stop suddenly? Much appreciated! class Sensor extends MovieClip { public function Sensor() { } public function onEnterFrame() { // var active:Boolean; // is mouse within sensor? if ((_level2._xmouse >= this._x) && _level2._xmouse <= (this._x + this._width)) { active = true; } else { active = false; } if(active) { // which area of the sensor is it in? var relative_position:Number; var relative_difference:Number; relative_position = _level2._xmouse / this._width * 100.0; //_level2._logger.message("relative position is " + relative_position); if (!isNaN(relative_position)) { // depending on which area it is in, tend towards a particular adjustment if(relative_position > _level2._background_right_threshold) { relative_difference = Math.abs(relative_position - _level2._background_right_threshold); //relative_difference = 10; } else if(relative_position < _level2._background_left_threshold) { relative_difference = Math.abs(_level2._background_left_threshold - relative_position); relative_difference *= -1; } else { _level2._background_ideal_adjustment = 0; } var direction:Number; if(_level2._pan_direction == "left") { direction = 1; } else { direction = -1; } _level2._background_ideal_adjustment = direction * (relative_difference / 10) * _level2._pan_augmentation; //_level2._logger.message("ideal adjustment is " + _level2._background_ideal_adjustment); if (!isNaN(_level2._background_ideal_adjustment)) { // what is the difference between the ideal adjustment and the current adjustment? // add a portion of the difference to the adjustment: // this has the effect that the adjustment "tends towards" the ideal var difference:Number; difference = _level2._background_ideal_adjustment - _level2._background_adjustment; _level2._background_adjustment += (difference / _level2._background_tension); // calculate what the new background _x position would be var background_x:Number; var projected_x:Number; background_x = _level2["_background"]._x; projected_x = background_x += _level2._background_adjustment; //_level2._logger.message("projected _x is " + projected_x); // if the _x position is valid, change it if(projected_x > 0) projected_x = 0; if(projected_x < -(_level2["_background"]._width - Stage.width)) projected_x = -(_level2["_background"]._width - Stage.width); _level2["_background"]._x = projected_x; // i recommend that you move your other movieclips with code here } } } } }

    Read the article

  • C#: Windows Forms: What could cause Invalidate() to not redraw?

    - by Rosarch
    I'm using Windows Forms. For a long time, pictureBox.Invalidate(); worked to make the screen be redrawn. However, it now doesn't work and I'm not sure why. this.worldBox = new System.Windows.Forms.PictureBox(); this.worldBox.BackColor = System.Drawing.SystemColors.Control; this.worldBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.worldBox.Location = new System.Drawing.Point(170, 82); this.worldBox.Name = "worldBox"; this.worldBox.Size = new System.Drawing.Size(261, 250); this.worldBox.TabIndex = 0; this.worldBox.TabStop = false; this.worldBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.worldBox_MouseMove); this.worldBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.worldBox_MouseDown); this.worldBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.worldBox_MouseUp); Called in my code to draw the world appropriately: view.DrawWorldBox(worldBox, canvas, gameEngine.GameObjectManager.Controllers, selectedGameObjects, LevelEditorUtils.PREVIEWS); View.DrawWorldBox: public void DrawWorldBox(PictureBox worldBox, Panel canvas, ICollection<IGameObjectController> controllers, ICollection<IGameObjectController> selectedGameObjects, IDictionary<string, Image> previews) { int left = Math.Abs(worldBox.Location.X); int top = Math.Abs(worldBox.Location.Y); Rectangle screenRect = new Rectangle(left, top, canvas.Width, canvas.Height); IDictionary<float, ICollection<IGameObjectController>> layers = LevelEditorUtils.LayersOfControllers(controllers); IOrderedEnumerable<KeyValuePair<float, ICollection<IGameObjectController>>> sortedLayers = from item in layers orderby item.Key descending select item; using (Graphics g = Graphics.FromImage(worldBox.Image)) { foreach (KeyValuePair<float, ICollection<IGameObjectController>> kv in sortedLayers) { foreach (IGameObjectController controller in kv.Value) { // ... float scale = controller.View.Scale; float width = controller.View.Width; float height = controller.View.Height; Rectangle controllerRect = new Rectangle((int)controller.Model.Position.X, (int)controller.Model.Position.Y, (int)(width * scale), (int)(height * scale)); // cull objects that aren't intersecting with the canvas if (controllerRect.IntersectsWith(screenRect)) { Image img = previews[controller.Model.HumanReadableName]; g.DrawImage(img, controllerRect); } if (selectedGameObjects.Contains(controller)) { selectionRectangles.Add(controllerRect); } } } foreach (Rectangle rect in selectionRectangles) { g.DrawRectangle(drawingPen, rect); } selectionRectangles.Clear(); } worldBox.Invalidate(); } What could I be doing wrong here?

    Read the article

  • Define polynomial function

    - by user1822707
    How can I define a function - say, def polyToString(poly) - to return a string containing the polynomial poly in standard form? For example: the polynomial represented by [-1, 2, -3, 4, -5] would be returned as: "-5x**4 + 4x**3 -3x**2 + 2x**1 - 1x**0" def polyToString(poly): standard_form='' n=len(poly) - 1 while n >=0: if poly[n]>=0: if n==len(poly)-1: standard_form= standard_form + ' '+ str(poly[n]) + 'x**%d'%n else: standard_form= standard_form + ' + '+str(poly[n]) + 'x**%d'%n else: standard_form= standard_form + ' - ' + str(abs(poly[n])) + 'x**' + str(n) n=n-1 return standard_form

    Read the article

  • Is there a floating point value of x, for which x-x == 0 is false?

    - by Andrew Walker
    In most cases, I understand that a floating point comparison test should be implemented using over a range of values (abs(x-y) < epsilon), but does self subtraction imply that the result will be zero? // can the assertion be triggered? float x = //?; assert( x-x == 0 ) My guess is that nan/inf might be special cases, but I'm more interested in what happens for simple values.

    Read the article

  • Getting my string value from my form into my class( not another form)

    - by jovany
    Hello all, I have a question regarding the some data which is being transfered from one form to my class. It's not going quite the way i'd like to , so I figured maybe there is someone who could help me. This is my code in my class Public Class DrawableTextBox Inherits Drawable Dim i_testString As Integer Private s_InsertLabel As String Private drawFont As Font Public Sub New(ByVal fore_color As Color, ByVal fill_color As Color, Optional ByVal line_width As Integer = 0, Optional ByVal new_x1 As Integer = 0, Optional ByVal new_y1 As Integer = 0, Optional ByVal new_x2 As Integer = 1, Optional ByVal new_y2 As Integer = 1) MyBase.New(fore_color, fill_color, line_width) X1 = new_x1 Y1 = new_y1 X2 = new_x2 Y2 = new_y2 Trace.WriteLine(s_InsertLabel) End Sub Friend WriteOnly Property _textBox() As String Set(ByVal Value As String) s_InsertLabel = Value Trace.WriteLine(s_InsertLabel) End Set End Property ' Draw the object on this Graphics surface. Public Overrides Sub Draw(ByVal gr As System.Drawing.Graphics) ' Make a Rectangle representing this rectangle. Dim rect As Rectangle = GetBounds() ' Fill the rectangle as usual. Dim fill_brush As New SolidBrush(FillColor) gr.FillRectangle(fill_brush, rect) fill_brush.Dispose() ' See if we're selected. If IsSelected Then ' Draw the rectangle highlighted. Dim highlight_pen As New Pen(Color.Yellow, LineWidth) gr.DrawRectangle(highlight_pen, rect) highlight_pen.Dispose() ' Draw grab handles. Trace.WriteLine("drawing the lines for my textbox") DrawGrabHandle(gr, X1, Y1) DrawGrabHandle(gr, X1, Y2) DrawGrabHandle(gr, X2, Y2) DrawGrabHandle(gr, X2, Y1) Else 'TextBox() Dim fg_pen As New Pen(Color.Red, LineWidth) 'Dim fontSize As Single = 0.1 + ((Y2 - Y1) / 2) Dim fontSize As Single = 20 Try Dim drawFont As New Font("Arial", fontSize, FontStyle.Bold) Trace.WriteLine(s_InsertLabel) gr.DrawString(s_InsertLabel, drawFont, Brushes.Brown, X1, Y1) Catch ex As ArgumentException End Try gr.DrawRectangle(Pens.Azure, rect) ' gr.DrawRectangle(fg_pen, rect) fg_pen.Dispose() End If End Sub Public Function GetValueString(ByVal ValueType As String) Return ValueType End Function ' Return the object's bounding rectangle. Public Overrides Function GetBounds() As System.Drawing.Rectangle Return New Rectangle( _ Min(X1, X2), _ Min(Y1, Y2), _ Abs(100), _ Abs(30)) Trace.WriteLine("don't forget to make variables in GetBounds DrawableTextbox") End Function ' Return True if this point is on the object. Public Overrides Function IsAt(ByVal x As Integer, ByVal y As Integer) As Boolean Return (x >= Min(X1, X2)) AndAlso _ (x <= Max(X1, X2)) AndAlso _ (y >= Min(Y1, Y2)) AndAlso _ (y <= Max(Y1, Y2)) End Function ' Move the second point. Public Overrides Sub NewPoint(ByVal x As Integer, ByVal y As Integer) X2 = x Y2 = y End Sub ' Return True if the object is empty (e.g. a zero-length line). Public Overrides Function IsEmpty() As Boolean Return (X1 = X2) AndAlso (Y1 = Y2) End Function End Class I've got a form with a textbox( form1) in which the text is being inserted and passed through a buttonclick (al via properties). As you can see I've placed several traces and in the property of the class my trace works fine , however if I look in my Draw function it is already gone. And I get a blank trace. Does anyone know what's happening here. thanks in advance. (forgive me I'm new )

    Read the article

  • Is frozenset adequate for caching of symmetric input data in a python dict?

    - by Debilski
    The title more or less says it all: I have a function which takes symmetric input in two arguments, e.g. something like def f(a1, a2): return heavy_stuff(abs(a1 - a2)) Now, I want to introduce some caching method. Would it be correct / pythonic / reasonably efficient to do something like this: cache = {} def g(a1, a2): return cache.setdefault(frozenset((tuple(a1), tuple(a2))), f(a1, a2)) Or would there be some better way?

    Read the article

  • Runge-Kutta Method with adaptive step

    - by infoholic_anonymous
    I am implementing Runge-Kutta method with adaptive step in matlab. I get different results as compared to matlab's own ode45 and my own implementation of Runge-Kutta method with fixed step. What am I doing wrong in my code? Is it possible? function [ result ] = rk4_modh( f, int, init, h, h_min ) % % f - function handle % int - interval - pair (x_min, x_max) % init - initial conditions - pair (y1(0),y2(0)) % h_min - lower limit for h (step length) % h - initial step length % x - independent variable ( for example time ) % y - dependent variable - vertical vector - in our case ( y1, y2 ) function [ k1, k2, k3, k4, ka, y ] = iteration( f, h, x, y ) % core functionality performed within loop k1 = h * f(x,y); k2 = h * f(x+h/2, y+k1/2); k3 = h * f(x+h/2, y+k2/2); k4 = h * f(x+h, y+k3); ka = (k1 + 2*k2 + 2*k3 + k4)/6; y = y + ka; end % constants % relative error eW = 1e-10; % absolute error eB = 1e-10; s = 0.9; b = 5; % initialization i = 1; x = int(1); y = init; while true hy = y; hx = x; %algorithm [ k1, k2, k3, k4, ka, y ] = iteration( f, h, x, y ); % error estimation for j=1:2 [ hk1, hk2, hk3, hk4, hka, hy ] = iteration( f, h/2, hx, hy ); hx = hx + h/2; end err(:,i) = abs(hy - y); % step adjustment e = abs( hy ) * eW + eB; a = min( e ./ err(:,i) )^(0.2); mul = a * s; if mul >= 1 % step length admitted keepH(i) = h; k(:,:,i) = [ k1, k2, k3, k4, ka ]; previous(i,:) = [ x+h, y' ]; %' i = i + 1; if floor( x + h + eB ) == int(2) break; else h = min( [mul*h, b*h, int(2)-x] ); x = x + keepH(i-1); end else % step length requires further adjustments h = mul * h; if ( h < h_min ) error('Computation with given precision impossible'); end end end result = struct( 'val', previous, 'k', k, 'err', err, 'h', keepH ); end The function in question is: function [ res ] = fun( x, y ) % res(1) = y(2) + y(1) * ( 0.9 - y(1)^2 - y(2)^2 ); res(2) = -y(1) + y(2) * ( 0.9 - y(1)^2 - y(2)^2 ); res = res'; %' end The call is: res = rk4( @fun, [0,20], [0.001; 0.001], 0.008 ); The resulting plot for x1 : The result of ode45( @fun, [0, 20], [0.001, 0.001] ) is:

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >