Circle-Rectangle collision detection (intersection)

Question: How can I tell whether a circle and a rectangle intersect in 2D Euclidean space? (i.e. classic 2D geometry)
Comment: @eJames: how does it matter? You're checking the rectangle for intersection with a *circle*; you always can transform your coordinate system so that the rectangle is axis-parallel with no change in the circle :-)
Comment: @ShreevatsaR: It matters in terms of wether or not I need to worry about that coordinate translation or not.

@aib: Oh dear!
Comment: Is the rectangle always aligned with the axes, or can it be rotated by an arbitrary angle?
Comment: You should add that as an answer, rotating through -Θ and all...
Answer: Here is how I would do it:
bool intersects(CircleType circle, RectType rect)
{
    circleDistance.x = abs(circle.x - rect.x);
    circleDistance.y = abs(circle.y - rect.y);

    if (circleDistance.x > (rect.width/2 + circle.r)) { return false; }
    if (circleDistance.y > (rect.height/2 + circle.r)) { return false; }

    if (circleDistance.x <= (rect.width/2)) { return true; }
    if (circleDistance.y <= (rect.height/2)) { return true; }

    cornerDistance_sq = (circleDistance.x - rect.width/2)^2 +
                         (circleDistance.y - rect.height/2)^2;

    return (cornerDistance_sq <= (circle.r^2));
}

Here's how it works:

The first pair of lines calculate the absolute values of the x and y difference between the center of the circle and the center of the rectangle. This collapses the four quadrants down into one, so that the calculations do not have to be done four times. The image shows the area in which the center of the circle must now lie. Note that only the single quadrant is shown. The rectangle is the grey area, and the red border outlines the critical area which is exactly one radius away from the edges of the rectangle. The center of the circle has to be within this red border for the intersection to occur.
The second pair of lines eliminate the easy cases where the circle is far enough away from the rectangle (in either direction) that no intersection is possible. This corresponds to the green area in the image.
The third pair of lines handle the easy cases where the circle is close enough to the rectangle (in either direction) that an intersection is guaranteed. This corresponds to the orange and grey sections in the image. Note that this step must be done after step 2 for the logic to make sense.
The remaining lines calculate the difficult case where the circle may intersect the corner of the rectangle. To solve, compute the distance from the center of the circle and the corner, and then verify that the distance is not more than the radius of the circle. This calculation returns false for all circles whose center is within the red shaded area and returns true for all circles whose center is within the white shaded area.
Comment: just to clarify -- this answer applies only to axis-aligned rectangles.  that's clear from reading through comments on other answers but not obvious from this answer+comments alone.  (great answer for axis-aligned rects tho!)
Comment: Great! It's important for readers to know that here I believe the definition of a rect is rect.x & rect.y are the _center_ of the rect. In my world a rect's xy is top/left of rect, and 0,0 is top/left of the screen, so I used:
`circleDistance_x = abs(circle.x - (rect.x-rect.w/2));
circleDistance_y = abs(circle.y - (rect.y-rect.h/2));`
Comment: Very nice!

Notes: apparently here, rect.x/y is at the upper right corner of the rectangle.

Also you can eliminate the expensive square root, by instead comparing against the square of the radius.
Comment: Oh no, my bad.   rect.x/y is at the lower left of the rectangle.  I would have written:

circleDistance.x = abs(circle.x - (rect.x + rect.width/2));
Comment: I thought you had an error in your logic until I read into it further. Your third step should not say "This corresponds to the orange sections..." because that's not true. The third step only guarantees that if the center is inside the grey area the function will immediately end with true. The orange area and grey area was "safe" as soon as you passed step 2. Step 3 just allows you to bypass the expensive step 4. Which catches the rare corner case. But thank you this helped a lot.
Comment: @Tanner: There we go. Hooray for backups and OCD `;)`
Comment: This is just what I was looking for. No complicated loops, no handwaving, no "checking for X is trivial in geometry engines", just straight pseudocode and a great explanation.
Comment: Very nice algorithm and great explanation. I have a slight qualm about the statement "o that the calculations do not have to be done four times". Direct comparisons and doing this in four quadrants might be on average theoretically more efficient as this code has two calls to abs(). Of course in reality this is intrinsic function and thus no call and in IEEE float abs is pretty fast op and it makes the code very easy to follow in 1st quadrant only. Well done.
Comment: Thank you, ShreevatsaR. I drew it with Photoshop because that was the only tool I had available on short notice :)
Comment: If the center is in the orange area, step 3 will definitely return true. Step 3 will return true for everything in the grey *and* orange areas. It also simplifies step 4 by ensuring that the distance calculation is simply point-to-point (circle center to edge of rectangle).
Comment: Anyway, glad to hear that it was useful `:)`
Comment: @e.James Just wondering if you could upload the picture again. I've implemented your algorithm, and it works great; however, I also am checking for the case of whether the rectangle is completely inside the square and would like to see the diagram
Comment: @Tanner: That's weird. The internet appears to have eaten my illustration. I'm sure I have a copy of it *somewhere*. I'll look for it when I get home from work.
Comment: As some one wrote before, you need to change to:  Math.Abs(circle.Center.X - (rectangle.X+rectangle.Width/2)) and same for y axis. But thank you very much for this great answer!
Comment: Bringing a bit tmore balanced load, I suggest you can subtract the half rect width & height back in the beginning. You burn 1 arithmetics if you hit the first "if", but you save 2 if you hit the last one. Thanks for the code, btw!
Comment: This is awesome. I just implemented in my game and it works great! thanks for the valuable information.
Answer: There are only two cases when the circle intersects with the rectangle:

Either the circle's centre lies inside the rectangle, or
One of the edges of the rectangle has a point in the circle.

Note that this does not require the rectangle to be axis-parallel.

(One way to see this: if none of the edges has a point in the circle (if all the edges are completely "outside" the circle), then the only way the circle can still intersect the polygon is if it lies completely inside the polygon.)
With that insight, something like the following will work, where the circle has centre P and radius R, and the rectangle has vertices A, B, C, D in that order (not complete code):
def intersect(Circle(P, R), Rectangle(A, B, C, D)):
    S = Circle(P, R)
    return (pointInRectangle(P, Rectangle(A, B, C, D)) or
            intersectCircle(S, (A, B)) or
            intersectCircle(S, (B, C)) or
            intersectCircle(S, (C, D)) or
            intersectCircle(S, (D, A)))

If you're writing any geometry you probably have the above functions in your library already. Otherwise, pointInRectangle() can be implemented in several ways; any of the general point in polygon methods will work, but for a rectangle you can just check whether this works:
0 ≤ AP·AB ≤ AB·AB and 0 ≤ AP·AD ≤ AD·AD

And intersectCircle() is easy to implement too: one way would be to check if the foot of the perpendicular from P to the line is close enough and between the endpoints, and check the endpoints otherwise.
The cool thing is that the same idea works not just for rectangles but for the intersection of a circle with any simple polygon — doesn't even have to be convex!
Comment: For what it's worth, I really think this answer is better than mine. Two main reasons: 1: it does not require a rotation if the rectangle is not axis-parallel, and, 2: the concept easily extends to *all* polygons.
Comment: I find this answer distastefully overrated. Sure, it looks like it has fancy diagrams and code samples. But it's all smoke and mirrors explaining some obvious stuff, and then ultimately leaves the implementation as an exercise to the reader. If we had magical "lineIntersectsCircle" or "pointInRectangle" library functions, we'd probably already have "rectangleIntersectsCircle" function in that library as well!
Comment: what about the case in which the rectangle is completely inside the circle, but the circle's center is not within the rectangle?
Comment: @ericsoco: Good observation. :-) I guess I should have said "intersects the disc" in "one of the edges of the rectangle intersects the circle", because I meant means that it shares a point with the circle itself, not necessarily the circle's boundary. Anyway, the description above, "check if the foot of the perpendicular from P [the circle's centre] to the line is close enough and between the endpoints, and check the endpoints otherwise" will still work — e.g. the endpoints lie inside the circle (disc).
Comment: @PaulK You must be smarter than me. :-) It wasn't "obvious stuff" to me; I had to work out that checking these conditions was enough. Similarly it wasn't obvious how to implement `pointInRectangle` and `intersectCircle`; that's why I explained one possible way for implementing each of them, even though each has many ways (possibly answered on other questions). (BTW all this stuff is *still* not obvious to me; that's why the proof was added. The answer was written in 2008; I only added the pictures in 2017.) I was only sharing my understanding, and didn't intend to cause you any distaste. :-)
Comment: @paniq: Well, both are constant-time. :-) But yes, this is more useful as a general solution, covering rectangles with any orientation, and in fact any simple polygon.
Comment: @DexD.Hunter If the center of the circle is outside the rectangle, but a part of it is inside the rectangle, then necessarily one of the edges of the rectangle intersects the circle.
Comment: If the rectangles _are_ parallel though, e.James' solution is computationally more efficient.
Comment: What about part of circle (not including center) inside the middle of a wide rectangle?
Comment: @DexD.Hunter No problem, as there was a chance of misunderstanding, I tweaked the wording and added some pictures.
Comment: Could someone maybe provide example / pseudo code for `intersectCircle`? Thanks :)
Comment: love this answer! I completely missed the centerInRectangle check. It took me a second to realize why my game entities were sometimes not colliding! thanks!
Comment: @PaulK I have thought about your comment several times, and I think I understand your perspective better. This answer was written in the early days of Stack Overflow (it entered public beta in Sep 2008), when the site as a community was focused on knowledge and ideas: many questions were more abstract, and we often wrote answers as enthusiasts trying to share our understanding. These days, I take it that many people visit StackOverflow to get solutions to problems they encounter at work, for which working code would be more useful, while conceptual understanding can be considered as unhelpful.
Comment: Hmm, true. I started out with the simple (corner in circle) check and moved on to other cases from there. I did not see the simplification resulting from the fact that corners ARE points on the edges.
Comment: sorry, my bad. I was thinking about corners when you meant edges.
Comment: @ShreevatsaR a circle is defined as the set of points equidistant from its center, so the "circle's boundary" == the circle...but i'm sure you know this already :)  anyway, i get what you're saying about the endpoints inside the circle.  thanks for the solid answer, and for verification it works in this case as well!
Comment: To find a version of this answer made in the Python Programming language, go to http://stackoverflow.com/a/24728182/3787376 (from "Detecting Rectangle collision with a Circle", http://stackoverflow.com/q/24727773/3787376)
Comment: Sorry! Accident. Removed. Thanks for a helpful answer.
Comment: @ShreevatsaR yep, the "edge". Sorry, I misunderstood what you have written
Comment: you introduced pointInRectangle implementation, why not to do it for intersectCircle?
Answer: Here is another solution that's pretty simple to implement (and pretty fast, too). It will catch all intersections, including when the sphere has fully entered the rectangle.
// clamp(value, min, max) - limits value to the range min..max

// Find the closest point to the circle within the rectangle
float closestX = clamp(circle.X, rectangle.Left, rectangle.Right);
float closestY = clamp(circle.Y, rectangle.Top, rectangle.Bottom);

// Calculate the distance between the circle's center and this closest point
float distanceX = circle.X - closestX;
float distanceY = circle.Y - closestY;

// If the distance is less than the circle's radius, an intersection occurs
float distanceSquared = (distanceX * distanceX) + (distanceY * distanceY);
return distanceSquared < (circle.Radius * circle.Radius);

With any decent math library, that can be shortened to 3 or 4 lines.
Comment: I like this answer the best.  It's short, easy to understand, and fast.
Comment: I think that your solution fails if the rectangle is oblique to the x- and y-axes.
Comment: @Leo I think it's not hard to modify this algorithm to accommodate that case, one should simply apply a coordinate transformation where the origin is at the rectangle center and the rectangle isn't oblique anymore. You need to apply the transformation to the circle center only.
Comment: You have a bug in there, you search for closestY with Left and Right, not Top and Bottom, otherwise lovely solution.
Comment: This is basically the same as the code found at http://www.migapro.com/circle-and-rotated-rectangle-collision-detection/ which I've also ported to Objective-C.  Works very well; it's a nice solution to the problem.
Comment: `<` is valid if you're checking whether the area of intersection is 0, but in some use cases `<=` would be better, where a rectangle with a side tangent to a circle is considered to intersect it at a single point. Likewise, a circle with radius 0 within rectangle intersects it at a single point.
Comment: @Cygon shouldn't you be clamping circle.Y between rectnagle.Bottom and rectangle.Top (or do you assume Top has a lower Y value than Bottom)?
Comment: Ah, darn, that happens when you fix up code on-the-fly in Firefox :)
Good find!
Comment: I like this answer the best because it's easy to understand intuitively, step by step, without need for diagrams or the like. Also, the math operations are simple, so I expect it's about as fast as you could get it. (Anyone want to do a perf test between this and e.James' solution? I'm curious how they compare.)
Answer: The simplest solution I've come up with is pretty straightforward.
It works by finding the point in the rectangle closest to the circle, then comparing the distance.
You can do all of this with a few operations, and even avoid the sqrt function.
public boolean intersects(float cx, float cy, float radius, float left, float top, float right, float bottom)
{
   float closestX = (cx < left ? left : (cx > right ? right : cx));
   float closestY = (cy < top ? top : (cy > bottom ? bottom : cy));
   float dx = closestX - cx;
   float dy = closestY - cy;

   return ( dx * dx + dy * dy ) <= radius * radius;
}

And that's it! The above solution assumes an origin in the upper left of the world with the x-axis pointing down.
If you want a solution to handling collisions between a moving circle and rectangle, it's far more complicated and covered in another answer of mine.
Comment: Can you provide actual input that makes this fail? When the circle is inside, the left part of the test is 0.0. Unless the radius is zero the right part of the test should be > 0.0
Comment: This will fail to detect intersections if the circle radius is too small and its center is inside the rectangle!
Comment: Will this work for rotated rectangles too ? if not then please give me a hint about that.....
Comment: Thanks man. It is working for me perfect.
Comment: what is the origin of the circle? in the top left or in the center?
Comment: This is basically the same as @Cygon's answer, but without the extra variables and comments.
Answer: your sphere and rect intersect IIF
the distance between the circle-center and one vertex of your rect is smaller than the radius of your sphere
OR
the distance between the circle-center and one edge of your rect is smaller than the radius of your sphere ([point-line distance ])
OR
the circle center is inside the rect

point-point distance:

P1 = [x1,y1]
P2 = [x2,y2]
Distance = sqrt(abs(x1 - x2)+abs(y1-y2))

point-line distance:

L1 = [x1,y1],L2 = [x2,y2] (two points of your line, ie the vertex points)
P1 = [px,py] some point

Distance d =  abs( (x2-x1)(y1-py)-(x1-px)(y2-y1) ) / Distance(L1,L2)

 circle center inside rect:
take an seperating axis aproach: if there exists a projection onto a line that seperates the rectangle from the point, they do not intersect
you project the point on lines parallel to the sides of your rect and can then easily determine if they intersect. if they intersect not on all 4 projections, they (the point and the rectangle) can not intersect.
you just need the inner-product ( x= [x1,x2] , y = [y1,y2] , x*y = x1*y1 + x2*y2 )
your test would look like that:

//rectangle edges: TL (top left), TR (top right), BL (bottom left), BR (bottom right)
//point to test: POI

seperated = false
for egde in { {TL,TR}, {BL,BR}, {TL,BL},{TR-BR} }:  // the edges
    D = edge[0] - edge[1]
    innerProd =  D * POI
    Interval_min = min(D*edge[0],D*edge[1])
    Interval_max = max(D*edge[0],D*edge[1])
    if not (  Interval_min ≤ innerProd ≤  Interval_max )
           seperated = true
           break  // end for loop
    end if
end for
if (seperated is true)
      return "no intersection"
else
      return "intersection"
end if

this does not assume an axis-aligned rectangle and is easily extendable for testing intersections between convex sets.
Comment: Shouldn't the point to point distance be using a square, not an abs?
Answer: This is the fastest solution:
public static boolean intersect(Rectangle r, Circle c)
{
    float cx = Math.abs(c.x - r.x - r.halfWidth);
    float xDist = r.halfWidth + c.radius;
    if (cx > xDist)
        return false;
    float cy = Math.abs(c.y - r.y - r.halfHeight);
    float yDist = r.halfHeight + c.radius;
    if (cy > yDist)
        return false;
    if (cx <= r.halfWidth || cy <= r.halfHeight)
        return true;
    float xCornerDist = cx - r.halfWidth;
    float yCornerDist = cy - r.halfHeight;
    float xCornerDistSq = xCornerDist * xCornerDist;
    float yCornerDistSq = yCornerDist * yCornerDist;
    float maxCornerDistSq = c.radius * c.radius;
    return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
}

Note the order of execution, and half the width/height is pre-computed. Also the squaring is done "manually" to save some clock cycles.
Comment: I don't think you can claim that five tests/comparisons in the most expensive code path is the "fastest solution" without some proof.
Comment: See https://en.wikipedia.org/wiki/Argumentum_ad_populum and https://en.wikipedia.org/wiki/Argument_from_ignorance
Comment: In my experience with this method, collision does not happen most of the time. Therefore the tests will cause an exit before before most of the code gets executed.
Answer: Actually, this is much more simple. You need only two things.
First, you need to find four orthogonal distances from the circle centre to each line of the rectangle. Then your circle will not intersect the rectangle if any three of them are larger than the circle radius.
Second, you need to find the distance between the circle centre and the rectangle centre, then you circle will not be inside of the rectangle if the distance is larger than a half of the rectangle diagonal length.
Good luck!
Answer: If you are interested in a more graphical solution which even works on (in plane) rotated rectangles..
Demo: https://jsfiddle.net/exodus4d/94mxLvqh/2691/
The idea is:

Translate the scenary to the origin [0,0]

In case the rect is not in plane, the rotation center should be at
[0, 0]

Rotate the scenary back into plane
Calculate intersection

const hasIntersection = ({x: cx, y: cy, r: cr}, {x, y, width, height}) => {
  const distX = Math.abs(cx - x - width / 2);
  const distY = Math.abs(cy - y - height / 2);

  if (distX > (width / 2 + cr)) {
    return false;
  }
  if (distY > (height / 2 + cr)) {
    return false;
  }

  if (distX <= (width / 2)) {
    return true;
  }
  if (distY <= (height / 2)) {
    return true;
  }

  const Δx = distX - width / 2;
  const Δy = distY - height / 2;
  return Δx * Δx + Δy * Δy <= cr * cr;
};

const rect = new DOMRect(50, 20, 100, 50);
const circ1 = new DOMPoint(160, 80);
circ1.r = 20;

const circ2 = new DOMPoint(80, 95);
circ2.r = 20;

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.strokeRect(rect.x, rect.y, rect.width, rect.height);

ctx.beginPath();
ctx.strokeStyle = hasIntersection(circ1, rect) ? 'red' : 'green';
ctx.arc(circ1.x, circ1.y, circ1.r, 0, 2 * Math.PI);
ctx.stroke();

ctx.beginPath();
ctx.strokeStyle = hasIntersection(circ2, rect) ? 'red' : 'green';
ctx.arc(circ2.x, circ2.y, circ2.r, 0, 2 * Math.PI);
ctx.stroke();
<canvas id="canvas"></canvas>

Tip: Instead of rotating the rect (4 points). You can rotate the circle (1 point) in opposite direction.
Comment: How would it work with multiple rectangles & multiple circles ?
Answer: Here's my C code for resolving a collision between a sphere and a non-axis aligned box. It relies on a couple of my own library routines, but it may prove useful to some. I'm using it in a game and it works perfectly.
float physicsProcessCollisionBetweenSelfAndActorRect(SPhysics *self, SPhysics *actor)
{
    float diff = 99999;

    SVector relative_position_of_circle = getDifference2DBetweenVectors(&self->worldPosition, &actor->worldPosition);
    rotateVector2DBy(&relative_position_of_circle, -actor->axis.angleZ); // This aligns the coord system so the rect becomes an AABB

    float x_clamped_within_rectangle = relative_position_of_circle.x;
    float y_clamped_within_rectangle = relative_position_of_circle.y;
    LIMIT(x_clamped_within_rectangle, actor->physicsRect.l, actor->physicsRect.r);
    LIMIT(y_clamped_within_rectangle, actor->physicsRect.b, actor->physicsRect.t);

    // Calculate the distance between the circle's center and this closest point
    float distance_to_nearest_edge_x = relative_position_of_circle.x - x_clamped_within_rectangle;
    float distance_to_nearest_edge_y = relative_position_of_circle.y - y_clamped_within_rectangle;

    // If the distance is less than the circle's radius, an intersection occurs
    float distance_sq_x = SQUARE(distance_to_nearest_edge_x);
    float distance_sq_y = SQUARE(distance_to_nearest_edge_y);
    float radius_sq = SQUARE(self->physicsRadius);
    if(distance_sq_x + distance_sq_y < radius_sq)
    {
        float half_rect_w = (actor->physicsRect.r - actor->physicsRect.l) * 0.5f;
        float half_rect_h = (actor->physicsRect.t - actor->physicsRect.b) * 0.5f;

        CREATE_VECTOR(push_vector);

        // If we're at one of the corners of this object, treat this as a circular/circular collision
        if(fabs(relative_position_of_circle.x) > half_rect_w && fabs(relative_position_of_circle.y) > half_rect_h)
        {
            SVector edges;
            if(relative_position_of_circle.x > 0) edges.x = half_rect_w; else edges.x = -half_rect_w;
            if(relative_position_of_circle.y > 0) edges.y = half_rect_h; else edges.y = -half_rect_h;

            push_vector = relative_position_of_circle;
            moveVectorByInverseVector2D(&push_vector, &edges);

            // We now have the vector from the corner of the rect to the point.
            float delta_length = getVector2DMagnitude(&push_vector);
            float diff = self->physicsRadius - delta_length; // Find out how far away we are from our ideal distance

            // Normalise the vector
            push_vector.x /= delta_length;
            push_vector.y /= delta_length;
            scaleVector2DBy(&push_vector, diff); // Now multiply it by the difference
            push_vector.z = 0;
        }
        else // Nope - just bouncing against one of the edges
        {
            if(relative_position_of_circle.x > 0) // Ball is to the right
                push_vector.x = (half_rect_w + self->physicsRadius) - relative_position_of_circle.x;
            else
                push_vector.x = -((half_rect_w + self->physicsRadius) + relative_position_of_circle.x);

            if(relative_position_of_circle.y > 0) // Ball is above
                push_vector.y = (half_rect_h + self->physicsRadius) - relative_position_of_circle.y;
            else
                push_vector.y = -((half_rect_h + self->physicsRadius) + relative_position_of_circle.y);

            if(fabs(push_vector.x) < fabs(push_vector.y))
                push_vector.y = 0;
            else
                push_vector.x = 0;
        }

        diff = 0; // Cheat, since we don't do anything with the value anyway
        rotateVector2DBy(&push_vector, actor->axis.angleZ);
        SVector *from = &self->worldPosition;
        moveVectorBy2D(from, push_vector.x, push_vector.y);
    }
    return diff;
}

Answer: To visualise, take your keyboard's numpad. If the key '5' represents your rectangle, then all the keys 1-9 represent the 9 quadrants of space divided by the lines that make up your rectangle (with 5 being the inside.)
1) If the circle's center is in quadrant 5 (i.e. inside the rectangle) then the two shapes intersect.
With that out of the way, there are two possible cases:
a) The circle intersects with two or more neighboring edges of the rectangle.
b) The circle intersects with one edge of the rectangle.
The first case is simple. If the circle intersects with two neighboring edges of the rectangle, it must contain the corner connecting those two edges. (That, or its center lies in quadrant 5, which we have already covered. Also note that the case where the circle intersects with only two opposing edges of the rectangle is covered as well.)
2) If any of the corners A, B, C, D of the rectangle lie inside the circle, then the two shapes intersect.
The second case is trickier. We should make note of that it may only happen when the circle's center lies in one of the quadrants 2, 4, 6 or 8. (In fact, if the center is on any of the quadrants 1, 3, 7, 8, the corresponding corner will be the closest point to it.)
Now we have the case that the circle's center is in one of the 'edge' quadrants, and it only intersects with the corresponding edge. Then, the point on the edge that is closest to the circle's center, must lie inside the circle.
3) For each line AB, BC, CD, DA, construct perpendicular lines p(AB,P), p(BC,P), p(CD,P), p(DA,P) through the circle's center P. For each perpendicular line, if the intersection with the original edge lies inside the circle, then the two shapes intersect.
There is a shortcut for this last step. If the circle's center is in quadrant 8 and the edge AB is the top edge, the point of intersection will have the y-coordinate of A and B, and the x-coordinate of center P.
You can construct the four line intersections and check if they lie on their corresponding edges, or find out which quadrant P is in and check the corresponding intersection. Both should simplify to the same boolean equation. Be wary of that the step 2 above did not rule out P being in one of the 'corner' quadrants; it just looked for an intersection.
Edit: As it turns out, I have overlooked the simple fact that #2 is a subcase of #3 above. After all, corners too are points on the edges. See @ShreevatsaR's answer below for a great explanation. And in the meanwhile, forget #2 above unless you want a quick but redundant check.
Answer: This function detect collisions (intersections) between Circle and Rectangle. He works like e.James method in his answer, but this one detect collisions for all angles of rectangle (not only right up corner).
NOTE:
aRect.origin.x and aRect.origin.y are coordinates of bottom left angle of rectangle!
aCircle.x and aCircle.y are coordinates of Circle Center!
static inline BOOL RectIntersectsCircle(CGRect aRect, Circle aCircle) {

    float testX = aCircle.x;
    float testY = aCircle.y;

    if (testX < aRect.origin.x)
        testX = aRect.origin.x;
    if (testX > (aRect.origin.x + aRect.size.width))
        testX = (aRect.origin.x + aRect.size.width);
    if (testY < aRect.origin.y)
        testY = aRect.origin.y;
    if (testY > (aRect.origin.y + aRect.size.height))
        testY = (aRect.origin.y + aRect.size.height);

    return ((aCircle.x - testX) * (aCircle.x - testX) + (aCircle.y - testY) * (aCircle.y - testY)) < aCircle.radius * aCircle.radius;
}

Answer: Improving a little bit the answer of e.James:
double dx = abs(circle.x - rect.x) - rect.w / 2,
       dy = abs(circle.y - rect.y) - rect.h / 2;

if (dx > circle.r || dy > circle.r) { return false; }
if (dx <= 0 || dy <= 0) { return true; }

return (dx * dx + dy * dy <= circle.r * circle.r);

This subtracts rect.w / 2 and rect.h / 2 once instead of up to three times.
Comment: My point was that nowadays many compilers will likely optimize the machine-code generated so that calculation of `dx` and `dy` values only happens once (without you needing to do it like this explicitly).
Comment: I strongly suspect that most modern compilers would (or at least could) automatically optimize the redundant calculations away for you.
Comment: martineau - No, I didn't join several calculations in only one, directly. I changed them to delete these extra calculations in the process.
Answer: Here is the modfied code 100% working:
public static bool IsIntersected(PointF circle, float radius, RectangleF rectangle)
{
    var rectangleCenter = new PointF((rectangle.X +  rectangle.Width / 2),
                                     (rectangle.Y + rectangle.Height / 2));

    var w = rectangle.Width  / 2;
    var h = rectangle.Height / 2;

    var dx = Math.Abs(circle.X - rectangleCenter.X);
    var dy = Math.Abs(circle.Y - rectangleCenter.Y);

    if (dx > (radius + w) || dy > (radius + h)) return false;

    var circleDistance = new PointF
                             {
                                 X = Math.Abs(circle.X - rectangle.X - w),
                                 Y = Math.Abs(circle.Y - rectangle.Y - h)
                             };

    if (circleDistance.X <= (w))
    {
        return true;
    }

    if (circleDistance.Y <= (h))
    {
        return true;
    }

    var cornerDistanceSq = Math.Pow(circleDistance.X - w, 2) +
                                    Math.Pow(circleDistance.Y - h, 2);

    return (cornerDistanceSq <= (Math.Pow(radius, 2)));
}

Bassam Alugili
Answer: I've a method which avoids the expensive pythagoras if not necessary - ie. when bounding boxes of the rectangle and the circle do not intersect.
And it'll work for non-euclidean too:
class Circle {
 // create the bounding box of the circle only once
 BBox bbox;

 public boolean intersect(BBox b) {
    // test top intersect
    if (lat > b.maxLat) {
        if (lon < b.minLon)
            return normDist(b.maxLat, b.minLon) <= normedDist;
        if (lon > b.maxLon)
            return normDist(b.maxLat, b.maxLon) <= normedDist;
        return b.maxLat - bbox.minLat > 0;
    }

    // test bottom intersect
    if (lat < b.minLat) {
        if (lon < b.minLon)
            return normDist(b.minLat, b.minLon) <= normedDist;
        if (lon > b.maxLon)
            return normDist(b.minLat, b.maxLon) <= normedDist;
        return bbox.maxLat - b.minLat > 0;
    }

    // test middle intersect
    if (lon  0;
    if (lon > b.maxLon)
        return b.maxLon - bbox.minLon > 0;
    return true;
  }
}

minLat,maxLat can be replaced with minY,maxY and the same for minLon, maxLon: replace it with minX, maxX
normDist ist just a bit faster method then the full distance calculation. E.g. without the square-root in euclidean space (or without a lot of other stuff for haversine): dLat=(lat-circleY); dLon=(lon-circleX); normed=dLat*dLat+dLon*dLon. Of course if you use that normDist method you'll need to do create a normedDist = dist*dist; for the circle

See the full BBox and Circle code of my GraphHopper project.
Answer: I created class for work with shapes
hope you enjoy
public class Geomethry {
  public static boolean intersectionCircleAndRectangle(int circleX, int circleY, int circleR, int rectangleX, int rectangleY, int rectangleWidth, int rectangleHeight){
    boolean result = false;

    float rectHalfWidth = rectangleWidth/2.0f;
    float rectHalfHeight = rectangleHeight/2.0f;

    float rectCenterX = rectangleX + rectHalfWidth;
    float rectCenterY = rectangleY + rectHalfHeight;

    float deltax = Math.abs(rectCenterX - circleX);
    float deltay = Math.abs(rectCenterY - circleY);

    float lengthHypotenuseSqure = deltax*deltax + deltay*deltay;

    do{
        // check that distance between the centerse is more than the distance between the circumcircle of rectangle and circle
        if(lengthHypotenuseSqure > ((rectHalfWidth+circleR)*(rectHalfWidth+circleR) + (rectHalfHeight+circleR)*(rectHalfHeight+circleR))){
            //System.out.println("distance between the centerse is more than the distance between the circumcircle of rectangle and circle");
            break;
        }

        // check that distance between the centerse is less than the distance between the inscribed circle
        float rectMinHalfSide = Math.min(rectHalfWidth, rectHalfHeight);
        if(lengthHypotenuseSqure < ((rectMinHalfSide+circleR)*(rectMinHalfSide+circleR))){
            //System.out.println("distance between the centerse is less than the distance between the inscribed circle");
            result=true;
            break;
        }

        // check that the squares relate to angles
        if((deltax > (rectHalfWidth+circleR)*0.9) && (deltay > (rectHalfHeight+circleR)*0.9)){
            //System.out.println("squares relate to angles");
            result=true;
        }
    }while(false);

    return result;
}

public static boolean intersectionRectangleAndRectangle(int rectangleX, int rectangleY, int rectangleWidth, int rectangleHeight, int rectangleX2, int rectangleY2, int rectangleWidth2, int rectangleHeight2){
    boolean result = false;

    float rectHalfWidth = rectangleWidth/2.0f;
    float rectHalfHeight = rectangleHeight/2.0f;
    float rectHalfWidth2 = rectangleWidth2/2.0f;
    float rectHalfHeight2 = rectangleHeight2/2.0f;

    float deltax = Math.abs((rectangleX + rectHalfWidth) - (rectangleX2 + rectHalfWidth2));
    float deltay = Math.abs((rectangleY + rectHalfHeight) - (rectangleY2 + rectHalfHeight2));

    float lengthHypotenuseSqure = deltax*deltax + deltay*deltay;

    do{
        // check that distance between the centerse is more than the distance between the circumcircle
        if(lengthHypotenuseSqure > ((rectHalfWidth+rectHalfWidth2)*(rectHalfWidth+rectHalfWidth2) + (rectHalfHeight+rectHalfHeight2)*(rectHalfHeight+rectHalfHeight2))){
            //System.out.println("distance between the centerse is more than the distance between the circumcircle");
            break;
        }

        // check that distance between the centerse is less than the distance between the inscribed circle
        float rectMinHalfSide = Math.min(rectHalfWidth, rectHalfHeight);
        float rectMinHalfSide2 = Math.min(rectHalfWidth2, rectHalfHeight2);
        if(lengthHypotenuseSqure < ((rectMinHalfSide+rectMinHalfSide2)*(rectMinHalfSide+rectMinHalfSide2))){
            //System.out.println("distance between the centerse is less than the distance between the inscribed circle");
            result=true;
            break;
        }

        // check that the squares relate to angles
        if((deltax > (rectHalfWidth+rectHalfWidth2)*0.9) && (deltay > (rectHalfHeight+rectHalfHeight2)*0.9)){
            //System.out.println("squares relate to angles");
            result=true;
        }
    }while(false);

    return result;
  }
}

Answer: Here's a fast one-line test for this:
if (length(max(abs(center - rect_mid) - rect_halves, 0)) <= radius ) {
  // They intersect.
}

This is the axis-aligned case where rect_halves is a positive vector pointing from the rectangle middle to a corner. The expression inside length() is a delta vector from center to a closest point in the rectangle. This works in any dimension.
Answer:
First check if the rectangle and the square tangent to the circle overlaps (easy). If they do not overlaps, they do not collide.
Check if the circle's center is inside the rectangle (easy). If it's inside, they collide.
Calculate the minimum squared distance from the rectangle sides to the circle's center (little hard). If it's lower that the squared radius, then they collide, else they don't.

It's efficient, because:

First it checks the most common scenario with a cheap algorithm and when it's sure they do not collide, it ends.
Then it checks the next most common scenario with a cheap algorithm (do not calculate square root, use the squared values) and when it's sure they collide it ends.
Then it executes the more expensive algorithm to check collision with the rectangle borders.
Answer: worked for me (only work when angle of rectangle is 180)
function intersects(circle, rect) {
  let left = rect.x + rect.width > circle.x - circle.radius;
  let right = rect.x < circle.x + circle.radius;
  let top = rect.y < circle.y + circle.radius;
  let bottom = rect.y + rect.height > circle.y - circle.radius;
  return left && right && bottom && top;
}

Comment: hmmm... I voted this up but then tested properly and I think it does not work on the corners for instance.  It would work for two rectangles.
Answer: Works, just figured this out a week ago, and just now got to testing it.
double theta = Math.atan2(cir.getX()-sqr.getX()*1.0,
                          cir.getY()-sqr.getY()*1.0); //radians of the angle
double dBox; //distance from box to edge of box in direction of the circle

if((theta >  Math.PI/4 && theta <  3*Math.PI / 4) ||
   (theta < -Math.PI/4 && theta > -3*Math.PI / 4)) {
    dBox = sqr.getS() / (2*Math.sin(theta));
} else {
    dBox = sqr.getS() / (2*Math.cos(theta));
}
boolean touching = (Math.abs(dBox) >=
                    Math.sqrt(Math.pow(sqr.getX()-cir.getX(), 2) +
                              Math.pow(sqr.getY()-cir.getY(), 2)));

Comment: Might work for Circle-Square, but the question is about Circle-Rectangle.
Answer: For those have to calculate Circle/Rectangle collision in Geographic Coordinates with SQL,
this is my implementation in oracle 11 of e.James suggested algorithm.
In input it requires circle coordinates, circle radius in km and two vertices coordinates of the rectangle:
CREATE OR REPLACE FUNCTION "DETECT_CIRC_RECT_COLLISION"
(
    circleCenterLat     IN NUMBER,      -- circle Center Latitude
    circleCenterLon     IN NUMBER,      -- circle Center Longitude
    circleRadius        IN NUMBER,      -- circle Radius in KM
    rectSWLat           IN NUMBER,      -- rectangle South West Latitude
    rectSWLon           IN NUMBER,      -- rectangle South West Longitude
    rectNELat           IN NUMBER,      -- rectangle North Est Latitude
    rectNELon           IN NUMBER       -- rectangle North Est Longitude
)
RETURN NUMBER
AS
    -- converts km to degrees (use 69 if miles)
    kmToDegreeConst     NUMBER := 111.045;

    -- Remaining rectangle vertices
    rectNWLat   NUMBER;
    rectNWLon   NUMBER;
    rectSELat   NUMBER;
    rectSELon   NUMBER;

    rectHeight  NUMBER;
    rectWIdth   NUMBER;

    circleDistanceLat   NUMBER;
    circleDistanceLon   NUMBER;
    cornerDistanceSQ    NUMBER;

BEGIN
    -- Initialization of remaining rectangle vertices
    rectNWLat := rectNELat;
    rectNWLon := rectSWLon;
    rectSELat := rectSWLat;
    rectSELon := rectNELon;

    -- Rectangle sides length calculation
    rectHeight := calc_distance(rectSWLat, rectSWLon, rectNWLat, rectNWLon);
    rectWidth := calc_distance(rectSWLat, rectSWLon, rectSELat, rectSELon);

    circleDistanceLat := abs( (circleCenterLat * kmToDegreeConst) - ((rectSWLat * kmToDegreeConst) + (rectHeight/2)) );
    circleDistanceLon := abs( (circleCenterLon * kmToDegreeConst) - ((rectSWLon * kmToDegreeConst) + (rectWidth/2)) );

    IF circleDistanceLon > ((rectWidth/2) + circleRadius) THEN
        RETURN -1;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLat > ((rectHeight/2) + circleRadius) THEN
        RETURN -1;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLon <= (rectWidth/2) THEN
        RETURN 0;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLat <= (rectHeight/2) THEN
        RETURN 0;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    cornerDistanceSQ := POWER(circleDistanceLon - (rectWidth/2), 2) + POWER(circleDistanceLat - (rectHeight/2), 2);

    IF cornerDistanceSQ <=  POWER(circleRadius, 2) THEN
        RETURN 0;  --  -1 => NO Collision ; 0 => Collision Detected
    ELSE
        RETURN -1;  --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    RETURN -1;  --  -1 => NO Collision ; 0 => Collision Detected
END;

Answer: def colision(rect, circle):
dx = rect.x - circle.x
dy = rect.y - circle.y
distance = (dy**2 + dx**2)**0.5
angle_to = (rect.angle + math.atan2(dx, dy)/3.1415*180.0) % 360
if((angle_to>135 and angle_to<225) or (angle_to>0 and angle_to<45) or (angle_to>315 and angle_to<360)):
    if distance <= circle.rad/2.+((rect.height/2.0)*(1.+0.5*abs(math.sin(angle_to*math.pi/180.)))):
        return True
else:
    if distance <= circle.rad/2.+((rect.width/2.0)*(1.+0.5*abs(math.cos(angle_to*math.pi/180.)))):
        return True
return False

Answer: I developed this algorithm while making this game: https://mshwf.github.io/mates/

If the circle touches the square, then the distance between the centerline of the circle and the centerline of the square should equal (diameter+side)/2.
So, let's have a variable named touching that holds that distance. The problem was: which centerline should I consider: the horizontal or the vertical?
Consider this frame:

Each centerline gives different distances, and only one is a correct indication to a no-collision, but using our human intuition is a start to understand how the natural algorithm works.
They are not touching, which means that the distance between the two centerlines should be greater than touching, which means that the natural algorithm picks the horizontal centerlines (the vertical centerlines says there's a collision!). By noticing multiple circles, you can tell: if the circle intersects with the vertical extension of the square, then we pick the vertical distance (between the horizontal centerlines), and if the circle intersects with the horizontal extension, we pick the horizontal distance:

Another example, circle number 4: it intersects with the horizontal extension of the square, then we consider the horizontal distance which is equal to touching.
Ok, the tough part is demystified, now we know how the algorithm will work, but how we know with which extension the circle intersects?
It's easy actually: we calculate the distance between the most right x and the most left x (of both the circle and the square), and the same for the y-axis, the one with greater value is the axis with the extension that intersects with the circle (if it's greater than diameter+side then the circle is outside the two square extensions, like circle #7). The code looks like:
right = Math.max(square.x+square.side, circle.x+circle.rad);
left = Math.min(square.x, circle.x-circle.rad);

bottom = Math.max(square.y+square.side, circle.y+circle.rad);
top = Math.min(square.y, circle.y-circle.rad);

if (right - left > down - top) {
 //compare with horizontal distance
}
else {
 //compare with vertical distance
}

/*These equations assume that the reference point of the square is at its top left corner, and the reference point of the circle is at its center*/

Answer:
do a pre-check whether a circle fully encapsulating the rectangle collides with the circle.
check for rectangle corners within the circle.
For each edge, see if there is a line intersection with the circle. Project the center point C onto the line AB to get a point D.  If the length of CD is less than radius, there was a collision.

    projectionScalar=dot(AC,AB)/(mag(AC)*mag(AB));
    if(projectionScalar>=0 && projectionScalar<=1) {
        D=A+AB*projectionScalar;
        CD=D-C;
        if(mag(CD)<circle.radius){
            // there was a collision
        }
    }

Answer: There is an incredibly simple way to do this, you have to clamp a point in x and y, but inside the square, while the center of the circle is between the two square border points in one of the perpendicular axis you need to clamp those coordinates to the parallel axis, just make sure the clamped coordinates do not exeed the limits of the square.
Then just get the distance between the center of the circle and the clamped coordinates and check if the distance is less than the radius of the circle.
Here is how I did it (First 4 points are the square coordinates, the rest are circle points):
bool DoesCircleImpactBox(float x, float y, float x1, float y1, float xc, float yc, float radius){
    float ClampedX=0;
    float ClampedY=0;

    if(xc>=x and xc<=x1){
    ClampedX=xc;
    }

    if(yc>=y and yc<=y1){
    ClampedY=yc;
    }

    radius = radius+1;

    if(xc<x) ClampedX=x;
    if(xc>x1) ClampedX=x1-1;
    if(yc<y) ClampedY=y;
    if(yc>y1) ClampedY=y1-1;

    float XDif=ClampedX-xc;
    XDif=XDif*XDif;
    float YDif=ClampedY-yc;
    YDif=YDif*YDif;

    if(XDif+YDif<=radius*radius) return true;

    return false;
}

Comment: Note that this answer is for AABB (Axis aligned Bounding Box), not for OBB (Oriented Bounding box).
Answer: My method:

Calculate closest_point from the circle on/in OBB / rectangle
(Closest point will lie on an edge/corner or inside)
Calculate squared_distance from the closest_point to the centre of the circle
(Squared distance avoids a square root)
Return squared_distance <= circle radius squared
Answer: Using the answer below my Java version of circle - square collision/intersection detection:
public static boolean circleIntersectsSquare(Point circle, double radius,
        Point squareCenter, double halfSize) {
    double deltaX = Math.abs(circle.x - squareCenter.x);
    double deltaY = Math.abs(circle.y - squareCenter.y);

    if (deltaX >= (halfSize + radius)) return false;
    if (deltaY >= (halfSize + radius)) return false;

    if (deltaX < halfSize) return true;
    if (deltaY < halfSize) return true;

    double cornerDist = Math.pow(deltaX - halfSize, 2) +
        Math.pow(deltaY - halfSize, 2);

    return (cornerDist < radius*radius);
}

Original answer: Circle-Rectangle collision detection (intersection)
Answer: Assuming you have the four edges of the rectangle check the distance from the edges to the center of the circle, if its less then the radius, then the shapes are intersecting.
if sqrt((rectangleRight.x - circleCenter.x)^2 +
        (rectangleBottom.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleRight.x - circleCenter.x)^2 +
        (rectangleTop.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleLeft.x - circleCenter.x)^2 +
        (rectangleTop.y - circleCenter.y)^2) < radius
// then they intersect

if sqrt((rectangleLeft.x - circleCenter.x)^2 +
        (rectangleBottom.y - circleCenter.y)^2) < radius
// then they intersect

Comment: What about the case where a small circle is entirely enclosed by a large rectangle?  Surely that's an intersection, and would fail the test in this answer.
Comment: Ah yes, I didn't think of that. You could just add more checks like

if sqrt( (rectangleRight.x/2 - circleCenter.x)^2 + (rectangleBottom.y/2 - circleCenter.y)^2) < radius then they intersect

This will be long and slow, but off the top of my head thats the best I can come up with.
Comment: They can intersect on any [single one] point on any of the edges. You should find the edge-center distances as well. (Oh, and call your corners "corners" :)
Comment: This appears to only detect when a corner is inside the circle.


Lost wallet address from 5 years ago.

Question: I purchased 250$ worth of bitcoin back in 2012 on coinRnr and made two transfers with coinRnr with what I bought from them too two different addresses. I was quite messed up at the time since I spent most of that money on Silkroad but do know that I had 106$ of bitcoin left that I bought and I am hoping it is still out there. I have the emails from coinRnr and Blockchain wallet that's empty and bitstamp which I can't remember my password. With the email from coinRnr that had the address they sent the bitcoin to can I find out what wallet it went to or is that not possible ?
Answer: No, addresses are randomly generated and carry no information about what wallet they are associated with.
Answer: Since you know one of your addresses, and have access to your Blockchain wallet, you may be able to identify which transaction you used to deposit money to Bitstamp. If you can provide your identity to Bitstamp and a deposit transaction that is linked to your account, Bitstamp may be able to help you restore your account. On the other hand, just restoring your account at Bitstamp would likely have the same effect.
If you've sent your bitcoins to another wallet or service, and only have the address to go on, you'll probably be unable to recover your bitcoins, since the address alone does not provide any information that can be used to identify the owner.

Lost wallet address from 5 years ago.


Intuitive explanation of geometric mean

Question: Suppose that the 10 Year Treasury Yield Rate varies every trading day during the year X1 (which in practice is accurate) what is the intuitive explanation behind calculating the geometric mean using this equation $[(1+R_1)(1+R_2)...(1+R_{252})]^{(1/252)}-1$? Is this simply the daily compound rate instead of the annualized compound rate?  I realize that to calculate say the market risk premium for the year I can simply take the average of the rate for the whole year and use that but would I also be able to use the geometric mean as calculated above to do this and is it meaningful?
Answer: For a simple example, say you start with \$100 in an account.
In the first year, it makes 50% gain (+50% interest) => \$150
In the second year, it makes 50% loss (-50% interest) => \$75
The arithmetic mean is
<code>(50% - 50%)/2 = 0%
</code>
The geometric mean is
<code>(150% * 50%)^0.5 - 1 = 86.6% - 1 = -13.4% pear year
</code>
You know that you go from \$100 to \$75 over 2 years, so you have definitely lost money. The geometric mean will capture the reality better if you apply a -13.4% return on each year, yielding:
<code>$100 -> $86.6 -> $75
</code>
Answer: The arithmetic mean (simple mean) is not as useful for measuring rates of return over time because of compounding. When you are plotting a time series or forecasting into the future, it is more appropriate to use the geometric mean because it tells you what % return you would need per day/month/year (depends what time scale you are measuring).
Since the example you provided is based on days, you answered your own question. It is the daily compound rate of return.
Conversely, if you were to measure a fund's returns over 10 years it would be the same math except to ^1/10th power.
Comment: Thanks for the answer HK47.  So that means I can simply get the EAR by using the regular formula (1 + dividing that rate by 252)^(252) -1  correct? And this would be the effective annual rate for a 10 Year Treasury Rate Yield for year X1?
Comment: @Dmitriy Yes, precisely. There will be those with different opinions but generally speaking, getting the geometric mean and then using it to calculate EAR is effective. Be careful of using this strategy to price securities that have continuous compounding, though.
Comment: one more question.  So what I've effectively done is calculate an effective annual rate for a 10 Year Treasury Yield using the geometric mean derived from the daily 10 Year Treasury Yield.  This means that I can invest on any day in year X1 in a 10 Year Treasury security and expect a return of the EAR that I compounded on average.  Is this a correct conclusion?
Comment: @Dmitriy Geometric mean is better for forecasting into the future or measuring returns on different time scales (quarterly returns, monthly, etc). EAR calculates based on annual compounding. Treasuries pay annual coupons, so the EAR would be a good approximation of your expected return. There's many other ways to bootstrap an expected return too, but your method is effective.

Intuitive explanation of geometric mean


loop closure detection in visual SLAM

Question: A robotic system is moving a getting its current location using visual odometry (incremental estimation of rotation and translation). To correct its localization, a loop closure technique may be added. However, this technique based on image comparison is costly. I want to find a way to only use this technique of loop closure only when a potential loop closure is present.
Is there a way to use the $x$ and $y$ coordinates of the vehicle provided by visual odometry to say that based on their values a loop closure may have occured?
Answer: You can of course check if the robot is close to a prior position and looking in a similar direction (after he had moved away from this position sufficiently). But if your odometry was reliable enough to do this, you wouldn't really need loop closing. Loop closing was invented for exactly the reason that you cannot trust your odometry over a long time.
Comment: So instead of that, I rather have to run the loop closing algo every 10 images for example? The problem is that the algo I'm using is not very robust against false positives. I wanted to check that it is really a loop closing using visual odometry data
Answer: Well, there is an old solution that finds a possible loop closure by a growing uncertainty of the current location which was popular in EKF based SLAMs. In such way, you can reduce the number of the candidates for the place recognition. But I guess trajectory only is probably not enough for a loop closure unless you assume a special situation.
Answer: I think you should go for iterative closest point algorithm. This algorithm is used for detecting loop closing. This is not very reliable but still it work well. You can check this link Visual navigation for flying Robots
Comment: I think you haven't understood ICP correctly. ICP is a way to align two pointclouds which are already(!) quite well aligned as it's doing only a local optimization.

loop closure detection in visual SLAM


Wi-Fi vs. Ethernet on AirPort Express

Question: I use an AirPort Express to extend my Wi-Fi network and it works great. My question is whether I would notice a significant signal boost by plugging in an ethernet cable into the AirPort Express rather than accessing it over a Wi-Fi network?
Answer: I would not expect a significant Signal Boost from Cabling the connection back to the main network.  However, if you have several devices connected to the AP, then you may see an increase in speed.  Say you have three PCs connected to the AP at 54Mbs, all trying to open large files from the file server.  Right now they all share the 54Mbs connection to the wired network.  The WiFi connection to the network becomes the bottleneck.  If you replace it with a 100Mbs or GigaBit cabled connection, then the PC's will down the files faster.  Of course this could push the bottleneck somewhere else, like the internet connection if they are downloading music or something...

Wi-Fi vs. Ethernet on AirPort Express


What are the different variations of the word "workplace" in German and what is their most appropriate context?

Question: I understand that Workplace translates into german as Arbeitsplatz but in America we use variations such as "the office", "the shop", etc. And it seems that much of the context depends on the type of labor. Are their equivalents in German that are frequently used? Perhaps some to be more formal and others to be casual?
Answer: Arbeitsplatz, as you already mentioned. However, that does not neccesarily mean workplace (in the sense i'd translate workplace, at least); i could say "Ich arbeite nun schon 6 Jahre am gleichen (Arbeits)platz" (which i would translate with workplace), but it could also be used in a newspaper headline "Die neue Fabrik schafft 130 Arbeitsplätze in der Gegend", which i'd translate to jobs, not workplaces.
Arbeitsstelle - a bit more formal, and with a slightly different meaning, more like "the company i'm working for". "Ich habe die Arbeitsstelle gewechselt" does always mean you changed your employer, while "Ich habe den Arbeitsplatz gewechselt" can mean you changed your employer, but might also mean you're just sitting at a different desk now.
Betrieb, Firma - if i come home late and my wife is mad at me, i'd say "Ich mußte länger im Betrieb bleiben" oder "ich mußte länger in der Firma bleiben", i wouldn't use either of the other words in that case.
Büro, Baustelle, Werkhalle, Laden, Backstube (bakery), ... - lots of words that refer to the building, or the room, i'm working in, so they don't translate to workplace, they rather imply workplace.
Answer: That depends on what your work actually is / where it takes place.
Every room with a desk in it might be called Büro.
If the office is just a (small) part of the workplace, one probably refers to the part which is most significant. For instance someone working on a construction area would rather refer to his workplace with auf der Baustelle than im Büro, even though most of the time he is actually working at the desk (even e. g. in a construction trailer/container or something like that).
Answer: Arbeitsplatz ist der allgemeine Begriff, Büro, Werkstatt und Laden sind spezielle Formen des Arbeitsplatzes.


Should the currently selected item in a combo/dropdown box also be included in the list of choices?

Question: For example, you have a combo box which contains 10 elements including the one that is currently selected. When you prompt to drop down the list to choose another, should the currently selected item also be in this list?
Comment: Possible duplicate of [Show or don't show the currently selected option in menu or dropdown](http://ux.stackexchange.com/questions/67954/show-or-dont-show-the-currently-selected-option-in-menu-or-dropdown)
Answer: It should be listed. And the default behaviour of browser combox box dropdowns is to have the selected item as first item.
Otherwise, clicking the combo box, it would be unclear how to retain the currently selected value once the drop down has opened. While clicking outside the combo box might reselect or reset to the currently selected value, it is much clearer to have the currently selected value in the combo box listing, preferably as first item, thus allowing to reset to same value by clicking it. This also presents all choices in a clear and consistent way.
Answer: Yes, it should remain in the list.
Imagining myself as the user for a moment, when I type something in a combo-box, it helps me select an item from the list below.  How will I know that I've typed something that's actually found in the list if as soon as I finish typing it the item no longer appears in the list?  Instead, give the me visual feedback by keeping the item in the list and highlighting it.
It may seem redundant to display the same text in both places--which, I assume, was the reason for your question--but the second place it's displayed (highlighted in the list) serves to confirm that the first (in the box) is a valid entry.  You might be able to get around this by highlighting the text box once the full query is formed, but it won't give the feedback the user's accustomed to so many users will likely find such a format unintuitive.  There's nothing to loose by the slight redundancy, so you might as well leave the entry in the list....just make sure to highlight it.
Comment: In the case of a combo box however, you can't edit the field at all. So the choices are not editable.
Answer: Yes, since a combobox is a select box with the added benefit of an autocomplete-style-suggestion, it should still do at minimum what a normal select does.


Manufacturer "best if used by dates" - how long that container has been on the store shelf

Question: I bought a jar of grated Parmesan cheese that has a "use by date" three months from today.  Has that jar been on the shelf a year, six months, three months, how long? Do Kraft, Sargento, Signature Kitchens, etc. all have to use the same amount of time between packaging and "use by" dates, i.e. for Parmesan cheese 1 year, six months, etc., or can they just pick a shelf life out of the air based on their "calculations?"  Please note: this has nothing to do with how long it lasts after I open it, but instead, how long has it been on the shelf.  Thanks
Comment: Well I don't know about those items but the date on milk came from the cow themselves. https://www.youtube.com/watch?v=qguDBXXOsWw the cow will basically tell you the date
Answer: It probably hasn't been there very long, a few days to a few weeks at most. Shelf space in a grocery store is very valuable. They want to use it for products that move, not for inventory. Some vendors even have to pay a slotting fee to the stores to keep their products there.
That's not to say it was made yesterday. It may have sat in a manufacturer's or distributor's warehouse for months. Again, they don't want to pay the costs of inventory, but the logistics of manufacturing sometimes mean that they have to make a lot of stuff at once and store it. That would be most obvious for something like seasonal fruits, such as cherries, which are harvested all at once, canned, and then kept in warehouses before being shipped to retailers.
I don't know how far they'd set the "best before" date for grated hard cheese. It probably varies from manufacturer to manufacturer. I wouldn't have anticipated it being much more than three months, but if you've got a jar with a three-month date then it was probably at least six. Which means it could well be three months old before you bought it.
But it probably spent little of that time taking up shelf space.
Answer: Expiration (use by or sell by) dates do not come out of thin air, since the actual meaning of this expression is the limit date that the manufacturer is liable for the quality and stability of the product as long as recommended storage conditions are followed.
Manufacturers (usually the big ones) have extensive documentation proving this through stability studies performed in a whole lot of different conditions and the small manufacturers typically draw on the experience and documentation of the big manufacturers - similar products behave in similar ways if no extensive changes are done to the formulation.
If you're curious, you can find a lot of this information in patent filing :)


How was Dovid a descendant of Miriam?

Question: It says in Sota 11b that the houses which were given to Yocheved and Miriam are interpreted as kingship, and the gemarah says that Dovid comes from Miriam. I'd like to know how that is possible given that Miriam married Calev and Dovid's ancestry is pretty clearly not from that line on either side. In Divrei haYamim I chapters 2 and 4 it shows unequivocally that Dovid comes from Ram, Calev's brother.
Comment: Was inter-shevet marriage not common?
Comment: @Noach In the desert it was forbidden
Comment: @DoubleAA, would their descendants need to have married in the desert, seeing how Shevet Levi seems to have been mainly concentrated in Yehuda, it would not be surprising if there were a relationship within the intervening hundred-odd years.
Answer: Ruth 4: 18 - 22
Peretz, Chetzron, Ram, Aminadav, Nachshon, Salmon, Boaz, Oved, Yishai, Dovid.
Nachshon was the nasi of Yehudah at the time of the Exodus.
Sotah 11b says that Dovid descended from Miriam. However, Calev is not mentioned. Some commentators connect Dovid being called Efrati with Miriam (Efrat) and say that one of her descendants married into the family (possibly a wife of Nachshon, Salmon, Oved, or Yishai)
As an example, Illegitimate Origins of King David's Dynasty

The Talmud says (Sotah 11b) that because Miriam aided her mother Jochebed in saving the Jewish babies in Egypt, Miriam merited that King David's dynasty should descend from her. The proves that Miriam was a foremother to King David by explaining that Miriam is called Efrat[23], after Caleb nursed her back to health following her deadly illness[24], and King David is known as an Efrati[25]. Rabbi Shmuel Eliezer Eidels (1555-1631) asks[26] that the lineage of King David is traced in the end of the book of Ruth (as mentioned above), yet neither Miriam nor her husband Caleb are listed as being ancestors of King David. Rabbi Eidels offers the possibility that Ram son of Chetzron, a great-grandson of Judah, was the same person as Caleb. However, he disproves such a possibility because Caleb was actually a brother of Ram, as is evident from Chronicles 1 2:9 which lists Yerachmiel, Ram, and Caleb–referred to there as "Celuv"—as the sons of Chetzron. Rabbi Eidels assumes that the Caleb referred to in that verse is identical with the Caleb who married Miriam, however this assumption is debatable[27], and so it is possible according to some explanations that Ram indeed is identical with Caleb and "Celuv" mentioned in the above-cited verse is another person. Rabbi Eidels concludes that since the family of Elimelech (the father of Machlon) is also called Efrati[28], it must be that Ram or one of his descendants (Aminadav or Nachshon) married a female descendant of Miriam and Caleb and the resulting offspring fathered the Davidic Dynasty.
Comment: To add to your point about Nachshon, the Midrash Shocher Tov 18:27 says that Dovid came from the seed of Nachshon.

How was Dovid a descendant of Miriam?


Threading Question

Question:
Possible Duplicate:
Creating a blocking Queue<T> in .NET?

I have typical producer and consumer threading issue. However the only difference is that the producer is allowed to build up a buffer of 5 items after which it has to wait until some items are consumed.
What would be the best solutions to implement this in c#.
Currently I have it implemented using a semaphore however the producer seems to build up a buffer of over 100 items very rapidly. I have no syntax to handle limiting the buffer to 5 items. I was thinking of using a static integer - have the producer increment it - when it reaches 5 the producer goes to sleep. Have the consumer decrement it and wake up the producer.
Answer: Why don't you just use a bounded queue (size 5) and have the producer block if the queue is full?
Answer: You can use a queue which will ensure first in first out for all your data packets. However since you mentioned that queue gets filled quickly i think you may want to increase the queue limit to some greater number. You mentioned that you would be using sleep to avoid populating more than 5 data in queue, i feel producer is producing at much higher rate than consumer. So you may need to optimize queue size based on requirement.
Also you can have simple event for signalling the consumer thread that queue is filled and needs to be cleared. Semaphores in my view become tedious to handle. Again, this is just a personal opinion.

Threading Question


What was Benedick and Beatrice's relationship?

Question: Whedon's "Much Ado About Nothing" added many visual details to the text of the play. One of these appeared to be a prior sexual relationship between Beatrice and Benedick. However, it's not exactly easy to follow the dialog. Was this a correct interpretation of events? If so, was this at all referenced in Shakespeare's dialog, or was this an extrapolation by Whedon?
Comment: I'm not familiar with the specific version you're referencing, so I can't tell you if your interpretation is correct. However I can tell you that nothing like this is part of the original Shakespeare. With regard to the dialogue being difficult to understand, I used to think so too. You might be interesting in watching this play (and others) as produced by the Royal Shakespearian Company. Those actors truly understand their lines, so even if some of the words don't quite make sense, you easily can understand what's happening through inflection, body language, etc. I enjoyed reading (cont'd)
Comment: Hamlet (that is, the actual text of the play), but I appreciated it even more when I watched the RSC version with David Tennant and Patrick Stewart. You get a lot more out of it when you get that real sense of how the characters think and feel. The RSC has a version of Much Ado About Nothing also (I think you can buy it on their website somewhere, I forget exactly where.) It's also very good. So, just a thought :) It might help you appreciate Shakespeare even more. I know I really *got it* for the first time, watching the RSC.
Comment: Thanks for the recommendation! Whedon's version was similarly easy to follow, even though it used the original text word-for-word. You might enjoy it. It's just the exact wording that's difficult, like you said.
Answer: From the text:

DON PEDRO
Come, lady, come; you have lost the heart of
     Signior Benedick.
BEATRICE
Indeed, my lord, he lent it me awhile; and I gave
     him use for it, a double heart for his single one:
     marry, once before he won it of me with false dice,
     therefore your grace may well say I have lost it.
DON PEDRO
You have put him down, lady, you have put him down.
BEATRICE
So I would not he should do me, my lord, lest I
     should prove the mother of fools.

So, at some point in the past, Benedick told Beatrice he loved her (he lent her his heart).  She returned his love ( gave him use for it, a double heart for his single).  However, he was not faithful (he won it of me with false dice, i.e. he cheated).  Therefore she insults him/keeps him at arms length because of how he treated her.
Now, Whedon presents this as a sexual relationship, possibly a one night stand, during the prelude/opening credits.  Given the horror of Hero's assumed loss of virginity, however, this would NOT be the original intent of Shakespeare.
Answer: Yeah, my favorite version is the one with Robert Lindsay and Cherie Lunghi from the '80's, followed by the more recent filmed production from the Globe. I've always been a little confused about this one, myself. Just from Beatrice's words, without of the context of the rest of the play, I would agree that maybe that they had a romantic attachment in the past but he "dumped" her or something. But, then, from earlier scenes one is led to believe that Benedict has always held women at arms' length, never showing more than civility, perhaps, from what he says and what his friends say about him.  And then, when he "overhears" of Beatrice's love for him later he is completely taken aback. If they had some sort of mutual romantic attachment in the past or if he was aware of her being romantically inclined to him in the past, I don't think he would be as taken aback at the idea that she was in love with him. If she was in love with him once, why not again or still?
I think that many, many years ago when Beatrice was open to love and uncynical she met Benedict and they hit it off, friendship-wise, and maybe he was flirtatious in the courtly-love sense, and noble country bumpkin Beatrice, who maybe was a little sheltered without parental instruction and only her uncle, thought he was serious and fell into full fledged infatuation, her "double heart for his single one"; while clueless Benedick just enjoyed her company, he 16th century friend-zoned her, with a little customary court flirtation thrown in.
So she's expecting some sort solid attachment to form and it never materializes and he leaves, she realizes it was just empty fliratation, he never took her seriously, maybe she even feels cheated and taken advantage of. Maybe she asks around and finds out that this behavior is par for the course with Benedick. Her feelings sour. So, when next they meet, still before the events of MAAN, she's verbally cutting and cold. Benedick, totally clueless as to why she's suddenly hostile, he probably never paid her serious attention in the first place, is paying attention now, and is on the verbal defensive back, thus begins the sparring, and maybe begins or deepens his scorn of women. But underneath it all, maybe even unknown to Beatrice, is still the young girl who fell in love with Benedick, and it's woken up when she "overheard" of Benedick's alleged love for her.
Just a thought. A very long thought.


Source for saying Aramaic parts of davening quietly?

Question: I remember reading somewhere that there is a kabbalistic tradition to say the parts of davening that are in Aramaic (e.g. the targum in Uva Letziyon) quietly. What is the source for this?
Comment: @SethJ That question asks specifically about the Uva Letziyon while this one uses it as an example with respect to a question about a broader rule, so I'd say not a dupe.  Although this question might not be a really valid question since we see that the tradition at least doesn't apply in some cases (kaddish), and maybe doesn't apply in any case besides Uva Letziyon.
Comment: See Taz (OC 132:1,לפי שכל שהוא בלשון תרגום אין לאומרו ברבים כן כתב בספר הזוהר, citing Zohar, *T'ruma* 132b), as well as the *P'ri M'gadim* (OC *Mishb'tzos Zahav* ad loc.) who discusses alternative reasons. See also *Beit Yosef* (OC 59). (If I get around to it, I'll write up an answer. If someone beats me to it, that's great too).
Comment: What about kadish?
Comment: Presumably it doesn't apply to kaddish, but I really have no idea.
Comment: Dupe? http://judaism.stackexchange.com/q/17557/5
Answer: The Rama in Orach Chaim siman 132 seif 1 says that in Uvah LeTzion (kedusha de'sidra) the parts of the kedusha that are translated into Aramaic should not be said aloud.
The Mishnah Berurah sk4 says that the Aramaic should be said as an individual since "everything that is in Aramaic should not be said berabim"
The perush Matok MiDvash explains the reason behind this halacha according to the Zohar (chelek 2 132b) which states that the shoresh (root) of Aramaic is from the sitra achah and we need to diminish the power of the sitra achah by means of reciting it as an individual.
As an aside: The Mishna Berurah concludes that if an individual is not praying with a tzibur they are allowed to say the Aramaic aloud. This is quoted from the Sha'arei Teshuva. However according to other explanations for the Rama's halacha (some brought in the Peri Megadim) you might not be allowed to say the Aramaic aloud even when not praying with a tzibur
Answer: The Gemara in Shabbos 12b mentions that one shouldn't daven in Aramaic because angels don't understand Aramaic.  The angels "carry" the prayers to G-d, and if they don't understand them, they won't take them because they don't want to take unacceptable prayers.  However, in prayers which are a davar sheb'kedusha, the prayers are listened to directly by Hashem, and therefore Kaddish is said aloud in Aramaic (along the lines of the gemara there, that davening in the presence of the sick person can be done in Aramaic because Hashem is with the sick).


How to customize the url of a field in views?

Question: I have a view that displays product images using a jcarousel. In the view, I have a jCarousel format and it displays fields. In the Fields section, I'm displaying Content: Image. I want to link the image to a specific url. I can modify it using Rewrite Results and selecting Output this field as a link.
According to the answer I got from how to make a field in a view be the link destination to another field? & http://64sqft.danapellerin.com/2011/06/07/drupal-custom-cck-field-tokens-in-views. Views takes into consideration the order in which your fields are in the view. The taxonomy field that you want to use as a token needs to be reordered above the field you want to use the token in the url.
Things I've tried:

I tried content:category (which is my taxonomy field), and hid it so it wouldn't display. In the field's replacement patterns it gave me [taxonomy_catalog] & [taxonomy_catalog-tid]. I tried [taxonomy_catalog] but the replacement gave me the text from taxonomy description.
I tried Content: All taxonomy terms, but it gave me the name of the term instead of the ID.

How can I modify the rewrite to include the taxonomy term id associated with the node?
Comment: Have you tried adding the taxonomy term as a relationship?
Answer: The problem was the way that Content: All taxonomy terms required a rewrite to [term_node_tid-tid]. Otherwise it would display the term name instead of the tid.


Can I upgrade a Windows 7 student licence?

Question: I have a computer with a windows 7 student licence key, from the Microsoft Academic Alliance. Which I have from when I was studying. Is it possible to upgrade it to Windows 8? Or do I need to buy a retail licence?
Answer: You can upgrade your Windows 7 student license to Windows 8.
The only requirement for the upgrade, as per the terms and conditions, is that you have a valid base license. A student license is still a valid license.
Answer: You can upgrade it, but you will need to get a legitimate Windows 8 Key.
If you are part of the Dream Spark Premium, then you can use one of those. Otherwise you will need to purchase a retail upgrade key or full retail copy.
Answer: So, far from what I've read, Microsoft is offering Windows 8 for two prices at this point - $15 and $40.
The first ($15) option is for owners of Windows 7 PCs which have been purchased after June 02, 2012. This page can be found here.
The second ($40) is for everyone else who is running Windows XP SP3, Windows Vista, or Windows 7 and is a regular Windows 8 Pro Upgrade license. This price is only valid until January 31, 2012 and the page can be found here.
So, essentially, yes - as long as you have a valid base install (Windows XP-7), you can upgrade to Windows 8.
If you are still have access to Microsoft Academic Alliance* they can provide you with a license key for Windows 8.

It is now known as Dreamspark.
Comment: I'm not studying any more so no I'm not part of it
Comment: Then, you would have to purchase a $15 or $40 license (depending on when you bought the computer). But, yes you can upgrade.
Answer: You can upgrade to windows higher versions at any time. However, you need to buy the licence key for windows 8 upgrade unless or otherwise you have a windows 8 key from your DreamSpark (MSDNNA).


How much power can the Pi supply?

Question: I am making a project in which I will be using an arduino to control several servo motors and LED's. And I ll be using a Rqspberry pi to control arduino. They will be connected serially. In this situation, will Pi be able to power the arduino?
 Because I will power all the motors and external components seperatel from the battery.
I will also connect a camera and WIFI Adapter to the Pi. Will it be able to provide this much current?
Note: it is arduino mega 2560. If not, then is there anything I can do? Like external power or something?
Answer: The Raspberry pi provides around 100ma. If the Arduino, wifi, and camera take more than that, you could connect them to an external powered USB hub.
Answer: If you power the Pi via the standard microUSB socket you can feed 2 amps at 5V into the Pi (the current limit is imposed by the 2 amp polyfuse).
The Pi plus wifi adapter plus camera will probably take 750mA.  That would leave over an amp for the Mega2560 which is plenty (I'd guess it would draw around 100mA).
You should have no problems.

How much power can the Pi supply?


Can I use pump spells with Fighting?

Question: In a "fight," can "pump" spells be used?
As an example, I have my 2/2 fight my opponent's 4/4, then I add a +3/3 pump to my 2/2. Would his 4/4 die to my now 5/5?
Answer: This depends on the order in which spells are played. I'm assuming you know about the stack: When spells are played or effects are triggered, they are placed on the top of the stack. When no player wants to add spells or effects to the stack, the stack gets resolved top-to-bottom; in effect in reverse order of placing things on it.
Having said that, I also assume that with "fight" you are not referring to regular combat but to spells that pit two creatures against each other. Then it matters in what order spells are played:

You play Giant Growth on your creature, the stack resolves and you now own a 5/5. You or your opponent set up a 'fight' between your 5/5 and his 4/4. Your creature survives, his dies.
Your opponent casts a fight-spell on his 4/4 and your 2/2. While that's still on the stack, you react with an instant to make your 2/2 a 5/5. Same result.
You cast a Giant Growth on your 2/2 and your opponent reacts with a fight-spell pitting your Grizzly Bears against his 4/4. In this instance, the Giant Growth hasn't resolved yet, and the 4/4 will win the duel, killing your 2/2. Giant Growth will fizzle when it resolves because its target is no longer legal.

On a side note, in the last scenario you could react to the fight-spell with another Giant Growth if you have a second spell in your hand and the mana available.
Answer: When two creatures fight they deal damage to each other based on their power. A Grizzly Bear that has had Giant Growth cast on it will be a 5/5 creature until the end of the current turn. Therefore it will deal 5 damage when it fights. The 4/4 creature will then have 5 damage marked on it after fighting which is more than its 4 toughness so it will die.

701.10a A spell or ability may instruct a creature to fight another creature or it may instruct two creatures to fight each other. Each of those creatures deals damage equal to its power to the other creature.

Can I use pump spells with Fighting?


How to compute the storage cost of encrypted data

Question: Let's say I have (as an example only) 1 MB of plaintexts. I want to encrypt it using symmetric encryption algorithm (e.g. AES) and store the plaintext and ciphertext in a memory space. Does a ciphertext take the same size as its corresponding plaintext? I mean, in my example, does this mean I need 2 MB to store plaintexts and ciphertexts? Can you provide references?
Comment: For standard techniques, the encryption storage overhead is constant and usually way less than 100 bytes.
Comment: @SEJPM Thanks. But, can you clarify. What do you mean by `storage overhead is constant`? Do you mean that the ciphertext costs storage equal to the plaintext storage?
Answer: Your question is too broad in this form.
There are plenty of different symmetric encryption algorithms. Most of them produce 1MB output for 1MB input. Most of them are block-based, so they round up the input size to a multiple of a block-size. If you choose a specific algorithm, you can check the exact details yourselves. You should not choose encryption algorithm based on the overhead though, but rather choose one based on security and performance.
Also, it is usual to compress data before encrypting it, because it is impossible to do so after encryption.
Comment: *`…because it is impossible to do so after encryption.`* – I'm aware that this is nit-picking, but compression **is possible** after encryption. Yet, I certainly agree that doing so will produce rather negligible compression results due to the random nature of encrypted data.
Comment: :facepalm: You are completely right about that. How does this compliment feel? :P
Answer:
Does a ciphertext take the same size as its corresponding plaintext?

It really depends. From a cryptographic standpoint you can do this, however there are a few pieces of info you really want to be sent along with your message. The overhead thus is constant, i.e. independent of the actual message length. If you go with crazy double-encryption variants or weird custom schemes though you may of course get a linear increase here.
The (interesting) values you may or may not provide with your ciphertext may include the following ones:

Authentication tag. You really want this one or otherwise you won't be able to verify the integrity of the message you're receiving. Its size usually ranges from 16 (GCM) to 64 bytes (HMAC-SHA-512).
Nonce / IV. You really want this as otherwise you have no chance of getting actually secure encryption and same messages encrypt to same ciphertexts. The overhead introduced here is around 0 (fully context dependent) to 16 bytes (CBC-IV) usually.
Scheme identifier. You may want to add an identifier for your scheme used in case your application supports or will support multiple encryption algorithms. The overhead here may reach from a single byte up to a few bytes (OID).
Structuring. More often than not you want your various data types to be structured as standards-compliant as possible and thus you may want to use something like ASN.1 which also adds a few bytes as overhead (for encoding lengths and types).
Data encryption keys. Sometimes people also use different keys for the each packet of data to limit the amount of data per key. A data encryption key is then an encrypted key which can decrypt the message content. This overhead of course also depends on all the other listed overheads.
Other auxilliary data. This may include application-defined content such protocol version and other routing information.

So all in all you tend to be looking at a constant overhead with 32 bytes minimum in size and a few hundred bytes in size maximum.


Practical difference between TTL and flash sensor

Question: On an speedlite 600EX-RT, what is the practical difference between E-TTL II and Ext. A? I know the technical one, but how does it change flash exposure if you measure through the flash sensor rather than through the lens?
Comment: This is very similar to [Does auto mode of flash metering have any advantage over TTL?](http://photo.stackexchange.com/questions/45090/does-auto-mode-of-flash-metering-have-any-advantage-over-ttl), although that doesn't have an answer either.
Answer: In theory, ETTL or iTTL for Nikon, should be more accurate in more situations, especially for closeups where the flash sensor is not pointed directly at the subject.  However, it has some drawbacks.  It is a much more complicated process which takes some time and requires a preflash test which is measured.  The preflash and the calculation can take just long enough that some people begin the blink which is captured.  In some situations, it will slow down fast multi shot sequences.  Flash auto sensor is always extremely quick, is consistent in how it behaves, and does not cause blinking.  So, neither is perfect, but the technology of ETTL, used with lenses that provide distance data, gets the nod for most situations.
Hope that helps.
Comment: In ETTL Canon does emit a preflash, I believe at 1/32 power.
Comment: But Canon doesn't uses a preflash in neither mode?
Answer: There is some situation where the flash sensor is just off:

With a non coupled lens stopped down (unless you can input the f-number into the flash...)
When dealing with a small subject detached from the background: spot TTL metering will do the job, flash sensor will overexpose the subject trying to get enough light to the background.
All the situation where the flash is not on the body grip (as example: I do macro with a cobra flash hold in one hand in this situation the flash sensor is not directed to the subject and is not at the same distance than the camera)


tried to update from lucid lynx, now computer won't boot

Question: I  don't know much about my computer, I  have been trying to get an old custom computer updated.  it was running on lucid lynx, I  tried to update from the terminal  with  some 'copy and pasted' 'sudo  get  upgrade',  I'm not sure what exactly I put in the terminal but it looked like it was doing its thing,  then it got hung up somewhere and I  mistakenly tried to resart.  now when I turn the computer on  it goes  to the 'ubuntu'  loading screen  but never completely boots.  I'm sad, and have no idea what to do, and am way beyond my understanding.... please help
Answer: My answer might not be exactly what you are looking for but since your level of experience as you say is low I would suggest you do the following:
First, boot-up your system using a liveCD or liveUSB and make a complete backup of your home folder to some external media.
Second, do a completely new install on your system. Of course, this will wipe out all data on your hard disk.
Last, restore your backed-up home folder to the new installation. You might have to perform this step while booted from a liveCD/USB to avoid overwriting open system files on your home folder.
These procedure will at least give you a working system as fast as possible.
Answer: hmayag's answer will get you up and running again, but if I were you I'd switch to Lubuntu 13.04 rather than running that old **box version of Ubuntu. ;OP
Unless you require the older operating system for running certain programs or drivers that aren't compatible with later versions of Ubuntu, personally I'd want to try and get an up to date OS.
In that case you'll still want to do the /home folder thing so that you've got a backup should you want to return to Lucid Lynx, but when copying files back into the home folder of 13.04, it'd be best to only copy the folders such as documents pictures videos Desktop etc, as those folders don't contain any program settings, just your documents.
That way you'll have a clean slate of settings for the new Ubuntu version, as the ones from a really old Ubuntu may stuff things up on the new Ubuntu version.
You can get Lubuntu here:
http://lubuntu.net/
It's a cut down version of the current release of Ubuntu designed for older computers. As the full Ubuntu 13.04 requires more of the hardware than many old PC's can deal with.


Setting TCP_NODELAY

Question: My application running on Solaris need send tcp packages to client in time, but sometimes the packages send delayed. I know can create socket with TCP_NODELAY to resolve the issue, but the code can not be changed. Can someone tell me where do I set the TCP_NODELAY to ON in Solaris ( Any version ). Does Solaris supports this parameter. I searched of the manual, but not see any useful information.
Answer: Solaris supports TCP_NODELAY as a socket option you can set in the code - there is no global setting to force it on for all connections.    The best I can think of is to write a small LD_PRELOAD module that interposes on socket() or connect() to call the required getsockopt() as well.
Answer: You can't fix code without changing it. You won't find a real solution because the problem is in the code and you aren't willing to change the code. There are rules that have to be followed when handing outbound data to the TCP stack, and if the code doesn't follow them, it will get 200ms delays. That's just the way TCP works -- it doesn't guarantee timely transmission.

Setting TCP_NODELAY


Looking for a third party application that would create restore point and triggers it in every boot up

Question: I am looking for a thrid party restore point application (preferbly free ones) that enables to restore back to it's original point in every bootup.
I am managing the environment where many annonimus people would use the public workstations, so I need these workstations to be restored every time when the computer reboots.
If you can suggest any, please let me know. Many thanks in advance.
Answer: Which version of Windows?  For 32-bit XP/Vista, Microsoft's SteadyState will do what you want for free (though it's only available to download until Dec 31, 2010, so hurry up!  :-) ).  Other (commercial) options are Deep Freeze and Fortres.
You should be able to use that information as a starting point to find other possible competitors.  That's just what I've heard of over the years.
One thing to be careful of: Most of these products will allow the system to be modified while it is booted, they just clear out any modifications on reboot.  A malicious user could theoretically come in at the start of the day, infect the system, and leave it running for others to use all day.  You'll need other procedures to mitigate these kind of attacks if they're a concern.  It's more problematic if these kiosks are unattended.  Even a user-mode keylogger could send a day's worth of user info out onto the internet.