Search Results

Search found 233 results on 10 pages for 'mat banik'.

Page 2/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • Opposite Force to Apply to a Collided Rigid Body?

    - by Milo
    I'm working on the physics for my GTA2-like game so I can learn more about game physics. The collision detection and resolution are working great. I'm now just unsure how to compute the force to apply to a body after it collides with a wall. My rigid body looks like this: /our simulation object class RigidBody extends Entity { //linear private Vector2D velocity = new Vector2D(); private Vector2D forces = new Vector2D(); private float mass; private Vector2D v = new Vector2D(); //angular private float angularVelocity; private float torque; private float inertia; //graphical private Vector2D halfSize = new Vector2D(); private Bitmap image; private Matrix mat = new Matrix(); private float[] Vector2Ds = new float[2]; private Vector2D tangent = new Vector2D(); private static Vector2D worldRelVec = new Vector2D(); private static Vector2D relWorldVec = new Vector2D(); private static Vector2D pointVelVec = new Vector2D(); private static Vector2D acceleration = new Vector2D(); public RigidBody() { //set these defaults so we don't get divide by zeros mass = 1.0f; inertia = 1.0f; setLayer(LAYER_OBJECTS); } protected void rectChanged() { if(getWorld() != null) { getWorld().updateDynamic(this); } } //intialize out parameters public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //store physical parameters this.halfSize = halfSize; this.mass = mass; image = bitmap; inertia = (1.0f / 20.0f) * (halfSize.x * halfSize.x) * (halfSize.y * halfSize.y) * mass; RectF rect = new RectF(); float scalar = 10.0f; rect.left = (int)-halfSize.x * scalar; rect.top = (int)-halfSize.y * scalar; rect.right = rect.left + (int)(halfSize.x * 2.0f * scalar); rect.bottom = rect.top + (int)(halfSize.y * 2.0f * scalar); setRect(rect); } public void setLocation(Vector2D position, float angle) { getRect().set(position.x,position.y, getWidth(), getHeight(), angle); rectChanged(); } public Vector2D getPosition() { return getRect().getCenter(); } @Override public void update(float timeStep) { doUpdate(timeStep); } public void doUpdate(float timeStep) { //integrate physics //linear acceleration.x = forces.x / mass; acceleration.y = forces.y / mass; velocity.x += (acceleration.x * timeStep); velocity.y += (acceleration.y * timeStep); //velocity = Vector2D.add(velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); v.x = getRect().getCenter().getX() + (velocity.x * timeStep); v.y = getRect().getCenter().getY() + (velocity.y * timeStep); setCenter(v.x, v.y); forces.x = 0; //clear forces forces.y = 0; //angular float angAcc = torque / inertia; angularVelocity += angAcc * timeStep; setAngle(getAngle() + angularVelocity * timeStep); torque = 0; //clear torque } //take a relative Vector2D and make it a world Vector2D public Vector2D relativeToWorld(Vector2D relative) { mat.reset(); Vector2Ds[0] = relative.x; Vector2Ds[1] = relative.y; mat.postRotate(JMath.radToDeg(getAngle())); mat.mapVectors(Vector2Ds); relWorldVec.x = Vector2Ds[0]; relWorldVec.y = Vector2Ds[1]; return relWorldVec; } //take a world Vector2D and make it a relative Vector2D public Vector2D worldToRelative(Vector2D world) { mat.reset(); Vector2Ds[0] = world.x; Vector2Ds[1] = world.y; mat.postRotate(JMath.radToDeg(-getAngle())); mat.mapVectors(Vector2Ds); worldRelVec.x = Vector2Ds[0]; worldRelVec.y = Vector2Ds[1]; return worldRelVec; } //velocity of a point on body public Vector2D pointVelocity(Vector2D worldOffset) { tangent.x = -worldOffset.y; tangent.y = worldOffset.x; pointVelVec.x = (tangent.x * angularVelocity) + velocity.x; pointVelVec.y = (tangent.y * angularVelocity) + velocity.y; return pointVelVec; } public void applyForce(Vector2D worldForce, Vector2D worldOffset) { //add linear force forces.x += worldForce.x; forces.y += worldForce.y; //add associated torque torque += Vector2D.cross(worldOffset, worldForce); } @Override public void draw( GraphicsContext c) { c.drawRotatedScaledBitmap(image, getPosition().x, getPosition().y, getWidth(), getHeight(), getAngle()); } public Vector2D getVelocity() { return velocity; } public void setVelocity(Vector2D velocity) { this.velocity = velocity; } } The way it is given force is by the applyForce method, this method considers angular torque. I'm just not sure how to come up with the vectors in the case where: RigidBody hits static entity RigidBody hits other RigidBody that may or may not be in motion. Would anyone know a way (without too complex math) that I could figure out the opposite force I need to apply to the car? I know the normal it is colliding with and how deep it collided. My main goal is so that say I hit a building from the side, well the car should not just stay there, it should slowly rotate out of it if I'm more than 45 degrees. Right now when I hit a wall I only change the velocity directly which does not consider angular force. Thanks!

    Read the article

  • can lapply not modify variables in a higher scope

    - by stevejb
    I often want to do essentially the following: mat <- matrix(0,nrow=10,ncol=1) lapply(1:10, function(i) { mat[i,] <- rnorm(1,mean=i)}) But, I would expect that mat would have 10 random numbers in it, but rather it has 0. (I am not worried about the rnorm part. Clearly there is a right way to do that. I am worry about affecting mat from within an anonymous function of lapply) Can I not affect matrix mat from inside lapply? Why not? Is there a scoping rule of R that is blocking this?

    Read the article

  • Efficient calculation of matrix cumulative standard deviation in r

    - by Abiel
    I recently posted this question on the r-help mailing list but got no answers, so I thought I would post it here as well and see if there were any suggestions. I am trying to calculate the cumulative standard deviation of a matrix. I want a function that accepts a matrix and returns a matrix of the same size where output cell (i,j) is set to the standard deviation of input column j between rows 1 and i. NAs should be ignored, unless cell (i,j) of the input matrix itself is NA, in which case cell (i,j) of the output matrix should also be NA. I could not find a built-in function, so I implemented the following code. Unfortunately, this uses a loop that ends up being somewhat slow for large matrices. Is there a faster built-in function or can someone suggest a better approach? cumsd <- function(mat) { retval <- mat*NA for (i in 2:nrow(mat)) retval[i,] <- sd(mat[1:i,], na.rm=T) retval[is.na(mat)] <- NA retval } Thanks.

    Read the article

  • OpenCV: Shift/Align face image relative to reference Image (Image Registration)

    - by Abhischek
    I am new to OpenCV2 and working on a project in emotion recognition and would like to align a facial image in relation to a reference facial image. I would like to get the image translation working before moving to rotation. Current idea is to run a search within a limited range on both x and y coordinates and use the sum of squared differences as error metric to select the optimal x/y parameters to align the image. I'm using the OpenCV face_cascade function to detect the face images, all images are resized to a fixed (128x128). Question: Which parameters of the Mat image do I need to modify to shift the image in a positive/negative direction on both x and y axis? I believe setImageROI is no longer supported by Mat datatypes? I have the ROIs for both faces available however I am unsure how to use them. void alignImage(vector<Rect> faceROIstore, vector<Mat> faceIMGstore) { Mat refimg = faceIMGstore[1]; //reference image Mat dispimg = faceIMGstore[52]; // "displaced" version of reference image //Rect refROI = faceROIstore[1]; //Bounding box for face in reference image //Rect dispROI = faceROIstore[52]; //Bounding box for face in displaced image Mat aligned; matchTemplate(dispimg, refimg, aligned, CV_TM_SQDIFF_NORMED); imshow("Aligned image", aligned); } The idea for this approach is based on Image Alignment Tutorial by Richard Szeliski Working on Windows with OpenCV 2.4. Any suggestions are much appreciated.

    Read the article

  • Convert image color space and output separate channels in OpenCV

    - by Victor May
    I'm trying to reduce the runtime of a routine that converts an RGB image to a YCbCr image. My code looks like this: cv::Mat input(BGR->m_height, BGR->m_width, CV_8UC3, BGR->m_imageData); cv::Mat output(BGR->m_height, BGR->m_width, CV_8UC3); cv::cvtColor(input, output, CV_BGR2YCrCb); cv::Mat outputArr[3]; outputArr[0] = cv::Mat(BGR->m_height, BGR->m_width, CV_8UC1, Y->m_imageData); outputArr[1] = cv::Mat(BGR->m_height, BGR->m_width, CV_8UC1, Cr->m_imageData); outputArr[2] = cv::Mat(BGR->m_height, BGR->m_width, CV_8UC1, Cb->m_imageData); split(output,outputArr); But, this code is slow because there is a redundant split operation which copies the interleaved RGB image into the separate channel images. Is there a way to make the cvtColor function create an output that is already split into channel images? I tried to use constructors of the _OutputArray class that accepts a vector or array of matrices as an input, but it didn't work.

    Read the article

  • 3x3 array = 10 numbers

    - by user1708505
    i have this code #include <math.h> #include <stdio.h> const int n = 3; const int s = 3; int getm(int mat[n][s]); int printm(int mat[n][s]); int main() { int m[n][s]; getm(m); printm(m); return 0; } int getm(int mat[n][s]) { for(int x = 0;x < n;x++) { for (int y = 0;y<s;y++) { scanf("%i ", &mat[x][y]); } } return 0; } int printm(int mat[n][s]) { for(int x = 0;x<n;x++) { for(int y = 0;y<s;y++) { printf("%i ", mat[x][y]); if(y==(s-1)) { printf("\n"); } } } } which shoud ask for 9 numbers to make a 3x3 matrix array, but it actually asks for 10 numbers, printm is working well - printing only 9 numbers. Where is error?

    Read the article

  • Help with Collision Resolution?

    - by Milo
    I'm trying to learn about physics by trying to make a simplified GTA 2 clone. My only problem is collision resolution. Everything else works great. I have a rigid body class and from there cars and a wheel class: class RigidBody extends Entity { //linear private Vector2D velocity = new Vector2D(); private Vector2D forces = new Vector2D(); private OBB2D predictionRect = new OBB2D(new Vector2D(), 1.0f, 1.0f, 0.0f); private float mass; private Vector2D deltaVec = new Vector2D(); private Vector2D v = new Vector2D(); //angular private float angularVelocity; private float torque; private float inertia; //graphical private Vector2D halfSize = new Vector2D(); private Bitmap image; private Matrix mat = new Matrix(); private float[] Vector2Ds = new float[2]; private Vector2D tangent = new Vector2D(); private static Vector2D worldRelVec = new Vector2D(); private static Vector2D relWorldVec = new Vector2D(); private static Vector2D pointVelVec = new Vector2D(); public RigidBody() { //set these defaults so we don't get divide by zeros mass = 1.0f; inertia = 1.0f; setLayer(LAYER_OBJECTS); } protected void rectChanged() { if(getWorld() != null) { getWorld().updateDynamic(this); } } //intialize out parameters public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //store physical parameters this.halfSize = halfSize; this.mass = mass; image = bitmap; inertia = (1.0f / 20.0f) * (halfSize.x * halfSize.x) * (halfSize.y * halfSize.y) * mass; RectF rect = new RectF(); float scalar = 10.0f; rect.left = (int)-halfSize.x * scalar; rect.top = (int)-halfSize.y * scalar; rect.right = rect.left + (int)(halfSize.x * 2.0f * scalar); rect.bottom = rect.top + (int)(halfSize.y * 2.0f * scalar); setRect(rect); predictionRect.set(rect); } public void setLocation(Vector2D position, float angle) { getRect().set(position, getWidth(), getHeight(), angle); rectChanged(); } public void setPredictionLocation(Vector2D position, float angle) { getPredictionRect().set(position, getWidth(), getHeight(), angle); } public void setPredictionCenter(Vector2D center) { getPredictionRect().moveTo(center); } public void setPredictionAngle(float angle) { predictionRect.setAngle(angle); } public Vector2D getPosition() { return getRect().getCenter(); } public OBB2D getPredictionRect() { return predictionRect; } @Override public void update(float timeStep) { doUpdate(false,timeStep); } public void doUpdate(boolean prediction, float timeStep) { //integrate physics //linear Vector2D acceleration = Vector2D.scalarDivide(forces, mass); if(prediction) { Vector2D velocity = Vector2D.add(this.velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); c = Vector2D.add(getRect().getCenter(), Vector2D.scalarMultiply(velocity , timeStep)); setPredictionCenter(c); //forces = new Vector2D(0,0); //clear forces } else { velocity.x += (acceleration.x * timeStep); velocity.y += (acceleration.y * timeStep); //velocity = Vector2D.add(velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); v.x = getRect().getCenter().getX() + (velocity.x * timeStep); v.y = getRect().getCenter().getY() + (velocity.y * timeStep); deltaVec.x = v.x - c.x; deltaVec.y = v.y - c.y; deltaVec.normalize(); setCenter(v.x, v.y); forces.x = 0; //clear forces forces.y = 0; } //angular float angAcc = torque / inertia; if(prediction) { float angularVelocity = this.angularVelocity + angAcc * timeStep; setPredictionAngle(getAngle() + angularVelocity * timeStep); //torque = 0; //clear torque } else { angularVelocity += angAcc * timeStep; setAngle(getAngle() + angularVelocity * timeStep); torque = 0; //clear torque } } public void updatePrediction(float timeStep) { doUpdate(true, timeStep); } //take a relative Vector2D and make it a world Vector2D public Vector2D relativeToWorld(Vector2D relative) { mat.reset(); Vector2Ds[0] = relative.x; Vector2Ds[1] = relative.y; mat.postRotate(JMath.radToDeg(getAngle())); mat.mapVectors(Vector2Ds); relWorldVec.x = Vector2Ds[0]; relWorldVec.y = Vector2Ds[1]; return new Vector2D(Vector2Ds[0], Vector2Ds[1]); } //take a world Vector2D and make it a relative Vector2D public Vector2D worldToRelative(Vector2D world) { mat.reset(); Vector2Ds[0] = world.x; Vector2Ds[1] = world.y; mat.postRotate(JMath.radToDeg(-getAngle())); mat.mapVectors(Vector2Ds); return new Vector2D(Vector2Ds[0], Vector2Ds[1]); } //velocity of a point on body public Vector2D pointVelocity(Vector2D worldOffset) { tangent.x = -worldOffset.y; tangent.y = worldOffset.x; return Vector2D.add( Vector2D.scalarMultiply(tangent, angularVelocity) , velocity); } public void applyForce(Vector2D worldForce, Vector2D worldOffset) { //add linear force forces.x += worldForce.x; forces.y += worldForce.y; //add associated torque torque += Vector2D.cross(worldOffset, worldForce); } @Override public void draw( GraphicsContext c) { c.drawRotatedScaledBitmap(image, getPosition().x, getPosition().y, getWidth(), getHeight(), getAngle()); } public Vector2D getVelocity() { return velocity; } public void setVelocity(Vector2D velocity) { this.velocity = velocity; } public Vector2D getDeltaVec() { return deltaVec; } } Vehicle public class Wheel { private Vector2D forwardVec; private Vector2D sideVec; private float wheelTorque; private float wheelSpeed; private float wheelInertia; private float wheelRadius; private Vector2D position = new Vector2D(); public Wheel(Vector2D position, float radius) { this.position = position; setSteeringAngle(0); wheelSpeed = 0; wheelRadius = radius; wheelInertia = (radius * radius) * 1.1f; } public void setSteeringAngle(float newAngle) { Matrix mat = new Matrix(); float []vecArray = new float[4]; //forward Vector vecArray[0] = 0; vecArray[1] = 1; //side Vector vecArray[2] = -1; vecArray[3] = 0; mat.postRotate(newAngle / (float)Math.PI * 180.0f); mat.mapVectors(vecArray); forwardVec = new Vector2D(vecArray[0], vecArray[1]); sideVec = new Vector2D(vecArray[2], vecArray[3]); } public void addTransmissionTorque(float newValue) { wheelTorque += newValue; } public float getWheelSpeed() { return wheelSpeed; } public Vector2D getAnchorPoint() { return position; } public Vector2D calculateForce(Vector2D relativeGroundSpeed, float timeStep, boolean prediction) { //calculate speed of tire patch at ground Vector2D patchSpeed = Vector2D.scalarMultiply(Vector2D.scalarMultiply( Vector2D.negative(forwardVec), wheelSpeed), wheelRadius); //get velocity difference between ground and patch Vector2D velDifference = Vector2D.add(relativeGroundSpeed , patchSpeed); //project ground speed onto side axis Float forwardMag = new Float(0.0f); Vector2D sideVel = velDifference.project(sideVec); Vector2D forwardVel = velDifference.project(forwardVec, forwardMag); //calculate super fake friction forces //calculate response force Vector2D responseForce = Vector2D.scalarMultiply(Vector2D.negative(sideVel), 2.0f); responseForce = Vector2D.subtract(responseForce, forwardVel); float topSpeed = 500.0f; //calculate torque on wheel wheelTorque += forwardMag * wheelRadius; //integrate total torque into wheel wheelSpeed += wheelTorque / wheelInertia * timeStep; //top speed limit (kind of a hack) if(wheelSpeed > topSpeed) { wheelSpeed = topSpeed; } //clear our transmission torque accumulator wheelTorque = 0; //return force acting on body return responseForce; } public void setTransmissionTorque(float newValue) { wheelTorque = newValue; } public float getTransmissionTourque() { return wheelTorque; } public void setWheelSpeed(float speed) { wheelSpeed = speed; } } //our vehicle object public class Vehicle extends RigidBody { private Wheel [] wheels = new Wheel[4]; private boolean throttled = false; public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //front wheels wheels[0] = new Wheel(new Vector2D(halfSize.x, halfSize.y), 0.45f); wheels[1] = new Wheel(new Vector2D(-halfSize.x, halfSize.y), 0.45f); //rear wheels wheels[2] = new Wheel(new Vector2D(halfSize.x, -halfSize.y), 0.75f); wheels[3] = new Wheel(new Vector2D(-halfSize.x, -halfSize.y), 0.75f); super.initialize(halfSize, mass, bitmap); } public void setSteering(float steering) { float steeringLock = 0.13f; //apply steering angle to front wheels wheels[0].setSteeringAngle(steering * steeringLock); wheels[1].setSteeringAngle(steering * steeringLock); } public void setThrottle(float throttle, boolean allWheel) { float torque = 85.0f; throttled = true; //apply transmission torque to back wheels if (allWheel) { wheels[0].addTransmissionTorque(throttle * torque); wheels[1].addTransmissionTorque(throttle * torque); } wheels[2].addTransmissionTorque(throttle * torque); wheels[3].addTransmissionTorque(throttle * torque); } public void setBrakes(float brakes) { float brakeTorque = 15.0f; //apply brake torque opposing wheel vel for (Wheel wheel : wheels) { float wheelVel = wheel.getWheelSpeed(); wheel.addTransmissionTorque(-wheelVel * brakeTorque * brakes); } } public void doUpdate(float timeStep, boolean prediction) { for (Wheel wheel : wheels) { float wheelVel = wheel.getWheelSpeed(); //apply negative force to naturally slow down car if(!throttled && !prediction) wheel.addTransmissionTorque(-wheelVel * 0.11f); Vector2D worldWheelOffset = relativeToWorld(wheel.getAnchorPoint()); Vector2D worldGroundVel = pointVelocity(worldWheelOffset); Vector2D relativeGroundSpeed = worldToRelative(worldGroundVel); Vector2D relativeResponseForce = wheel.calculateForce(relativeGroundSpeed, timeStep,prediction); Vector2D worldResponseForce = relativeToWorld(relativeResponseForce); applyForce(worldResponseForce, worldWheelOffset); } //no throttling yet this frame throttled = false; if(prediction) { super.updatePrediction(timeStep); } else { super.update(timeStep); } } @Override public void update(float timeStep) { doUpdate(timeStep,false); } public void updatePrediction(float timeStep) { doUpdate(timeStep,true); } public void inverseThrottle() { float scalar = 0.2f; for(Wheel wheel : wheels) { wheel.setTransmissionTorque(-wheel.getTransmissionTourque() * scalar); wheel.setWheelSpeed(-wheel.getWheelSpeed() * 0.1f); } } } And my big hack collision resolution: private void update() { camera.setPosition((vehicle.getPosition().x * camera.getScale()) - ((getWidth() ) / 2.0f), (vehicle.getPosition().y * camera.getScale()) - ((getHeight() ) / 2.0f)); //camera.move(input.getAnalogStick().getStickValueX() * 15.0f, input.getAnalogStick().getStickValueY() * 15.0f); if(input.isPressed(ControlButton.BUTTON_GAS)) { vehicle.setThrottle(1.0f, false); } if(input.isPressed(ControlButton.BUTTON_STEAL_CAR)) { vehicle.setThrottle(-1.0f, false); } if(input.isPressed(ControlButton.BUTTON_BRAKE)) { vehicle.setBrakes(1.0f); } vehicle.setSteering(input.getAnalogStick().getStickValueX()); //vehicle.update(16.6666666f / 1000.0f); boolean colided = false; vehicle.updatePrediction(16.66666f / 1000.0f); List<Entity> buildings = world.queryStaticSolid(vehicle,vehicle.getPredictionRect()); if(buildings.size() > 0) { colided = true; } if(!colided) { vehicle.update(16.66f / 1000.0f); } else { Vector2D delta = vehicle.getDeltaVec(); vehicle.setVelocity(Vector2D.negative(vehicle.getVelocity().multiply(0.2f)). add(delta.multiply(-1.0f))); vehicle.inverseThrottle(); } } Here is OBB public class OBB2D { // Corners of the box, where 0 is the lower left. private Vector2D corner[] = new Vector2D[4]; private Vector2D center = new Vector2D(); private Vector2D extents = new Vector2D(); private RectF boundingRect = new RectF(); private float angle; //Two edges of the box extended away from corner[0]. private Vector2D axis[] = new Vector2D[2]; private double origin[] = new double[2]; public OBB2D(Vector2D center, float w, float h, float angle) { set(center,w,h,angle); } public OBB2D(float left, float top, float width, float height) { set(new Vector2D(left + (width / 2), top + (height / 2)),width,height,0.0f); } public void set(Vector2D center,float w, float h,float angle) { Vector2D X = new Vector2D( (float)Math.cos(angle), (float)Math.sin(angle)); Vector2D Y = new Vector2D((float)-Math.sin(angle), (float)Math.cos(angle)); X = X.multiply( w / 2); Y = Y.multiply( h / 2); corner[0] = center.subtract(X).subtract(Y); corner[1] = center.add(X).subtract(Y); corner[2] = center.add(X).add(Y); corner[3] = center.subtract(X).add(Y); computeAxes(); extents.x = w / 2; extents.y = h / 2; computeDimensions(center,angle); } private void computeDimensions(Vector2D center,float angle) { this.center.x = center.x; this.center.y = center.y; this.angle = angle; boundingRect.left = Math.min(Math.min(corner[0].x, corner[3].x), Math.min(corner[1].x, corner[2].x)); boundingRect.top = Math.min(Math.min(corner[0].y, corner[1].y),Math.min(corner[2].y, corner[3].y)); boundingRect.right = Math.max(Math.max(corner[1].x, corner[2].x), Math.max(corner[0].x, corner[3].x)); boundingRect.bottom = Math.max(Math.max(corner[2].y, corner[3].y),Math.max(corner[0].y, corner[1].y)); } public void set(RectF rect) { set(new Vector2D(rect.centerX(),rect.centerY()),rect.width(),rect.height(),0.0f); } // Returns true if other overlaps one dimension of this. private boolean overlaps1Way(OBB2D other) { for (int a = 0; a < axis.length; ++a) { double t = other.corner[0].dot(axis[a]); // Find the extent of box 2 on axis a double tMin = t; double tMax = t; for (int c = 1; c < corner.length; ++c) { t = other.corner[c].dot(axis[a]); if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } } // We have to subtract off the origin // See if [tMin, tMax] intersects [0, 1] if ((tMin > 1 + origin[a]) || (tMax < origin[a])) { // There was no intersection along this dimension; // the boxes cannot possibly overlap. return false; } } // There was no dimension along which there is no intersection. // Therefore the boxes overlap. return true; } //Updates the axes after the corners move. Assumes the //corners actually form a rectangle. private void computeAxes() { axis[0] = corner[1].subtract(corner[0]); axis[1] = corner[3].subtract(corner[0]); // Make the length of each axis 1/edge length so we know any // dot product must be less than 1 to fall within the edge. for (int a = 0; a < axis.length; ++a) { axis[a] = axis[a].divide((axis[a].length() * axis[a].length())); origin[a] = corner[0].dot(axis[a]); } } public void moveTo(Vector2D center) { Vector2D centroid = (corner[0].add(corner[1]).add(corner[2]).add(corner[3])).divide(4.0f); Vector2D translation = center.subtract(centroid); for (int c = 0; c < 4; ++c) { corner[c] = corner[c].add(translation); } computeAxes(); computeDimensions(center,angle); } // Returns true if the intersection of the boxes is non-empty. public boolean overlaps(OBB2D other) { if(right() < other.left()) { return false; } if(bottom() < other.top()) { return false; } if(left() > other.right()) { return false; } if(top() > other.bottom()) { return false; } if(other.getAngle() == 0.0f && getAngle() == 0.0f) { return true; } return overlaps1Way(other) && other.overlaps1Way(this); } public Vector2D getCenter() { return center; } public float getWidth() { return extents.x * 2; } public float getHeight() { return extents.y * 2; } public void setAngle(float angle) { set(center,getWidth(),getHeight(),angle); } public float getAngle() { return angle; } public void setSize(float w,float h) { set(center,w,h,angle); } public float left() { return boundingRect.left; } public float right() { return boundingRect.right; } public float bottom() { return boundingRect.bottom; } public float top() { return boundingRect.top; } public RectF getBoundingRect() { return boundingRect; } public boolean overlaps(float left, float top, float right, float bottom) { if(right() < left) { return false; } if(bottom() < top) { return false; } if(left() > right) { return false; } if(top() > bottom) { return false; } return true; } }; What I do is when I predict a hit on the car, I force it back. It does not work that well and seems like a bad idea. What could I do to have more proper collision resolution. Such that if I hit a wall I will never get stuck in it and if I hit the side of a wall I can steer my way out of it. Thanks I found this nice ppt. It talks about pulling objects apart and calculating new velocities. How could I calc new velocities in my case? http://www.google.ca/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0CC8QFjAB&url=http%3A%2F%2Fcoitweb.uncc.edu%2F~tbarnes2%2FGameDesignFall05%2FSlides%2FCh4.2-CollDet.ppt&ei=x4ucULy5M6-N0QGRy4D4Cg&usg=AFQjCNG7FVDXWRdLv8_-T5qnFyYld53cTQ&cad=rja

    Read the article

  • Just installed Ubuntu 12.04 - integrated speakers aren't working but headphones are

    - by Mat Elkan
    I've just installed Ubuntu 12.04 alongside Windows Vista. There were no previous versions of Ubuntu installed. My computer is a Sony Vaio all in one, with integrated sound card and speakers. I can't get any sound coming from the speakers, but if I plug headphones into the jack on the side of the computer and select "headphones" under "sound" in "system settings" I can get sound through them. I have been searching all day trying to find a fix but haven't had any luck. Any advice would be greatly appreciated. Thanks! Mat :-)

    Read the article

  • How to move the camera sideways in libgdx

    - by Bubblewrap
    I want to move the camera sideways (strafe/truck), now i had the following in mind, but it doesn't look like there are standard methods to achieve this in libgdx. If i want to move the camera sideways by x, i think i need to do the following: Create a Matrix4 mat Determine the orthogonal vector v between camera.direction and camera.up translate mat by v*x multiply camera.position by mat Will this approach do what i think it does, and is it a good way to do it? And how can i do this in libgdx? I get "stuck" at step 2, as in, i have not found any standard method in libgdx to calculate an orthogonal vector. EDIT: I think i can use camera.direction.crs(camera.up) to find v. Guess i can now try this approach tonight and see if it works.

    Read the article

  • How do I move the camera sideways in Libgdx?

    - by Bubblewrap
    I want to move the camera sideways (strafe). I had the following in mind, but it doesn't look like there are standard methods to achieve this in Libgdx. If I want to move the camera sideways by x, I think I need to do the following: Create a Matrix4 mat Determine the orthogonal vector v between camera.direction and camera.up Translate mat by v*x Multiply camera.position by mat Will this approach do what I think it does, and is it a good way to do it? And how can I do this in libgdx? I get "stuck" at step 2, as I have not found any standard method in Libgdx to calculate an orthogonal vector. EDIT: I think I can use camera.direction.crs(camera.up) to find v. I'll try this approach tonight and see if it works. EDIT2: I got it working and didn't need the matrix after all: Vector3 right = camera.direction.cpy().crs(camera.up).nor(); camera.position.add(right.mul(x));

    Read the article

  • 2D OBB collision detection, resolving collisions?

    - by Milo
    I currently use OBBs and I have a vehicle that is a rigid body and some buildings. Here is my update() private void update() { camera.setPosition((vehicle.getPosition().x * camera.getScale()) - ((getWidth() ) / 2.0f), (vehicle.getPosition().y * camera.getScale()) - ((getHeight() ) / 2.0f)); //camera.move(input.getAnalogStick().getStickValueX() * 15.0f, input.getAnalogStick().getStickValueY() * 15.0f); if(input.isPressed(ControlButton.BUTTON_GAS)) { vehicle.setThrottle(1.0f, false); } if(input.isPressed(ControlButton.BUTTON_BRAKE)) { vehicle.setBrakes(1.0f); } vehicle.setSteering(input.getAnalogStick().getStickValueX()); vehicle.update(16.6666f / 1000.0f); ArrayList<Building> buildings = city.getBuildings(); for(Building b : buildings) { if(vehicle.getRect().overlaps(b.getRect())) { vehicle.update(-17.0f / 1000.0f); break; } } } The collision detection works well. What doesn't is how they are dealt with. My goal is simple. If the vehicle hits a building, it should stop, and never go into the building. When I apply negative torque to reverse the car should not feel buggy and move away from the building. I don't want this to look buggy. This is my rigid body class: class RigidBody extends Entity { //linear private Vector2D velocity = new Vector2D(); private Vector2D forces = new Vector2D(); private float mass; //angular private float angularVelocity; private float torque; private float inertia; //graphical private Vector2D halfSize = new Vector2D(); private Bitmap image; public RigidBody() { //set these defaults so we don't get divide by zeros mass = 1.0f; inertia = 1.0f; } //intialize out parameters public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //store physical parameters this.halfSize = halfSize; this.mass = mass; image = bitmap; inertia = (1.0f / 20.0f) * (halfSize.x * halfSize.x) * (halfSize.y * halfSize.y) * mass; RectF rect = new RectF(); float scalar = 10.0f; rect.left = (int)-halfSize.x * scalar; rect.top = (int)-halfSize.y * scalar; rect.right = rect.left + (int)(halfSize.x * 2.0f * scalar); rect.bottom = rect.top + (int)(halfSize.y * 2.0f * scalar); setRect(rect); } public void setLocation(Vector2D position, float angle) { getRect().set(position, getWidth(), getHeight(), angle); } public Vector2D getPosition() { return getRect().getCenter(); } @Override public void update(float timeStep) { //integrate physics //linear Vector2D acceleration = Vector2D.scalarDivide(forces, mass); velocity = Vector2D.add(velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); c = Vector2D.add(getRect().getCenter(), Vector2D.scalarMultiply(velocity , timeStep)); setCenter(c.x, c.y); forces = new Vector2D(0,0); //clear forces //angular float angAcc = torque / inertia; angularVelocity += angAcc * timeStep; setAngle(getAngle() + angularVelocity * timeStep); torque = 0; //clear torque } //take a relative Vector2D and make it a world Vector2D public Vector2D relativeToWorld(Vector2D relative) { Matrix mat = new Matrix(); float[] Vector2Ds = new float[2]; Vector2Ds[0] = relative.x; Vector2Ds[1] = relative.y; mat.postRotate(JMath.radToDeg(getAngle())); mat.mapVectors(Vector2Ds); return new Vector2D(Vector2Ds[0], Vector2Ds[1]); } //take a world Vector2D and make it a relative Vector2D public Vector2D worldToRelative(Vector2D world) { Matrix mat = new Matrix(); float[] Vectors = new float[2]; Vectors[0] = world.x; Vectors[1] = world.y; mat.postRotate(JMath.radToDeg(-getAngle())); mat.mapVectors(Vectors); return new Vector2D(Vectors[0], Vectors[1]); } //velocity of a point on body public Vector2D pointVelocity(Vector2D worldOffset) { Vector2D tangent = new Vector2D(-worldOffset.y, worldOffset.x); return Vector2D.add( Vector2D.scalarMultiply(tangent, angularVelocity) , velocity); } public void applyForce(Vector2D worldForce, Vector2D worldOffset) { //add linear force forces = Vector2D.add(forces ,worldForce); //add associated torque torque += Vector2D.cross(worldOffset, worldForce); } @Override public void draw( GraphicsContext c) { c.drawRotatedScaledBitmap(image, getPosition().x, getPosition().y, getWidth(), getHeight(), getAngle()); } } Essentially, when any rigid body hits a building it should exhibit the same behavior. How is collision solving usually done? Thanks

    Read the article

  • OpenCV multiply scalar and a Matrix

    - by jarjarbinks
    Hi, I am trying to find the easiest way to add, subtract a scalar value with a opencv 2.0 cv::Mat class. Most of the existing function allows only matrix-matrix and matrix-scalar operations. I am looking for a scalar-matrix operations. I am doing it currently by creating a temporary matrix with the same scalar value and doing required arithmetic operation. Example below.. Mat M(Size(100,100), CV_8U); Mat temp = Mat::ones(100, 100, CV_8U)*255; M = temp-M; But I think there should be better/easier ways to do it. Any suggestions ?

    Read the article

  • simple Stata program

    - by Cyrus S
    I am trying to write a simple program to combine coefficient and standard error estimates from a set of regression fits. I run, say, 5 regressions, and store the coefficient(s) and standard error(s) of interest into vectors (Stata matrix objects, actually). Then, I need to do the following: Find the mean value of the coefficient estimates. Combine the standard error estimates according to the formula suggested for combining results from "multiple imputation". The formula is the square root of the formula for "T" on page 6 of the following document: http://bit.ly/b05WX3 I have written Stata code that does this once, but I want to write this as a function (or "program", in Stata speak) that takes as arguments the vector (or matrix, if possible, to combine multiple estimates at once) of regression coefficient estimates and the vector (or matrix) of corresponding standard error estimates, and then generates 1 and 2 above. Here is the code that I wrote: (breg is a 1x5 vector of the regression coefficient estimates, and sereg is a 1x5 vector of the associated standard error estimates) mat ones = (1,1,1,1,1) mat bregmean = (1/5)*(ones*breg’) scalar bregmean_s = bregmean[1,1] mat seregmean = (1/5)*(ones*sereg’) mat seregbtv = (1/4)*(breg - bregmean#ones)* (breg - bregmean#ones)’ mat varregmi = (1/5)*(sereg*sereg’) + (1+(1/5))* seregbtv scalar varregmi_s = varregmi[1,1] scalar seregmi = sqrt(varregmi_s) disp bregmean_s disp seregmi This gives the right answer for a single instance. Any pointers would be great! UPDATE: I completed the code for combining estimates in a kXm matrix of coefficients/parameters (k is the number of parameters, m the number of imputations). Code can be found here: http://bit.ly/cXJRw1 Thanks to Tristan and Gabi for the pointers.

    Read the article

  • Python to MATLAB: exporting list of strings using scipy.io

    - by user292461
    I am trying to export a list of text strings from Python to MATLAB using scipy.io. I would like to use scipy.io because my desired .mat file should include both numerical matrices (which I learned to do here) and text cell arrays. I tried: import scipy.io my_list = ['abc', 'def', 'ghi'] scipy.io.savemat('test.mat', mdict={'my_list': my_list) In MATLAB, I load test.mat and get a character array: my_list = adg beh cfi How do I make scipy.io export a list into a MATLAB cell array?

    Read the article

  • 3D Triangle - WPF

    - by user300423
    I am trying to apply an image brush to a Triangle in WPF without success. What am i doing wrong? This is my attempt: Dim ModelTri As New MeshGeometry3D ModelTri.Positions.Add(New Point3D(0, 0, 0)) ModelTri.Positions.Add(New Point3D(100, 0, 0)) ModelTri.Positions.Add(New Point3D(100, 100, 0)) Dim MeshTri As New MeshGeometry3D MeshTri.TriangleIndices.Add(0) MeshTri.TriangleIndices.Add(1) MeshTri.TriangleIndices.Add(2) 'Texture Dim TexturePoints As New PointCollection TexturePoints.Add(New Point(100, 0)) TexturePoints.Add(New Point(0, 100)) TexturePoints.Add(New Point(100, 100)) MeshTri.TextureCoordinates = TexturePoints 'Image Brush Dim imgBrush As New ImageBrush() imgBrush.ImageSource = New BitmapImage(New Uri("Mercury.jpg", UriKind.Relative)) imgBrush.Stretch = Stretch.Fill imgBrush.TileMode = TileMode.Tile imgBrush.SetValue(NameProperty, "imgBrush") Dim Mat As Material Dim DMaterial As New DiffuseMaterial DMaterial.Brush = imgBrush Dim Bind As New Binding("imgBrush") Bind.Source = imgBrush BindingOperations.SetBinding(DMaterial, BindingGroupProperty, Bind) 'This doesnt work Mat = DMaterial 'This works 'Mat = New DiffuseMaterial(New SolidColorBrush(Colors.Khaki)) Dim triangleModel As GeometryModel3D = New GeometryModel3D(ModelTri, Mat) Dim model As New ModelVisual3D() model.Content = triangleModel Viewport.Children.Add(model)

    Read the article

  • SVM in OpenCV: Visual Studio 2008 reported error wrongly (or is it right?)

    - by Risa
    I'm using MS Visual Studio 2008, OpenCV, C++ and SVM for a OCR-related project. At least I can run the code until yesterday, when I open the project to continue working, VS reported this error: error C2664: 'bool CvSVM::train(const CvMat *,const CvMat *,const CvMat *,const CvMat *,CvSVMParams)' : cannot convert parameter 1 from 'cv::Mat' to 'const CvMat *' It didn't happen before and I haven't changed any code relating to it (I only changed the parameters for the kernel). The code got error is: Mat curTrainData, curTrainLabel; CvSVM svm; . . . svm.train(curTrainData, curTrainLabel, Mat(), Mat(), params); If I hover on the code, I still got this tip: image. Which means my syntax isn't wrong. So why do VS bother to report such an error?

    Read the article

  • Subset and lagging list data structure R

    - by user1234440
    I have a list that is indexed like the following: >list.stuff [[1]] [[1]]$vector ... [[1]]$matrix .... [[1]]$vector [[2]] null [[3]] [[3]]$vector ... [[3]]$matrix .... [[3]]$vector . . . Each segment in the list is indexed according to another vector of indexes: >index.list 1, 3, 5, 10, 15 In list.stuff, only at each of the indexes 1,3,5,10,15 will there be 2 vectors and one matrix; everything else will be null like [[2]]. What I want to do is to lag like the lag.xts function so that whatever is stored in [[1]] will be pushed to [[3]] and the last one drops off. This also requires subsetting the list, if its possible. I was wondering if there exists some functions that handle list manipulation. My thinking is that for xts, a time series can be extracted based on an index you supply: xts.object[index,] #returns the rows 1,3,5,10,15 From here I can lag it with: lag.xts(xts.object[index,]) Any help would be appreciated thanks: EDIT: Here is a reproducible example: list.stuff<-list() vec<-c(1,2,3,4,5,6,7,8,9) vec2<-c(1,2,3,4,5,6,7,8,9) mat<-matrix(c(1,2,3,4,5,6,7,8),4,2) list.vec.mat<-list(vec=vec,mat=mat,vec2=vec2) ind<-c(2,4,6,8,10) for(i in ind){ list.stuff[[i]]<-list.vec.mat }

    Read the article

  • Tutorial: Getting Started with the NoSQL JavaScript / Node.js API for MySQL Cluster

    - by Mat Keep
    Tutorial authored by Craig Russell and JD Duncan  The MySQL Cluster team are working on a new NoSQL JavaScript connector for MySQL. The objectives are simplicity and high performance for JavaScript users: - allows end-to-end JavaScript development, from the browser to the server and now to the world's most popular open source database - native "NoSQL" access to the storage layer without going first through SQL transformations and parsing. Node.js is a complete web platform built around JavaScript designed to deliver millions of client connections on commodity hardware. With the MySQL NoSQL Connector for JavaScript, Node.js users can easily add data access and persistence to their web, cloud, social and mobile applications. While the initial implementation is designed to plug and play with Node.js, the actual implementation doesn't depend heavily on Node, potentially enabling wider platform support in the future. Implementation The architecture and user interface of this connector are very different from other MySQL connectors in a major way: it is an asynchronous interface that follows the event model built into Node.js. To make it as easy as possible, we decided to use a domain object model to store the data. This allows for users to query data from the database and have a fully-instantiated object to work with, instead of having to deal with rows and columns of the database. The domain object model can have any user behavior that is desired, with the NoSQL connector providing the data from the database. To make it as fast as possible, we use a direct connection from the user's address space to the database. This approach means that no SQL (pun intended) is needed to get to the data, and no SQL server is between the user and the data. The connector is being developed to be extensible to multiple underlying database technologies, including direct, native access to both the MySQL Cluster "ndb" and InnoDB storage engines. The connector integrates the MySQL Cluster native API library directly within the Node.js platform itself, enabling developers to seamlessly couple their high performance, distributed applications with a high performance, distributed, persistence layer delivering 99.999% availability. The following sections take you through how to connect to MySQL, query the data and how to get started. Connecting to the database A Session is the main user access path to the database. You can get a Session object directly from the connector using the openSession function: var nosql = require("mysql-js"); var dbProperties = {     "implementation" : "ndb",     "database" : "test" }; nosql.openSession(dbProperties, null, onSession); The openSession function calls back into the application upon creating a Session. The Session is then used to create, delete, update, and read objects. Reading data The Session can read data from the database in a number of ways. If you simply want the data from the database, you provide a table name and the key of the row that you want. For example, consider this schema: create table employee (   id int not null primary key,   name varchar(32),   salary float ) ENGINE=ndbcluster; Since the primary key is a number, you can provide the key as a number to the find function. function onSession = function(err, session) {   if (err) {     console.log(err);     ... error handling   }   session.find('employee', 0, onData); }; function onData = function(err, data) {   if (err) {     console.log(err);     ... error handling   }   console.log('Found: ', JSON.stringify(data));   ... use data in application }; If you want to have the data stored in your own domain model, you tell the connector which table your domain model uses, by specifying an annotation, and pass your domain model to the find function. var annotations = new nosql.Annotations(); function Employee = function(id, name, salary) {   this.id = id;   this.name = name;   this.salary = salary;   this.giveRaise = function(percent) {     this.salary *= percent;   } }; annotations.mapClass(Employee, {'table' : 'employee'}); function onSession = function(err, session) {   if (err) {     console.log(err);     ... error handling   }   session.find(Employee, 0, onData); }; Updating data You can update the emp instance in memory, but to make the raise persistent, you need to write it back to the database, using the update function. function onData = function(err, emp) {   if (err) {     console.log(err);     ... error handling   }   console.log('Found: ', JSON.stringify(emp));   emp.giveRaise(0.12); // gee, thanks!   session.update(emp); // oops, session is out of scope here }; Using JavaScript can be tricky because it does not have the concept of block scope for variables. You can create a closure to handle these variables, or use a feature of the connector to remember your variables. The connector api takes a fixed number of parameters and returns a fixed number of result parameters to the callback function. But the connector will keep track of variables for you and return them to the callback. So in the above example, change the onSession function to remember the session variable, and you can refer to it in the onData function: function onSession = function(err, session) {   if (err) {     console.log(err);     ... error handling   }   session.find(Employee, 0, onData, session); }; function onData = function(err, emp, session) {   if (err) {     console.log(err);     ... error handling   }   console.log('Found: ', JSON.stringify(emp));   emp.giveRaise(0.12); // gee, thanks!   session.update(emp, onUpdate); // session is now in scope }; function onUpdate = function(err, emp) {   if (err) {     console.log(err);     ... error handling   } Inserting data Inserting data requires a mapped JavaScript user function (constructor) and a session. Create a variable and persist it: function onSession = function(err, session) {   var data = new Employee(999, 'Mat Keep', 20000000);   session.persist(data, onInsert);   } }; Deleting data To remove data from the database, use the session remove function. You use an instance of the domain object to identify the row you want to remove. Only the key field is relevant. function onSession = function(err, session) {   var key = new Employee(999);   session.remove(Employee, onDelete);   } }; More extensive queries We are working on the implementation of more extensive queries along the lines of the criteria query api. Stay tuned. How to evaluate The MySQL Connector for JavaScript is available for download from labs.mysql.com. Select the build: MySQL-Cluster-NoSQL-Connector-for-Node-js You can also clone the project on GitHub Since it is still early in development, feedback is especially valuable (so don't hesitate to leave comments on this blog, or head to the MySQL Cluster forum). Try it out and see how easy (and fast) it is to integrate MySQL Cluster into your Node.js platforms. You can learn more about other previewed functionality of MySQL Cluster 7.3 here

    Read the article

  • Error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException [migrated]

    - by user134212
    I'm new here. I'm learning how to program on java and I have a problem with my code. I really have no clue why my code is not working. I think my mistake may be here, but I'm not quite sure. m3 = new Matriz(ren2,col2); btSumar.addActionListener(new ActionListener() { Matriz m3;//(ren2,col2); public void actionPerformed(ActionEvent e) { m3 = new Matriz(ren2,col2); if(ventanaAbierta==true) { try { crearMat.SUMA(m1,m2); } catch(Exception nul) { System.out.println(nul); } } else { JOptionPane.showMessageDialog(null,"Ya se realizo la suma"); } } }); My Complete code import java.awt.*; import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.border.Border; import java.awt.event.*; import java.awt.*; import java.io.*; import java.util.*; public class Practica2 { private int opcion,ren2,col2; private JFrame ventana,ventanaPrintMatriz; private JPanel panel,panel2; private Border borderRed2,borderBlue2,borderGreen2,borderGreen4; private Color red,green,blue,white,black; private Font Verdana14,ArialBlack18; private JLabel labelTitulo; public JButton btSalir,btSumar,btRestar,btMultiplica,btTranspuesta,btCrear; private ImageIcon suma,resta,multi,crear,salir,trans; private boolean ventanaAbierta = false; private static ValidacionesMatrices valida; private static Operaciones operacion; private static Matriz m1,m2,m3; private static ImprimirMatriz printMat; public Practica2() { panel = new JPanel(); panel.setLayout(null); ventana = new JFrame("Operaciones con Matrices"); ventana.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Sale del programa System.exit(0); } }); ventana.setContentPane(panel); ventana.setVisible(true); ventana.setResizable(false); ventana.setBounds(150,150,300,380); //ventana.setBounds(0,0,650,650); } public void inicializarComponentes() { panel2 = new JPanel(); panel2.setLayout(null); labelTitulo = new JLabel("Practica #2"); suma = new ImageIcon("suma1.png"); resta = new ImageIcon("resta1.png"); multi = new ImageIcon("multi1.png"); trans = new ImageIcon("trans2.png"); crear = new ImageIcon("crear1.png"); salir = new ImageIcon("salir1.png"); btTranspuesta = new JButton("Transpuesta",trans); btMultiplica = new JButton("Multiplica",multi); btRestar = new JButton("Restar",resta); btSumar = new JButton("Sumar",suma); btCrear = new JButton("Crear",crear); btSalir = new JButton("Salir",salir); //Tipo de letra ArialBlack18 = new Font("Arial Black",Font.BOLD,18); //Color green = new Color(0,255,0); //Formato labelTitulo labelTitulo.setBounds(80,-60,200,150); labelTitulo.setFont(ArialBlack18); labelTitulo.setForeground(blue); labelTitulo.setVisible(true); //Formato de CrearMatriz btCrear.setBounds(80,50,130,30); btCrear.setToolTipText("Crea una matriz"); //Formato de Muliplica btMultiplica.setBounds(80,100,130,30); btMultiplica.setToolTipText("Mat[A] * Mat[B]"); //Formato de botonRestar btRestar.setBounds(80,150,130,30); btRestar.setToolTipText("Mat[A] - Mat[B]"); //Formato del botonSumar btSumar.setBounds(80,200,130,30); btSumar.setToolTipText("Mat[A] + Mat[B]"); //Formato de Transpuesta btTranspuesta.setBounds(80,250,130,30); btTranspuesta.setToolTipText("Mat[A]^-1"); //Formato del botonSalir btSalir.setBounds(80,300,130,30); //Agregando componentes al panel1 panel2.add(labelTitulo); panel2.add(btMultiplica); panel2.add(btCrear); panel2.add(btRestar); panel2.add(btSumar); panel2.add(btSalir); panel2.add(btTranspuesta); //Formato panel2 panel2.setBackground(green); panel2.setVisible(true); panel2.setBounds(0,0,300,380); //Argregamos componentes al panelPrincipal= panel.add(panel2); //BotonCrear btCrear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) //throws IOException { if(ventanaAbierta==false) { ventanaAbierta=true; new CrearMatriz(); } else { JOptionPane.showMessageDialog(null,"Ya se crearon las Matrices"); } } }); m3 = new Matriz(ren2,col2); btSumar.addActionListener(new ActionListener() { Matriz m3;//(ren2,col2); public void actionPerformed(ActionEvent e) { m3 = new Matriz(ren2,col2); if(ventanaAbierta==true) { try { crearMat.SUMA(m1,m2); } catch(Exception nul) { System.out.println(nul); } } else { JOptionPane.showMessageDialog(null,"Ya se realizo la suma"); } } }); //BotonSalir btSalir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); panel.setVisible(true); panel.setBounds(0,0,350,380); } class VentanaMatriz { private JFrame ventana; private JPanel panel; private JTextArea textArea1,textArea2; private JLabel mat1,mat2; private JTextField textField1; public VentanaMatriz() { panel = new JPanel(); panel.setLayout(null); ventana = new JFrame("Creacion de Matrices"); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { ventana.dispose(); } }); ventana.setContentPane(panel); ventana.setVisible(true); ventana.setResizable(false); ventana.setBounds(200,100,850,420); } public void inicializarComponentes() { //Colores black = new Color(0,0,0); white = new Color(255,255,255); blue = new Color(0,0,255); green = new Color(0,255,0); red = new Color(255,0,0); //Tipo de letra Verdana14 = new Font("Verdana",Font.BOLD,14); //Tipos de borde borderRed2 = BorderFactory.createLineBorder(red,2); borderBlue2 = BorderFactory.createLineBorder(blue,2); borderGreen2 = BorderFactory.createLineBorder(green,2); borderGreen4 = BorderFactory.createLineBorder(green,4); //Agregando componentes al panel1 panel.add(mat1); panel.add(textArea1); panel.add(mat2); panel.add(textArea2); //Formato panel2 panel.setBackground(blue); panel.setVisible(true); panel.setBounds(0,0,850,420); } } class CrearMatriz { public int col1,re1,ren2,col2; public Matriz m1,m2,m3; public CrearMatriz() { int col1,ren1,ren2,col2; ren2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Renglones Matriz A: ")); col2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Columnas Matriz A: ")); final Matriz m1= new Matriz(ren2,col2); ren2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Renglones Matriz B: ")); col2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Columnas Matriz B: ")); final Matriz m2= new Matriz(ren2,col2); m3 = new Matriz(ren2,col2); m1.llenarMatriz(); m2.llenarMatriz(); m1.printMat(); m2.printMat(); } public void SUMA(Matriz m1,Matriz m2) { Matriz m3; if(ventanaAbierta==false) { m3 = new Matriz(ren2,col2); if(valida.validaSumayResta(m1,m2)) { m3 = operacion.sumaMat(m1,m2); JOptionPane.showMessageDialog(null,"La suma es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la suma"); } } } public void RESTA() { } //btSumar = new JButton("Sumar",suma); //BotonSumar //Mostrar matriz 1 y 2 // System.out.println("\n\n\nMatriz 1="); // m1.imprimeMatriz(); // System.out.println("\nMatriz 2="); //Poner en botones /* if(valida.validaSumayResta(m1,m2)) { m3 = operacion.sumaMat(m1,m2); JOptionPane.showMessageDialog(null,"La suma es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la suma"); } if(valida.validaSumayResta(m1,m2)) { m3=operacion.restaMat(m1,m2); JOptionPane.showMessageDialog(null,"La resta es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la resta"); } if(valida.validaMultiplicacion(m1,m2)){ m3=operacion.multiplicaMat(m1,m2); JOptionPane.showMessageDialog(null,"La multiplicacion es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la multiplicacion"); } JOptionPane.showMessageDialog(null,"La multiplicacion es = "); m1=operacion.transpuesta(m1); m2=operacion.transpuesta(m2); */ } class Matriz { public JTextField matriz; //public JTextArea texto; private JFrame ventanaPrintMatriz; private JPanel panel2; int ren; int col; int pos[][]; public Matriz(int ren1, int col1) { ren = ren1; col = col1; pos = new int [ren][col];/*una matriz de enteros de renglon por columan*/ } public void llenarMatriz() { for(int i=0;i<ren;i++) for(int j=0;j<col;j++) pos[i][j]=(int) (Math.random()*10);/*la posicion i y j crea un entero random*/ } /*vuelve a recorrer los espacio de i y j*/ } //Esta clase era un metodo de CrearMatriz class ImprimirMatriz { public void ImprimirMatriz() { panel2 = new JPanel(); panel2.setLayout(null); ventanaPrintMatriz = new JFrame("Matriz"); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Practica2.ventanaAbierta=false; ventana.dispose(); } }); int i,j; int x=0,y=0; borderRed2 = BorderFactory.createLineBorder(red,2); white = new Color(255,255,255); red = new Color(255,0,0); black = new Color(0,0,0); blue = new Color(0,0,255); for(i=0;i<ren;i++) { for(j=0;j<col;j++) { matriz = new JTextField(" "+pos[i][j]); matriz.setBorder(borderRed2); matriz.setForeground(white); matriz.setBounds(x+25,y+25,25,25); matriz.setBackground(black); matriz.setEditable(false); matriz.setVisible(true); //Se incrementa la coordenada en X //para el siguiente Textfield no se encime x=x+35; //Agregamos el textField al panel panel2.add(matriz); } //Regreso las cordenadas de X a 0 para que el //siguiente renglon empieze en donde mismo x=0; //Incremento las coordenada Y para que se brinque //de linea y=y+35; } //Formato panel2 panel2.setBounds(150,150,350,380); panel2.setBackground(blue); //panel2.setEditable(false); panel2.setVisible(true); //Formato de Ventana ventanaPrintMatriz.setContentPane(panel2); ventanaPrintMatriz.setBounds(150,150,350,380); ventanaPrintMatriz.setResizable(false); ventanaPrintMatriz.setVisible(true); } } class Operaciones { public Matriz sumaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m1.col); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[i][j]+m2.pos[i][j]; return m3; } public Matriz restaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m1.col); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[i][j]-m2.pos[i][j]; return m3; } public Matriz multiplicaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m2.col); for(int i=0;i<m1.ren;i++) for(int j=0;j<m2.col;j++) { m3.pos[i][j]=0; for(int k=0;k<m1.col;k++) m3.pos[i][j]+=(m1.pos[i][k]*m2.pos[k][j]); } return m3; } public Matriz transpuesta(Matriz m1) { Matriz m3=new Matriz(m1.col,m1.ren); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[j][i]; return m3; } } class ValidacionesMatrices { public boolean validaSumayResta(Matriz m1, Matriz m2) { if((m1.ren==m2.ren) && (m1.col==m2.col)) return true; else return false; } public boolean validaMultiplicacion(Matriz m1, Matriz m2) { if(((m1.ren==m2.ren) && (m1.col==m2.col)) || (m1.col==m2.ren)) return true; else return false; } } public static void main(String[] args) { Practica2 practica2 = new Practica2(); practica2.inicializarComponentes(); } } Exc

    Read the article

  • Is XML a good logic to load data??

    - by Mat
    Hi stack, i'm working on an app that loads some data from xml file from internet. Is this a good way to develop iPhone apps??...I think xml is more light than SQlite database... Basically my logic is: 1 - Parsing Xml file from internet to retrive the data 2 - Load data on device Security?..other stuff??.. Thanks Mat

    Read the article

  • A python random function acts differently when assigned to a list or called directly...

    - by Dror Hilman
    I have a python function that randomize a dictionary representing a position specific scoring matrix. for example: mat = { 'A' : [ 0.53, 0.66, 0.67, 0.05, 0.01, 0.86, 0.03, 0.97, 0.33, 0.41, 0.26 ] 'C' : [ 0.14, 0.04, 0.13, 0.92, 0.99, 0.04, 0.94, 0.00, 0.07, 0.23, 0.35 ] 'T' : [ 0.25, 0.07, 0.01, 0.01, 0.00, 0.04, 0.00, 0.03, 0.06, 0.12, 0.14 ] 'G' : [ 0.08, 0.23, 0.20, 0.02, 0.00, 0.06, 0.04, 0.00, 0.54, 0.24, 0.25 ] } The scambling function: def scramble_matrix(matrix, iterations): mat_len = len(matrix["A"]) pos1 = pos2 = 0 for count in range(iterations): pos1,pos2 = random.sample(range(mat_len), 2) #suffle the matrix: for nuc in matrix.keys(): matrix[nuc][pos1],matrix[nuc][pos2] = matrix[nuc][pos2],matrix[nuc][pos1] return matrix def print_matrix(matrix): for nuc in matrix.keys(): print nuc+"[", for count in matrix[nuc]: print "%.2f"%count, print "]" now to the problem... When I try to scramble a matrix directly, It's works fine: print_matrix(mat) print "" print_matrix(scramble_matrix(mat,10)) gives: A[ 0.53 0.66 0.67 0.05 0.01 0.86 0.03 0.97 0.33 0.41 0.26 ] C[ 0.14 0.04 0.13 0.92 0.99 0.04 0.94 0.00 0.07 0.23 0.35 ] T[ 0.25 0.07 0.01 0.01 0.00 0.04 0.00 0.03 0.06 0.12 0.14 ] G[ 0.08 0.23 0.20 0.02 0.00 0.06 0.04 0.00 0.54 0.24 0.25 ] A[ 0.41 0.97 0.03 0.86 0.53 0.66 0.33.05 0.67 0.26 0.01 ] C[ 0.23 0.00 0.94 0.04 0.14 0.04 0.07 0.92 0.13 0.35 0.99 ] T[ 0.12 0.03 0.00 0.04 0.25 0.07 0.06 0.01 0.01 0.14 0.00 ] G[ 0.24 0.00 0.04 0.06 0.08 0.23 0.54 0.02 0.20 0.25 0.00 ] but when I try to assign this scrambling to a list , it does not work!!! ... print_matrix(mat) s=[] for x in range(3): s.append(scramble_matrix(mat,10)) for matrix in s: print "" print_matrix(matrix) result: A[ 0.53 0.66 0.67 0.05 0.01 0.86 0.03 0.97 0.33 0.41 0.26 ] C[ 0.14 0.04 0.13 0.92 0.99 0.04 0.94 0.00 0.07 0.23 0.35 ] T[ 0.25 0.07 0.01 0.01 0.00 0.04 0.00 0.03 0.06 0.12 0.14 ] G[ 0.08 0.23 0.20 0.02 0.00 0.06 0.04 0.00 0.54 0.24 0.25 ] A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ] C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ] T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ] G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ] A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ] C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ] T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ] G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ] A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ] C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ] T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ] G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ] What is the problem??? Why the scrambling do not work after the first time, and all the list filled with the same matrix?!

    Read the article

  • Go - Using a container/heap to implement a priority queue

    - by Seth Hoenig
    In the big picture, I'm trying to implement Dijkstra's algorithm using a priority queue. According to members of golang-nuts, the idiomatic way to do this in Go is to use the heap interface with a custom underlying data structure. So I have created Node.go and PQueue.go like so: //Node.go package pqueue type Node struct { row int col int myVal int sumVal int } func (n *Node) Init(r, c, mv, sv int) { n.row = r n.col = c n.myVal = mv n.sumVal = sv } func (n *Node) Equals(o *Node) bool { return n.row == o.row && n.col == o.col } And PQueue.go: // PQueue.go package pqueue import "container/vector" import "container/heap" type PQueue struct { data vector.Vector size int } func (pq *PQueue) Init() { heap.Init(pq) } func (pq *PQueue) IsEmpty() bool { return pq.size == 0 } func (pq *PQueue) Push(i interface{}) { heap.Push(pq, i) pq.size++ } func (pq *PQueue) Pop() interface{} { pq.size-- return heap.Pop(pq) } func (pq *PQueue) Len() int { return pq.size } func (pq *PQueue) Less(i, j int) bool { I := pq.data.At(i).(Node) J := pq.data.At(j).(Node) return (I.sumVal + I.myVal) < (J.sumVal + J.myVal) } func (pq *PQueue) Swap(i, j int) { temp := pq.data.At(i).(Node) pq.data.Set(i, pq.data.At(j).(Node)) pq.data.Set(j, temp) } And main.go: (the action is in SolveMatrix) // Euler 81 package main import "fmt" import "io/ioutil" import "strings" import "strconv" import "./pqueue" const MATSIZE = 5 const MATNAME = "matrix_small.txt" func main() { var matrix [MATSIZE][MATSIZE]int contents, err := ioutil.ReadFile(MATNAME) if err != nil { panic("FILE IO ERROR!") } inFileStr := string(contents) byrows := strings.Split(inFileStr, "\n", -1) for row := 0; row < MATSIZE; row++ { byrows[row] = (byrows[row])[0 : len(byrows[row])-1] bycols := strings.Split(byrows[row], ",", -1) for col := 0; col < MATSIZE; col++ { matrix[row][col], _ = strconv.Atoi(bycols[col]) } } PrintMatrix(matrix) sum, len := SolveMatrix(matrix) fmt.Printf("len: %d, sum: %d\n", len, sum) } func PrintMatrix(mat [MATSIZE][MATSIZE]int) { for r := 0; r < MATSIZE; r++ { for c := 0; c < MATSIZE; c++ { fmt.Printf("%d ", mat[r][c]) } fmt.Print("\n") } } func SolveMatrix(mat [MATSIZE][MATSIZE]int) (int, int) { var PQ pqueue.PQueue var firstNode pqueue.Node var endNode pqueue.Node msm1 := MATSIZE - 1 firstNode.Init(0, 0, mat[0][0], 0) endNode.Init(msm1, msm1, mat[msm1][msm1], 0) if PQ.IsEmpty() { // make compiler stfu about unused variable fmt.Print("empty") } PQ.Push(firstNode) // problem return 0, 0 } The problem is, upon compiling i get the error message: [~/Code/Euler/81] $ make 6g -o pqueue.6 Node.go PQueue.go 6g main.go main.go:58: implicit assignment of unexported field 'row' of pqueue.Node in function argument make: *** [all] Error 1 And commenting out the line PQ.Push(firstNode) does satisfy the compiler. But I don't understand why I'm getting the error message in the first place. Push doesn't modify the argument in any way.

    Read the article

  • I can't compile android projetc wiht JNI code

    - by lobi
    I'm trying to build simple android app with some JNI code. When I press build project in eclipse I get this error: Description Resource Path Location Type fatal error: algorithm: No such file or directory Tracker line 56, external location: /home/slani/code/OpenCV-2.4.6-android-sdk/sdk/native/jni/include/opencv2/core/core.hpp C/C++ Problem make: *** [obj/local/armeabi/objs/detect_jni/detect_jni.o] Error 1 Tracker C/C++ Problem Line 56 in core.hpp contains the relevant include. This is my Android.mk file jni folder: LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) include /home/slani/code/OpenCV-2.4.6-android-sdk/sdk/native/jni/OpenCV.mk LOCAL_MODULE := detect_jni LOCAL_SRC_FILES := detect_jni.cpp include $(BUILD_SHARED_LIBRARY) This is my Aplication.mk file in jni folder: APP_STL := gnustl_static APP_CPPFLAGS := -frtti -fexceptions APP_ABI := armeabi-v7a APP_PLATFORM := all This is my .cpp file: #include <jni.h> #include <opencv/cv.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/features2d/features2d.hpp> using namespace cv; extern "C"{ JNIEXPORT void JNICALL Java_com_slani_tracker_OpenCamera_findObject((JNIEnv *env, jlong addRgba, jlong addHsv); JNIEXPORT void JNICALL Java_com_slani_tracker_OpenCamera_findObject((JNIEnv *env, jlong addRgba, jlong addHsv) { Mat& rgba = *(Mat*)addRgba; Mat& hsv = *(Mat*)addHsv; cvtColor(rgba, hsv,CV_RGBA2HSV); } } Can someone please help me? What could be causing this problem? Thanks

    Read the article

  • Problem with Silverlight/wpf in scrolling html div.

    - by Mat
    Hi all, I have a Silverlight object sitting at the bottom of a scrollable div. This object is submitted to a wcf backend via a javascript button. The problem is, as the silverlight is at the bottom of the scrollable div it is not viewable until you have scrolled down. This is generating an error when the javascript button is clicked ( if i havent scrolled down ) awfully strange, or am i just an idiot :/ if i scroll down so the silverlight object, so it is in view it submits just fine. The error i got is an alert type error which says : The parameter value must be greater than zero. Parameter name: pixelWidth This seems to be returned from the wcf service. What could cause this? Can anyone help me rectify. Kind regards Mat.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >