Search Results

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

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

  • how to use expressons as function parameters in powershell

    - by rmeador
    This is a very simple task in every language I have ever used, but I can't seem to figure it out in PowerShell. An example of what I'm talking about in C: abs(x + y) The expression x + y is evaluated, and the result passed to abs as the parameter... how do I do that in PowerShell? The only way I have figured out so far is to create a temporary variable to store the result of the expression, and pass that. PowerShell seems to have very strange grammar and parsing rules that are constantly catching me by surprise, just like this situation. Does anyone know of documentation or a tutorial that explains the basic underlying theory of the language? I can't believe these are all special cases, there must be some rhyme or reason that no tutorial I have yet read explains. And yes, I've read this question, and all of those tutorials are awful. I've pretty much been relegated to learning from existing code.

    Read the article

  • Error in asp.net C#

    - by Ishan
    How to pass Editor1 as Parameter: In my aspx.cs i am giving a call to a function which is in .cs file for the same project, as follows: protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e) { DropDown abs = new DropDown(); abs.dd(this.DropDownList2, this.DropDownList3); } .CS file code public void dd(DropDownList DropDownList2, DropDownList DropDownList3) { //My code which contains DropDownList2 DropDownList3 and Editor1 } The error that i am getting is: Error 1 The name 'Editor1' does not exist in the current context The way i have passed DropDownList2 and DropDownList3 i am not able to pass Editor1(It is an ajax control). How do i pass it?

    Read the article

  • Context Menu event with QGraphicsWidget

    - by onurozcelik
    In my application I subclass QGraphicsWidget In paint I am drawing a line with pen width 4. I reimplemented boundingRect() and shape(). But I can't catch context menu event every time I click right mouse button. What is the problem.(Pen Width ? ) //Sample code for boundingRect() and shape() QRectF boundingRect() const { qreal rectLeft = x1 < x2 ? x1 : x2; qreal rectTop = y1 < y2 ? y1 : y2; qreal rectWidth = (x1 - x2) != 0 ? abs(x1-x2) : 4; qreal rectHeight = (y1 - y2) != 0 ? abs(y1 -y2) : 4; return QRectF(rectLeft,rectTop,rectWidth,rectHeigt); } QPainterPath shape() { QPainterPath path; path.addRect(boundingRect()); return path; }

    Read the article

  • misleading plot issue in mathematica

    - by Qiang Li
    I want to study some "strange" functions by plotting them out in mathematica. One example is the following: mod2[x_] := Which[Mod[x, 2] >= 1, -2 + Mod[x, 2], True, Mod[x, 2]]; f[x_] := Which[-1 <= x <= 1, Abs[x], True, Abs[mod2[x]]]; fn[x_, n_] := Sum[(3/4)^i*f[4^n*x], {i, 0, n}] Plot[{fn[x, 0], fn[x, 1], fn[x, 2], fn[x, 5]}, {x, -2, 2}] However, the plot I got from mma is misleading, in the sense that the maxima and minima of fn[x, 5] should be on the same two levels. But due to high oscillation of the function, and the fact that clearly mma only takes limited number of points to draw the function, you see the plot exhibit strange behavior. Is there any option in plot to remedy for this? Many thanks.

    Read the article

  • Testing a quadratic equation

    - by user1201587
    I'm doing a code testing for a program that calculate the results for a quadratic equation I need to have test data for the following situation, when a is not zero and d positive there is two possibilities which are in the code below, I need to find an example for the first satiation when Math.abs(b / a - 200.0) < 1.0e-4 , all the values that I have tried, excute the second one caption= "Two roots"; if (Math.abs(b / a - 200.0) < 1.0e-4) { System.out.println("first one"); x1 = (-100.0 * (1.0 + Math.sqrt(1.0 - 1.0 / (10000.0 * a)))); x2 = (-100.0 * (1.0 - Math.sqrt(1.0 - 1.0 / (10000.0 * a)))); } else { System.out.println("secrst one"); x1 = (-b - Math.sqrt(d)) / (2.0 * a); x2 = (-b + Math.sqrt(d)) / (2.0 * a); } } }

    Read the article

  • date.getHours() to calendar.hour

    - by user1487045
    I want to get the hour of day in 24hour cycle. I know that date.getHours() is depreciated. But I'm tempted to use it since I cant get the same result out of calendar.hour call. Can anyone tell me how to fix what I have below to get the hours out correctly with calendar.hour? ...much appreciated. Date d = new Date(); Calendar c = Calendar.getInstance(); c.setTime(d); System.out.println("hour: "+Math.abs(c.HOUR-24)+", mins: "+Math.abs(c.MINUTE-60)+", d.h: "+d.getHours() +", d.m: "+d.getMinutes());

    Read the article

  • x axis detection issues platformer starter kit

    - by dbomb101
    I've come across a problem with the collision detection code in the platformer starter kit for xna.It will send up the impassible flag on the x axis despite being nowhere near a wall in either direction on the x axis, could someone could tell me why this happens ? Here is the collision method. /// <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, TileCollision collision = Level.GetCollision(x, y); if (collision != TileCollision.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 == TileCollision.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 == TileCollision.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; } } //This is the section which deals with collision on the x-axis else if (collision == TileCollision.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; }

    Read the article

  • Android Swipe In Unity 3D World with AR

    - by Christian
    I am working on an AR application using Unity3D and the Vuforia SDK for Android. The way the application works is a when the designated image(a frame marker in our case) is recognized by the camera, a 3D island is rendered at that spot. Currently I am able to detect when/which objects are touched on the model by raycasting. I also am able to successfully detect a swipe using this code: if (Input.touchCount > 0) { Touch touch = Input.touches[0]; switch (touch.phase) { case TouchPhase.Began: couldBeSwipe = true; startPos = touch.position; startTime = Time.time; break; case TouchPhase.Moved: if (Mathf.Abs(touch.position.y - startPos.y) > comfortZoneY) { couldBeSwipe = false; } //track points here for raycast if it is swipe break; case TouchPhase.Stationary: couldBeSwipe = false; break; case TouchPhase.Ended: float swipeTime = Time.time - startTime; float swipeDist = (touch.position - startPos).magnitude; if (couldBeSwipe && (swipeTime < maxSwipeTime) && (swipeDist > minSwipeDist)) { // It's a swiiiiiiiiiiiipe! float swipeDirection = Mathf.Sign(touch.position.y - startPos.y); // Do something here in reaction to the swipe. swipeCounter.IncrementCounter(); } break; } touchInfo.SetTouchInfo (Time.time-startTime,(touch.position-startPos).magnitude,Mathf.Abs (touch.position.y-startPos.y)); } Thanks to andeeeee for the logic. But I want to have some interaction in the 3D world based on the swipe on the screen. I.E. If the user swipes over unoccluded enemies, they die. My first thought was to track all the points in the moved TouchPhase, and then if it is a swipe raycast into all those points and kill any enemy that is hit. Is there a better way to do this? What is the best approach? Thanks for the help!

    Read the article

  • I need to move an entity to the mouse location after i rightclick

    - by I.Hristov
    Well I've read the related questions-answers but still cant find a way to move my champion to the mouse position after a right-button mouse-click. I use this code at the top: float speed = (float)1/3; And this is in my void Update: //check if right mouse button is clicked if (mouse.RightButton == ButtonState.Released && previousButtonState == ButtonState.Pressed) { // gets the position of the mouse in mousePosition mousePosition = new Vector2(mouse.X, mouse.Y); //gets the current position of champion (the drawRectangle) currentChampionPosition = new Vector2(drawRectangle.X, drawRectangle.Y); // move champion to mouse position: //handles the case when the mouse position is really close to current position if (Math.Abs(currentChampionPosition.X - mousePosition.X) <= speed && Math.Abs(currentChampionPosition.Y - mousePosition.Y) <= speed) { drawRectangle.X = (int)mousePosition.X; drawRectangle.Y = (int)mousePosition.Y; } else if (currentChampionPosition != mousePosition) { drawRectangle.X += (int)((mousePosition.X - currentChampionPosition.X) * speed); drawRectangle.Y += (int)((mousePosition.Y - currentChampionPosition.Y) * speed); } } previousButtonState = mouse.RightButton; What that code does at the moment is on a click it brings the sprite 1/3 of the distance to the mouse but only once. How do I make it move consistently all the time? It seems I am not updating the sprite at all. EDIT I added the Vector2 as Nick said and with speed changed to 50 it should be OK. I tried it with if ButtonState.Pressed and it works while pressing the button. Thanks. However I wanted it to start moving when single mouse clicked. It should be moving until reaches the mousePosition. The Edit of Nick's post says to create another Vector2, But I already have the one called mousePosition. Not sure how to use another one. //gets a Vector2 direction to move *by Nick Wilson Vector2 direction = mousePosition - currentChampionPosition; //make the direction vector a unit vector direction.Normalize(); //multiply with speed (number of pixels) direction *= speed; // move champion to mouse position if (currentChampionPosition != mousePosition) { drawRectangle.X += (int)(direction.X); drawRectangle.Y += (int)(direction.Y); } } previousButtonState = mouse.RightButton;

    Read the article

  • How to remove the boundary effects arising due to zero padding in scipy/numpy fft?

    - by Omkar
    I have made a python code to smoothen a given signal using the Weierstrass transform, which is basically the convolution of a normalised gaussian with a signal. The code is as follows: #Importing relevant libraries from __future__ import division from scipy.signal import fftconvolve import numpy as np def smooth_func(sig, x, t= 0.002): N = len(x) x1 = x[-1] x0 = x[0] # defining a new array y which is symmetric around zero, to make the gaussian symmetric. y = np.linspace(-(x1-x0)/2, (x1-x0)/2, N) #gaussian centered around zero. gaus = np.exp(-y**(2)/t) #using fftconvolve to speed up the convolution; gaus.sum() is the normalization constant. return fftconvolve(sig, gaus/gaus.sum(), mode='same') If I run this code for say a step function, it smoothens the corner, but at the boundary it interprets another corner and smoothens that too, as a result giving unnecessary behaviour at the boundary. I explain this with a figure shown in the link below. Boundary effects This problem does not arise if we directly integrate to find convolution. Hence the problem is not in Weierstrass transform, and hence the problem is in the fftconvolve function of scipy. To understand why this problem arises we first need to understand the working of fftconvolve in scipy. The fftconvolve function basically uses the convolution theorem to speed up the computation. In short it says: convolution(int1,int2)=ifft(fft(int1)*fft(int2)) If we directly apply this theorem we dont get the desired result. To get the desired result we need to take the fft on a array double the size of max(int1,int2). But this leads to the undesired boundary effects. This is because in the fft code, if size(int) is greater than the size(over which to take fft) it zero pads the input and then takes the fft. This zero padding is exactly what is responsible for the undesired boundary effects. Can you suggest a way to remove this boundary effects? I have tried to remove it by a simple trick. After smoothening the function I am compairing the value of the smoothened signal with the original signal near the boundaries and if they dont match I replace the value of the smoothened func with the input signal at that point. It is as follows: i = 0 eps=1e-3 while abs(smooth[i]-sig[i])> eps: #compairing the signals on the left boundary smooth[i] = sig[i] i = i + 1 j = -1 while abs(smooth[j]-sig[j])> eps: # compairing on the right boundary. smooth[j] = sig[j] j = j - 1 There is a problem with this method, because of using an epsilon there are small jumps in the smoothened function, as shown below: jumps in the smooth func Can there be any changes made in the above method to solve this boundary problem?

    Read the article

  • Why is my arrow texture being drawn in odd places?

    - by tyjkenn
    This is a script I wrote that places an arrow on the screen, pointing to an enemy off-screen, or, if the enemy is on-screen, it places an arrow hovering above the enemy. Everything seems to work, except for some odd reason, I see random arrows floating around, often skewed and resized (which I really don't understand, because I only rotate and place in this script). Even when I only have one enemy in the scene, I still see these random arrows. It should only be drawing one per enemy. Note: when all enemies are removed, no arrows appear. var arrow : Texture; var cam : Camera; var dim : int = 30; function OnGUI() { var objects = GameObject.FindGameObjectsWithTag("Enemy"); for(var ob : GameObject in objects) { var pos = cam.WorldToViewportPoint(ob.transform.position); if(gameObject.GetComponent(FollowCamera).target != null){ var tar = gameObject.GetComponent(FollowCamera).target.parent; } if(pos.z>1 && ob.transform != tar){ var xDiff = (pos.x*cam.pixelWidth)-(cam.pixelWidth/2); var yDiff = (pos.y*cam.pixelHeight)-(cam.pixelHeight/2); var angle = Mathf.Rad2Deg*Mathf.Atan(yDiff/xDiff)+180; if(xDiff>0) angle += 180; var dist = Mathf.Sqrt(xDiff*xDiff + yDiff*yDiff); var slope = yDiff/xDiff; var camSlope = cam.pixelHeight/cam.pixelWidth; var theX = -1000.0; var theY = -1000.0; var mult = 0; var temp; if(Mathf.Abs(xDiff)>(cam.pixelWidth/2)||Mathf.Abs(yDiff)>(cam.pixelHeight/2)){ //touching right if(slope<camSlope && slope>-camSlope) { if(xDiff>(cam.pixelWidth/2)) { theX = cam.pixelWidth - (dim/2); mult = -1; }else if(xDiff<-(cam.pixelWidth/2)) { theX = (dim/2); mult = 1; } temp = ((cam.pixelWidth/2)*yDiff)/xDiff; theY =(cam.pixelHeight/2)+(mult*temp); } else{ if(yDiff>(cam.pixelHeight/2)) { theY = (dim/2); mult = 1; }else if(yDiff<-(cam.pixelHeight/2)) { theY = cam.pixelHeight - (dim/2); mult = -1; } temp = ((cam.pixelHeight/2)*xDiff)/yDiff; theX =(cam.pixelWidth/2)+(mult*temp); } } else { angle = -90; theX = (cam.pixelWidth/2)+xDiff; theY = (cam.pixelHeight/2)-yDiff-dim; } GUIUtility.RotateAroundPivot(-angle, Vector2(theX, theY)); Graphics.DrawTexture(Rect(theX-(dim/2),theY-(dim/2),dim,dim),arrow,null); GUIUtility.RotateAroundPivot(angle, Vector2(theX, theY)); } } }

    Read the article

  • I need help with specific types of movement.

    - by IronGiraffe
    I'm adding movable crates to my game and I need some help with my movement code. The way I've set up my movement code the crate's X and Y are moved according to a vector2 unless it hits a wall. Here's the movement code: if (frameCount % (delay / 2) == 0) { for (int i = 0; i < Math.Abs(cSpeed.X); i++) { if (!Level.PlayerHit(new Rectangle(crateBounds.X + (Math.Sign(cSpeed.X) * 32), crateBounds.Y, crateBounds.Width, crateBounds.Height))) { if (!Level.CollideTiles(crateBounds.X + (Math.Sign(cSpeed.X) * 32), crateBounds.Y, crateBounds.Width, crateBounds.Height)) { if (cSpeed.X != 0) { crateBounds.X += Math.Sign(cSpeed.X); } else { Equalize(2); } } else { cSpeed.X = 0f; } } else { if (!Level.CollideTiles(crateBounds.X - (Math.Sign(cSpeed.X) * 32), crateBounds.Y, crateBounds.Width, crateBounds.Height)) { if (cSpeed.X != 0) { crateBounds.X -= Math.Sign(cSpeed.X); } else { Equalize(2); } } else { cSpeed.X = 0f; } } } for (int i = 0; i < Math.Abs(cSpeed.Y); i++) { if (!Level.PlayerHit(new Rectangle(crateBounds.X, crateBounds.Y + Math.Sign(cSpeed.Y), crateBounds.Width, crateBounds.Height))) { if (!Level.CollideTiles(crateBounds.X, crateBounds.Y + Math.Sign(cSpeed.Y), crateBounds.Width, crateBounds.Height)) { crateBounds.Y += Math.Sign(cSpeed.Y); } else { cSpeed.Y = 0f; } } else { if (!Level.CollideTiles(crateBounds.X, crateBounds.Y - Math.Sign(cSpeed.Y), crateBounds.Width, crateBounds.Height)) { crateBounds.Y -= Math.Sign(cSpeed.Y); } else { cSpeed.Y = 0f; } } } } The frameCount and delay variables just slow down the movement somewhat. Anyway, I've added a tool to my game that acts as a gravity well (drawing objects into it's center; the closer they get to the center the faster they go) and what I'm trying to do is make it so that the crate will bounce off the player (and vice versa) when they collide. Thus far, my code only keeps the crate and player from getting stuck inside each other (the player can still get stuck under the crate, but I'll fix that later.) So what I'd like to know is how I can best make the crate bounce off the player. The other movement problem I'm having is related to another tool which allows the player to pick up crates and move around with them. The problem is that the crate's movement while being carried isn't tied to the movement script (it moves the crate itself, instead of adding to speed), which makes the crate go through walls and such. I know what I have to do: make the crate's speed match the player's speed while the player is holding it, but I need the crate to snap to a certain position (just in front of the player) when the player grabs it and it needs to switch to another position (just in front of the player on the other side) when they player faces the other direction while holding it. What would be the best way to make it switch places while keeping all the movement tied to the speed vector?

    Read the article

  • calculate AUC (GAM) in R [migrated]

    - by ahmad
    I used the following script to calculate AUC in R: library(mgcv) library(ROCR) library(AUC) data1=read.table("d:\\2005.txt", header=T) GAM<-gam(tuna ~ s(chla)+s(sst)+s(ssha),family=binomial, data=data1) gampred<- predict(GAM, type="response") rp <- prediction(gampred, data1$tuna) auc <- performance( rp, "auc")@y.values[[1]] auc roc <- performance( rp, "tpr", "fpr") plot( roc ) But when I was running the script, the result is: **rp <- prediction(gampred, data1$tuna) Error in prediction(gampred, data1$tuna) : Format of predictions is invalid. > > auc <- performance( rp, "auc")@y.values[[1]] Error in performance(rp, "auc") : object 'rp' not found > auc function (x, min = 0, max = 1) { if (any(class(x) == "roc")) { if (min != 0 || max != 1) { x$fpr <- x$fpr[x$cutoffs >= min & x$cutoffs <= max] x$tpr <- x$tpr[x$cutoffs >= min & x$cutoffs <= max] } ans <- 0 for (i in 2:length(x$fpr)) { ans <- ans + 0.5 * abs(x$fpr[i] - x$fpr[i - 1]) * (x$tpr[i] + x$tpr[i - 1]) } } else if (any(class(x) %in% c("accuracy", "sensitivity", "specificity"))) { if (min != 0 || max != 1) { x$cutoffs <- x$cutoffs[x$cutoffs >= min & x$cutoffs <= max] x$measure <- x$measure[x$cutoffs >= min & x$cutoffs <= max] } ans <- 0 for (i in 2:(length(x$cutoffs))) { ans <- ans + 0.5 * abs(x$cutoffs[i - 1] - x$cutoffs[i]) * (x$measure[i] + x$measure[i - 1]) } } return(as.numeric(ans)) } <bytecode: 0x03012f10> <environment: namespace:AUC> > > roc <- performance( rp, "tpr", "fpr") Error in performance(rp, "tpr", "fpr") : object 'rp' not found > plot( roc ) Error in levels(labels) : argument "labels" is missing, with no default** Can anybody help me to solve this problem? Thank you in advance.

    Read the article

  • Android question - how to prep 100 images to be shown via Fling/Swipe?

    - by fooyee
    I'm totally new to this, been tinkering around for a week. Came up with a simple image viewer app for 2 images. Feature: Left and right swipes will switch the images. Dead simple. What i'd like to do: Have up to 100 images. note: All my images are in my res/drawable folder. They're named image1.png to image100.png I obviously don't want to do: ImageView i = new ImageView(this); i.setImageResource(R.drawable.image1); viewFlipper.addView(i); ImageView i2 = new ImageView(this); i2.setImageResource(R.drawable.image2); viewFlipper.addView(i2); ImageView i3 = new ImageView(this); i3.setImageResource(R.drawable.image3); viewFlipper.addView(i3); all the way to i100. how do I make this into a loop, which is flexible and reads everything from the drawable folder ( and not be limited to 100 images)? source: public class ImageViewTest extends Activity { private static final String LOGID = "CHECKTHISOUT"; private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private GestureDetector gestureDetector; View.OnTouchListener gestureListener; private Animation slideLeftIn; private Animation slideLeftOut; private Animation slideRightIn; private Animation slideRightOut; private ViewFlipper viewFlipper; String message = "Initial Message"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Set up viewflipper viewFlipper = new ViewFlipper(this); ImageView i = new ImageView(this); i.setImageResource(R.drawable.sample_1); ImageView i2 = new ImageView(this); i2.setImageResource(R.drawable.sample_2); viewFlipper.addView(i); viewFlipper.addView(i2); //set up animations slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in); slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out); slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in); slideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out); //put up a brownie as a starter setContentView(viewFlipper); gestureDetector = new GestureDetector(new MyGestureDetector()); } public class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false; // right to left swipe if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Log.v(LOGID,"right to left swipe detected"); viewFlipper.setInAnimation(slideLeftIn); viewFlipper.setOutAnimation(slideLeftOut); viewFlipper.showNext(); setContentView(viewFlipper); } // left to right swipe else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Log.v(LOGID,"left to right swipe detected"); viewFlipper.setInAnimation(slideRightIn); viewFlipper.setOutAnimation(slideRightOut); viewFlipper.showPrevious(); setContentView(viewFlipper); } } catch (Exception e) { // nothing } return false; } } // This doesn't work @Override public boolean onTouchEvent(MotionEvent event) { if (gestureDetector.onTouchEvent(event)){ Log.v(LOGID,"screen touched"); return true; } else{ return false; } } }

    Read the article

  • Trouble with detecting gestures over ListView

    - by Andrew
    I have an Activity that contains a ViewFlipper. The ViewFlipper includes 2 layouts, both of which are essentially just ListViews. So the idea here is that I have two lists and to navigate from one to the other I would use a horizontal swipe. I have that working. However, what ever list item your finger is on when the swipe begins executing, that item will also be long-clicked. Here is the relevant code I have: public class MyActivity extends Activity implements OnItemClickListener, OnClickListener { private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private GestureDetector mGestureDetector; View.OnTouchListener mGestureListener; class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false; // right to left swipe if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { if (mCurrentScreen != SCREEN_SECONDLIST) { mCurrentScreen = SCREEN_SECONDLIST; mFlipper.setInAnimation(inFromRightAnimation()); mFlipper.setOutAnimation(outToLeftAnimation()); mFlipper.showNext(); updateNavigationBar(); } } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { if (mCurrentScreen != SCREEN_FIRSTLIST) { mCurrentScreen = SCREEN_FIRSTLIST; mFlipper.setInAnimation(inFromLeftAnimation()); mFlipper.setOutAnimation(outToRightAnimation()); mFlipper.showPrevious(); updateNavigationBar(); } } } catch (Exception e) { // nothing } return true; } } @Override public boolean onTouchEvent(MotionEvent event) { if (mGestureDetector.onTouchEvent(event)) return true; else return false; } ViewFlipper mFlipper; private int mCurrentScreen = SCREEN_FIRSTLIST; private ListView mList1; private ListView mList2; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.layout_flipper); mFlipper = (ViewFlipper) findViewById(R.id.flipper); mGestureDetector = new GestureDetector(new MyGestureDetector()); mGestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (mGestureDetector.onTouchEvent(event)) { return true; } return false; } }; // set up List1 screen mList1List = (ListView)findViewById(R.id.list1); mList1List.setOnItemClickListener(this); mList1List.setOnTouchListener(mGestureListener); // set up List2 screen mList2List = (ListView)findViewById(R.id.list2); mList2List.setOnItemClickListener(this); mList2List.setOnTouchListener(mGestureListener); } … } If I change the "return true;" statement from the GestureDetector to "return false;", I do not get long-clicks. Unfortunately, I get regular clicks. Does anyone know how I can get around this?

    Read the article

  • Anything wrong with this function for comparing floats?

    - by Michael Borgwardt
    When my Floating-Point Guide was yesterday published on slashdot, I got a lot of flak for my suggested comparison function, which was indeed inadequate. So I finally did the sensible thing and wrote a test suite to see whether I could get them all to pass. Here is my result so far. And I wonder if this is really as good as one can get with a generic (i.e. not application specific) float comparison function, or whether I still missed some edge cases. import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class NearlyEqualsTest { public static boolean nearlyEqual(float a, float b) { final float epsilon = 0.000001f; final float absA = Math.abs(a); final float absB = Math.abs(b); final float diff = Math.abs(a-b); if (a*b==0) { // a or b or both are zero // relative error is not meaningful here return diff < Float.MIN_VALUE / epsilon; } else { // use relative error return diff / (absA+absB) < epsilon; } } /** Regular large numbers - generally not problematic */ @Test public void big() { assertTrue(nearlyEqual(1000000f, 1000001f)); assertTrue(nearlyEqual(1000001f, 1000000f)); assertFalse(nearlyEqual(10000f, 10001f)); assertFalse(nearlyEqual(10001f, 10000f)); } /** Negative large numbers */ @Test public void bigNeg() { assertTrue(nearlyEqual(-1000000f, -1000001f)); assertTrue(nearlyEqual(-1000001f, -1000000f)); assertFalse(nearlyEqual(-10000f, -10001f)); assertFalse(nearlyEqual(-10001f, -10000f)); } /** Numbers around 1 */ @Test public void mid() { assertTrue(nearlyEqual(1.0000001f, 1.0000002f)); assertTrue(nearlyEqual(1.0000002f, 1.0000001f)); assertFalse(nearlyEqual(1.0002f, 1.0001f)); assertFalse(nearlyEqual(1.0001f, 1.0002f)); } /** Numbers around -1 */ @Test public void midNeg() { assertTrue(nearlyEqual(-1.000001f, -1.000002f)); assertTrue(nearlyEqual(-1.000002f, -1.000001f)); assertFalse(nearlyEqual(-1.0001f, -1.0002f)); assertFalse(nearlyEqual(-1.0002f, -1.0001f)); } /** Numbers between 1 and 0 */ @Test public void small() { assertTrue(nearlyEqual(0.000000001000001f, 0.000000001000002f)); assertTrue(nearlyEqual(0.000000001000002f, 0.000000001000001f)); assertFalse(nearlyEqual(0.000000000001002f, 0.000000000001001f)); assertFalse(nearlyEqual(0.000000000001001f, 0.000000000001002f)); } /** Numbers between -1 and 0 */ @Test public void smallNeg() { assertTrue(nearlyEqual(-0.000000001000001f, -0.000000001000002f)); assertTrue(nearlyEqual(-0.000000001000002f, -0.000000001000001f)); assertFalse(nearlyEqual(-0.000000000001002f, -0.000000000001001f)); assertFalse(nearlyEqual(-0.000000000001001f, -0.000000000001002f)); } /** Comparisons involving zero */ @Test public void zero() { assertTrue(nearlyEqual(0.0f, 0.0f)); assertFalse(nearlyEqual(0.00000001f, 0.0f)); assertFalse(nearlyEqual(0.0f, 0.00000001f)); } /** Comparisons of numbers on opposite sides of 0 */ @Test public void opposite() { assertFalse(nearlyEqual(1.000000001f, -1.0f)); assertFalse(nearlyEqual(-1.0f, 1.000000001f)); assertFalse(nearlyEqual(-1.000000001f, 1.0f)); assertFalse(nearlyEqual(1.0f, -1.000000001f)); assertTrue(nearlyEqual(10000f*Float.MIN_VALUE, -10000f*Float.MIN_VALUE)); } /** * The really tricky part - comparisons of numbers * very close to zero. */ @Test public void ulp() { assertTrue(nearlyEqual(Float.MIN_VALUE, -Float.MIN_VALUE)); assertTrue(nearlyEqual(-Float.MIN_VALUE, Float.MIN_VALUE)); assertTrue(nearlyEqual(Float.MIN_VALUE, 0)); assertTrue(nearlyEqual(0, Float.MIN_VALUE)); assertTrue(nearlyEqual(-Float.MIN_VALUE, 0)); assertTrue(nearlyEqual(0, -Float.MIN_VALUE)); assertFalse(nearlyEqual(0.000000001f, -Float.MIN_VALUE)); assertFalse(nearlyEqual(0.000000001f, Float.MIN_VALUE)); assertFalse(nearlyEqual(Float.MIN_VALUE, 0.000000001f)); assertFalse(nearlyEqual(-Float.MIN_VALUE, 0.000000001f)); assertFalse(nearlyEqual(1e20f*Float.MIN_VALUE, 0.0f)); assertFalse(nearlyEqual(0.0f, 1e20f*Float.MIN_VALUE)); assertFalse(nearlyEqual(1e20f*Float.MIN_VALUE, -1e20f*Float.MIN_VALUE)); } }

    Read the article

  • Roguelike FOV problem

    - by Manderin87
    I am working on a college compsci project and I would like some help with a field of view algorithm. I works mostly, but in some situations the algorithm sees through walls and hilights walls the player should not be able to see. void cMap::los(int x0, int y0, int radius) { //Does line of sight from any particular tile for(int x = 0; x < m_Height; x++) { for(int y = 0; y < m_Width; y++) { getTile(x,y)->setVisible(false); } } double xdif = 0; double ydif = 0; bool visible = false; float dist = 0; for (int x = MAX(x0 - radius,0); x < MIN(x0 + radius, m_Height); x++) { //Loops through x values within view radius for (int y = MAX(y0 - radius,0); y < MIN(y0 + radius, m_Width); y++) { //Loops through y values within view radius xdif = pow( (double) x - x0, 2); ydif = pow( (double) y - y0, 2); dist = (float) sqrt(xdif + ydif); //Gets the distance between the two points if (dist <= radius) { //If the tile is within view distance, visible = line(x0, y0, x, y); //check if it can be seen. if (visible) { //If it can be seen, getTile(x,y)->setVisible(true); //Mark that tile as viewable } } } } } bool cMap::line(int x0,int y0,int x1,int y1) { bool steep = abs(y1-y0) > abs(x1-x0); if (steep) { swap(x0, y0); swap(x1, y1); } if (x0 > x1) { swap(x0,x1); swap(y0,y1); } int deltax = x1-x0; int deltay = abs(y1-y0); int error = deltax/2; int ystep; int y = y0; if (y0 < y1) ystep = 1; else ystep = -1; for (int x = x0; x < x1; x++) { if ( steep && getTile(y,x)->isBlocked()) { getTile(y,x)->setVisible(true); getTile(y,x)->setDiscovered(true); return false; } else if (!steep && getTile(x,y)->isBlocked()) { getTile(x,y)->setVisible(true); getTile(x,y)->setDiscovered(true); return false; } error -= deltay; if (error < 0) { y = y + ystep; error = error + deltax; } } return true; } If anyone could help me make the first blocked tiles visible but stops the rest, I would appreciate it. thanks, Manderin87

    Read the article

  • Java algorithm for normalizing audio

    - by Marty Pitt
    I'm trying to normalize an audio file of speech. Specifically, where an audio file contains peaks in volume, I'm trying to level it out, so the quiet sections are louder, and the peaks are quieter. I know very little about audio manipulation, beyond what I've learnt from working on this task. Also, my math is embarrassingly weak. I've done some research, and the Xuggle site provides a sample which shows reducing the volume using the following code: (full version here) @Override public void onAudioSamples(IAudioSamplesEvent event) { // get the raw audio byes and adjust it's value ShortBuffer buffer = event.getAudioSamples().getByteBuffer().asShortBuffer(); for (int i = 0; i < buffer.limit(); ++i) buffer.put(i, (short)(buffer.get(i) * mVolume)); super.onAudioSamples(event); } Here, they modify the bytes in getAudioSamples() by a constant of mVolume. Building on this approach, I've attempted a normalisation modifies the bytes in getAudioSamples() to a normalised value, considering the max/min in the file. (See below for details). I have a simple filter to leave "silence" alone (ie., anything below a value). I'm finding that the output file is very noisy (ie., the quality is seriously degraded). I assume that the error is either in my normalisation algorithim, or the way I manipulate the bytes. However, I'm unsure of where to go next. Here's an abridged version of what I'm currently doing. Step 1: Find peaks in file: Reads the full audio file, and finds this highest and lowest values of buffer.get() for all AudioSamples @Override public void onAudioSamples(IAudioSamplesEvent event) { IAudioSamples audioSamples = event.getAudioSamples(); ShortBuffer buffer = audioSamples.getByteBuffer().asShortBuffer(); short min = Short.MAX_VALUE; short max = Short.MIN_VALUE; for (int i = 0; i < buffer.limit(); ++i) { short value = buffer.get(i); min = (short) Math.min(min, value); max = (short) Math.max(max, value); } // assign of min/max ommitted for brevity. super.onAudioSamples(event); } Step 2: Normalize all values: In a loop similar to step1, replace the buffer with normalized values, calling: buffer.put(i, normalize(buffer.get(i)); public short normalize(short value) { if (isBackgroundNoise(value)) return value; short rawMin = // min from step1 short rawMax = // max from step1 short targetRangeMin = 1000; short targetRangeMax = 8000; int abs = Math.abs(value); double a = (abs - rawMin) * (targetRangeMax - targetRangeMin); double b = (rawMax - rawMin); double result = targetRangeMin + ( a/b ); // Copy the sign of value to result. result = Math.copySign(result,value); return (short) result; } Questions: Is this a valid approach for attempting to normalize an audio file? Is my math in normalize() valid? Why would this cause the file to become noisy, where a similar approach in the demo code doesn't?

    Read the article

  • Path to background in servlet

    - by kapil chhattani
    //the below line is the element of my HTML form which renders the image sent by the servlet written further below. <img style="margin-left:91px; margin-top:-6px;" class="image" src="http://www.abcd.com/captchaServlet"> I generate a captcha code using the following code in java. public class captchaServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 150; int height = 50; int charsToPrint = 6; String elegibleChars = "ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy1234567890"; char[] chars = elegibleChars.toCharArray(); StringBuffer finalString = new StringBuffer(); for ( int i = 0; i < charsToPrint; i++ ) { double randomValue = Math.random(); int randomIndex = (int) Math.round(randomValue * (chars.length - 1)); char characterToShow = chars[randomIndex]; finalString.append(characterToShow); } System.out.println(finalString); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bufferedImage.createGraphics(); Font font = new Font("Georgia", Font.BOLD, 18); g2d.setFont(font); RenderingHints rh = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(rh); GradientPaint gp = new GradientPaint(0, 0, Color.BLUE, 0, height/2, Color.black, true); g2d.setPaint(gp); g2d.fillRect(0, 0, width, height); g2d.setColor(new Color(255, 255, 0)); Random r = new Random(); int index = Math.abs(r.nextInt()) % 5; char[] data=new String(finalString).toCharArray(); String captcha = String.copyValueOf(data); int x = 0; int y = 0; for (int i=0; i<data.length; i++) { x += 10 + (Math.abs(r.nextInt()) % 15); y = 20 + Math.abs(r.nextInt()) % 20; g2d.drawChars(data, i, 1, x, y); } g2d.dispose(); response.setContentType("image/png"); OutputStream os = response.getOutputStream(); ImageIO.write(bufferedImage, "png", os); os.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } } But in the above code background is also generated using the setPaint menthod I am guessing. I want the background to be some image from my local machine whoz URL i should be able to mention like URL url=this.getClass().getResource("Desktop/images.jpg"); BufferedImage bufferedImage = ImageIO.read(url); I am just writing the above two lines for making the reader understand better what the issue is. Dont want to use the exact same commands. All I want is the the background of the captcha code generated should be an image of my choice.

    Read the article

  • Help finding time of collision

    - by WannaBe
    I am making a simple game right now and am struggling with collision response. My goal is to someday be able to turn it into a 2D platformer but I have a long way to go. I am currently making this in JavaScript and using the canvas element so (0,0) is in the top left and positive X is to the right and positive Y is down. I read a helpful post on StackExchange that got me started on this but I can't seem to get the algorithm 100% correct. How to deal with corner collisions in 2D? I can detect the collision fine but I can't seem to get the response right. The goal is to detect which side the player hit first since minimum displacement doesn't always work. The X response seems to work fine but the Y only works when I am far from the corners. Here is a picture showing what happens Here is the code var bx = box.x; var by = box.y; var bw = box.width; var bh = box.height; var boxCenterX = bx + (bw/2); var boxCenterY = by + (bh/2); var playerCenterX = player.x + player.xvel + (player.width/2); var playerCenterY = player.y + player.yvel + (player.height/2); //left = negative and right = positve, 0 = middle var distanceXin = playerCenterX - boxCenterX; var distanceYin = playerCenterY - boxCenterY; var distanceWidth = Math.abs(distanceXin); var distanceHeight = Math.abs(distanceYin); var halfWidths = (bw/2) + (player.width/2); var halfHeights = (bh/2) + (player.height/2); if(distanceWidth < halfWidths){ //xcollision if(distanceHeight < halfHeights){ //ycollision if(player.xvel == 0){ //adjust y if(distanceYin > 0){ //bottom player.y = by + bh; player.yvel = 0; }else{ player.y = by - player.height; player.yvel = 0; } }else if(player.yvel == 0){ //adjust x if(distanceXin > 0){ //right player.x = bx + bw; player.xvel = 0; }else{ //left player.x = bx - player.width; player.xvel = 0; } }else{ var yTime = distanceYin / player.yvel; var xTime = distanceXin / player.xvel; if(xTime < yTime){ //adjust the x it collided first if(distanceXin > 0){ //right player.x = bx + bw; player.xvel = 0; }else{ //left player.x = bx - player.width; player.xvel = 0; } }else{ //adjust the y it collided first if(distanceYin > 0){ //bottom player.y = by + bh; player.yvel = 0; }else{ player.y = by - player.height; player.yvel = 0; } } } } } And here is a JSFiddle if you would like to see the problem yourself. http://jsfiddle.net/dMumU/ To recreate this move the player to here And press up and left at the same time. The player will jump to the right for some reason. Any advice? I know I am close but I can't seem to get xTime and yTime to equal what I want every time.

    Read the article

  • Tile engine Texture not updating when numbers in array change

    - by Corey
    I draw my map from a txt file. I am using java with slick2d library. When I print the array the number changes in the array, but the texture doesn't change. public class Tiles { public Image[] tiles = new Image[5]; public int[][] map = new int[64][64]; public Image grass, dirt, fence, mound; private SpriteSheet tileSheet; public int tileWidth = 32; public int tileHeight = 32; public void init() throws IOException, SlickException { tileSheet = new SpriteSheet("assets/tiles.png", tileWidth, tileHeight); grass = tileSheet.getSprite(0, 0); dirt = tileSheet.getSprite(7, 7); fence = tileSheet.getSprite(2, 0); mound = tileSheet.getSprite(2, 6); tiles[0] = grass; tiles[1] = dirt; tiles[2] = fence; tiles[3] = mound; int x=0, y=0; BufferedReader in = new BufferedReader(new FileReader("assets/map.dat")); String line; while ((line = in.readLine()) != null) { String[] values = line.split(","); x = 0; for (String str : values) { int str_int = Integer.parseInt(str); map[x][y]=str_int; //System.out.print(map[x][y] + " "); x++; } //System.out.println(""); y++; } in.close(); } public void update(GameContainer gc) { } public void render(GameContainer gc) { for(int y = 0; y < map.length; y++) { for(int x = 0; x < map[0].length; x ++) { int textureIndex = map[x][y]; Image texture = tiles[textureIndex]; texture.draw(x*tileWidth,y*tileHeight); } } } } Mouse Picking Where I change the number in the array Input input = gc.getInput(); gc.getInput().setOffset(cameraX-400, cameraY-300); float mouseX = input.getMouseX(); float mouseY = input.getMouseY(); double mousetileX = Math.floor((double)mouseX/tiles.tileWidth); double mousetileY = Math.floor((double)mouseY/tiles.tileHeight); double playertileX = Math.floor(playerX/tiles.tileWidth); double playertileY = Math.floor(playerY/tiles.tileHeight); double lengthX = Math.abs((float)playertileX - mousetileX); double lengthY = Math.abs((float)playertileY - mousetileY); double distance = Math.sqrt((lengthX*lengthX)+(lengthY*lengthY)); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON) && distance < 4) { System.out.println("Clicked"); if(tiles.map[(int)mousetileX][(int)mousetileY] == 1) { tiles.map[(int)mousetileX][(int)mousetileY] = 0; } } I never ask a question until I have tried to figure it out myself. I have been stuck with this problem for two weeks. It's not like this site is made for asking questions or anything. So if you actually try to help me instead of telling me to use a debugger thank you. You either get told you have too much or too little code. Nothing is never enough for the people on here it's as bad as something like reddit. Idk what is wrong all my textures work when I render them it just doesn't update when the number in the array changes. I am obviously debugging when I say that I was printing the array and the number is changing like it should, so it's not a problem with my mouse picking code. It is a problem with my textures, but I don't know what because they all render correctly. That is why I need help.

    Read the article

  • Indexed view deadlocking

    - by Dave Ballantyne
    Deadlocks can be a really tricky thing to track down the root cause of.  There are lots of articles on the subject of tracking down deadlocks, but seldom do I find that in a production system that the cause is as straightforward.  That being said,  deadlocks are always caused by process A needs a resource that process B has locked and process B has a resource that process A needs.  There may be a longer chain of processes involved, but that is the basic premise. Here is one such (much simplified) scenario that was at first non-obvious to its cause: The system has two tables,  Products and Stock.  The Products table holds the description and prices of a product whilst Stock records the current stock level. USE tempdb GO CREATE TABLE Product ( ProductID INTEGER IDENTITY PRIMARY KEY, ProductName VARCHAR(255) NOT NULL, Price MONEY NOT NULL ) GO CREATE TABLE Stock ( ProductId INTEGER PRIMARY KEY, StockLevel INTEGER NOT NULL ) GO INSERT INTO Product SELECT TOP(1000) CAST(NEWID() AS VARCHAR(255)), ABS(CAST(CAST(NEWID() AS VARBINARY(255)) AS INTEGER))%100 FROM sys.columns a CROSS JOIN sys.columns b GO INSERT INTO Stock SELECT ProductID,ABS(CAST(CAST(NEWID() AS VARBINARY(255)) AS INTEGER))%100 FROM Product There is a single stored procedure of GetStock: Create Procedure GetStock as SELECT Product.ProductID,Product.ProductName FROM dbo.Product join dbo.Stock on Stock.ProductId = Product.ProductID where Stock.StockLevel <> 0 Analysis of the system showed that this procedure was causing a performance overhead and as reads of this data was many times more than writes,  an indexed view was created to lower the overhead. CREATE VIEW vwActiveStock With schemabinding AS SELECT Product.ProductID,Product.ProductName FROM dbo.Product join dbo.Stock on Stock.ProductId = Product.ProductID where Stock.StockLevel <> 0 go CREATE UNIQUE CLUSTERED INDEX PKvwActiveStock on vwActiveStock(ProductID) This worked perfectly, performance was improved, the team name was cheered to the rafters and beers all round.  Then, after a while, something else happened… The system updating the data changed,  The update pattern of both the Stock update and the Product update used to be: BEGIN TRAN UPDATE... COMMIT BEGIN TRAN UPDATE... COMMIT BEGIN TRAN UPDATE... COMMIT It changed to: BEGIN TRAN UPDATE... UPDATE... UPDATE... COMMIT Nothing that would raise an eyebrow in even the closest of code reviews.  But after this change we saw deadlocks occuring. You can reproduce this by opening two sessions. In session 1 begin transaction Update Product set ProductName ='Test' where ProductID = 998 Then in session 2 begin transaction Update Stock set Stocklevel = 5 where ProductID = 999 Update Stock set Stocklevel = 5 where ProductID = 998 Hop back to session 1 and.. Update Product set ProductName ='Test' where ProductID = 999 Looking at the deadlock graphs we could see the contention was between two processes, one updating stock and the other updating product, but we knew that all the processes do to the tables is update them.  Period.  There are separate processes that handle the update of stock and product and never the twain shall meet, no reason why one should be requiring data from the other.  Then it struck us,  AH the indexed view. Naturally, when you make an update to any table involved in a indexed view, the view has to be updated.  When this happens, the data in all the tables have to be read, so that explains our deadlocks.  The data from stock is read when you update product and vice-versa. The fix, once you understand the problem fully, is pretty simple, the apps did not guarantee the order in which data was updated.  Luckily it was a relatively simple fix to order the updates and deadlocks went away.  Note, that there is still a *slight* risk of a deadlock occurring, if both a stock update and product update occur at *exactly* the same time.

    Read the article

  • Wikipedia A* pathfinding algorithm takes a lot of time

    - by Vee
    I've successfully implemented A* pathfinding in C# but it is very slow, and I don't understand why. I even tried not sorting the openNodes list but it's still the same. The map is 80x80, and there are 10-11 nodes. I took the pseudocode from here Wikipedia And this is my implementation: public static List<PGNode> Pathfind(PGMap mMap, PGNode mStart, PGNode mEnd) { mMap.ClearNodes(); mMap.GetTile(mStart.X, mStart.Y).Value = 0; mMap.GetTile(mEnd.X, mEnd.Y).Value = 0; List<PGNode> openNodes = new List<PGNode>(); List<PGNode> closedNodes = new List<PGNode>(); List<PGNode> solutionNodes = new List<PGNode>(); mStart.G = 0; mStart.H = GetManhattanHeuristic(mStart, mEnd); solutionNodes.Add(mStart); solutionNodes.Add(mEnd); openNodes.Add(mStart); // 1) Add the starting square (or node) to the open list. while (openNodes.Count > 0) // 2) Repeat the following: { openNodes.Sort((p1, p2) => p1.F.CompareTo(p2.F)); PGNode current = openNodes[0]; // a) We refer to this as the current square.) if (current == mEnd) { while (current != null) { solutionNodes.Add(current); current = current.Parent; } return solutionNodes; } openNodes.Remove(current); closedNodes.Add(current); // b) Switch it to the closed list. List<PGNode> neighborNodes = current.GetNeighborNodes(); double cost = 0; bool isCostBetter = false; for (int i = 0; i < neighborNodes.Count; i++) { PGNode neighbor = neighborNodes[i]; cost = current.G + 10; isCostBetter = false; if (neighbor.Passable == false || closedNodes.Contains(neighbor)) continue; // If it is not walkable or if it is on the closed list, ignore it. if (openNodes.Contains(neighbor) == false) { openNodes.Add(neighbor); // If it isn’t on the open list, add it to the open list. isCostBetter = true; } else if (cost < neighbor.G) { isCostBetter = true; } if (isCostBetter) { neighbor.Parent = current; // Make the current square the parent of this square. neighbor.G = cost; neighbor.H = GetManhattanHeuristic(current, neighbor); } } } return null; } Here's the heuristic I'm using: private static double GetManhattanHeuristic(PGNode mStart, PGNode mEnd) { return Math.Abs(mStart.X - mEnd.X) + Math.Abs(mStart.Y - mEnd.Y); } What am I doing wrong? It's an entire day I keep looking at the same code.

    Read the article

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