qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
87,713
<p>For example, right now I have a roll-my-own solution that uses data files that include blocks like:</p> <pre><code>PlayerCharacter Fighter Hitpoints 25 Strength 10 StartPosition (0, 0, 0) Art Model BigBuffGuy Footprint LargeFootprint end InventoryItem Sword InventoryItem Shield InventoryItem HealthPotion end </code></pre> <ul> <li>human editable (w/ minimal junk characters, ideally)</li> <li>resilient to errors (fewest 'wow i can't parse anything useful anymore' style errors, and thus i've lost all of the data in the rest of the file) - but still able to identify and report them, of course. My example the only complete failure case is missing 'end's.</li> <li>nested structure style data</li> <li>array/list style data</li> <li>customizable foundation types</li> <li>fast</li> </ul> <p>Are there any well known solutions that meet/exceed these requirements?</p>
[ { "answer_id": 87725, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 3, "selected": false, "text": "<p>Yaml is a good solution and very close to what you have. Search for it.</p>\n" }, { "answer_id": 87736, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 1, "selected": false, "text": "<p>I second the <a href=\"http://www.yaml.org/\" rel=\"nofollow noreferrer\">YAML</a> suggestion. It's extremely easy to edit, very forgiving of mistakes and widely supported (especially among the dynamic languages).</p>\n" }, { "answer_id": 87748, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 1, "selected": false, "text": "<p>I'd say the most common choices are: </p>\n\n<ol>\n<li><a href=\"http://en.wikipedia.org/wiki/Json\" rel=\"nofollow noreferrer\">JSON</a> (<a href=\"http://www.json.org/\" rel=\"nofollow noreferrer\">offical site</a>) - very flexible, though the punctuation can take a bit for people to get used to</li>\n<li><a href=\"http://en.wikipedia.org/wiki/INI_file\" rel=\"nofollow noreferrer\">INI</a> - super simple to use, but a bit limited in data-types</li>\n<li><a href=\"http://en.wikipedia.org/wiki/XML\" rel=\"nofollow noreferrer\">XML</a> - pretty flexible, common, but way too verbose sometimes</li>\n</ol>\n" }, { "answer_id": 87755, "author": "user16773", "author_id": 16773, "author_profile": "https://Stackoverflow.com/users/16773", "pm_score": 0, "selected": false, "text": "<p>You could try JSON available at: <a href=\"http://www.json.org/\" rel=\"nofollow noreferrer\">http://www.json.org/</a></p>\n\n<p>It was designed for javascript and web usage initially. But it's pretty clean, and supported in many languages.</p>\n" }, { "answer_id": 87774, "author": "jjrv", "author_id": 16509, "author_profile": "https://Stackoverflow.com/users/16509", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.lua.org/\" rel=\"nofollow noreferrer\">Lua</a> was designed to be a programming language where the syntax lets you easily use it as a markup language as well, so that you include data files as if they were code. Many computer games use it for their scripting, such as World of Warcraft due to its speed and ease of use. However it's originally designed and maintained for the energy industry so there's a serious background.</p>\n\n<p>Scheme with its S-expressions is also a very nice but different-looking syntax for data. Finally, you've got XML that has the benefit of the most entry-level developers knowing it. You can also roll your own well-defined and efficient parser with a nice development suite such as <a href=\"http://www.antlr.org/\" rel=\"nofollow noreferrer\">ANTLR</a>.</p>\n" }, { "answer_id": 87789, "author": "Ranguard", "author_id": 12850, "author_profile": "https://Stackoverflow.com/users/12850", "pm_score": -1, "selected": false, "text": "<p>I would suggest <a href=\"http://www.json.org/\" rel=\"nofollow noreferrer\">JSON</a>.</p>\n\n<ul>\n<li>Just as readable/editable as YAML</li>\n<li>If you happen to use for Web then can be eval()'ed into JavaScript objects</li>\n<li>Probably as cross language as YAML</li>\n</ul>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16639/" ]
For example, right now I have a roll-my-own solution that uses data files that include blocks like: ``` PlayerCharacter Fighter Hitpoints 25 Strength 10 StartPosition (0, 0, 0) Art Model BigBuffGuy Footprint LargeFootprint end InventoryItem Sword InventoryItem Shield InventoryItem HealthPotion end ``` * human editable (w/ minimal junk characters, ideally) * resilient to errors (fewest 'wow i can't parse anything useful anymore' style errors, and thus i've lost all of the data in the rest of the file) - but still able to identify and report them, of course. My example the only complete failure case is missing 'end's. * nested structure style data * array/list style data * customizable foundation types * fast Are there any well known solutions that meet/exceed these requirements?
Yaml is a good solution and very close to what you have. Search for it.
87,734
<p>If the major axis of the ellipse is vertical or horizontal, it's easy to calculate the bounding box, but what about when the ellipse is rotated?</p> <p>The only way I can think of so far is to calculate all the points around the perimeter and find the max/min x and y values. It seems like there should be a simpler way.</p> <p>If there's a function (in the mathematical sense) that describes an ellipse at an arbitrary angle, then I could use its derivative to find points where the slope is zero or undefined, but I can't seem to find one.</p> <p><strong>Edit: to clarify, I need the axis-aligned bounding box, i.e. it should not be rotated with the ellipse, but stay aligned with the x axis so transforming the bounding box won't work.</strong></p>
[ { "answer_id": 87965, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 2, "selected": false, "text": "<p>I think the most useful formula is this one. An ellipsis rotated from an angle phi from the origin has as equation:</p>\n\n<p><img src=\"https://upload.wikimedia.org/math/0/3/c/03c5881fa31396b50318778bb607ebf9.png\" alt=\"alt text\"></p>\n\n<p><img src=\"https://upload.wikimedia.org/math/0/c/0/0c06c7767e37335e07a0ba821d390180.png\" alt=\"alt text\"></p>\n\n<p>where (h,k) is the center, a and b the size of the major and minor axis and t varies from -pi to pi.</p>\n\n<p>From that, you should be able to derive for which t dx/dt or dy/dt goes to 0.</p>\n" }, { "answer_id": 88020, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 6, "selected": true, "text": "<p>You could try using the parametrized equations for an ellipse rotated at an arbitrary angle:</p>\n\n<pre><code>x = h + a*cos(t)*cos(phi) - b*sin(t)*sin(phi) [1]\ny = k + b*sin(t)*cos(phi) + a*cos(t)*sin(phi) [2]\n</code></pre>\n\n<p>...where ellipse has centre (h,k) semimajor axis a and semiminor axis b, and is rotated through angle phi.</p>\n\n<p>You can then differentiate and solve for gradient = 0:</p>\n\n<pre><code>0 = dx/dt = -a*sin(t)*cos(phi) - b*cos(t)*sin(phi)\n</code></pre>\n\n<p>=></p>\n\n<pre><code>tan(t) = -b*tan(phi)/a [3]\n</code></pre>\n\n<p>Which should give you many solutions for t (two of which you are interested in), plug that back into [1] to get your max and min x.</p>\n\n<p>Repeat for [2]:</p>\n\n<pre><code>0 = dy/dt = b*cos(t)*cos(phi) - a*sin(t)*sin(phi)\n</code></pre>\n\n<p>=></p>\n\n<pre><code>tan(t) = b*cot(phi)/a [4]\n</code></pre>\n\n<p><strong>Lets try an example:</strong></p>\n\n<p>Consider an ellipse at (0,0) with a=2, b=1, rotated by PI/4:</p>\n\n<p>[1] =></p>\n\n<pre><code>x = 2*cos(t)*cos(PI/4) - sin(t)*sin(PI/4)\n</code></pre>\n\n<p>[3] =></p>\n\n<pre><code>tan(t) = -tan(PI/4)/2 = -1/2\n</code></pre>\n\n<p>=></p>\n\n<pre><code>t = -0.4636 + n*PI\n</code></pre>\n\n<p>We are interested in t = -0.4636 and t = -3.6052</p>\n\n<p>So we get:</p>\n\n<pre><code>x = 2*cos(-0.4636)*cos(PI/4) - sin(-0.4636)*sin(PI/4) = 1.5811\n</code></pre>\n\n<p>and</p>\n\n<pre><code>x = 2*cos(-3.6052)*cos(PI/4) - sin(-3.6052)*sin(PI/4) = -1.5811\n</code></pre>\n" }, { "answer_id": 88349, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": false, "text": "<p>This is relative simple but a bit hard to explain since you haven't given us the way you represent your ellipse. There are so many ways to do it.. </p>\n\n<p>Anyway, the general principle goes like this: You can't calculate the axis aligned boundary box directly. You can however calculate the extrema of the ellipse in x and y as points in 2D space. </p>\n\n<p>For this it's sufficient to take the equation x(t) = ellipse_equation(t) and y(t) = ellipse_equation(t). Get the first order derivate of it and solve it for it's root. Since we're dealing with ellipses that are based on trigonometry that's straight forward. You should end up with an equation that either gets the roots via atan, acos or asin.</p>\n\n<p>Hint: To check your code try it with an unrotated ellipse: You should get roots at 0, Pi/2, Pi and 3*Pi/2.</p>\n\n<p>Do that for each axis (x and y). You will get at most four roots (less if your ellipse is degenerated, e.g. one of the radii is zero). Evalulate the positions at the roots and you get all extreme points of the ellipse. </p>\n\n<p>Now you're almost there. Getting the boundary box of the ellipse is as simple as scanning these four points for xmin, xmax, ymin and ymax.</p>\n\n<p>Btw - if you have problems finding the equation of your ellipse: try to reduce it to the case that you have an axis aligned ellipse with a center, two radii and a rotation angle around the center.</p>\n\n<p>If you do so the equations become:</p>\n\n<pre><code> // the ellipse unrotated:\n temp_x(t) = radius.x * cos(t);\n temp_y(t) = radius.y * sin(t);\n\n // the ellipse with rotation applied:\n x(t) = temp_x(t) * cos(angle) - temp_y(t) * sin(angle) + center.x;\n y(t) = temp_x(t) * sin(angle) + temp_y(t) * cos(angle) + center.y;\n</code></pre>\n" }, { "answer_id": 14163413, "author": "user1789690", "author_id": 1789690, "author_profile": "https://Stackoverflow.com/users/1789690", "pm_score": 4, "selected": false, "text": "<p>I found a simple formula at <a href=\"http://www.iquilezles.org/www/articles/ellipses/ellipses.htm\" rel=\"noreferrer\">http://www.iquilezles.org/www/articles/ellipses/ellipses.htm</a> (and ignored the z axis).</p>\n\n<p>I implemented it roughly like this:</p>\n\n<pre><code>num ux = ellipse.r1 * cos(ellipse.phi);\nnum uy = ellipse.r1 * sin(ellipse.phi);\nnum vx = ellipse.r2 * cos(ellipse.phi+PI/2);\nnum vy = ellipse.r2 * sin(ellipse.phi+PI/2);\n\nnum bbox_halfwidth = sqrt(ux*ux + vx*vx);\nnum bbox_halfheight = sqrt(uy*uy + vy*vy); \n\nPoint bbox_ul_corner = new Point(ellipse.center.x - bbox_halfwidth, \n ellipse.center.y - bbox_halfheight);\n\nPoint bbox_br_corner = new Point(ellipse.center.x + bbox_halfwidth, \n ellipse.center.y + bbox_halfheight);\n</code></pre>\n" }, { "answer_id": 17955576, "author": "Johan Nilsson", "author_id": 2635526, "author_profile": "https://Stackoverflow.com/users/2635526", "pm_score": 0, "selected": false, "text": "<p>This code is based on the code user1789690 contributed above, but implemented in Delphi. I have tested this and as far as I can tell it works perfectly. I spent an entire day searching for an algorithm or some code, tested some that didn't work, and I was very happy to finally find the code above. I hope someone finds this useful. This code will calculate the bounding box of a rotated ellipse. The bounding box is axis aligned and NOT rotated with the ellipse. The radiuses are for the ellipse before it was rotated.</p>\n\n<pre><code>type\n\n TSingleRect = record\n X: Single;\n Y: Single;\n Width: Single;\n Height: Single;\n end;\n\nfunction GetBoundingBoxForRotatedEllipse(EllipseCenterX, EllipseCenterY, EllipseRadiusX, EllipseRadiusY, EllipseAngle: Single): TSingleRect;\nvar\n a: Single;\n b: Single;\n c: Single;\n d: Single;\nbegin\n a := EllipseRadiusX * Cos(EllipseAngle);\n b := EllipseRadiusY * Sin(EllipseAngle);\n c := EllipseRadiusX * Sin(EllipseAngle);\n d := EllipseRadiusY * Cos(EllipseAngle);\n Result.Width := Hypot(a, b) * 2;\n Result.Height := Hypot(c, d) * 2;\n Result.X := EllipseCenterX - Result.Width * 0.5;\n Result.Y := EllipseCenterY - Result.Height * 0.5;\nend;\n</code></pre>\n" }, { "answer_id": 22811283, "author": "Jaan", "author_id": 188986, "author_profile": "https://Stackoverflow.com/users/188986", "pm_score": 1, "selected": false, "text": "<p>Here is the formula for the case if the ellipse is given by its <strong>foci and eccentricity</strong> (for the case where it is given by axis lengths, center and angle, see e. g. the answer by user1789690).</p>\n\n<p>Namely, if the foci are (x0, y0) and (x1, y1) and the eccentricity is e, then</p>\n\n<pre><code>bbox_halfwidth = sqrt(k2*dx2 + (k2-1)*dy2)/2\nbbox_halfheight = sqrt((k2-1)*dx2 + k2*dy2)/2\n</code></pre>\n\n<p>where</p>\n\n<pre><code>dx = x1-x0\ndy = y1-y0\ndx2 = dx*dx\ndy2 = dy*dy\nk2 = 1.0/(e*e)\n</code></pre>\n\n<p>I derived the formulas from the answer by user1789690 and Johan Nilsson.</p>\n" }, { "answer_id": 23816227, "author": "Kenneth Bo Christensen", "author_id": 1240593, "author_profile": "https://Stackoverflow.com/users/1240593", "pm_score": 2, "selected": false, "text": "<p>Brilian Johan Nilsson.\nI have transcribed your code to c# - ellipseAngle are now in degrees:</p>\n\n<pre><code>private static RectangleF EllipseBoundingBox(int ellipseCenterX, int ellipseCenterY, int ellipseRadiusX, int ellipseRadiusY, double ellipseAngle)\n{\n double angle = ellipseAngle * Math.PI / 180;\n double a = ellipseRadiusX * Math.Cos(angle);\n double b = ellipseRadiusY * Math.Sin(angle);\n double c = ellipseRadiusX * Math.Sin(angle);\n double d = ellipseRadiusY * Math.Cos(angle);\n double width = Math.Sqrt(Math.Pow(a, 2) + Math.Pow(b, 2)) * 2;\n double height = Math.Sqrt(Math.Pow(c, 2) + Math.Pow(d, 2)) * 2;\n var x= ellipseCenterX - width * 0.5;\n var y= ellipseCenterY + height * 0.5;\n return new Rectangle((int)x, (int)y, (int)width, (int)height);\n}\n</code></pre>\n" }, { "answer_id": 35520262, "author": "Pranay Soni", "author_id": 5861144, "author_profile": "https://Stackoverflow.com/users/5861144", "pm_score": 0, "selected": false, "text": "<p>This is my function for finding tight fit rectangle to ellipse with arbitrary orientation</p>\n\n<p>I have opencv rect and point for implementation:</p>\n\n<p>cg - center of the ellipse</p>\n\n<p>size - major, minor axis of ellipse</p>\n\n<p>angle - orientation of ellipse</p>\n\n<pre><code>cv::Rect ellipse_bounding_box(const cv::Point2f &amp;cg, const cv::Size2f &amp;size, const float angle) {\n\n float a = size.width / 2;\n float b = size.height / 2;\n cv::Point pts[4];\n\n float phi = angle * (CV_PI / 180);\n float tan_angle = tan(phi);\n float t = atan((-b*tan_angle) / a);\n float x = cg.x + a*cos(t)*cos(phi) - b*sin(t)*sin(phi);\n float y = cg.y + b*sin(t)*cos(phi) + a*cos(t)*sin(phi);\n pts[0] = cv::Point(cvRound(x), cvRound(y));\n\n t = atan((b*(1 / tan(phi))) / a);\n x = cg.x + a*cos(t)*cos(phi) - b*sin(t)*sin(phi);\n y = cg.y + b*sin(t)*cos(phi) + a*cos(t)*sin(phi);\n pts[1] = cv::Point(cvRound(x), cvRound(y));\n\n phi += CV_PI;\n tan_angle = tan(phi);\n t = atan((-b*tan_angle) / a);\n x = cg.x + a*cos(t)*cos(phi) - b*sin(t)*sin(phi);\n y = cg.y + b*sin(t)*cos(phi) + a*cos(t)*sin(phi);\n pts[2] = cv::Point(cvRound(x), cvRound(y));\n\n t = atan((b*(1 / tan(phi))) / a);\n x = cg.x + a*cos(t)*cos(phi) - b*sin(t)*sin(phi);\n y = cg.y + b*sin(t)*cos(phi) + a*cos(t)*sin(phi);\n pts[3] = cv::Point(cvRound(x), cvRound(y));\n\n long left = 0xfffffff, top = 0xfffffff, right = 0, bottom = 0;\n for (int i = 0; i &lt; 4; i++) {\n left = left &lt; pts[i].x ? left : pts[i].x;\n top = top &lt; pts[i].y ? top : pts[i].y;\n right = right &gt; pts[i].x ? right : pts[i].x;\n bottom = bottom &gt; pts[i].y ? bottom : pts[i].y;\n }\n cv::Rect fit_rect(left, top, (right - left) + 1, (bottom - top) + 1);\n return fit_rect;\n}\n</code></pre>\n" }, { "answer_id": 44887438, "author": "Maksym Ganenko", "author_id": 737904, "author_profile": "https://Stackoverflow.com/users/737904", "pm_score": 1, "selected": false, "text": "<p>If you work with OpenCV/C++ and use <code>cv::fitEllipse(..)</code> function, you may need bounding rect of ellipse. Here I made a solution using Mike's answer:</p>\n\n<pre><code>// tau = 2 * pi, see tau manifest\nconst double TAU = 2 * std::acos(-1);\n\ncv::Rect calcEllipseBoundingBox(const cv::RotatedRect &amp;anEllipse)\n{\n if (std::fmod(std::abs(anEllipse.angle), 90.0) &lt;= 0.01) {\n return anEllipse.boundingRect();\n }\n\n double phi = anEllipse.angle * TAU / 360;\n double major = anEllipse.size.width / 2.0;\n double minor = anEllipse.size.height / 2.0;\n\n if (minor &gt; major) {\n std::swap(minor, major);\n phi += TAU / 4;\n }\n\n double cosPhi = std::cos(phi), sinPhi = std::sin(phi);\n double tanPhi = sinPhi / cosPhi;\n\n double tx = std::atan(-minor * tanPhi / major);\n cv::Vec2d eqx{ major * cosPhi, - minor * sinPhi };\n double x1 = eqx.dot({ std::cos(tx), std::sin(tx) });\n double x2 = eqx.dot({ std::cos(tx + TAU / 2), std::sin(tx + TAU / 2) });\n\n double ty = std::atan(minor / (major * tanPhi));\n cv::Vec2d eqy{ major * sinPhi, minor * cosPhi };\n double y1 = eqy.dot({ std::cos(ty), std::sin(ty) });\n double y2 = eqy.dot({ std::cos(ty + TAU / 2), std::sin(ty + TAU / 2) });\n\n cv::Rect_&lt;float&gt; bb{\n cv::Point2f(std::min(x1, x2), std::min(y1, y2)),\n cv::Point2f(std::max(x1, x2), std::max(y1, y2))\n };\n\n return bb + anEllipse.center;\n}\n</code></pre>\n" }, { "answer_id": 66986020, "author": "user1671400", "author_id": 1671400, "author_profile": "https://Stackoverflow.com/users/1671400", "pm_score": 0, "selected": false, "text": "<p>Here's a simple example of bounding box around rotated ellipse in javascript:\n<a href=\"https://jsfiddle.net/rkn61mjL/1/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/rkn61mjL/1/</a></p>\n<p>The idea is pretty simple and doesn't require complex calculations and solving gradients:</p>\n<ol>\n<li><p>calculate a simple bounding box of non-rotated ellipse:</p>\n<pre><code>let p1 = [centerX - radiusX, centerY - radiusY];\nlet p2 = [centerX + radiusX, centerY - radiusY];\nlet p3 = [centerX + radiusX, centerY + radiusY];\nlet p4 = [centerX - radiusX, centerY + radiusY];\n</code></pre>\n</li>\n<li><p>rotate all of the four points around the center of the ellipse:</p>\n<pre><code>p1 = [(p1[0]-centerX) * Math.cos(radians) - (p1[1]-centerY) * Math.sin(radians) + centerX,\n (p1[0]-centerX) * Math.sin(radians) + (p1[1]-centerY) * Math.cos(radians) + centerY]; \np2 = [(p2[0]-centerX) * Math.cos(radians) - (p2[1]-centerY) * Math.sin(radians) + centerX,\n (p2[0]-centerX) * Math.sin(radians) + (p2[1]-centerY) * Math.cos(radians) + centerY]; \np3 = [(p3[0]-centerX) * Math.cos(radians) - (p3[1]-centerY) * Math.sin(radians) + centerX,\n (p3[0]-centerX) * Math.sin(radians) + (p3[1]-centerY) * Math.cos(radians) + centerY]; \np4 = [(p4[0]-centerX) * Math.cos(radians) - (p4[1]-centerY) * Math.sin(radians) + centerX,\n (p4[0]-centerX) * Math.sin(radians) + (p4[1]-centerY) * Math.cos(radians) + centerY];\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 67654195, "author": "Stephen Ruiz", "author_id": 9727022, "author_profile": "https://Stackoverflow.com/users/9727022", "pm_score": 1, "selected": false, "text": "<p>Here's a typescript function based on the above answers.</p>\n<pre><code>export function getRotatedEllipseBounds(\n x: number,\n y: number,\n rx: number,\n ry: number,\n rotation: number\n) {\n const c = Math.cos(rotation)\n const s = Math.sin(rotation)\n const w = Math.hypot(rx * c, ry * s)\n const h = Math.hypot(rx * s, ry * c)\n\n return {\n minX: x + rx - w,\n minY: y + ry - h,\n maxX: x + rx + w,\n maxY: y + ry + h,\n width: w * 2,\n height: h * 2,\n }\n}\n</code></pre>\n" }, { "answer_id": 74564462, "author": "serg Ks", "author_id": 14408255, "author_profile": "https://Stackoverflow.com/users/14408255", "pm_score": 0, "selected": false, "text": "<p>Here is another version of Pranay Soni's code, implemented in js <a href=\"https://codepen.io/citizen55/pen/LYmXMJP?editors=1011\" rel=\"nofollow noreferrer\">codepen</a> I hope someone will find it useful</p>\n<pre><code>/**\n* @param {Number} rotation\n* @param {Number} majorAxis\n* @param {Nmber} minorAxis\n* @pivot {Point} pivot {x: number, y: number}\n* @returns {Object}\n*/\nexport function getElipseBoundingLines(ratation, majorAxis, minorAxis, pivot) {\n const {cos, sin, tan, atan, round, min, max, PI} = Math;\n\n let phi = rotation / 180 * PI;\n\n if(phi === 0) phi = 0.00001;\n // major axis\n let a = majorAxis;\n //minor axis\n let b = minorAxis;\n\n const getX = (pivot, phi, t) =&gt; {\n return round(pivot.x + a * cos(t) * cos(phi) - b * sin(t) * sin(phi))\n }\n const getY = (pivot, phi, t) =&gt; {\n return round(pivot.y + b * sin(t) * cos(phi) + a * cos(t) * sin(phi))\n }\n\n const X = [], Y = [];\n\n let t = atan(-b * tan(phi) / a);\n X.push(getX(pivot, phi, t));\n Y.push(getY(pivot, phi, t));\n\n t = atan(b * (1 / tan(phi) / a));\n X.push(getX(pivot, phi, t));\n Y.push(getY(pivot, phi, t));\n\n phi += PI;\n\n t = atan(-b * tan(phi) / a);\n X.push(getX(pivot, phi, t));\n Y.push(getY(pivot, phi, t));\n\n t = atan(b * (1 / tan(phi)) / a);\n X.push(getX(pivot, phi, t));\n Y.push(getY(pivot, phi, t));\n\n const left = min(...X);\n const right = max(...X);\n const top = min(...Y);\n const bottom = max(...Y);\n\n return {left, top, right, bottom};\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2214/" ]
If the major axis of the ellipse is vertical or horizontal, it's easy to calculate the bounding box, but what about when the ellipse is rotated? The only way I can think of so far is to calculate all the points around the perimeter and find the max/min x and y values. It seems like there should be a simpler way. If there's a function (in the mathematical sense) that describes an ellipse at an arbitrary angle, then I could use its derivative to find points where the slope is zero or undefined, but I can't seem to find one. **Edit: to clarify, I need the axis-aligned bounding box, i.e. it should not be rotated with the ellipse, but stay aligned with the x axis so transforming the bounding box won't work.**
You could try using the parametrized equations for an ellipse rotated at an arbitrary angle: ``` x = h + a*cos(t)*cos(phi) - b*sin(t)*sin(phi) [1] y = k + b*sin(t)*cos(phi) + a*cos(t)*sin(phi) [2] ``` ...where ellipse has centre (h,k) semimajor axis a and semiminor axis b, and is rotated through angle phi. You can then differentiate and solve for gradient = 0: ``` 0 = dx/dt = -a*sin(t)*cos(phi) - b*cos(t)*sin(phi) ``` => ``` tan(t) = -b*tan(phi)/a [3] ``` Which should give you many solutions for t (two of which you are interested in), plug that back into [1] to get your max and min x. Repeat for [2]: ``` 0 = dy/dt = b*cos(t)*cos(phi) - a*sin(t)*sin(phi) ``` => ``` tan(t) = b*cot(phi)/a [4] ``` **Lets try an example:** Consider an ellipse at (0,0) with a=2, b=1, rotated by PI/4: [1] => ``` x = 2*cos(t)*cos(PI/4) - sin(t)*sin(PI/4) ``` [3] => ``` tan(t) = -tan(PI/4)/2 = -1/2 ``` => ``` t = -0.4636 + n*PI ``` We are interested in t = -0.4636 and t = -3.6052 So we get: ``` x = 2*cos(-0.4636)*cos(PI/4) - sin(-0.4636)*sin(PI/4) = 1.5811 ``` and ``` x = 2*cos(-3.6052)*cos(PI/4) - sin(-3.6052)*sin(PI/4) = -1.5811 ```
87,747
<p>I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL.</p> <p>Results would be something like:</p> <p>TableName, ColumnName</p>
[ { "answer_id": 87773, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 6, "selected": false, "text": "<p>sys.columns.is_identity = 1</p>\n\n<p>e.g.,</p>\n\n<pre><code>select o.name, c.name\nfrom sys.objects o inner join sys.columns c on o.object_id = c.object_id\nwhere c.is_identity = 1\n</code></pre>\n" }, { "answer_id": 87776, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 3, "selected": false, "text": "<p>In SQL 2005:</p>\n\n<pre><code>select object_name(object_id), name\nfrom sys.columns\nwhere is_identity = 1\n</code></pre>\n" }, { "answer_id": 87800, "author": "Brian", "author_id": 2831, "author_profile": "https://Stackoverflow.com/users/2831", "pm_score": 1, "selected": false, "text": "<p>I think this works for SQL 2000:</p>\n\n<pre><code>SELECT \n CASE WHEN C.autoval IS NOT NULL THEN\n 'Identity'\n ELSE\n 'Not Identity'\n AND\nFROM\n sysobjects O\nINNER JOIN\n syscolumns C\nON\n O.id = C.id\nWHERE\n O.NAME = @TableName\nAND\n C.NAME = @ColumnName\n</code></pre>\n" }, { "answer_id": 87845, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 2, "selected": false, "text": "<p>This query seems to do the trick:</p>\n\n<pre><code>SELECT \n sys.objects.name AS table_name, \n sys.columns.name AS column_name\nFROM sys.columns JOIN sys.objects \n ON sys.columns.object_id=sys.objects.object_id\nWHERE \n sys.columns.is_identity=1\n AND\n sys.objects.type in (N'U')\n</code></pre>\n" }, { "answer_id": 87983, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Another way (for 2000 / 2005/2012/2014):</p>\n\n<pre><code>IF ((SELECT OBJECTPROPERTY( OBJECT_ID(N'table_name_here'), 'TableHasIdentity')) = 1)\n PRINT 'Yes'\nELSE\n PRINT 'No'\n</code></pre>\n\n<p>NOTE: <code>table_name_here</code> should be <code>schema.table</code>, unless the schema is <code>dbo</code>.</p>\n" }, { "answer_id": 87993, "author": "DaveCrawford", "author_id": 16865, "author_profile": "https://Stackoverflow.com/users/16865", "pm_score": 9, "selected": true, "text": "<p>Another potential way to do this for SQL Server, which has less reliance on the system tables (which are subject to change, version to version) is to use the\nINFORMATION_SCHEMA views:</p>\n\n<pre><code>select COLUMN_NAME, TABLE_NAME\nfrom INFORMATION_SCHEMA.COLUMNS\nwhere COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1\norder by TABLE_NAME \n</code></pre>\n" }, { "answer_id": 5027088, "author": "S.E.", "author_id": 621078, "author_profile": "https://Stackoverflow.com/users/621078", "pm_score": 2, "selected": false, "text": "<p>here's a working version for MSSQL 2000. I've modified the 2005 code found here: <a href=\"http://sqlfool.com/2011/01/identity-columns-are-you-nearing-the-limits/\" rel=\"nofollow\">http://sqlfool.com/2011/01/identity-columns-are-you-nearing-the-limits/</a></p>\n\n<pre><code>/* Define how close we are to the value limit\n before we start throwing up the red flag.\n The higher the value, the closer to the limit. */\nDECLARE @threshold DECIMAL(3,2);\nSET @threshold = .85;\n\n/* Create a temp table */\nCREATE TABLE #identityStatus\n(\n database_name VARCHAR(128)\n , table_name VARCHAR(128)\n , column_name VARCHAR(128)\n , data_type VARCHAR(128)\n , last_value BIGINT\n , max_value BIGINT\n);\n\nDECLARE @dbname sysname;\nDECLARE @sql nvarchar(4000);\n\n-- Use an cursor to iterate through the databases since in 2000 there's no sp_MSForEachDB command...\n\nDECLARE c cursor FAST_FORWARD FOR\nSELECT\n name\nFROM\n master.dbo.sysdatabases \nWHERE \n name NOT IN('master', 'model', 'msdb', 'tempdb');\n\nOPEN c;\n\nFETCH NEXT FROM c INTO @dbname;\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n SET @sql = N'Use [' + @dbname + '];\n Insert Into #identityStatus\n Select ''' + @dbname + ''' As [database_name]\n , Object_Name(id.id) As [table_name]\n , id.name As [column_name]\n , t.name As [data_type]\n , IDENT_CURRENT(Object_Name(id.id)) As [last_value]\n , Case \n When t.name = ''tinyint'' Then 255 \n When t.name = ''smallint'' Then 32767 \n When t.name = ''int'' Then 2147483647 \n When t.name = ''bigint'' Then 9223372036854775807\n End As [max_value]\n From \n syscolumns As id\n Join systypes As t On id.xtype = t.xtype\n Where \n id.colstat&amp;1 = 1 -- this identifies the identity columns (as far as I know)\n ';\n\n EXECUTE sp_executesql @sql;\n\n FETCH NEXT FROM c INTO @dbname;\nEND\n\nCLOSE c;\nDEALLOCATE c;\n\n/* Retrieve our results and format it all prettily */\nSELECT database_name\n , table_name\n , column_name\n , data_type\n , last_value\n , CASE \n WHEN last_value &lt; 0 THEN 100\n ELSE (1 - CAST(last_value AS FLOAT(4)) / max_value) * 100 \n END AS [percentLeft]\n , CASE \n WHEN CAST(last_value AS FLOAT(4)) / max_value &gt;= @threshold\n THEN 'warning: approaching max limit'\n ELSE 'okay'\n END AS [id_status]\nFROM #identityStatus\nORDER BY percentLeft;\n\n/* Clean up after ourselves */\nDROP TABLE #identityStatus;\n</code></pre>\n" }, { "answer_id": 18533518, "author": "James Drinkard", "author_id": 543572, "author_profile": "https://Stackoverflow.com/users/543572", "pm_score": 1, "selected": false, "text": "<p>This worked for me using Sql Server 2008:</p>\n\n<pre><code>USE &lt;database_name&gt;;\nGO\nSELECT SCHEMA_NAME(schema_id) AS schema_name\n , t.name AS table_name\n , c.name AS column_name\nFROM sys.tables AS t\nJOIN sys.identity_columns c ON t.object_id = c.object_id\nORDER BY schema_name, table_name;\nGO\n</code></pre>\n" }, { "answer_id": 18658799, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 1, "selected": false, "text": "<p>Use this :</p>\n\n<pre><code>DECLARE @Table_Name VARCHAR(100) \nDECLARE @Column_Name VARCHAR(100)\nSET @Table_Name = ''\nSET @Column_Name = ''\n\nSELECT RowNumber = ROW_NUMBER() OVER ( PARTITION BY T.[Name] ORDER BY T.[Name], C.column_id ) ,\n SCHEMA_NAME(T.schema_id) AS SchemaName ,\n T.[Name] AS Table_Name ,\n C.[Name] AS Field_Name ,\n sysType.name ,\n C.max_length ,\n C.is_nullable ,\n C.is_identity ,\n C.scale ,\n C.precision\nFROM Sys.Tables AS T\n LEFT JOIN Sys.Columns AS C ON ( T.[Object_Id] = C.[Object_Id] )\n LEFT JOIN sys.types AS sysType ON ( C.user_type_id = sysType.user_type_id )\nWHERE ( Type = 'U' )\n AND ( C.Name LIKE '%' + @Column_Name + '%' )\n AND ( T.Name LIKE '%' + @Table_Name + '%' )\nORDER BY T.[Name] ,\n C.column_id\n</code></pre>\n" }, { "answer_id": 27847032, "author": "Sergey", "author_id": 320427, "author_profile": "https://Stackoverflow.com/users/320427", "pm_score": 2, "selected": false, "text": "<p>List of tables without Identity column based on <a href=\"https://stackoverflow.com/a/87983/320427\">Guillermo</a> answer:</p>\n\n<pre><code>SELECT DISTINCT TABLE_NAME\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE (TABLE_SCHEMA = 'dbo') AND (OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') = 0)\nORDER BY TABLE_NAME\n</code></pre>\n" }, { "answer_id": 40116024, "author": "Nikolai Bielik", "author_id": 4313505, "author_profile": "https://Stackoverflow.com/users/4313505", "pm_score": 1, "selected": false, "text": "<p>This worked for SQL Server 2005, 2008, and 2012. \nI found that the sys.identity_columns did not contain all my tables with identity columns.</p>\n\n<pre><code>SELECT a.name AS TableName, b.name AS IdentityColumn\nFROM sys.sysobjects a \nJOIN sys.syscolumns b \nON a.id = b.id\nWHERE is_identity = 1\nORDER BY name;\n</code></pre>\n\n<p>Looking at the documentation page the status column can also be utilized. Also you can add the four part identifier and it will work across different servers.</p>\n\n<pre><code>SELECT a.name AS TableName, b.name AS IdentityColumn\nFROM [YOUR_SERVER_NAME].[YOUR_DB_NAME].sys.sysobjects a \nJOIN [YOUR_SERVER_NAME].[YOUR_DB_NAME].sys.syscolumns b \nON a.id = b.id\nWHERE is_identity = 1\nORDER BY name;\n</code></pre>\n\n<p>Source:\n<a href=\"https://msdn.microsoft.com/en-us/library/ms186816.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/ms186816.aspx</a></p>\n" }, { "answer_id": 51310408, "author": "Jorge Santos Neill", "author_id": 7994269, "author_profile": "https://Stackoverflow.com/users/7994269", "pm_score": 2, "selected": false, "text": "<p>The following query work for me:</p>\n\n<pre><code>select TABLE_NAME tabla,COLUMN_NAME columna\nfrom INFORMATION_SCHEMA.COLUMNS\nwhere COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1\norder by TABLE_NAME\n</code></pre>\n" }, { "answer_id": 51311552, "author": "Jorge Santos Neill", "author_id": 7994269, "author_profile": "https://Stackoverflow.com/users/7994269", "pm_score": 1, "selected": false, "text": "<p>By some reason sql server save some identity columns in different tables, the code that work for me, is the following:</p>\n\n<pre><code>select TABLE_NAME tabla,COLUMN_NAME columna\nfrom INFORMATION_SCHEMA.COLUMNS\nwhere COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1\nunion all\nselect o.name tabla, c.name columna\nfrom sys.objects o \ninner join sys.columns c on o.object_id = c.object_id\nwhere c.is_identity = 1\n</code></pre>\n" }, { "answer_id": 72053797, "author": "Rax", "author_id": 6012337, "author_profile": "https://Stackoverflow.com/users/6012337", "pm_score": 0, "selected": false, "text": "<p>Get all columns with Identity. Modern version for MSSQL 2017+. Locks down to specific database:</p>\n<pre><code>SELECT\n [COLUMN_NAME]\n , [TABLE_NAME]\n , [TABLE_CATALOG]\nFROM\n [INFORMATION_SCHEMA].[COLUMNS]\nWHERE\n COLUMNPROPERTY(OBJECT_ID(CONCAT_WS('.' ,[TABLE_CATALOG] ,[TABLE_SCHEMA] ,[TABLE_NAME])) ,[COLUMN_NAME] ,'IsIdentity') = 1\nORDER BY\n [TABLE_NAME]\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL. Results would be something like: TableName, ColumnName
Another potential way to do this for SQL Server, which has less reliance on the system tables (which are subject to change, version to version) is to use the INFORMATION\_SCHEMA views: ``` select COLUMN_NAME, TABLE_NAME from INFORMATION_SCHEMA.COLUMNS where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 order by TABLE_NAME ```
87,753
<p>How can I resize an image, with the image quality unaffected?</p>
[ { "answer_id": 87763, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 5, "selected": false, "text": "<p>Unless you're doing vector graphics, there's no way to resize an image without potentially losing some image quality.</p>\n" }, { "answer_id": 87786, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 8, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/questions/87753/resizing-an-image-without-losing-any-quality#87763\">rcar</a> says, you can't without losing some quality, the best you can do in c# is:</p>\n\n<pre><code>Bitmap newImage = new Bitmap(newWidth, newHeight);\nusing (Graphics gr = Graphics.FromImage(newImage))\n{\n gr.SmoothingMode = SmoothingMode.HighQuality;\n gr.InterpolationMode = InterpolationMode.HighQualityBicubic;\n gr.PixelOffsetMode = PixelOffsetMode.HighQuality;\n gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));\n}\n</code></pre>\n" }, { "answer_id": 87817, "author": "AaronS", "author_id": 26932, "author_profile": "https://Stackoverflow.com/users/26932", "pm_score": 2, "selected": false, "text": "<p>You can't resize an image without losing some quality, simply because you are reducing the number of pixels. </p>\n\n<p>Don't reduce the size client side, because browsers don't do a good job of resizing images. </p>\n\n<p>What you can do is programatically change the size before you render it, or as a user uploads it.</p>\n\n<p>Here is an article that explains one way to do this in c#:\n<a href=\"http://www.codeproject.com/KB/GDI-plus/imageresize.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/GDI-plus/imageresize.aspx</a></p>\n" }, { "answer_id": 87836, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<p>Unless you resize up, you cannot do this with raster graphics.</p>\n\n<p>What you can do with good filtering and smoothing is to resize without losing any <strong>noticable</strong> quality.</p>\n\n<p>You can also alter the DPI metadata of the image (assuming it has some) which will keep exactly the same pixel count, but will alter how image editors think of it in 'real-world' measurements.</p>\n\n<p>And just to cover all bases, if you really meant just the file size of the image and not the actual image dimensions, I suggest you look at a lossless encoding of the image data. My suggestion for this would be to resave the image as a .png file (I tend to use paint as a free transcoder for images in windows. Load image in paint, save as in the new format)</p>\n" }, { "answer_id": 87873, "author": "Victor", "author_id": 14514, "author_profile": "https://Stackoverflow.com/users/14514", "pm_score": 1, "selected": false, "text": "<p>There is something out there, context aware resizing, don't know if you will be able to use it, but it's worth looking at, that's for sure</p>\n\n<p>A nice video demo (Enlarging appears towards the middle)\n<a href=\"http://www.youtube.com/watch?v=vIFCV2spKtg\" rel=\"nofollow noreferrer\">http://www.youtube.com/watch?v=vIFCV2spKtg</a></p>\n\n<p>Here there could be some code.\n<a href=\"http://www.semanticmetadata.net/2007/08/30/content-aware-image-resizing-gpl-implementation/\" rel=\"nofollow noreferrer\">http://www.semanticmetadata.net/2007/08/30/content-aware-image-resizing-gpl-implementation/</a></p>\n\n<p>Was that overkill? Maybe there are some easy filters you can apply to an enlarged image to blur the pixels a bit, you could look into that.</p>\n" }, { "answer_id": 87929, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 1, "selected": false, "text": "<p>Are you resizing larger, or smaller? By a small % or by a larger factor like 2x, 3x? What do you mean by quality for your application? And what type of images - photographs, hard-edged line drawings, or what? Writing your own low-level pixel grinding code or trying to do it as much as possible with existing libraries (.net or whatever)?</p>\n\n<p>There is a large body of knowledge on this topic. The key concept is interpolation. </p>\n\n<p>Browsing recommendations:<br>\n* <a href=\"http://www.all-in-one.ee/~dersch/interpolator/interpolator.html\" rel=\"nofollow noreferrer\">http://www.all-in-one.ee/~dersch/interpolator/interpolator.html</a><br>\n* <a href=\"http://www.cambridgeincolour.com/tutorials/image-interpolation.htm\" rel=\"nofollow noreferrer\">http://www.cambridgeincolour.com/tutorials/image-interpolation.htm</a><br>\n* for C#: <a href=\"https://secure.codeproject.com/KB/GDI-plus/imageprocessing4.aspx?display=PrintAll&amp;fid=3657&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;fr=26&amp;select=629945\" rel=\"nofollow noreferrer\">https://secure.codeproject.com/KB/GDI-plus/imageprocessing4.aspx?display=PrintAll&amp;fid=3657&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;fr=26&amp;select=629945</a>\n* this is java-specific but might be educational - <a href=\"http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html\" rel=\"nofollow noreferrer\">http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html</a> </p>\n" }, { "answer_id": 87976, "author": "jimg", "author_id": 2621, "author_profile": "https://Stackoverflow.com/users/2621", "pm_score": 0, "selected": false, "text": "<p>Here is a <a href=\"http://forums.asp.net/t/1038068.aspx\" rel=\"nofollow noreferrer\">forum thread</a> that provides a C# image resizing code sample. You could use one of the <a href=\"http://www.libgd.org/Binders\" rel=\"nofollow noreferrer\">GD library</a> binders to do resampling in C#.</p>\n" }, { "answer_id": 266698, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>See if you like the <a href=\"http://nathanaeljones.com/products/asp-net-image-resizer/\" rel=\"nofollow noreferrer\">image resizing quality of this open source ASP.NET module.</a> There's a live demo, so you can mess around with it yourself. It yields results that are (to me) impossible to distinguish from Photoshop output. It also has similar file sizes - MS did a good job on their JPEG encoder.</p>\n" }, { "answer_id": 416090, "author": "Ashlocke", "author_id": 10288, "author_profile": "https://Stackoverflow.com/users/10288", "pm_score": 3, "selected": false, "text": "<p>I believe what you're looking to do is \"Resize/Resample\" your images. Here is a good site that gives instructions and provides a utility class(That I also happen to use):</p>\n\n<p><a href=\"http://www.codeproject.com/KB/GDI-plus/imgresizoutperfgdiplus.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/GDI-plus/imgresizoutperfgdiplus.aspx</a></p>\n" }, { "answer_id": 10735132, "author": "ozba", "author_id": 237461, "author_profile": "https://Stackoverflow.com/users/237461", "pm_score": 5, "selected": false, "text": "<pre><code>private static Image resizeImage(Image imgToResize, Size size)\n{\n int sourceWidth = imgToResize.Width;\n int sourceHeight = imgToResize.Height;\n\n float nPercent = 0;\n float nPercentW = 0;\n float nPercentH = 0;\n\n nPercentW = ((float)size.Width / (float)sourceWidth);\n nPercentH = ((float)size.Height / (float)sourceHeight);\n\n if (nPercentH &lt; nPercentW)\n nPercent = nPercentH;\n else\n nPercent = nPercentW;\n\n int destWidth = (int)(sourceWidth * nPercent);\n int destHeight = (int)(sourceHeight * nPercent);\n\n Bitmap b = new Bitmap(destWidth, destHeight);\n Graphics g = Graphics.FromImage((Image)b);\n g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n\n g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);\n g.Dispose();\n\n return (Image)b;\n}\n</code></pre>\n\n<h2>from <a href=\"http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing\" rel=\"noreferrer\">here</a></h2>\n" }, { "answer_id": 14711672, "author": "cagin", "author_id": 117899, "author_profile": "https://Stackoverflow.com/users/117899", "pm_score": 2, "selected": false, "text": "<p>Here you can find also add watermark codes in this class : </p>\n\n<pre><code>public class ImageProcessor\n {\n public Bitmap Resize(Bitmap image, int newWidth, int newHeight, string message)\n {\n try\n {\n Bitmap newImage = new Bitmap(newWidth, Calculations(image.Width, image.Height, newWidth));\n\n using (Graphics gr = Graphics.FromImage(newImage))\n {\n gr.SmoothingMode = SmoothingMode.AntiAlias;\n gr.InterpolationMode = InterpolationMode.HighQualityBicubic;\n gr.PixelOffsetMode = PixelOffsetMode.HighQuality;\n gr.DrawImage(image, new Rectangle(0, 0, newImage.Width, newImage.Height));\n\n var myBrush = new SolidBrush(Color.FromArgb(70, 205, 205, 205));\n\n double diagonal = Math.Sqrt(newImage.Width * newImage.Width + newImage.Height * newImage.Height);\n\n Rectangle containerBox = new Rectangle();\n\n containerBox.X = (int)(diagonal / 10);\n float messageLength = (float)(diagonal / message.Length * 1);\n containerBox.Y = -(int)(messageLength / 1.6);\n\n Font stringFont = new Font(\"verdana\", messageLength);\n\n StringFormat sf = new StringFormat();\n\n float slope = (float)(Math.Atan2(newImage.Height, newImage.Width) * 180 / Math.PI);\n\n gr.RotateTransform(slope);\n gr.DrawString(message, stringFont, myBrush, containerBox, sf);\n return newImage;\n }\n }\n catch (Exception exc)\n {\n throw exc;\n }\n }\n\n public int Calculations(decimal w1, decimal h1, int newWidth)\n {\n decimal height = 0;\n decimal ratio = 0;\n\n\n if (newWidth &lt; w1)\n {\n ratio = w1 / newWidth;\n height = h1 / ratio;\n\n return height.To&lt;int&gt;();\n }\n\n if (w1 &lt; newWidth)\n {\n ratio = newWidth / w1;\n height = h1 * ratio;\n return height.To&lt;int&gt;();\n }\n\n return height.To&lt;int&gt;();\n }\n\n }\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
How can I resize an image, with the image quality unaffected?
As [rcar](https://stackoverflow.com/questions/87753/resizing-an-image-without-losing-any-quality#87763) says, you can't without losing some quality, the best you can do in c# is: ``` Bitmap newImage = new Bitmap(newWidth, newHeight); using (Graphics gr = Graphics.FromImage(newImage)) { gr.SmoothingMode = SmoothingMode.HighQuality; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight)); } ```
87,758
<p>I have several old 3.5in floppy disks that I would like to backup. My attempts to create an image of the disks have failed. I tried using the UNIX utility dd_rescue, but when the kernel tries to open (<code>/dev/fd0</code>) I get a kernel error,</p> <pre><code>floppy0: probe failed... </code></pre> <p>I would like an image because some of the floppies are using the LIF file system format. Does anyone have any ideas as to what I should do?</p> <p>HP now Agilent made some tools that could read and write to files on LIF formatted disk. I could use these tools to copy and convert the files to the local disk but not without possibly losing some data in the process. In other words, converting from LIF to some other format back to LIF will lose some information.</p> <p>I just want to backup the raw bytes on the disk and not be concerned with the type of file system.</p>
[ { "answer_id": 88447, "author": "user10392", "author_id": 10392, "author_profile": "https://Stackoverflow.com/users/10392", "pm_score": 3, "selected": true, "text": "<p>I think you'll find the best resource <a href=\"http://www.hpcc.org/datafile/hpil/lif_utils.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Also, if you're going to use raw dd, LIF format has 77 cylinders vs 80 for a normal floppy.</p>\n" }, { "answer_id": 89689, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 0, "selected": false, "text": "<pre><code>dd if=/dev/floppy0 of=animage.bin conv=noerror\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4778/" ]
I have several old 3.5in floppy disks that I would like to backup. My attempts to create an image of the disks have failed. I tried using the UNIX utility dd\_rescue, but when the kernel tries to open (`/dev/fd0`) I get a kernel error, ``` floppy0: probe failed... ``` I would like an image because some of the floppies are using the LIF file system format. Does anyone have any ideas as to what I should do? HP now Agilent made some tools that could read and write to files on LIF formatted disk. I could use these tools to copy and convert the files to the local disk but not without possibly losing some data in the process. In other words, converting from LIF to some other format back to LIF will lose some information. I just want to backup the raw bytes on the disk and not be concerned with the type of file system.
I think you'll find the best resource [here](http://www.hpcc.org/datafile/hpil/lif_utils.html). Also, if you're going to use raw dd, LIF format has 77 cylinders vs 80 for a normal floppy.
87,760
<p>Ive been smashing my head with this for a while. I have 2 completely identical .wmv files encoded with wmv3 codec. I put them both through ffmpeg with the following command:</p> <pre><code>/usr/bin/ffmpeg -i file.wmv -ar 44100 -ab 64k -qscale 9 -s 512x384 -f flv file.flv </code></pre> <p>One file converts just fine, and gives me the following output:</p> <pre><code> FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al. configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip libavutil version: 49.5.0 libavcodec version: 51.48.0 libavformat version: 51.19.0 built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33) Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -&gt; 29.97 (30000/1001) Input #0, asf, from 'ok.wmv': Duration: 00:14:22.3, start: 3.000000, bitrate: 467 kb/s Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s Stream #0.1: Video: wmv3, yuv420p, 320x240 [PAR 0:1 DAR 0:1], 400 kb/s, 29.97 tb(r) Output #0, flv, to 'ok.flv': Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 29.97 tb(c) Stream #0.1: Audio: libmp3lame, 44100 Hz, stereo, 64 kb/s Stream mapping: Stream #0.1 -&gt; #0.0 Stream #0.0 -&gt; #0.1 Press [q] to stop encoding frame=25846 fps=132 q=9.0 Lsize= 88486kB time=862.4 bitrate= 840.5kbits/s video:80827kB audio:6738kB global headers:0kB muxing overhead 1.050642% </code></pre> <p>While another file, fails:</p> <pre><code>FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al. configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip libavutil version: 49.5.0 libavcodec version: 51.48.0 libavformat version: 51.19.0 built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33) [wmv3 @ 0x3700940d20]Extra data: 8 bits left, value: 0 Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -&gt; 25.00 (25/1) Input #0, asf, from 'bad3.wmv': Duration: 00:06:34.9, start: 4.000000, bitrate: 1666 kb/s Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 256 kb/s Stream #0.1: Video: wmv3, yuv420p, 512x384 [PAR 0:1 DAR 0:1], 1395 kb/s, 25.00 tb(r) File 'ok.flv' already exists. Overwrite ? [y/N] y Output #0, flv, to 'ok.flv': Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 25.00 tb(c) Stream #0.1: Audio: libmp3lame, 48000 Hz, stereo, 64 kb/s Stream mapping: Stream #0.1 -&gt; #0.0 Stream #0.0 -&gt; #0.1 Unsupported codec (id=0) for input stream #0.0 </code></pre> <p>The only difference I see is with the Input audio codec</p> <p>Working:</p> <pre><code>Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s </code></pre> <p>Not working:</p> <pre><code> Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 64 kb/s </code></pre> <p>Any ideas?</p>
[ { "answer_id": 87837, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 2, "selected": false, "text": "<p>Well the obvious answer is that the audio is encoded differently in the second wmv file, so they are not completely identical. You could try forcing it to use a specific audio codec for the 'bad' wmv, and see if that works. Perhaps it's just having trouble picking the right codec? However it seems more likely that the 'bad' wmv has some sort of audio codec that's not supported by ffmpeg. </p>\n\n<p>Also try the usual stuff, make sure you've upgraded to the latest version, check out any development versions that may contain bugfixes etc.</p>\n" }, { "answer_id": 87946, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": -1, "selected": false, "text": "<p>Or, alternatively, use mencoder</p>\n" }, { "answer_id": 239656, "author": "razong", "author_id": 29885, "author_profile": "https://Stackoverflow.com/users/29885", "pm_score": 4, "selected": true, "text": "<p>It is in fact the audio format, which causes trouble. Audio formats are identified by its TwoCC (0x0162 here). You can look up the different TwoCCs here: <a href=\"http://wiki.multimedia.cx/index.php?title=TwoCC\" rel=\"noreferrer\">http://wiki.multimedia.cx/index.php?title=TwoCC</a> and you'll find:</p>\n\n<p>0x0162 Windows Media Audio Professional V9 </p>\n\n<p>This codec isn't supported yet by ffmpeg and mencoder as far as I know. You can search at google for \"<code>ffmpeg audio 0x0162</code>\" and check for yourself. </p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Ive been smashing my head with this for a while. I have 2 completely identical .wmv files encoded with wmv3 codec. I put them both through ffmpeg with the following command: ``` /usr/bin/ffmpeg -i file.wmv -ar 44100 -ab 64k -qscale 9 -s 512x384 -f flv file.flv ``` One file converts just fine, and gives me the following output: ``` FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al. configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip libavutil version: 49.5.0 libavcodec version: 51.48.0 libavformat version: 51.19.0 built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33) Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -> 29.97 (30000/1001) Input #0, asf, from 'ok.wmv': Duration: 00:14:22.3, start: 3.000000, bitrate: 467 kb/s Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s Stream #0.1: Video: wmv3, yuv420p, 320x240 [PAR 0:1 DAR 0:1], 400 kb/s, 29.97 tb(r) Output #0, flv, to 'ok.flv': Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 29.97 tb(c) Stream #0.1: Audio: libmp3lame, 44100 Hz, stereo, 64 kb/s Stream mapping: Stream #0.1 -> #0.0 Stream #0.0 -> #0.1 Press [q] to stop encoding frame=25846 fps=132 q=9.0 Lsize= 88486kB time=862.4 bitrate= 840.5kbits/s video:80827kB audio:6738kB global headers:0kB muxing overhead 1.050642% ``` While another file, fails: ``` FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al. configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip libavutil version: 49.5.0 libavcodec version: 51.48.0 libavformat version: 51.19.0 built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33) [wmv3 @ 0x3700940d20]Extra data: 8 bits left, value: 0 Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -> 25.00 (25/1) Input #0, asf, from 'bad3.wmv': Duration: 00:06:34.9, start: 4.000000, bitrate: 1666 kb/s Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 256 kb/s Stream #0.1: Video: wmv3, yuv420p, 512x384 [PAR 0:1 DAR 0:1], 1395 kb/s, 25.00 tb(r) File 'ok.flv' already exists. Overwrite ? [y/N] y Output #0, flv, to 'ok.flv': Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 25.00 tb(c) Stream #0.1: Audio: libmp3lame, 48000 Hz, stereo, 64 kb/s Stream mapping: Stream #0.1 -> #0.0 Stream #0.0 -> #0.1 Unsupported codec (id=0) for input stream #0.0 ``` The only difference I see is with the Input audio codec Working: ``` Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s ``` Not working: ``` Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 64 kb/s ``` Any ideas?
It is in fact the audio format, which causes trouble. Audio formats are identified by its TwoCC (0x0162 here). You can look up the different TwoCCs here: <http://wiki.multimedia.cx/index.php?title=TwoCC> and you'll find: 0x0162 Windows Media Audio Professional V9 This codec isn't supported yet by ffmpeg and mencoder as far as I know. You can search at google for "`ffmpeg audio 0x0162`" and check for yourself.
87,795
<p>All I want is to update an ListViewItem's text whithout seeing any flickering.</p> <p>This is my code for updating (called several times):</p> <pre><code>listView.BeginUpdate(); listViewItem.SubItems[0].Text = state.ToString(); // update the state listViewItem.SubItems[1].Text = progress.ToString(); // update the progress listView.EndUpdate(); </code></pre> <p>I've seen some solutions that involve overriding the component's <code>WndProc():</code></p> <pre><code>protected override void WndProc(ref Message m) { if (m.Msg == (int)WM.WM_ERASEBKGND) { m.Msg = (int)IntPtr.Zero; } base.WndProc(ref m); } </code></pre> <p><strong>They say it solves the problem, but in my case It didn't</strong>. I believe this is because I'm using icons on every item.</p>
[ { "answer_id": 87840, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 0, "selected": false, "text": "<p>If you only want to update the text, simply set the changed SubItem's text directly rather than updating the entire ListViewItem (you've not said how you're doing your updates).</p>\n\n<p>The override you show is equivalent to simply overriding OnPaintBackground, which would be a \"more correct\" managed way to do that task, and it's not going to help for a single item.</p>\n\n<p>If you still have problems, we'll need clarification on what you've actually tried.</p>\n" }, { "answer_id": 87848, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 0, "selected": false, "text": "<p>This is a shot in the dark, but you could try double buffering the control.</p>\n\n<pre><code>SetStyle(\n ControlStyles.AllPaintingInWmPaint |\n ControlStyles.UserPaint |\n ControlStyles.DoubleBuffer, true)\n</code></pre>\n" }, { "answer_id": 103846, "author": "Brian Gillespie", "author_id": 6151, "author_profile": "https://Stackoverflow.com/users/6151", "pm_score": 4, "selected": false, "text": "<p>The ListView in CommonControls 6 (XP or newer) supports double buffering. Fortunately, .NET wraps the newest CommonControls on the system. To enable double buffering, send the appropriate Windows message to the ListView control.</p>\n\n<p>Here are the details:\n<a href=\"http://www.codeproject.com/KB/list/listviewxp.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/list/listviewxp.aspx</a></p>\n" }, { "answer_id": 162770, "author": "Jonas", "author_id": 10833, "author_profile": "https://Stackoverflow.com/users/10833", "pm_score": 7, "selected": true, "text": "<p>To end this question, here is a helper class that should be called when the form is loading for each ListView or any other ListView's derived control in your form. Thanks to \"Brian Gillespie\" for giving the solution.</p>\n\n<pre><code>public enum ListViewExtendedStyles\n{\n /// &lt;summary&gt;\n /// LVS_EX_GRIDLINES\n /// &lt;/summary&gt;\n GridLines = 0x00000001,\n /// &lt;summary&gt;\n /// LVS_EX_SUBITEMIMAGES\n /// &lt;/summary&gt;\n SubItemImages = 0x00000002,\n /// &lt;summary&gt;\n /// LVS_EX_CHECKBOXES\n /// &lt;/summary&gt;\n CheckBoxes = 0x00000004,\n /// &lt;summary&gt;\n /// LVS_EX_TRACKSELECT\n /// &lt;/summary&gt;\n TrackSelect = 0x00000008,\n /// &lt;summary&gt;\n /// LVS_EX_HEADERDRAGDROP\n /// &lt;/summary&gt;\n HeaderDragDrop = 0x00000010,\n /// &lt;summary&gt;\n /// LVS_EX_FULLROWSELECT\n /// &lt;/summary&gt;\n FullRowSelect = 0x00000020,\n /// &lt;summary&gt;\n /// LVS_EX_ONECLICKACTIVATE\n /// &lt;/summary&gt;\n OneClickActivate = 0x00000040,\n /// &lt;summary&gt;\n /// LVS_EX_TWOCLICKACTIVATE\n /// &lt;/summary&gt;\n TwoClickActivate = 0x00000080,\n /// &lt;summary&gt;\n /// LVS_EX_FLATSB\n /// &lt;/summary&gt;\n FlatsB = 0x00000100,\n /// &lt;summary&gt;\n /// LVS_EX_REGIONAL\n /// &lt;/summary&gt;\n Regional = 0x00000200,\n /// &lt;summary&gt;\n /// LVS_EX_INFOTIP\n /// &lt;/summary&gt;\n InfoTip = 0x00000400,\n /// &lt;summary&gt;\n /// LVS_EX_UNDERLINEHOT\n /// &lt;/summary&gt;\n UnderlineHot = 0x00000800,\n /// &lt;summary&gt;\n /// LVS_EX_UNDERLINECOLD\n /// &lt;/summary&gt;\n UnderlineCold = 0x00001000,\n /// &lt;summary&gt;\n /// LVS_EX_MULTIWORKAREAS\n /// &lt;/summary&gt;\n MultilWorkAreas = 0x00002000,\n /// &lt;summary&gt;\n /// LVS_EX_LABELTIP\n /// &lt;/summary&gt;\n LabelTip = 0x00004000,\n /// &lt;summary&gt;\n /// LVS_EX_BORDERSELECT\n /// &lt;/summary&gt;\n BorderSelect = 0x00008000,\n /// &lt;summary&gt;\n /// LVS_EX_DOUBLEBUFFER\n /// &lt;/summary&gt;\n DoubleBuffer = 0x00010000,\n /// &lt;summary&gt;\n /// LVS_EX_HIDELABELS\n /// &lt;/summary&gt;\n HideLabels = 0x00020000,\n /// &lt;summary&gt;\n /// LVS_EX_SINGLEROW\n /// &lt;/summary&gt;\n SingleRow = 0x00040000,\n /// &lt;summary&gt;\n /// LVS_EX_SNAPTOGRID\n /// &lt;/summary&gt;\n SnapToGrid = 0x00080000,\n /// &lt;summary&gt;\n /// LVS_EX_SIMPLESELECT\n /// &lt;/summary&gt;\n SimpleSelect = 0x00100000\n}\n\npublic enum ListViewMessages\n{\n First = 0x1000,\n SetExtendedStyle = (First + 54),\n GetExtendedStyle = (First + 55),\n}\n\n/// &lt;summary&gt;\n/// Contains helper methods to change extended styles on ListView, including enabling double buffering.\n/// Based on Giovanni Montrone's article on &lt;see cref=\"http://www.codeproject.com/KB/list/listviewxp.aspx\"/&gt;\n/// &lt;/summary&gt;\npublic class ListViewHelper\n{\n private ListViewHelper()\n {\n }\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n private static extern int SendMessage(IntPtr handle, int messg, int wparam, int lparam);\n\n public static void SetExtendedStyle(Control control, ListViewExtendedStyles exStyle)\n {\n ListViewExtendedStyles styles;\n styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0);\n styles |= exStyle;\n SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles);\n }\n\n public static void EnableDoubleBuffer(Control control)\n {\n ListViewExtendedStyles styles;\n // read current style\n styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0);\n // enable double buffer and border select\n styles |= ListViewExtendedStyles.DoubleBuffer | ListViewExtendedStyles.BorderSelect;\n // write new style\n SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles);\n }\n public static void DisableDoubleBuffer(Control control)\n {\n ListViewExtendedStyles styles;\n // read current style\n styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0);\n // disable double buffer and border select\n styles -= styles &amp; ListViewExtendedStyles.DoubleBuffer;\n styles -= styles &amp; ListViewExtendedStyles.BorderSelect;\n // write new style\n SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles);\n }\n}\n</code></pre>\n" }, { "answer_id": 3886695, "author": "Rolf Kristensen", "author_id": 193178, "author_profile": "https://Stackoverflow.com/users/193178", "pm_score": 3, "selected": false, "text": "<p>In .NET Winforms 2.0 there exist a protected property called DoubleBuffered.</p>\n\n<p>By inheriting from ListView, then one can set this protected property to true. This will enable double buffering without needing to call SendMessage.</p>\n\n<p>Setting the DoubleBuffered property is the same as setting the following style:</p>\n\n<pre><code>listview.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);\n</code></pre>\n\n<p><a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94096\" rel=\"noreferrer\">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94096</a></p>\n" }, { "answer_id": 10352490, "author": "Bjoern", "author_id": 1361355, "author_profile": "https://Stackoverflow.com/users/1361355", "pm_score": 1, "selected": false, "text": "<p>this will help:</p>\n\n<pre><code>class DoubleBufferedListView : System.Windows.Forms.ListView\n{\n public DoubleBufferedListView()\n :base()\n {\n this.DoubleBuffered = true;\n }\n}\n</code></pre>\n" }, { "answer_id": 12480853, "author": "Mike", "author_id": 598792, "author_profile": "https://Stackoverflow.com/users/598792", "pm_score": 0, "selected": false, "text": "<p>Call the BeginUpdate() method on the ListView before setting any of the list view items and then only call EndUpdate() after all of the items have been added.</p>\n\n<p>That will stop the flicker.</p>\n" }, { "answer_id": 15268338, "author": "Oliver", "author_id": 1838048, "author_profile": "https://Stackoverflow.com/users/1838048", "pm_score": 6, "selected": false, "text": "<p>The accepted answer works, but is quite lengthy, and deriving from the control (like mentioned in the other answers) just to enable double buffering is also a bit overdone. But fortunately we have reflection and can also call internal methods if we like to (but be sure what you do!).</p>\n\n<p>Be encapsulating this approach into an extension method, we'll get a quite short class:</p>\n\n<pre><code>public static class ControlExtensions\n{\n public static void DoubleBuffering(this Control control, bool enable)\n {\n var method = typeof(Control).GetMethod(\"SetStyle\", BindingFlags.Instance | BindingFlags.NonPublic);\n method.Invoke(control, new object[] { ControlStyles.OptimizedDoubleBuffer, enable });\n }\n}\n</code></pre>\n\n<p>Which can easily be called within our code:</p>\n\n<pre><code>InitializeComponent();\n\nmyListView.DoubleBuffering(true); //after the InitializeComponent();\n</code></pre>\n\n<p>And all flickering is gone.</p>\n\n<h3>Update</h3>\n\n<p>I stumbled on <a href=\"https://stackoverflow.com/questions/1967228/controlstyles-doublebuffer-vs-controlstyles-optimizeddoublebuffer\">this question</a> and due to this fact, the extension method should (maybe) better be:</p>\n\n<pre><code>public static void DoubleBuffered(this Control control, bool enable)\n{\n var doubleBufferPropertyInfo = control.GetType().GetProperty(\"DoubleBuffered\", BindingFlags.Instance | BindingFlags.NonPublic);\n doubleBufferPropertyInfo.SetValue(control, enable, null);\n}\n</code></pre>\n" }, { "answer_id": 25401701, "author": "jaiveeru", "author_id": 3258037, "author_profile": "https://Stackoverflow.com/users/3258037", "pm_score": 0, "selected": false, "text": "<h2><b>Simple solution is this:</b></h2>\n\n<p>yourlistview.BeginUpdate()</p>\n\n<p>//Do your update of adding and removing item from the list</p>\n\n<p>yourlistview.EndUpdate()</p>\n" }, { "answer_id": 29438857, "author": "T4cC0re", "author_id": 3433727, "author_profile": "https://Stackoverflow.com/users/3433727", "pm_score": 2, "selected": false, "text": "<p>I know this question is quite old, but because this is one of the first search results on Google I wanted to share my fix.</p>\n\n<p>The only way i could remove flickering 100% was to combine the answer from Oliver (extension class with double-buffering) and using the <code>BeignUpdate()</code> and <code>EndUpdate()</code> methods.</p>\n\n<p>Neither of those on their own could fix flickering for me.\nGranted, I use a very complex list, that I need to push into the list and also need to update it almost every sec.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10833/" ]
All I want is to update an ListViewItem's text whithout seeing any flickering. This is my code for updating (called several times): ``` listView.BeginUpdate(); listViewItem.SubItems[0].Text = state.ToString(); // update the state listViewItem.SubItems[1].Text = progress.ToString(); // update the progress listView.EndUpdate(); ``` I've seen some solutions that involve overriding the component's `WndProc():` ``` protected override void WndProc(ref Message m) { if (m.Msg == (int)WM.WM_ERASEBKGND) { m.Msg = (int)IntPtr.Zero; } base.WndProc(ref m); } ``` **They say it solves the problem, but in my case It didn't**. I believe this is because I'm using icons on every item.
To end this question, here is a helper class that should be called when the form is loading for each ListView or any other ListView's derived control in your form. Thanks to "Brian Gillespie" for giving the solution. ``` public enum ListViewExtendedStyles { /// <summary> /// LVS_EX_GRIDLINES /// </summary> GridLines = 0x00000001, /// <summary> /// LVS_EX_SUBITEMIMAGES /// </summary> SubItemImages = 0x00000002, /// <summary> /// LVS_EX_CHECKBOXES /// </summary> CheckBoxes = 0x00000004, /// <summary> /// LVS_EX_TRACKSELECT /// </summary> TrackSelect = 0x00000008, /// <summary> /// LVS_EX_HEADERDRAGDROP /// </summary> HeaderDragDrop = 0x00000010, /// <summary> /// LVS_EX_FULLROWSELECT /// </summary> FullRowSelect = 0x00000020, /// <summary> /// LVS_EX_ONECLICKACTIVATE /// </summary> OneClickActivate = 0x00000040, /// <summary> /// LVS_EX_TWOCLICKACTIVATE /// </summary> TwoClickActivate = 0x00000080, /// <summary> /// LVS_EX_FLATSB /// </summary> FlatsB = 0x00000100, /// <summary> /// LVS_EX_REGIONAL /// </summary> Regional = 0x00000200, /// <summary> /// LVS_EX_INFOTIP /// </summary> InfoTip = 0x00000400, /// <summary> /// LVS_EX_UNDERLINEHOT /// </summary> UnderlineHot = 0x00000800, /// <summary> /// LVS_EX_UNDERLINECOLD /// </summary> UnderlineCold = 0x00001000, /// <summary> /// LVS_EX_MULTIWORKAREAS /// </summary> MultilWorkAreas = 0x00002000, /// <summary> /// LVS_EX_LABELTIP /// </summary> LabelTip = 0x00004000, /// <summary> /// LVS_EX_BORDERSELECT /// </summary> BorderSelect = 0x00008000, /// <summary> /// LVS_EX_DOUBLEBUFFER /// </summary> DoubleBuffer = 0x00010000, /// <summary> /// LVS_EX_HIDELABELS /// </summary> HideLabels = 0x00020000, /// <summary> /// LVS_EX_SINGLEROW /// </summary> SingleRow = 0x00040000, /// <summary> /// LVS_EX_SNAPTOGRID /// </summary> SnapToGrid = 0x00080000, /// <summary> /// LVS_EX_SIMPLESELECT /// </summary> SimpleSelect = 0x00100000 } public enum ListViewMessages { First = 0x1000, SetExtendedStyle = (First + 54), GetExtendedStyle = (First + 55), } /// <summary> /// Contains helper methods to change extended styles on ListView, including enabling double buffering. /// Based on Giovanni Montrone's article on <see cref="http://www.codeproject.com/KB/list/listviewxp.aspx"/> /// </summary> public class ListViewHelper { private ListViewHelper() { } [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int SendMessage(IntPtr handle, int messg, int wparam, int lparam); public static void SetExtendedStyle(Control control, ListViewExtendedStyles exStyle) { ListViewExtendedStyles styles; styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0); styles |= exStyle; SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles); } public static void EnableDoubleBuffer(Control control) { ListViewExtendedStyles styles; // read current style styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0); // enable double buffer and border select styles |= ListViewExtendedStyles.DoubleBuffer | ListViewExtendedStyles.BorderSelect; // write new style SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles); } public static void DisableDoubleBuffer(Control control) { ListViewExtendedStyles styles; // read current style styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0); // disable double buffer and border select styles -= styles & ListViewExtendedStyles.DoubleBuffer; styles -= styles & ListViewExtendedStyles.BorderSelect; // write new style SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles); } } ```
87,812
<p>Say I have the following class</p> <pre><code>MyComponent : IMyComponent { public MyComponent(int start_at) {...} } </code></pre> <p>I can register an instance of it with castle windsor via xml as follows</p> <pre><code>&lt;component id="sample" service="NS.IMyComponent, WindsorSample" type="NS.MyComponent, WindsorSample"&gt; &lt;parameters&gt; &lt;start_at&gt;1&lt;/start_at &gt; &lt;/parameters&gt; &lt;/component&gt; </code></pre> <p>How would I go about doing the exact same thing but in code? (Notice, the constructor parameter)</p>
[ { "answer_id": 87893, "author": "Gareth", "author_id": 1313, "author_profile": "https://Stackoverflow.com/users/1313", "pm_score": 0, "selected": false, "text": "<p>You need to pass in an IDictionary when you ask the container for the instance.</p>\n\n<p>You'd use this Resolve overload of the IWindsorContainer:</p>\n\n<pre><code>T Resolve&lt;T&gt;(IDictionary arguments)\n</code></pre>\n\n<p>or the non generic one:</p>\n\n<pre><code>object Resolve(Type service, IDictionary arguments)\n</code></pre>\n\n<p>So, for example: (assuming container is an IWindsorContainer)</p>\n\n<pre><code>IDictionary&lt;string, object&gt; values = new Dictionary&lt;string, object&gt;();\nvalues[\"start_at\"] = 1;\ncontainer.Resolve&lt;IMyComponent&gt;(values);\n</code></pre>\n\n<p>Note that the key values in the dictionary are case sensitive.</p>\n" }, { "answer_id": 93337, "author": "Chris Canal", "author_id": 5802, "author_profile": "https://Stackoverflow.com/users/5802", "pm_score": 5, "selected": true, "text": "<p>Edit: Used the answers below code with the Fluent Interface :)</p>\n\n<pre><code>namespace WindsorSample\n{\n using Castle.MicroKernel.Registration;\n using Castle.Windsor;\n using NUnit.Framework;\n using NUnit.Framework.SyntaxHelpers;\n\n public class MyComponent : IMyComponent\n {\n public MyComponent(int start_at)\n {\n this.Value = start_at;\n }\n\n public int Value { get; private set; }\n }\n\n public interface IMyComponent\n {\n int Value { get; }\n }\n\n [TestFixture]\n public class ConcreteImplFixture\n {\n [Test]\n void ResolvingConcreteImplShouldInitialiseValue()\n {\n IWindsorContainer container = new WindsorContainer();\n\n container.Register(\n Component.For&lt;IMyComponent&gt;()\n .ImplementedBy&lt;MyComponent&gt;()\n .Parameters(Parameter.ForKey(\"start_at\").Eq(\"1\")));\n\n Assert.That(container.Resolve&lt;IMyComponent&gt;().Value, Is.EqualTo(1));\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 93446, "author": "Stacy A", "author_id": 17824, "author_profile": "https://Stackoverflow.com/users/17824", "pm_score": -1, "selected": false, "text": "<p>You can use the AddComponentWithProperties method of the IWindsorContainer interface to register a service with extended properties.</p>\n\n<p>Below is a 'working' sample of doing this with an NUnit Unit Test.</p>\n\n<pre><code>namespace WindsorSample\n{\n public class MyComponent : IMyComponent\n {\n public MyComponent(int start_at)\n {\n this.Value = start_at;\n }\n\n public int Value { get; private set; }\n }\n\n public interface IMyComponent\n {\n int Value { get; }\n }\n\n [TestFixture]\n public class ConcreteImplFixture\n {\n [Test]\n void ResolvingConcreteImplShouldInitialiseValue()\n {\n IWindsorContainer container = new WindsorContainer();\n IDictionary parameters = new Hashtable {{\"start_at\", 1}};\n\n container.AddComponentWithProperties(\"concrete\", typeof(IMyComponent), typeof(MyComponent), parameters);\n\n IMyComponent resolvedComp = container.Resolve&lt;IMyComponent&gt;();\n\n Assert.That(resolvedComp.Value, Is.EqualTo(1));\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 270946, "author": "neilb14", "author_id": 31336, "author_profile": "https://Stackoverflow.com/users/31336", "pm_score": 1, "selected": false, "text": "<p>Have you considered using Binsor to configure your container? Rather than verbose and clumsy XML you can configure Windsor using a Boo based DSL. Here's what your config will look like:</p>\n\n<pre><code>component IMyComponent, MyComponent:\n start_at = 1\n</code></pre>\n\n<p>The advantage is that you have a malleable config file but avoid the problems with XML. Also you don't have to recompile to change your config as you would if you configured the container in code. </p>\n\n<p>There's also plenty of helper methods that enable zero friction configuration:</p>\n\n<pre><code> for type in Assembly.Load(\"MyApp\").GetTypes():\n continue unless type.NameSpace == \"MyApp.Services\"\n continue if type.IsInterface or type.IsAbstract or type.GetInterfaces().Length == 0\n component type.GetInterfaces()[0], type\n</code></pre>\n\n<p>You can get started with it <a href=\"http://ayende.com/Blog/category/451.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 26363406, "author": "user2964808", "author_id": 2964808, "author_profile": "https://Stackoverflow.com/users/2964808", "pm_score": 2, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>int start_at = 1; \ncontainer.Register(Component.For().DependsOn(dependency: Dependency.OnValue(start_at)));\n</code></pre>\n" }, { "answer_id": 55732002, "author": "andrew pate", "author_id": 2668869, "author_profile": "https://Stackoverflow.com/users/2668869", "pm_score": 0, "selected": false, "text": "<p>You could use a configuration class to read the app.config. Then register that and get windsor to use it for its dependency. Ideally my MyConfiguration would use an interface.</p>\n\n<pre><code>public class MyConfiguration\n{\n public long CacheSize { get; }\n\n public MyConfiguration()\n {\n CacheSize = ConfigurationManager.AppSettings[\"cachesize\"].ToLong();\n }\n}\n\n\n\ncontainer.Register(Component.For&lt;MyConfiguration&gt;().ImplementedBy&lt;MyConfiguration&gt;());\n\ncontainer.Register(Component.For&lt;MostRecentlyUsedSet&lt;long&gt;&gt;()\n.ImplementedBy&lt;MostRecentlyUsedSet&lt;long&gt;&gt;().\nDependsOn(Dependency.OnValue(\"size\", container.Resolve&lt;MyConfiguration&gt;().CacheSize))\n.LifestyleSingleton());\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
Say I have the following class ``` MyComponent : IMyComponent { public MyComponent(int start_at) {...} } ``` I can register an instance of it with castle windsor via xml as follows ``` <component id="sample" service="NS.IMyComponent, WindsorSample" type="NS.MyComponent, WindsorSample"> <parameters> <start_at>1</start_at > </parameters> </component> ``` How would I go about doing the exact same thing but in code? (Notice, the constructor parameter)
Edit: Used the answers below code with the Fluent Interface :) ``` namespace WindsorSample { using Castle.MicroKernel.Registration; using Castle.Windsor; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; public class MyComponent : IMyComponent { public MyComponent(int start_at) { this.Value = start_at; } public int Value { get; private set; } } public interface IMyComponent { int Value { get; } } [TestFixture] public class ConcreteImplFixture { [Test] void ResolvingConcreteImplShouldInitialiseValue() { IWindsorContainer container = new WindsorContainer(); container.Register( Component.For<IMyComponent>() .ImplementedBy<MyComponent>() .Parameters(Parameter.ForKey("start_at").Eq("1"))); Assert.That(container.Resolve<IMyComponent>().Value, Is.EqualTo(1)); } } } ```
87,818
<p>Hi I am trying to find a way to read the cookie that i generated in .net web application to read that on the php page because i want the users to login once but they should be able to view .net and php pages ,until the cookie expires user should not need to login in again , but both .net and php web applications are on different servers , help me with this issue please , thanks</p>
[ { "answer_id": 87834, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>any cookie given to a browser will be readable by server processing the request --- they're language agnostic.</p>\n\n<p>try $_COOKIE in PHP </p>\n" }, { "answer_id": 87850, "author": "Rob Booth", "author_id": 16445, "author_profile": "https://Stackoverflow.com/users/16445", "pm_score": 0, "selected": false, "text": "<p>As long as the site is the same (i.e. www.example.com) then cookies are platform agnostic. As Todd Kennedy said try the super global $_COOKIE. If you site is different though you won't be able to read the cookies, they are supposed to be site specific and prevent this type of cross site access.</p>\n" }, { "answer_id": 87851, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 1, "selected": false, "text": "<p>Are the two servers on the machine within the same domain? if so you should set the cookie scope to the domain rather than the FQDN; then both machines will be able to read them;</p>\n\n<pre><code>Response.Cookies[\"domain\"].Domain = \"contoso.com\";\n</code></pre>\n\n<p>would allow contoso.com, www.contoso.com, hotnakedhamsters.contoso.com etc to access it.</p>\n" }, { "answer_id": 88174, "author": "Mike King", "author_id": 4408, "author_profile": "https://Stackoverflow.com/users/4408", "pm_score": 2, "selected": false, "text": "<p>You mention that :</p>\n\n<blockquote>\n <p>but both .net and php web applications are on different servers</p>\n</blockquote>\n\n<p>Are both applications running under the same domain name? (ie: www.mydomain.com) or are they on different domains?</p>\n\n<p>If they're on the same domain, then you can do what you're trying to do in PHP by using the $_COOKIE variable. Just get the cookie's value by </p>\n\n<pre><code>$myCookie = $_COOKIE[\"cookie_name\"];\n</code></pre>\n\n<p>Then you can do whatever you want with the value of $myCookie. </p>\n\n<p>But if they're on different domains (ie: foo.mydomain.com and bar.mydomain.com), you cannot access the cookie from both sites. The web browser will only send a cookie to pages on the domain that set the cookie. However, if you originally set the cookie with only the top-level domain (mydomain.com), then sub-domains (anything.mydomain.com) should be able to read the cookie.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Hi I am trying to find a way to read the cookie that i generated in .net web application to read that on the php page because i want the users to login once but they should be able to view .net and php pages ,until the cookie expires user should not need to login in again , but both .net and php web applications are on different servers , help me with this issue please , thanks
You mention that : > > but both .net and php web applications are on different servers > > > Are both applications running under the same domain name? (ie: www.mydomain.com) or are they on different domains? If they're on the same domain, then you can do what you're trying to do in PHP by using the $\_COOKIE variable. Just get the cookie's value by ``` $myCookie = $_COOKIE["cookie_name"]; ``` Then you can do whatever you want with the value of $myCookie. But if they're on different domains (ie: foo.mydomain.com and bar.mydomain.com), you cannot access the cookie from both sites. The web browser will only send a cookie to pages on the domain that set the cookie. However, if you originally set the cookie with only the top-level domain (mydomain.com), then sub-domains (anything.mydomain.com) should be able to read the cookie.
87,821
<p>Is it possible to use an <strong>IF</strong> clause within a <strong>WHERE</strong> clause in MS SQL?</p> <p>Example:</p> <pre><code>WHERE IF IsNumeric(@OrderNumber) = 1 OrderNumber = @OrderNumber ELSE OrderNumber LIKE '%' + @OrderNumber + '%' </code></pre>
[ { "answer_id": 87833, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>Use a <a href=\"http://msdn.microsoft.com/en-us/library/ms181765.aspx\" rel=\"noreferrer\">CASE</a> statement instead of IF.</p>\n" }, { "answer_id": 87839, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 9, "selected": true, "text": "<p>Use a <a href=\"http://msdn.microsoft.com/en-us/library/ms181765.aspx\" rel=\"noreferrer\">CASE</a> statement<br>\n<strong>UPDATE:</strong> The previous syntax (as pointed out by a few people) doesn't work. You can use CASE as follows:</p>\n\n<pre><code>WHERE OrderNumber LIKE\n CASE WHEN IsNumeric(@OrderNumber) = 1 THEN \n @OrderNumber \n ELSE\n '%' + @OrderNumber\n END\n</code></pre>\n\n<p>Or you can use an IF statement like @<a href=\"https://stackoverflow.com/questions/87821/sql-if-clause-within-where-clause#87992\">N. J. Reed</a> points out.</p>\n" }, { "answer_id": 87854, "author": "Jeff Martin", "author_id": 13100, "author_profile": "https://Stackoverflow.com/users/13100", "pm_score": 2, "selected": false, "text": "<p>You want the CASE statement</p>\n\n<pre><code>WHERE OrderNumber LIKE\nCASE WHEN IsNumeric(@OrderNumber)=1 THEN @OrderNumber ELSE '%' + @OrderNumber END\n</code></pre>\n" }, { "answer_id": 87992, "author": "njr101", "author_id": 9625, "author_profile": "https://Stackoverflow.com/users/9625", "pm_score": 7, "selected": false, "text": "<p>You should be able to do this without any IF or CASE</p>\n\n<pre><code> WHERE \n (IsNumeric(@OrderNumber) AND\n (CAST OrderNumber AS VARCHAR) = (CAST @OrderNumber AS VARCHAR)\n OR\n (NOT IsNumeric(@OrderNumber) AND\n OrderNumber LIKE ('%' + @OrderNumber))\n</code></pre>\n\n<p>Depending on the flavour of SQL you may need to tweak the casts on the order number to an INT or VARCHAR depending on whether implicit casts are supported.</p>\n\n<p>This is a very common technique in a WHERE clause. If you want to apply some \"IF\" logic in the WHERE clause all you need to do is add the extra condition with an boolean AND to the section where it needs to be applied.</p>\n" }, { "answer_id": 88024, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 4, "selected": false, "text": "<p>There isn't a good way to do this in SQL. Some approaches I have seen:</p>\n\n<p>1) Use CASE combined with boolean operators:</p>\n\n<pre><code>WHERE\n OrderNumber = CASE \n WHEN (IsNumeric(@OrderNumber) = 1)\n THEN CONVERT(INT, @OrderNumber)\n ELSE -9999 -- Some numeric value that just cannot exist in the column\n END\n OR \n FirstName LIKE CASE\n WHEN (IsNumeric(@OrderNumber) = 0)\n THEN '%' + @OrderNumber\n ELSE ''\n END\n</code></pre>\n\n<p>2) Use IF's outside the SELECT</p>\n\n<pre><code>IF (IsNumeric(@OrderNumber)) = 1\nBEGIN\n SELECT * FROM Table\n WHERE @OrderNumber = OrderNumber\nEND ELSE BEGIN\n SELECT * FROM Table\n WHERE OrderNumber LIKE '%' + @OrderNumber\nEND\n</code></pre>\n\n<p>3) Using a long string, compose your SQL statement conditionally, and then use EXEC</p>\n\n<p>The 3rd approach is hideous, but it's almost the only think that works if you have a number of variable conditions like that.</p>\n" }, { "answer_id": 4327682, "author": "William", "author_id": 526978, "author_profile": "https://Stackoverflow.com/users/526978", "pm_score": 2, "selected": false, "text": "<p>I think that where...like/=...case...then... can work with Booleans. I am using T-SQL.</p>\n\n<p>Scenario: Let's say you want to get Person-30's hobbies if bool is false, and Person-42's hobbies if bool is true. (According to some, hobby-lookups comprise over 90% of business computation cycles, so pay close attn.).</p>\n\n<pre><code>CREATE PROCEDURE sp_Case\n@bool bit\nAS\nSELECT Person.Hobbies\nFROM Person\nWHERE Person.ID = \n case @bool \n when 0 \n then 30\n when 1\n then 42\n end;\n</code></pre>\n" }, { "answer_id": 4741048, "author": "ns12345", "author_id": 538091, "author_profile": "https://Stackoverflow.com/users/538091", "pm_score": 2, "selected": false, "text": "<pre>\nWHERE (IsNumeric(@OrderNumber) &lt;&gt; 1 OR OrderNumber = @OrderNumber) \n AND (IsNumber(@OrderNumber) = 1 OR OrderNumber LIKE '%' \n + @OrderNumber + '%')\n</pre>\n" }, { "answer_id": 15378167, "author": "user2164001", "author_id": 2164001, "author_profile": "https://Stackoverflow.com/users/2164001", "pm_score": -1, "selected": false, "text": "<pre><code>If @LstTransDt is Null\n begin\n Set @OpenQty=0\n end\n else\n begin\n Select @OpenQty=IsNull(Sum(ClosingQty),0) \n From ProductAndDepotWiseMonitoring \n Where Pcd=@PCd And PtpCd=@PTpCd And TransDt=@LstTransDt \n end \n</code></pre>\n\n<p>See if this helps.</p>\n" }, { "answer_id": 16142812, "author": "hossein", "author_id": 2306637, "author_profile": "https://Stackoverflow.com/users/2306637", "pm_score": -1, "selected": false, "text": "<pre><code>USE AdventureWorks2012;\nGO\nIF \n(SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) &gt; 5\nPRINT 'There are more than 5 Touring-3000 bicycles.'\nELSE PRINT 'There are 5 or less Touring-3000 bicycles.' ;\nGO\n</code></pre>\n" }, { "answer_id": 16142939, "author": "hossein", "author_id": 2306637, "author_profile": "https://Stackoverflow.com/users/2306637", "pm_score": 0, "selected": false, "text": "<p>The following example executes a query as part of the Boolean expression and then executes slightly different statement blocks based on the result of the Boolean expression. Each statement block starts with BEGIN and completes with END.</p>\n\n<pre><code>USE AdventureWorks2012;\nGO\nDECLARE @AvgWeight decimal(8,2), @BikeCount int\nIF \n(SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) &gt; 5\nBEGIN\n SET @BikeCount = \n (SELECT COUNT(*) \n FROM Production.Product \n WHERE Name LIKE 'Touring-3000%');\n SET @AvgWeight = \n (SELECT AVG(Weight) \n FROM Production.Product \n WHERE Name LIKE 'Touring-3000%');\n PRINT 'There are ' + CAST(@BikeCount AS varchar(3)) + ' Touring-3000 bikes.'\n PRINT 'The average weight of the top 5 Touring-3000 bikes is ' + CAST(@AvgWeight AS varchar(8)) + '.';\nEND\nELSE \nBEGIN\nSET @AvgWeight = \n (SELECT AVG(Weight)\n FROM Production.Product \n WHERE Name LIKE 'Touring-3000%' );\n PRINT 'Average weight of the Touring-3000 bikes is ' + CAST(@AvgWeight AS varchar(8)) + '.' ;\nEND ;\nGO\n</code></pre>\n\n<p>Using nested IF...ELSE statements\nThe following example shows how an IF … ELSE statement can be nested inside another. Set the @Number variable to 5, 50, and 500 to test each statement.</p>\n\n<pre><code>DECLARE @Number int\nSET @Number = 50\nIF @Number &gt; 100\n PRINT 'The number is large.'\nELSE \n BEGIN\n IF @Number &lt; 10\n PRINT 'The number is small'\n ELSE\n PRINT 'The number is medium'\n END ;\nGO\n</code></pre>\n" }, { "answer_id": 34948428, "author": "Rivanni", "author_id": 3307627, "author_profile": "https://Stackoverflow.com/users/3307627", "pm_score": 5, "selected": false, "text": "<p>You don't need a IF statement at all.</p>\n\n<pre><code>WHERE\n (IsNumeric(@OrderNumber) = 1 AND OrderNumber = @OrderNumber)\nOR (IsNumeric(@OrderNumber) = 0 AND OrderNumber LIKE '%' + @OrderNumber + '%')\n</code></pre>\n" }, { "answer_id": 55119022, "author": "Majedur", "author_id": 3915410, "author_profile": "https://Stackoverflow.com/users/3915410", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p><strong>CASE</strong> Statement is better option than <strong>IF</strong> always.</p>\n</blockquote>\n\n<pre><code> WHERE vfl.CreatedDate &gt;= CASE WHEN @FromDate IS NULL THEN vfl.CreatedDate ELSE @FromDate END\n AND vfl.CreatedDate&lt;=CASE WHEN @ToDate IS NULL THEN vfl.CreatedDate ELSE @ToDate END \n</code></pre>\n" }, { "answer_id": 57133135, "author": "Jubayer Hossain", "author_id": 8163003, "author_profile": "https://Stackoverflow.com/users/8163003", "pm_score": 1, "selected": false, "text": "<pre><code> WHERE OrderNumber LIKE CASE WHEN IsNumeric(@OrderNumber) = 1 THEN @OrderNumber ELSE '%' + @OrderNumber END\n</code></pre>\n\n<p>In line case Condition will work properly.</p>\n" }, { "answer_id": 62145148, "author": "Aneeq Azam Khan", "author_id": 4960042, "author_profile": "https://Stackoverflow.com/users/4960042", "pm_score": 1, "selected": false, "text": "<p>In sql server I had same problem I wanted to use an and statement only if parameter is false and on true I had to show both values true and false so I used it this way</p>\n\n<pre><code>(T.IsPublic = @ShowPublic or @ShowPublic = 1)\n</code></pre>\n" }, { "answer_id": 65439563, "author": "jawdat abdallh", "author_id": 11471636, "author_profile": "https://Stackoverflow.com/users/11471636", "pm_score": 2, "selected": false, "text": "<p>// an example for using a stored procedure to select users filtered by country and site</p>\n<pre><code>CREATE STORED PROCEDURE GetUsers\n@CountryId int = null,\n@SiteId int = null\nAS\nBEGIN\nSELECT *\n FROM Users\n WHERE\n CountryId = CASE WHEN ISNUMERIC(@CountryId) = 1 THEN @CountryId ELSE CountryId END AND \n SiteId = CASE WHEN ISNUMERIC(@SiteId) = 1 THEN @SiteId ELSE SiteId END END\n</code></pre>\n<blockquote>\n<p>// take from the input countryId AND/OR siteId if exists else don't filter</p>\n</blockquote>\n" }, { "answer_id": 66123843, "author": "Basic.Bear", "author_id": 6928182, "author_profile": "https://Stackoverflow.com/users/6928182", "pm_score": 2, "selected": false, "text": "<p>To clarify some of the logical equivalence solutions.</p>\n<p>An if statement</p>\n<pre><code>if (a) then b\n</code></pre>\n<p>is logically equivalent to</p>\n<pre><code>(!a || b)\n</code></pre>\n<p>It's the first line on the <strong>Logical equivalences involving conditional statements</strong> section of the <a href=\"https://en.wikipedia.org/wiki/Logical_equivalence\" rel=\"nofollow noreferrer\">Logical equivalence wikipedia article</a>.</p>\n<p>To include the <strong>else</strong>, all you would do is add another conditional</p>\n<pre><code>if(a) then b; \nif(!a) then c;\n</code></pre>\n<p>which is logically equivalent to\n(!a || b) &amp;&amp; (a || c)</p>\n<p>So using the OP as an example:</p>\n<pre><code>IF IsNumeric(@OrderNumber) = 1\n OrderNumber = @OrderNumber\nELSE\n OrderNumber LIKE '%' + @OrderNumber + '%'\n</code></pre>\n<p>the logical equivalent would be:</p>\n<pre><code>(IsNumeric(@OrderNumber) &lt;&gt; 1 OR OrderNumber = @OrderNumber)\nAND (IsNumeric(@OrderNumber) = 1 OR OrderNumber LIKE '%' + @OrderNumber + '%' )\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ]
Is it possible to use an **IF** clause within a **WHERE** clause in MS SQL? Example: ``` WHERE IF IsNumeric(@OrderNumber) = 1 OrderNumber = @OrderNumber ELSE OrderNumber LIKE '%' + @OrderNumber + '%' ```
Use a [CASE](http://msdn.microsoft.com/en-us/library/ms181765.aspx) statement **UPDATE:** The previous syntax (as pointed out by a few people) doesn't work. You can use CASE as follows: ``` WHERE OrderNumber LIKE CASE WHEN IsNumeric(@OrderNumber) = 1 THEN @OrderNumber ELSE '%' + @OrderNumber END ``` Or you can use an IF statement like @[N. J. Reed](https://stackoverflow.com/questions/87821/sql-if-clause-within-where-clause#87992) points out.
87,831
<p>Nant seems very compiler-centric - which is guess is because it's considered a .NET development system. But I know it can be done! I've seen it. The platform we're building on has its own compiler and doesn't use 'cl.exe' for c++. We're building a C++ app on a different platform and would like to override with our own compiler. Can anyone point me at a way to do that or at least how to set up a target of my own that will use our target platform's compiler?</p>
[ { "answer_id": 87844, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 2, "selected": false, "text": "<p>You need to write your own task. <a href=\"http://www.atalasoft.com/cs/blogs/jake/archive/2008/05/07/writing-custom-nant-tasks.aspx\" rel=\"nofollow noreferrer\">This</a> is a nice reference.</p>\n" }, { "answer_id": 87857, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 1, "selected": false, "text": "<p>Initially, use the &lt;exec&gt; task to run an executable, passing in any required information as parameters and/or environment variables.</p>\n\n<p>For future use, you could also investigate writing your own task. I know with standard ant this is done with the &lt;taskdef&gt; task and a java class. I'm not sure of the Nant equivalent unfortunately.</p>\n" }, { "answer_id": 87878, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 0, "selected": false, "text": "<p>You could also use the <code>&lt;exec&gt;</code> task.</p>\n" }, { "answer_id": 87948, "author": "Jeff Cuscutis", "author_id": 2277, "author_profile": "https://Stackoverflow.com/users/2277", "pm_score": 4, "selected": true, "text": "<p>Here is one I did for Delphi. Each 'arg' is a separate param with a value defined elsewhere. The target is called with the params set up before calling it.</p>\n\n<pre><code>&lt;target name=\"build.application\"&gt;\n &lt;exec program=\"dcc32\" basedir=\"${Delphi.Bin}\" workingdir=\"${Application.Folder}\" verbose=\"true\"&gt;\n &lt;arg value=\"${Application.Compiler.Directive}\" /&gt;\n &lt;arg value=\"-Q\" /&gt;\n &lt;arg value=\"/B\" /&gt;\n &lt;arg value=\"/E${Application.Output.Folder}\" /&gt;\n &lt;arg value=\"/U${Application.Lib.Folder};${Application.Search.Folder}\" /&gt;\n &lt;arg value=\"${Application.Folder}\\${Delphi.Project}\" /&gt;\n &lt;/exec&gt;\n&lt;/target&gt;\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/424554/" ]
Nant seems very compiler-centric - which is guess is because it's considered a .NET development system. But I know it can be done! I've seen it. The platform we're building on has its own compiler and doesn't use 'cl.exe' for c++. We're building a C++ app on a different platform and would like to override with our own compiler. Can anyone point me at a way to do that or at least how to set up a target of my own that will use our target platform's compiler?
Here is one I did for Delphi. Each 'arg' is a separate param with a value defined elsewhere. The target is called with the params set up before calling it. ``` <target name="build.application"> <exec program="dcc32" basedir="${Delphi.Bin}" workingdir="${Application.Folder}" verbose="true"> <arg value="${Application.Compiler.Directive}" /> <arg value="-Q" /> <arg value="/B" /> <arg value="/E${Application.Output.Folder}" /> <arg value="/U${Application.Lib.Folder};${Application.Search.Folder}" /> <arg value="${Application.Folder}\${Delphi.Project}" /> </exec> </target> ```
87,877
<p>I am trying to build a dependency graph of tables based on the foreign keys between them. This graph needs to start with an arbitrary table name as its root. I could, given a table name look up the tables that reference it using the all_constraints view, then look up the tables that reference them, and so on, but this would be horrible inefficient. I wrote a recursive query that does this for all tables, but when I add:</p> <pre><code>START WITH Table_Name=:tablename </code></pre> <p>It doesn't return the entire tree.</p>
[ { "answer_id": 88217, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "<p>Simplest way to do this is to copy all the FK info into a simple, 2-column (parent,child) table, and then use the following algorithm:</p>\n\n<pre><code>while (rows left in that table)\n list = rows where table name exists in child but not in parent\n print list\n remove list from rows\n</code></pre>\n\n<p>that's all. Basically, you first print and remove all the nodes that don't depend on anything. After that being done, some other nodes will get free and you can repeat process.</p>\n\n<p>P.S. Make sure you don't insert self-referencing tables in the initial list (child=parent)</p>\n" }, { "answer_id": 88388, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 4, "selected": true, "text": "<pre><code> select parent, child, level from (\nselect parent_table.table_name parent, child_table.table_name child\n from user_tables parent_table,\n user_constraints parent_constraint,\n user_constraints child_constraint,\n user_tables child_table\nwhere parent_table.table_name = parent_constraint.table_name\n and parent_constraint.constraint_type IN( 'P', 'U' )\n and child_constraint.r_constraint_name = parent_constraint.constraint_name\n and child_constraint.constraint_type = 'R'\n and child_table.table_name = child_constraint.table_name\n and child_table.table_name != parent_table.table_name\n)\nstart with parent = 'DEPT'\nconnect by prior child = parent\n</code></pre>\n\n<p>should work (replace the table name, of course) assuming that everything is in the same schema. Use the DBA_ versions of the data dictionary tables and conditions for the OWNER and R_OWNER columns if you need to handle cross-schema dependencies. On further reflection, this does not account for self-referential constraints (i.e. a constraint on the EMP table that the MGR column references the EMPNO column) either, so you'd have to modify the code to handle that case if you need to deal with self-referential constraints.</p>\n\n<p>For testing purposes, I added a few new tables to the SCOTT schema that also reference the DEPT table (including a grandchild dependency)</p>\n\n<pre><code>SQL&gt; create table dept_child2 (\n 2 deptno number references dept( deptno )\n 3 );\n\nTable created.\n\nSQL&gt; create table dept_child3 (\n 2 dept_child3_no number primary key,\n 3 deptno number references dept( deptno )\n 4 );\n\nTable created.\n\nSQL&gt; create table dept_grandchild (\n 2 dept_child3_no number references dept_child3( dept_child3_no )\n 3 );\n\nTable created.\n</code></pre>\n\n<p>and verified that the query returned the expected output</p>\n\n<pre><code>SQL&gt; ed\nWrote file afiedt.buf\n\n 1 select parent, child, level from (\n 2 select parent_table.table_name parent, child_table.table_name child\n 3 from user_tables parent_table,\n 4 user_constraints parent_constraint,\n 5 user_constraints child_constraint,\n 6 user_tables child_table\n 7 where parent_table.table_name = parent_constraint.table_name\n 8 and parent_constraint.constraint_type IN( 'P', 'U' )\n 9 and child_constraint.r_constraint_name = parent_constraint.constraint_name\n 10 and child_constraint.constraint_type = 'R'\n 11 and child_table.table_name = child_constraint.table_name\n 12 and child_table.table_name != parent_table.table_name\n 13 )\n 14 start with parent = 'DEPT'\n 15* connect by prior child = parent\nSQL&gt; /\n\nPARENT CHILD LEVEL\n------------------------------ ------------------------------ ----------\nDEPT DEPT_CHILD3 1\nDEPT_CHILD3 DEPT_GRANDCHILD 2\nDEPT DEPT_CHILD2 1\nDEPT EMP 1\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I am trying to build a dependency graph of tables based on the foreign keys between them. This graph needs to start with an arbitrary table name as its root. I could, given a table name look up the tables that reference it using the all\_constraints view, then look up the tables that reference them, and so on, but this would be horrible inefficient. I wrote a recursive query that does this for all tables, but when I add: ``` START WITH Table_Name=:tablename ``` It doesn't return the entire tree.
``` select parent, child, level from ( select parent_table.table_name parent, child_table.table_name child from user_tables parent_table, user_constraints parent_constraint, user_constraints child_constraint, user_tables child_table where parent_table.table_name = parent_constraint.table_name and parent_constraint.constraint_type IN( 'P', 'U' ) and child_constraint.r_constraint_name = parent_constraint.constraint_name and child_constraint.constraint_type = 'R' and child_table.table_name = child_constraint.table_name and child_table.table_name != parent_table.table_name ) start with parent = 'DEPT' connect by prior child = parent ``` should work (replace the table name, of course) assuming that everything is in the same schema. Use the DBA\_ versions of the data dictionary tables and conditions for the OWNER and R\_OWNER columns if you need to handle cross-schema dependencies. On further reflection, this does not account for self-referential constraints (i.e. a constraint on the EMP table that the MGR column references the EMPNO column) either, so you'd have to modify the code to handle that case if you need to deal with self-referential constraints. For testing purposes, I added a few new tables to the SCOTT schema that also reference the DEPT table (including a grandchild dependency) ``` SQL> create table dept_child2 ( 2 deptno number references dept( deptno ) 3 ); Table created. SQL> create table dept_child3 ( 2 dept_child3_no number primary key, 3 deptno number references dept( deptno ) 4 ); Table created. SQL> create table dept_grandchild ( 2 dept_child3_no number references dept_child3( dept_child3_no ) 3 ); Table created. ``` and verified that the query returned the expected output ``` SQL> ed Wrote file afiedt.buf 1 select parent, child, level from ( 2 select parent_table.table_name parent, child_table.table_name child 3 from user_tables parent_table, 4 user_constraints parent_constraint, 5 user_constraints child_constraint, 6 user_tables child_table 7 where parent_table.table_name = parent_constraint.table_name 8 and parent_constraint.constraint_type IN( 'P', 'U' ) 9 and child_constraint.r_constraint_name = parent_constraint.constraint_name 10 and child_constraint.constraint_type = 'R' 11 and child_table.table_name = child_constraint.table_name 12 and child_table.table_name != parent_table.table_name 13 ) 14 start with parent = 'DEPT' 15* connect by prior child = parent SQL> / PARENT CHILD LEVEL ------------------------------ ------------------------------ ---------- DEPT DEPT_CHILD3 1 DEPT_CHILD3 DEPT_GRANDCHILD 2 DEPT DEPT_CHILD2 1 DEPT EMP 1 ```
87,902
<p>I am trying to validate user id's matching the example:</p> <pre><code>smith.jack or smith.jack.s </code></pre> <p>In other words, any number of non-whitespace characters (except dot), followed by exactly one dot, followed by any number of non-whitespace characters (except dot), optionally followed by exactly one dot followed by any number of non-whitespace characters (except dot). I have come up with several variations that work fine except for allowing consecutive dots! For example, the following Regex</p> <pre><code>^([\S][^.]*[.]{1}[\S][^.]*|[\S][^.]*[.]{1}[\S][^.]*[.]{1}[\S][^.]*)$ </code></pre> <p>matches "smith.jack" and "smith.jack.s" but also matches "smith..jack" "smith..jack.s" ! My gosh, it even likes a dot as a first character. It seems like it would be so simple to code, but it isn't. I am using .NET, btw.</p> <p>Frustrating.</p>
[ { "answer_id": 87919, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 1, "selected": false, "text": "<pre><code>[^\\s.]+\\.[^\\s.]+(\\.[^\\s.]+)?\n</code></pre>\n\n<p>BTW what you asked for allows \".\" and \"..\"</p>\n" }, { "answer_id": 87923, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 3, "selected": false, "text": "<p>that helps?</p>\n\n<pre><code>/^[^\\s\\.]+(?:\\.[^\\s\\.]+)*$/\n</code></pre>\n\n<p>or, in extended format, with comments (ruby-style)</p>\n\n<pre><code>/\n ^ # start of line\n [^\\s\\.]+ # one or more non-space non-dot\n (?: # non-capturing group\n \\. # dot something\n [^\\s\\.]+ # one or more non-space non-dot\n )* # zero or more times\n $ # end of line\n/x\n</code></pre>\n\n<p>you're not clear on how many times you can have dot-something, but you can replace the <code>*</code> with <code>{1,3}</code> or something, to specify how many repetitions are allowed.</p>\n\n<p>i should probably make it clear that the slashes are the literal regex delimiter in ruby (and perl and js, etc).</p>\n" }, { "answer_id": 87927, "author": "Lot105", "author_id": 9801, "author_profile": "https://Stackoverflow.com/users/9801", "pm_score": 0, "selected": false, "text": "<p>I think you'd benefit from using + which means \"1 or more\", instead of * meaning \"any number including zero\".</p>\n" }, { "answer_id": 87953, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 2, "selected": false, "text": "<p>You are using the * duplication, which allows for 0 iterations of the given component.</p>\n\n<p>You should be using plus, and putting the final .[^.]+ into a group followed by ? to represent the possibility of an extra set.</p>\n\n<p>Might not have the perfect syntax, but something similar to the following should work.</p>\n\n<p>^[^.\\s]+[.][^.\\s]+([.][^.\\s]+)?$</p>\n\n<p>Or in simple terms, any non-zero number of non-whitespace non-dot characters, followed by a dot, followed by any non-zero number of non-whitespace non-dot characters, optionally followed by a dot, followed by any non-zero number of non-whitespace non-dot characters.</p>\n" }, { "answer_id": 87961, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 0, "selected": false, "text": "<pre><code>(^.)+|(([^.]+)[.]([^.]+))+\n</code></pre>\n\n<p>But this would match x.y.z.a.b.c and from your description, I am not sure if this is sufficiently restrictive.</p>\n\n<p>BTW: feel free to modify if I made a silly mistake (I haven't used .NET, but have done plently of regexs)</p>\n" }, { "answer_id": 87972, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>[^.\\s]+\\.[^.\\s]+(\\.([^\\s.]+?)? \n</code></pre>\n\n<p>has unmatched paren. If corrected to </p>\n\n<pre><code>[^.\\s]+\\.[^.\\s]+(\\.([^\\s.]+?))?\n</code></pre>\n\n<p>is still too liberal. Matches a.b. as well as a.b.c.d. and .a.b<br>\nIf corrected to</p>\n\n<pre><code>[^.\\s]+\\.[^.\\s]+(\\.([^\\s.]+?)?)\n</code></pre>\n\n<p>doesn't match a.b</p>\n" }, { "answer_id": 87975, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 0, "selected": false, "text": "<pre><code>^([^.\\W]+)\\.?([^.\\W]+)\\.?([^.\\W]+)$\n</code></pre>\n\n<p>This should capture as described, group the parts of the id and stop duplicate periods</p>\n" }, { "answer_id": 88012, "author": "Terhorst", "author_id": 8062, "author_profile": "https://Stackoverflow.com/users/8062", "pm_score": 3, "selected": true, "text": "<p>^([^.\\s]+)\\.([^.\\s]+)(?:\\.([^.\\s]+))?$</p>\n" }, { "answer_id": 88066, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 2, "selected": false, "text": "<p>I'm not familiar with .NET's regexes. This will do what you want in Perl.</p>\n\n<pre><code>/^\\w+\\.\\w+(?:\\.\\w+)?$/\n</code></pre>\n\n<p>If .NET doesn't support the non-capturing <code>(?:xxx)</code> syntax, use this instead:</p>\n\n<pre><code>/^\\w+\\.\\w+(\\.\\w+)?$/\n</code></pre>\n\n<p>Note: I'm assuming that when you say \"non-whitespace, non-dot\" you really mean \"word characters.\"</p>\n" }, { "answer_id": 88108, "author": "Trey", "author_id": 16876, "author_profile": "https://Stackoverflow.com/users/16876", "pm_score": 0, "selected": false, "text": "<p>I took a slightly different approach. I figured you really just wanted a string of non-space characters followed by only one dot, but that dot is optional (for the last entry). Then you wanted this repeated.</p>\n\n<pre><code>^([^\\s\\.]+\\.?)+$\n</code></pre>\n\n<p>Right now, this means you have to have at least one string of characters, e.g. 'smith' to match. You, of course could limit it to only allow one to three repetitions with</p>\n\n<pre><code>^([^\\s\\.]+\\.?){1,3}$\n</code></pre>\n\n<p>I hope that helps.</p>\n" }, { "answer_id": 88129, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 2, "selected": false, "text": "<p>I realise this has already been solved, but I find <a href=\"http://regexpal.com/\" rel=\"nofollow noreferrer\">Regexpal</a> extremely helpful for prototyping regex's. The site has a load of simple explanations of the basics and lets you see what matches as you adjust the expression.</p>\n" }, { "answer_id": 94766, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.regexbuddy.com/\" rel=\"nofollow noreferrer\">RegexBuddy</a> Is a good (non-free) tool for regex stuff</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to validate user id's matching the example: ``` smith.jack or smith.jack.s ``` In other words, any number of non-whitespace characters (except dot), followed by exactly one dot, followed by any number of non-whitespace characters (except dot), optionally followed by exactly one dot followed by any number of non-whitespace characters (except dot). I have come up with several variations that work fine except for allowing consecutive dots! For example, the following Regex ``` ^([\S][^.]*[.]{1}[\S][^.]*|[\S][^.]*[.]{1}[\S][^.]*[.]{1}[\S][^.]*)$ ``` matches "smith.jack" and "smith.jack.s" but also matches "smith..jack" "smith..jack.s" ! My gosh, it even likes a dot as a first character. It seems like it would be so simple to code, but it isn't. I am using .NET, btw. Frustrating.
^([^.\s]+)\.([^.\s]+)(?:\.([^.\s]+))?$
87,909
<p>Is it possible to set the title of a page when it's simply a loaded SWF?</p>
[ { "answer_id": 87984, "author": "madcolor", "author_id": 13954, "author_profile": "https://Stackoverflow.com/users/13954", "pm_score": 0, "selected": false, "text": "<p>I would think you would be able to do it. You would have to access the javascript DOM. </p>\n\n<p>A couple links that may steer you down the correct path.. </p>\n\n<p><a href=\"http://homepage.ntlworld.com/kayseycarvey/document2.html\" rel=\"nofollow noreferrer\">http://homepage.ntlworld.com/kayseycarvey/document2.html</a></p>\n\n<p><a href=\"http://www.permadi.com/tutorial/flashjscommand/\" rel=\"nofollow noreferrer\">http://www.permadi.com/tutorial/flashjscommand/</a></p>\n" }, { "answer_id": 88131, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 2, "selected": false, "text": "<p>Sure. This should fix you up:</p>\n\n<pre><code>getURL('javascript:var x = (document.getElementsByTagName(\"head\")[0].getElementsByTagName(\"title\")[0].firstChild.nodeValue = \"This is a test!\");');\n</code></pre>\n\n<p>Just replace \"This is a test!\" with your new title.</p>\n" }, { "answer_id": 88928, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 0, "selected": false, "text": "<p>You could use <a href=\"http://www.asual.com/swfaddress/\" rel=\"nofollow noreferrer\">SWFAddress</a>, it has a setTitle method. Plus, you get the added benefit of beng able to modify the URL for deep-linking.</p>\n\n<p>EDIT: This won't work if the SWF is loaded directly in the browser, only if it is embedded in HTML.</p>\n" }, { "answer_id": 91752, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": false, "text": "<p>This is how I would do it:</p>\n\n<pre><code>ExternalInterface.call(\"document.title = 'Hello World'\");\n</code></pre>\n\n<p>Or more generalized:</p>\n\n<pre><code>function setPageTitle( newTitle : String ) : void {\n var jsCode : String = \"function( title ) { document.title = title; }\";\n\n ExternalInterface.call(jsCode, newTitle);\n}\n</code></pre>\n" }, { "answer_id": 2070060, "author": "sagarvarule", "author_id": 251351, "author_profile": "https://Stackoverflow.com/users/251351", "pm_score": 0, "selected": false, "text": "<p>I came up with the same problem of setting up the title of my page. Madw hell lot of efforts from downloading aspFlash controls to those swfObject....</p>\n\n<p>Finally my team lead came up the solution....</p>\n\n<p>open the pop of one page and in that page use one IFrame and use the Iframe to load the swf file.</p>\n\n<p>So there are 2 page outer one is our control so just set the title.. inner one is the Iframe which is just another page so load the swf file directly by setting the scr=\"<em>file path</em>\"</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69665/" ]
Is it possible to set the title of a page when it's simply a loaded SWF?
This is how I would do it: ``` ExternalInterface.call("document.title = 'Hello World'"); ``` Or more generalized: ``` function setPageTitle( newTitle : String ) : void { var jsCode : String = "function( title ) { document.title = title; }"; ExternalInterface.call(jsCode, newTitle); } ```
87,934
<p>In Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working.</p> <p>I has used the auto-complete plugin provided with Notepad++, which presented me with <code>onClick</code>.</p> <p>When I changed the capital <code>C</code> to a small <code>c</code>, it did work.</p> <p>So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals.</p> <p>But when you change <code>getElementById</code> to <code>getelementbyid</code>, you also get an error, and to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters.</p> <p>So what is it with JavaScript and its selective nature towards which functions can have capital letters in them and which can't?</p>
[ { "answer_id": 87958, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 6, "selected": true, "text": "<p>Javascript is <strong>ALWAYS</strong> case-sensitive, html is not.</p>\n\n<p>It sounds as thought you are talking about whether html attributes (e.g. onclick) are or are not case-sensitive. The answer is that the attributes are not case sensitive, but the way that we access them through the DOM is. \nSo, you can do this:</p>\n\n<pre><code>&lt;div id='divYo' onClick=\"alert('yo!');\"&gt;Say Yo&lt;/div&gt; // Upper-case 'C'\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>&lt;div id='divYo' onclick=\"alert('yo!');\"&gt;Say Yo&lt;/div&gt; // Lower-case 'C'\n</code></pre>\n\n<p>but through the DOM you must use the correct case. So this works:</p>\n\n<pre><code>getElementById('divYo').onclick = function() { alert('yo!'); }; // Lower-case 'C'\n</code></pre>\n\n<p>but you cannot do this:</p>\n\n<pre><code>getElementById('divYo').onClick = function() { alert('yo!'); }; // Upper-case 'C'\n</code></pre>\n\n<p>EDIT: CMS makes a great point that most DOM methods and properties are in <a href=\"http://www.perlmonks.org/?node_id=45213\" rel=\"noreferrer\">camelCase</a>. The one exception that comes to mind are event handler properties and these are generally accepted to be <a href=\"http://javascript.about.com/library/blonclick.htm\" rel=\"noreferrer\">the wrong way to attach to events</a> anyway. Prefer using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"noreferrer\"><code>addEventListener</code></a> as in:</p>\n\n<pre><code>document.getElementById('divYo').addEventListener('click', modifyText, false);\n</code></pre>\n" }, { "answer_id": 88008, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 1, "selected": false, "text": "<p>JavaScript API methods are almost all called with <a href=\"http://en.wikipedia.org/wiki/LowerCamelCase\" rel=\"nofollow noreferrer\">lowerCamelCase</a> names, and JavaScript is case-sensitive</p>\n" }, { "answer_id": 88009, "author": "Jeff", "author_id": 10157, "author_profile": "https://Stackoverflow.com/users/10157", "pm_score": 1, "selected": false, "text": "<p>Javascript <em>should</em> always be case sensitive, but I've seen cases in Internet Explorer where it tolerates all upper case for some function names but not others. I think it is limited to functions that also exist in Visual Basic, as there is some odd inbreeding between the interpreters. Clearly this behavior should be avoided, unless of course your intention is to make code that only runs in one browser :)</p>\n" }, { "answer_id": 88503, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 3, "selected": false, "text": "<p>A few objects is IE aren't always case-sensitive, including some/most/all ActiveX -- why both <strong>XHR.onReadyStateChange</strong> and <strong>XHR.onreadystatechange</strong> would work fine in IE5 or IE6, but only the latter would work with the native <strong>XMLHttpRequest</strong> object in IE7, FF, etc.</p>\n\n<p>But, a quick reference for \"<i>standard</i>\" API casing:</p>\n\n<ul>\n<li><strong>UPPERCASE</strong> - Constants (generally symbolic, since <strong>const</strong> isn't globally supported)</li>\n<li><strong>Capitalized</strong> - Classes/Object functions</li>\n<li><strong>lowercase</strong> - Events</li>\n<li><strong>camelCase</strong> - everything else</li>\n</ul>\n\n<p>No 100% guarantees. But, majority-wise, this is accurate.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11795/" ]
In Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working. I has used the auto-complete plugin provided with Notepad++, which presented me with `onClick`. When I changed the capital `C` to a small `c`, it did work. So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals. But when you change `getElementById` to `getelementbyid`, you also get an error, and to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters. So what is it with JavaScript and its selective nature towards which functions can have capital letters in them and which can't?
Javascript is **ALWAYS** case-sensitive, html is not. It sounds as thought you are talking about whether html attributes (e.g. onclick) are or are not case-sensitive. The answer is that the attributes are not case sensitive, but the way that we access them through the DOM is. So, you can do this: ``` <div id='divYo' onClick="alert('yo!');">Say Yo</div> // Upper-case 'C' ``` or: ``` <div id='divYo' onclick="alert('yo!');">Say Yo</div> // Lower-case 'C' ``` but through the DOM you must use the correct case. So this works: ``` getElementById('divYo').onclick = function() { alert('yo!'); }; // Lower-case 'C' ``` but you cannot do this: ``` getElementById('divYo').onClick = function() { alert('yo!'); }; // Upper-case 'C' ``` EDIT: CMS makes a great point that most DOM methods and properties are in [camelCase](http://www.perlmonks.org/?node_id=45213). The one exception that comes to mind are event handler properties and these are generally accepted to be [the wrong way to attach to events](http://javascript.about.com/library/blonclick.htm) anyway. Prefer using [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) as in: ``` document.getElementById('divYo').addEventListener('click', modifyText, false); ```
87,970
<p>I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method.</p> <p>For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist. I know for other arrays you can make the assignment like:</p> <pre><code>int[] IntArray = {1,2,3}; </code></pre> <p>Is there a similar way to do this for an arraylist? I tried the addrange method but the curly brace method doesn't implement the ICollection interface.</p>
[ { "answer_id": 88017, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 4, "selected": true, "text": "<p>Array list has ctor which accepts ICollection, which is implemented by the Array class.</p>\n\n<pre><code>object[] myArray = new object[] {1,2,3,\"string1\",\"string2\"};\nArrayList myArrayList = new ArrayList(myArray);\n</code></pre>\n" }, { "answer_id": 88018, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 4, "selected": false, "text": "<p>Depending on the version of C# you are using, you have different options.</p>\n\n<p>C# 3.0 has collection initializers, detail at <a href=\"http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx\" rel=\"noreferrer\">Scott Gu's Blog</a></p>\n\n<p>Here is an example of your problem.</p>\n\n<pre><code>ArrayList list = new ArrayList {1,2,3};\n</code></pre>\n\n<p>And if you are initializing a collection object, most have constructors that take similar components to AddRange, although again as you mentioned this may not be an option.</p>\n" }, { "answer_id": 88086, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 0, "selected": false, "text": "<p>I assume you're not using C# 3.0, which has collection initializers. If you're not bothered about the overhead of creating a temp array, you could do it like this in 1.1/2.0:</p>\n\n<pre><code>ArrayList list = new ArrayList(new object[] { 1, 2, 3, \"string1\", \"string2\"});\n</code></pre>\n" }, { "answer_id": 88236, "author": "Lyndon", "author_id": 16866, "author_profile": "https://Stackoverflow.com/users/16866", "pm_score": 1, "selected": false, "text": "<p>(kind of answering my own question but...)</p>\n\n<p>The closest thing I've found to what I want is to make use of the ArrayList.Adapter method:</p>\n\n<pre><code>object[] values = { 1, 2, 3, \"string1\", \"string2\" };\nArrayList AL = new ArrayList();\nAL = ArrayList.Adapter(values);\n\n//or during intialization\nArrayList AL2 = ArrayList.Adapter(values);\n</code></pre>\n\n<p>This is sufficient for what I need, but I was hoping it could be done in one line without creating the temporary array as someone else had suggested.</p>\n" }, { "answer_id": 88281, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 1, "selected": false, "text": "<p>Your comments imply you chose ArrayList because it was the first component you found.</p>\n\n<p>Assuming you are simply looking for a list of integers, this is probably the best way of doing that.</p>\n\n<pre><code>List&lt;int&gt; list = new List&lt;int&gt;{1,2,3};\n</code></pre>\n\n<p>And if you are using C# 2.0 (Which has generics, but not collection initializers).</p>\n\n<pre><code>List&lt;int&gt; list = new List&lt;int&gt;(new int[] {1, 2, 3});\n</code></pre>\n\n<p>Although the int[] format may not be correct in older versions, you may have to specify the number of items in the array.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16866/" ]
I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method. For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist. I know for other arrays you can make the assignment like: ``` int[] IntArray = {1,2,3}; ``` Is there a similar way to do this for an arraylist? I tried the addrange method but the curly brace method doesn't implement the ICollection interface.
Array list has ctor which accepts ICollection, which is implemented by the Array class. ``` object[] myArray = new object[] {1,2,3,"string1","string2"}; ArrayList myArrayList = new ArrayList(myArray); ```
87,986
<p>In C# you can get the original error and trace the execution path (stack trace) using the inner exception that is passed up. I would like to know how this can be achieved using the error handling try/catch in sql server 2005 when an error occurs in a stored procedure nested 2 or 3 levels deep. </p> <p>I am hoping that functions like ERROR_MESSAGE(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_SEVERITY() can be easily passed up the line so that the top level stored proc can access them.</p>
[ { "answer_id": 88941, "author": "Daniel", "author_id": 6852, "author_profile": "https://Stackoverflow.com/users/6852", "pm_score": 0, "selected": false, "text": "<p>One way you could do this would be to create an in memory table and insert rows into it when you catch an exception. You would then re-raise the exception and the next function up the chain would then have a chance to handle the exception or also log the exception to the in memory table. It's nasty, but unfortunately there doesn't seem to be a way to get the T-SQL call stack :(</p>\n" }, { "answer_id": 166372, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 2, "selected": false, "text": "<p>The best way to handle this is using OUTPUT parameters and XML. The sample code below will demonstrate how and you can modify what you do with the XML in the TopProcedure to better handle your response to the error.</p>\n\n<pre><code>USE tempdb\ngo\nCREATE PROCEDURE SubProcedure @RandomNumber int, @XMLErrors XML OUTPUT\nAS\nBEGIN\nBEGIN TRY\n IF @RandomNumber &gt; 50\n RaisError('Bad number set!',16,1)\n else\n select @RandomNumber\nEND TRY\nBEGIN CATCH\n SET @XMLErrors = (SELECT * FROM (SELECT ERROR_MESSAGE() ErrorMessage, \n ERROR_LINE() ErrorLine, ERROR_PROCEDURE() ErrorProcedure, \n ERROR_SEVERITY() ErrorSeverity) a FOR XML AUTO, ELEMENTS, ROOT('root'))\nEND CATCH\nEND\ngo\n\nCREATE PROCEDURE TopProcedure @RandomNumber int\nAS\nBEGIN\n declare @XMLErrors XML\n exec SubProcedure @RandomNumber, @XMLErrors OUTPUT\n IF @XMLErrors IS NOT NULL\n select @XMLErrors\nEND\n\ngo\nexec TopProcedure 25\ngo\nexec TopProcedure 55\ngo\nDROP PROCEDURE TopProcedure\nGO\nDROP PROCEDURE SubProcedure\nGO\n</code></pre>\n\n<p>The initial call to TopProcedure will return 25. The second will return an XML block that looks like this:</p>\n\n<pre><code>&lt;root&gt;\n &lt;a&gt;\n &lt;ErrorMessage&gt;Bad number set!&lt;/ErrorMessage&gt;\n &lt;ErrorLine&gt;6&lt;/ErrorLine&gt;\n &lt;ErrorProcedure&gt;SubProcedure&lt;/ErrorProcedure&gt;\n &lt;ErrorSeverity&gt;16&lt;/ErrorSeverity&gt;\n &lt;/a&gt;\n&lt;/root&gt;\n</code></pre>\n\n<p>Enjoy</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989/" ]
In C# you can get the original error and trace the execution path (stack trace) using the inner exception that is passed up. I would like to know how this can be achieved using the error handling try/catch in sql server 2005 when an error occurs in a stored procedure nested 2 or 3 levels deep. I am hoping that functions like ERROR\_MESSAGE(), ERROR\_LINE(), ERROR\_PROCEDURE(), ERROR\_SEVERITY() can be easily passed up the line so that the top level stored proc can access them.
The best way to handle this is using OUTPUT parameters and XML. The sample code below will demonstrate how and you can modify what you do with the XML in the TopProcedure to better handle your response to the error. ``` USE tempdb go CREATE PROCEDURE SubProcedure @RandomNumber int, @XMLErrors XML OUTPUT AS BEGIN BEGIN TRY IF @RandomNumber > 50 RaisError('Bad number set!',16,1) else select @RandomNumber END TRY BEGIN CATCH SET @XMLErrors = (SELECT * FROM (SELECT ERROR_MESSAGE() ErrorMessage, ERROR_LINE() ErrorLine, ERROR_PROCEDURE() ErrorProcedure, ERROR_SEVERITY() ErrorSeverity) a FOR XML AUTO, ELEMENTS, ROOT('root')) END CATCH END go CREATE PROCEDURE TopProcedure @RandomNumber int AS BEGIN declare @XMLErrors XML exec SubProcedure @RandomNumber, @XMLErrors OUTPUT IF @XMLErrors IS NOT NULL select @XMLErrors END go exec TopProcedure 25 go exec TopProcedure 55 go DROP PROCEDURE TopProcedure GO DROP PROCEDURE SubProcedure GO ``` The initial call to TopProcedure will return 25. The second will return an XML block that looks like this: ``` <root> <a> <ErrorMessage>Bad number set!</ErrorMessage> <ErrorLine>6</ErrorLine> <ErrorProcedure>SubProcedure</ErrorProcedure> <ErrorSeverity>16</ErrorSeverity> </a> </root> ``` Enjoy
87,999
<p>Well the docs finally said it, I need to take it easy on my wrist for a few months. Being that I'm a .NET Developer this could end my livelihood for a little while, something I'm not anxious to do. That said, are there any good handsfree options for developers? Anyone had success using any of the speech recognition software out there?</p> <p>POSTSCRIPT: I've recovered my arm again to the point where two-handed programming isn't a problem. Dragon Naturally speaking worked well enough, but was slower, not like the keyboard where I was programming faster than I thought.</p>
[ { "answer_id": 88070, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.hanselman.com/blog/SpeechRecognitionInWindowsVistaImListening.aspx\" rel=\"nofollow noreferrer\">Scott Hanselman</a> uses voice recognition <a href=\"http://www.hanselman.com/blog/TypingTestTwiceOnceWithVoiceRecognition.aspx\" rel=\"nofollow noreferrer\">quite a bit</a>.</p>\n" }, { "answer_id": 88081, "author": "marc", "author_id": 12260, "author_profile": "https://Stackoverflow.com/users/12260", "pm_score": 2, "selected": false, "text": "<p>I tried Dragon a couple of years ago and it was a nightmare of mish-mashed words and phrases - not recommended. I understand that it was the best thing going at that point in time so I'm not optimistic.</p>\n\n<p>As a fellow sufferer, recommendations would be:</p>\n\n<ol>\n<li>Find a job that demands as little OT as possible</li>\n<li>Try a variety of keyboards. In my experience, working on a laptop full-time worked best.</li>\n<li>Start a program of low-moderate stress weight lifting. </li>\n</ol>\n" }, { "answer_id": 88279, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 2, "selected": false, "text": "<p>As to the wrist issue, I learned using mouse with both hands some 10 years back.</p>\n\n<p>It's surprisingly easy, and relieves the tension substantially. Currently, I'm using a laptop and pressing the touchpad button is straining my thumb.</p>\n\n<p>Be careful. These problems can last way longer than one would think.</p>\n\n<hr>\n\n<p>p.s. you might add a tag 'ergonomics' or something - the title can be seen to be about <em>developing</em> for voice recognition.</p>\n" }, { "answer_id": 88557, "author": "Carlos Villela", "author_id": 16944, "author_profile": "https://Stackoverflow.com/users/16944", "pm_score": 3, "selected": false, "text": "<p>Another idea is to find another good developer to pair program with. It worked really well for me. I get to rest my hands without necessarily slowing down, end up producing better quality code - or at least not having to review as much of it.</p>\n" }, { "answer_id": 88564, "author": "David Turner", "author_id": 10171, "author_profile": "https://Stackoverflow.com/users/10171", "pm_score": 2, "selected": false, "text": "<p>I know I am little bit off-topic here, and know nothing about voice recognition software; however, you might find it useful to investigate changing your keyboard to the Dvorak layout, which I have heard is a lot kinder on the wrists.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Dvorak_Simplified_Keyboard\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Dvorak_Simplified_Keyboard</a></p>\n" }, { "answer_id": 88592, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 0, "selected": false, "text": "<p>I can't find a link to one (I did look) but there are keyboards with only 5 keys, allowing you to type with one hand, I assume that you only have one bad wrist.</p>\n\n<p>If I find a link I'll try to message you.</p>\n" }, { "answer_id": 334575, "author": "Keith Walton", "author_id": 22448, "author_profile": "https://Stackoverflow.com/users/22448", "pm_score": 4, "selected": false, "text": "<p>I dictate VB.net and TSQL using Dragon NaturallySpeaking 10 Professional. VB.net is inherently closer to a \"spoken\" language, but I don't see any reason why it couldn't work for C# or others. I start with a completely empty vocabulary, and build it from scratch to suit my needs (which is why I use the professional version). </p>\n\n<p>Here's the basic steps (this assumes you have already created and trained a user):</p>\n\n<ol>\n<li>Create a new vocabulary based on \"Base General - Empty Dictation\".</li>\n<li>Don't have it scan your documents or email.</li>\n<li>Add lists of keywords with pronunciation specific to your programming language (Dim, ByVal\\by-val, etc.).</li>\n<li>Create a .txt document that contains all of your code minus comments.</li>\n<li>Harvest words from this document and add them with pronunciations.</li>\n<li>Use the document to train the vocabulary's language model.</li>\n</ol>\n\n<p>I'll write up something with more detail when I get a chance if anyone is interested.</p>\n\n<p>Edit:</p>\n\n<p>Here's how to <a href=\"https://stackoverflow.com/questions/350348/can-i-write-sql-using-speech-recognition\">dictate SQL code</a>. The word list created here can be included in other vocabularies if you are a database developer.</p>\n" }, { "answer_id": 334678, "author": "Alan Featherston", "author_id": 16316, "author_profile": "https://Stackoverflow.com/users/16316", "pm_score": 2, "selected": false, "text": "<p>I started using my left hand for the mouse, this not only help me a bit, but allowed me to use my right hand more freely, if you write a lot of stuff dwon while you code this helps you a lot.. you can scroll and write down at the same time...</p>\n\n<p>When my problems began i put a water bag under my wrist, i loved it! the bag i had was perfect it was long and i put it before the keyboard so i could rest my wrists there.... until one day i step on it...</p>\n" }, { "answer_id": 350396, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 1, "selected": false, "text": "<p>I used Dragon Dictate in 1996 for the same reason as you. It was slow going, but better than not working. I found it easier to write code by filling 4x8 white board with code and then getting someone else to type it in. Then I used DD to debug.</p>\n\n<p>And while you're at it, you might look at <a href=\"http://www.rsihelp.com/\" rel=\"nofollow noreferrer\">Deborah Quilter's</a> books about RSI. They're very informative.</p>\n" }, { "answer_id": 350542, "author": "onnodb", "author_id": 1037, "author_profile": "https://Stackoverflow.com/users/1037", "pm_score": 6, "selected": true, "text": "<h3>It's out there, and it works...</h3>\n\n<p>There are quite a few speech recognition programs out there, of which <a href=\"http://www.nuance.com/naturallyspeaking/\" rel=\"noreferrer\">Dragon NaturallySpeaking</a> is, I think, one of the most widely used ones. I've used it myself, and have been impressed with its quality. That being a couple of years ago, I guess things have improved even further by now.</p>\n\n<h3>...but it ain't easy...</h3>\n\n<p>Even though it works amazingly well, I won't say it's an easy solution. It takes time to train the program, and even then, it'll make mistakes. It's painstakingly slow compared to typing, so I had to keep saying to myself \"Don't grab the keyboard, don't grab the keyboard, ...\" (after which I'd grab the keyboard anyway). I myself tend to mumble a bit, which didn't make things much better, either ;-). Especially the first weeks can be frustrating. You can even get <a href=\"http://www.ataword.com/voice.html\" rel=\"noreferrer\">voice-related problems</a> if you <a href=\"http://archives.cnn.com/2000/TECH/computing/05/23/voice.saving.tips.idg/\" rel=\"noreferrer\">strain your voice too much</a>.</p>\n\n<h3>...especially for programmers!</h3>\n\n<p>All in all, it's certainly a workable solution <strong>for people writing normal text/prose</strong>. As a programmer, you're in a completely different realm, for which there are no real solutions. Things might have changed by now, but I'd be surprised if they have.</p>\n\n<p>What's the problem? Most SR software is built to recognize normal language. Programmers write very cryptic stuff, and it's hard, if not impossible, to find software that does the conversion between normal language and code. For example, how would you dictate:</p>\n\n<pre><code>if (somevar == 'a')\n{\n print('You pressed a!');\n}\n</code></pre>\n\n<p>Using the commands in your average SR program, this is a huge pain: \"if space left bracket equal sign equal sign apostrophe spell a apostrophe ...\". And I'm not even talking about <em>navigating</em> your code. Ever noticed how much you're using the keyboard while programming, and how different that usage is from how a 'normal' user uses the keyboard?</p>\n\n<h3>How to make the best of it</h3>\n\n<p>Thus far, I've only worked with Dragon NaturallySpeaking (DNS), so I can only speak for that product. There are some interesting add-ons and websites targeted for people like programmers:</p>\n\n<ul>\n<li><a href=\"http://www.vocola.net\" rel=\"noreferrer\">Vocola</a> is an unofficial plugin that allows you to easily add your own commands to DNS. I found it essential, basically. You'll also be able to find command sets written by other programmers, for e.g. navigating code. It's based on a software package written in Python, so there are also some more advanced and fancy packages around. Also check out Vocola's <a href=\"http://vocola.net/VoiceResources.html\" rel=\"noreferrer\">Resources page</a>. (Warning: when I used it, there were some problems with installing Vocola; check out the newsgroup below for info!)</li>\n<li><a href=\"http://speechcomputing.com/\" rel=\"noreferrer\">SpeechComputing.com</a> is a forum/newsgroup with lots of interesting discussions. A good place to start.</li>\n</ul>\n\n<h3>Closing remarks</h3>\n\n<p>It seems that the best solution to this problem is, really:</p>\n\n<ul>\n<li>Find ways around actual coding.</li>\n<li>Try to recover. I'm somewhat reluctant to recommend this book, but it seems to work amazingly well for people with RSI/carpal tunnel and other chronic pain issues: <a href=\"https://rads.stackoverflow.com/amzn/click/com/0446675156\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">J.E. Sarno, Mindbody prescription</a>. I'm working with it right now, and I think it's definitely worth reading.</li>\n</ul>\n" }, { "answer_id": 400867, "author": "Scott Weinstein", "author_id": 25201, "author_profile": "https://Stackoverflow.com/users/25201", "pm_score": 2, "selected": false, "text": "<p>As mentioned above, Dragon Naturally Speaking is the best speech recognition software out there, however Microsoft Speech Recognition isn't far behind and comes bundled with Vista.</p>\n\n<p>Vocola has recently been ported to MSR, and has a .Net integration feature. </p>\n\n<p>A few tips</p>\n\n<ol>\n<li>Learning to dictate takes some time. Just because you can speak doesn't mean you know how to use speech recognition software</li>\n<li>Getting proficient with a mix of SR and keyboard/mouse is much easier than full hands-free operation.</li>\n<li>Use CodeRush or equivalent to type less. </li>\n</ol>\n" }, { "answer_id": 458717, "author": "Guillaume Marceau", "author_id": 35902, "author_profile": "https://Stackoverflow.com/users/35902", "pm_score": 2, "selected": false, "text": "<p>The gold standard for programming by voice is <a href=\"http://sourceforge.net/projects/voicecode/\" rel=\"nofollow noreferrer\">VoiceCode</a>. If I remember correctly, they supports C++ and Python.</p>\n" }, { "answer_id": 852182, "author": "max", "author_id": 82883, "author_profile": "https://Stackoverflow.com/users/82883", "pm_score": 2, "selected": false, "text": "<p>Dragon Naturally Speaking Preferred and Vocola. Autohotkey to automate as much as possible. Not easy to program though. I tried; almost impossible. Check out John Sarno's Healing Back Pain. It made me better. I'm back to programming all day!</p>\n" }, { "answer_id": 4594061, "author": "Grzegorz Wierzowiecki", "author_id": 544721, "author_profile": "https://Stackoverflow.com/users/544721", "pm_score": 2, "selected": false, "text": "<p>Another bit off-topic here, I've found that splitted keboard into two parts and other special keyboards helps, just check-out kinesis. I collected info about such hardware at diigo:</p>\n\n<ul>\n<li><a href=\"http://www.diigo.com/user/wierzowiecki/keyboard%20ergonomics\" rel=\"nofollow\">http://www.diigo.com/user/wierzowiecki/keyboard%20ergonomics</a></li>\n<li><a href=\"http://www.diigo.com/user/wierzowiecki/keyboard%20rsi\" rel=\"nofollow\">http://www.diigo.com/user/wierzowiecki/keyboard%20rsi</a> .</li>\n</ul>\n\n<p>What about direct links:</p>\n\n<ul>\n<li><a href=\"http://www.fentek-ind.com/ergo.htm\" rel=\"nofollow\">http://www.fentek-ind.com/ergo.htm</a> - different stuff</li>\n<li><a href=\"http://www.kinesis-ergo.com/contoured.htm\" rel=\"nofollow\">http://www.kinesis-ergo.com/contoured.htm</a> - Kinesis Advantage Contoured Keyboards (Programmable!)</li>\n<li><a href=\"http://www.kinesis-ergo.com/foot.htm\" rel=\"nofollow\">http://www.kinesis-ergo.com/foot.htm</a> some foot switches can be connected to keyboard (for example for window swiching)</li>\n<li><a href=\"http://www.kinesis-ergo.com/freestyle.htm\" rel=\"nofollow\">http://www.kinesis-ergo.com/freestyle.htm</a> - So far, I've found that even using two normal keyboards is better than one, so I think that splitted freestyle might work as well</li>\n<li><a href=\"http://www.typematrix.com/\" rel=\"nofollow\">http://www.typematrix.com/</a> - another solution</li>\n<li><a href=\"http://www.maltron.com/\" rel=\"nofollow\">http://www.maltron.com/</a> - sometimes when one hand suffers more than other typing with one hand</li>\n<li><a href=\"http://www.keybowl.com/\" rel=\"nofollow\">http://www.keybowl.com/</a> - this looks interesting as well</li>\n<li>I believe there are many other interesting solutions</li>\n</ul>\n\n<p>One more thing! Remember about breaks for exercises. Regular exercises (for example small exercise - every half \nand hour different one) make really really things better !</p>\n\n<ul>\n<li><a href=\"http://www.workrave.org/\" rel=\"nofollow\">http://www.workrave.org/</a> - this will remind you about breaks ;)</li>\n</ul>\n" }, { "answer_id": 7211144, "author": "Grzegorz Wierzowiecki", "author_id": 544721, "author_profile": "https://Stackoverflow.com/users/544721", "pm_score": 3, "selected": false, "text": "<p>For all Linux folks, I'd like to share some links.</p>\n\n<p>Let's begin from <a href=\"http://simon-listens.org\" rel=\"nofollow noreferrer\">Simon</a> - open source speech recognition software:</p>\n\n<ul>\n<li><a href=\"http://simon-listens.org\" rel=\"nofollow noreferrer\">Simon listens - non-profit organization for research and apprenticeship</a></li>\n<li><a href=\"http://simon-listens.blogspot.com/\" rel=\"nofollow noreferrer\">simon: Open-Source Speech Recognition</a> - related blog</li>\n<li><a href=\"http://htk.eng.cam.ac.uk/\" rel=\"nofollow noreferrer\">HTK speech recognition toolkit</a> - engine used internally</li>\n<li><a href=\"http://julius.sourceforge.jp/en_index.php\" rel=\"nofollow noreferrer\">Open-Source Large Vocabulary CSR Engine Julius</a></li>\n<li><a href=\"http://slashdot.org/story/08/01/19/1446213/Open-Source-Speech-Recognition\" rel=\"nofollow noreferrer\">Not on shlashdot about Simon fetures</a></li>\n</ul>\n\n<p>and some other:</p>\n\n<ul>\n<li><a href=\"http://live.gnome.org/GnomeVoiceControl\" rel=\"nofollow noreferrer\">Gnome Voice Control</a></li>\n<li><a href=\"https://wiki.ubuntu.com/SpeechRecognition\" rel=\"nofollow noreferrer\">https://wiki.ubuntu.com/SpeechRecognition</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Speech_recognition_in_Linux\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Speech_recognition_in_Linux</a></li>\n<li><a href=\"http://sourceforge.net/projects/voicecode/\" rel=\"nofollow noreferrer\">VoiceCode</a></li>\n</ul>\n\n<p>and</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/877508/need-text-to-speech-and-speech-recognition-tools-for-linux\">Related stackoverflow question about text to speech recognition tools for Linux.</a></li>\n</ul>\n" }, { "answer_id": 22183654, "author": "Steven Soroka", "author_id": 155585, "author_profile": "https://Stackoverflow.com/users/155585", "pm_score": 3, "selected": false, "text": "<p>Check out <a href=\"http://www.youtube.com/watch?v=8SkdfdXWYaI\">Using Python to Code by Voice</a>.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16868/" ]
Well the docs finally said it, I need to take it easy on my wrist for a few months. Being that I'm a .NET Developer this could end my livelihood for a little while, something I'm not anxious to do. That said, are there any good handsfree options for developers? Anyone had success using any of the speech recognition software out there? POSTSCRIPT: I've recovered my arm again to the point where two-handed programming isn't a problem. Dragon Naturally speaking worked well enough, but was slower, not like the keyboard where I was programming faster than I thought.
### It's out there, and it works... There are quite a few speech recognition programs out there, of which [Dragon NaturallySpeaking](http://www.nuance.com/naturallyspeaking/) is, I think, one of the most widely used ones. I've used it myself, and have been impressed with its quality. That being a couple of years ago, I guess things have improved even further by now. ### ...but it ain't easy... Even though it works amazingly well, I won't say it's an easy solution. It takes time to train the program, and even then, it'll make mistakes. It's painstakingly slow compared to typing, so I had to keep saying to myself "Don't grab the keyboard, don't grab the keyboard, ..." (after which I'd grab the keyboard anyway). I myself tend to mumble a bit, which didn't make things much better, either ;-). Especially the first weeks can be frustrating. You can even get [voice-related problems](http://www.ataword.com/voice.html) if you [strain your voice too much](http://archives.cnn.com/2000/TECH/computing/05/23/voice.saving.tips.idg/). ### ...especially for programmers! All in all, it's certainly a workable solution **for people writing normal text/prose**. As a programmer, you're in a completely different realm, for which there are no real solutions. Things might have changed by now, but I'd be surprised if they have. What's the problem? Most SR software is built to recognize normal language. Programmers write very cryptic stuff, and it's hard, if not impossible, to find software that does the conversion between normal language and code. For example, how would you dictate: ``` if (somevar == 'a') { print('You pressed a!'); } ``` Using the commands in your average SR program, this is a huge pain: "if space left bracket equal sign equal sign apostrophe spell a apostrophe ...". And I'm not even talking about *navigating* your code. Ever noticed how much you're using the keyboard while programming, and how different that usage is from how a 'normal' user uses the keyboard? ### How to make the best of it Thus far, I've only worked with Dragon NaturallySpeaking (DNS), so I can only speak for that product. There are some interesting add-ons and websites targeted for people like programmers: * [Vocola](http://www.vocola.net) is an unofficial plugin that allows you to easily add your own commands to DNS. I found it essential, basically. You'll also be able to find command sets written by other programmers, for e.g. navigating code. It's based on a software package written in Python, so there are also some more advanced and fancy packages around. Also check out Vocola's [Resources page](http://vocola.net/VoiceResources.html). (Warning: when I used it, there were some problems with installing Vocola; check out the newsgroup below for info!) * [SpeechComputing.com](http://speechcomputing.com/) is a forum/newsgroup with lots of interesting discussions. A good place to start. ### Closing remarks It seems that the best solution to this problem is, really: * Find ways around actual coding. * Try to recover. I'm somewhat reluctant to recommend this book, but it seems to work amazingly well for people with RSI/carpal tunnel and other chronic pain issues: [J.E. Sarno, Mindbody prescription](https://rads.stackoverflow.com/amzn/click/com/0446675156). I'm working with it right now, and I think it's definitely worth reading.
88,011
<p>For various reasons, such as cookies, SEO, and to keep things simple, I would like to make apache automatically redirect any requests for <a href="http://www.foobar.com/anything" rel="nofollow noreferrer">http://www.foobar.com/anything</a> to <a href="http://foobar.com/anything" rel="nofollow noreferrer">http://foobar.com/anything</a>. The best I could come up with is a mod_rewrite-based monstrosity, is there some easy simple way to tell it "Redirect all requests for domain ABC to XYZ"? </p> <p>PS: I found <a href="https://stackoverflow.com/questions/50931/redirecting-non-www-url-to-www">this somewhat related question</a>, but it's for IIS and does the opposite of what I want. Also it's still complex.</p>
[ { "answer_id": 88034, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]\nRewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]\n</code></pre>\n\n<p>That should do the trick.</p>\n" }, { "answer_id": 88042, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 2, "selected": false, "text": "<p>Pretty simple if you use mod_rewrite, as we all do ;)</p>\n\n<p>This is part of the .htaccess from my live website:</p>\n\n<pre><code>RewriteEngine on\n\n# Catches www.infinite-labs.net and redirects to the\n# same page on infinite-labs.net to normalize things.\n\nRewriteCond %{HTTP_HOST} ^www\\.infinite-labs\\.net$\nRewriteRule ^(.*)$ http://infinite-labs.net/$1 [R=301,L]\n</code></pre>\n" }, { "answer_id": 88044, "author": "TobiX", "author_id": 13258, "author_profile": "https://Stackoverflow.com/users/13258", "pm_score": 4, "selected": true, "text": "<p>It's as easy as:</p>\n\n<pre><code>&lt;VirtualHost 10.0.0.1:80&gt;\n ServerName www.example.com\n Redirect permanent / http://example.com/\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>Adapt host names and IPs as needed :)</p>\n" }, { "answer_id": 88046, "author": "sirprize", "author_id": 12902, "author_profile": "https://Stackoverflow.com/users/12902", "pm_score": 0, "selected": false, "text": "<p>Since you mentioned using mod_rewrite, I'd suggest a simple rule in your .htaccess - doesn't seem monstrous to me :)</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^www\\.foobar\\.com$ [NC]\nRewriteRule ^(.*)$ http://foobar.com/$1 [L,R=301]\n</code></pre>\n" }, { "answer_id": 88071, "author": "Michael", "author_id": 9316, "author_profile": "https://Stackoverflow.com/users/9316", "pm_score": 1, "selected": false, "text": "<p>Use an .htaccess file with some mod_rewrite rules:</p>\n\n<pre><code>RewriteEngine On\nRewriteRule ^www.SERVERNAME(.*) http://SERVERNAME$1 [L,QSA]\n</code></pre>\n\n<p>I'm not sure I got the syntax right with the <code>$1</code> there, but it's well documented. L sends a location: header to the browser, and QSA means Query String Append.</p>\n" }, { "answer_id": 697825, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>simpler and easier to copy from site to site:</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^www\\.(.+)$\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
For various reasons, such as cookies, SEO, and to keep things simple, I would like to make apache automatically redirect any requests for <http://www.foobar.com/anything> to <http://foobar.com/anything>. The best I could come up with is a mod\_rewrite-based monstrosity, is there some easy simple way to tell it "Redirect all requests for domain ABC to XYZ"? PS: I found [this somewhat related question](https://stackoverflow.com/questions/50931/redirecting-non-www-url-to-www), but it's for IIS and does the opposite of what I want. Also it's still complex.
It's as easy as: ``` <VirtualHost 10.0.0.1:80> ServerName www.example.com Redirect permanent / http://example.com/ </VirtualHost> ``` Adapt host names and IPs as needed :)
88,078
<p>I wand to construct an MSI which, in its installation process, will deploy itself along with its contained Files/Components, to the TargetDir.</p> <p>So MyApp.msi contains MyApp.exe and MyAppBootstrapperEmpty.exe (with no resources) in its File Table.</p> <p>The user launches a MyAppBootstrapperPackaged.exe (containing MyApp.msi as a resource, obtained from the internet somewhere, or email or otherwise). MyAppBootStrapperPackaged.exe extracts MyApp.msi to a temp folder and executes it via msiexec.exe.</p> <p>After the msiexec.exe process completes, I want MyApp.msi, MyBootstrapperEmpty.exe (AND MyApp.exe in %ProgramFiles%\MyApp folder so MyApp.exe can be assured access to MyApp.msi when it runs (for creating the below-mentioned packaged content).</p> <p>MyAppBootstrapper*.exe could try and copy MyApp.msi to %ProgramFiles%\MyApp folder, but would need elevation to do so, and would not allow for its removal via Windows Installer uninstall process (from Add/Remove Programs or otherwise), which should be preserved.</p> <p>Obviously (I think it's obvious - am I wrong?) I can't include the MSI as a file in my Media/CAB (chicken and egg scenario), so I believe it would have to be done via a Custom Action before the install process, adding the original MSI to the MSI DB's Media/CAB and the appropriate entry in the File table on the fly. Can this be done and if so how?</p> <p>Think of a content distribution model where content files are only ever to be distributed together with the App. Content is produced by the end user via the App at run time, and packaged into a distributable EXE which includes both the App and the content.</p> <p>MyApp's installer must remain an MSI, but may be executed by a Bootstrapper EXE. The installed MyApp.exe must have access to both MyApp.msi and EXE is to be "assembled" at runtime by the App from a base (empty) MyAppBootstrapper.exe, which is also installed by the MSI, and the content created by the end-user. The EXE's resource MSI must be the same as that used to install the App which is doing the runtime packaging.</p> <p>WIX is not to be installed with MyApp.</p> <p>There can be no network dependencies at run-/packaging- time (i.e. can't do the packaging via a Webservice - must be done locally).</p> <p>I am familiar with (and using) Custom Actions (managed and unmanaged, via DTF and otherwise).</p>
[ { "answer_id": 88366, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "<p>So if I understand, then I think I would have the app create a transform (MST) that has the content files and apply that to the base MSI. I'm still not convinced that I understand though. :)</p>\n" }, { "answer_id": 90094, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Having one .MSI package launch another .MSI package from \"within\" itself is called a <em>nested install</em>, and it's <a href=\"http://blogs.msdn.com/windows_installer_team/archive/2006/05/12/595950.aspx\" rel=\"nofollow noreferrer\" title=\"bad juju\">bad juju</a> (see Rule 20). Windows Installer has some global data that it uses to manage the current install, and it doesn't handle well multiple installs at the same time. For the same reason, if you start one install and then try to start another while the first is still in progress, you'll usually see a pop-up to the effect of \"another install in progress, please wait until it's done\".</p>\n\n<p>You can have a program, usually called a bootstrapper (I think that's what you're referring to) which is itself not an install package, but which <em>contains</em> an install package (such as an .MSI or an .EXE) as a resource, possibly compressed. The action of the bootstrapper program is to extract/expand the resource to a file, commonly in a <code>%TEMP%</code> directory, then either launch the extracted .EXE or run MSIEXEC on the extracted .MSI. The bootstrapper can contain multiple resources and extract+install them one by one, if you need to install prerequisites before the main package. Or you can ship multiple packages as separate files, and have the bootstrapper execute/install them directly from the distribution media one by one, or copy them down to the target machine and run the series of install from there, or...</p>\n\n<p>WiX itself does not get installed, no. It's a tool with which .MSI packages can be built. The WiX project has on its wishlist a generic bootstrapper program, but it hasn't been implemented yet. There are other bootstrappers available, e.g. <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163899.aspx\" rel=\"nofollow noreferrer\" title=\"this one\">this one</a>.</p>\n\n<p>You won't need a custom action -- in fact, since the bootstrapper isn't itself a Windows Installer installation package, \"custom action\" has no meaning to it. And, if you're familiar enough with CAs to know about managed/unmanaged/DTF, then you know enough to avoid custom actions whenever you can. (grin)</p>\n" }, { "answer_id": 106276, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 2, "selected": false, "text": "<p>I think it's much easier for your bootstrapper to extract MSI file to some predefined location rather than to the temp folder. For example, to C:\\Documents and Settings\\All Users\\Application Data\\My Company\\My Product Install Cache. After installation finishes bootstrapper would leave MSI file sitting there. If at some stage user decides to reinstall your product Windows Installer will be able to locate source MSI file.</p>\n\n<p>Also, add path to this file to <a href=\"http://msdn.microsoft.com/en-us/library/aa371201.aspx\" rel=\"nofollow noreferrer\">RemoveFile table</a> so that it gets deleted on uninstall. You can use <a href=\"http://wix.sourceforge.net/manual-wix2/wix_xsd_removefile.htm\" rel=\"nofollow noreferrer\">RemoveFile element</a> in WiX for that.</p>\n" }, { "answer_id": 300523, "author": "saschabeaumont", "author_id": 592, "author_profile": "https://Stackoverflow.com/users/592", "pm_score": 0, "selected": false, "text": "<p>I'd configure the MSI cache path to a known location.</p>\n\n<p>Then at runtime if you need to \"edit\" the MSI use VBScript or similar.</p>\n\n<p>But still, I ask WHY!?!</p>\n" }, { "answer_id": 559407, "author": "Wim Coenen", "author_id": 52626, "author_profile": "https://Stackoverflow.com/users/52626", "pm_score": 4, "selected": true, "text": "<p>Add an uncompressed medium to your wxs like this:</p>\n\n<pre><code>&lt;Media Id='2'/&gt;\n</code></pre>\n\n<p>And then create a component with a File element like this:</p>\n\n<pre><code>&lt;File Source='/path/to/myinstaller.msi' Compressed='no' DiskId='2' /&gt;\n</code></pre>\n\n<p>This will make the installer look for a file called \"myinstaller.msi\" on the installation medium, in the same folder as the msi that is being installed. The source path above should point to a dummy file, it is only there to appease wix.</p>\n\n<p><strong>Edit</strong>: The following sample test.wxs demonstrates that it works. It produces a test.msi file which installs itself to c:\\program files\\test. Note that you need to put a dummy test.msi file in the same folder as text.wxs to appease wix.</p>\n\n<pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt;\n&lt;Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'&gt;\n &lt;Product\n Name='ProductName'\n Id='*'\n Language='1033'\n Version='0.0.1'\n Manufacturer='ManufacturerName' &gt;\n &lt;Package\n Keywords='Installer'\n Description='Installer which installs itself'\n Manufacturer='ManufactererName'\n InstallerVersion='100'\n Languages='1033'\n Compressed='yes'\n SummaryCodepage='1252'/&gt;\n\n &lt;Media Id='1' Cabinet='test.cab' EmbedCab='yes'/&gt; \n &lt;Media Id='2' /&gt; \n\n &lt;Directory Id='TARGETDIR' Name=\"SourceDir\"&gt;\n &lt;Directory Id='ProgramFilesFolder'&gt;\n &lt;Directory Id='TestFolder' Name='Test' &gt;\n &lt;Component Id=\"InstallMyself\"&gt;\n &lt;File Source=\"./test.msi\" Compressed=\"no\" DiskId=\"2\" /&gt;\n &lt;/Component&gt;\n &lt;/Directory&gt;\n &lt;/Directory&gt;\n &lt;/Directory&gt;\n\n &lt;Feature\n Id='Complete'\n Display='expand'\n Level='1'\n Title='Copy msi file to program files folder'\n Description='Test'&gt;\n\n &lt;ComponentRef Id=\"InstallMyself\" /&gt;\n &lt;/Feature&gt;\n\n &lt;/Product&gt;\n&lt;/Wix&gt;\n</code></pre>\n" }, { "answer_id": 840488, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I am also working on a way to deploy multiple MSI files. I have a bootstrapper.exe program that bundles the MSI files and runs them one at a time. This solves my problem for most cases.</p>\n\n<p>The case it does not solve is GPO (Global Policy Object) distribution of the install. GPO requires a dot-msi file to run an install. </p>\n\n<p>To do this here's what I did which almost solved the problem (but not quite). I put the dot-msi files in the file table of an installer and put my bootstrapper in the binary table and run it from a custom action inserted after InstallFinalize in the InstallExecuteSequence. Of course the bootstrapper won't be able to run other MSI's because the top level MSI holds the _MSIExecute mutex. </p>\n\n<p>It was pretty easy to get a little further. I made the bootstrapper return control to the top level installer and continute. And then I added a WaitForSingleObject call to wait for the top level install to finish, and the bootstrapper can then continue to finish the install.</p>\n\n<p>My problem is that the GPO installation happens at boot time and the top level install completes before the sub installers are done and GPO reboots the machine. </p>\n\n<p>The toplevel install also returns a success status when the install may actually fail later on.</p>\n\n<p>I'm still looking for a way to block the top level install from completing until after the bootstrapper completes.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8787/" ]
I wand to construct an MSI which, in its installation process, will deploy itself along with its contained Files/Components, to the TargetDir. So MyApp.msi contains MyApp.exe and MyAppBootstrapperEmpty.exe (with no resources) in its File Table. The user launches a MyAppBootstrapperPackaged.exe (containing MyApp.msi as a resource, obtained from the internet somewhere, or email or otherwise). MyAppBootStrapperPackaged.exe extracts MyApp.msi to a temp folder and executes it via msiexec.exe. After the msiexec.exe process completes, I want MyApp.msi, MyBootstrapperEmpty.exe (AND MyApp.exe in %ProgramFiles%\MyApp folder so MyApp.exe can be assured access to MyApp.msi when it runs (for creating the below-mentioned packaged content). MyAppBootstrapper\*.exe could try and copy MyApp.msi to %ProgramFiles%\MyApp folder, but would need elevation to do so, and would not allow for its removal via Windows Installer uninstall process (from Add/Remove Programs or otherwise), which should be preserved. Obviously (I think it's obvious - am I wrong?) I can't include the MSI as a file in my Media/CAB (chicken and egg scenario), so I believe it would have to be done via a Custom Action before the install process, adding the original MSI to the MSI DB's Media/CAB and the appropriate entry in the File table on the fly. Can this be done and if so how? Think of a content distribution model where content files are only ever to be distributed together with the App. Content is produced by the end user via the App at run time, and packaged into a distributable EXE which includes both the App and the content. MyApp's installer must remain an MSI, but may be executed by a Bootstrapper EXE. The installed MyApp.exe must have access to both MyApp.msi and EXE is to be "assembled" at runtime by the App from a base (empty) MyAppBootstrapper.exe, which is also installed by the MSI, and the content created by the end-user. The EXE's resource MSI must be the same as that used to install the App which is doing the runtime packaging. WIX is not to be installed with MyApp. There can be no network dependencies at run-/packaging- time (i.e. can't do the packaging via a Webservice - must be done locally). I am familiar with (and using) Custom Actions (managed and unmanaged, via DTF and otherwise).
Add an uncompressed medium to your wxs like this: ``` <Media Id='2'/> ``` And then create a component with a File element like this: ``` <File Source='/path/to/myinstaller.msi' Compressed='no' DiskId='2' /> ``` This will make the installer look for a file called "myinstaller.msi" on the installation medium, in the same folder as the msi that is being installed. The source path above should point to a dummy file, it is only there to appease wix. **Edit**: The following sample test.wxs demonstrates that it works. It produces a test.msi file which installs itself to c:\program files\test. Note that you need to put a dummy test.msi file in the same folder as text.wxs to appease wix. ``` <?xml version='1.0' encoding='utf-8'?> <Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'> <Product Name='ProductName' Id='*' Language='1033' Version='0.0.1' Manufacturer='ManufacturerName' > <Package Keywords='Installer' Description='Installer which installs itself' Manufacturer='ManufactererName' InstallerVersion='100' Languages='1033' Compressed='yes' SummaryCodepage='1252'/> <Media Id='1' Cabinet='test.cab' EmbedCab='yes'/> <Media Id='2' /> <Directory Id='TARGETDIR' Name="SourceDir"> <Directory Id='ProgramFilesFolder'> <Directory Id='TestFolder' Name='Test' > <Component Id="InstallMyself"> <File Source="./test.msi" Compressed="no" DiskId="2" /> </Component> </Directory> </Directory> </Directory> <Feature Id='Complete' Display='expand' Level='1' Title='Copy msi file to program files folder' Description='Test'> <ComponentRef Id="InstallMyself" /> </Feature> </Product> </Wix> ```
88,094
<p>I seem to make this mistake every time I set up a new development box. Is there a way to make sure you don't have to manually assign rights for the ASPNET user? I usually install .Net then IIS, then Visual Studio but it seems I still have to manually assign rights to the ASPNET user to get everything running correctly. Is my install order wrong?</p>
[ { "answer_id": 88124, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 3, "selected": true, "text": "<p>Install IIS, then .NET. The .NET installation will automatically register the needed things with IIS.</p>\n\n<p>If you install .NET first, run this:</p>\n\n<pre><code>%windir%\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis.exe -i\n</code></pre>\n\n<p>to run the registration parts, and </p>\n\n<pre><code>%windir%\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis.exe -ga userA\n</code></pre>\n\n<p>to set up the security rights for userA</p>\n" }, { "answer_id": 88134, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 1, "selected": false, "text": "<p>If you install first IIS and then .Net, it'll be OK.</p>\n\n<p>In your scenario - use <a href=\"http://msdn.microsoft.com/en-us/library/k6h9cz8h(VS.80).aspx\" rel=\"nofollow noreferrer\">Aspnet_regiis.exe -qa <em>user</em></a> (not available for .Net &lt; 2.0)</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16636/" ]
I seem to make this mistake every time I set up a new development box. Is there a way to make sure you don't have to manually assign rights for the ASPNET user? I usually install .Net then IIS, then Visual Studio but it seems I still have to manually assign rights to the ASPNET user to get everything running correctly. Is my install order wrong?
Install IIS, then .NET. The .NET installation will automatically register the needed things with IIS. If you install .NET first, run this: ``` %windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i ``` to run the registration parts, and ``` %windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ga userA ``` to set up the security rights for userA
88,096
<p>I am working on a project with peek performance requirements, so we need to bulk (batch?) several operations (for example persisting the data to a database) for efficiency.</p> <p>However, I want our code to maintain an easy to understand flow, like:</p> <pre><code>input = Read(); parsed = Parse(input); if (parsed.Count &gt; 10) { status = Persist(parsed); ReportSuccess(status); return; } ReportFailure(); </code></pre> <p>The feature I'm looking for here is automatically have Persist() happen in bulks (and ergo asynchronously), but behave to its user as if it's synchronous (user should block until the bulk action completes). I want the implementor to be able to implement Persist(ICollection).</p> <p>I looked into flow-based programming, with which I am not highly familiar. I saw one library for fbp in C# <a href="http://www.jpaulmorrison.com/fbp/" rel="nofollow noreferrer">here</a>, and played a bit with Microsoft's Workflow Foundation, but my impression is that both are overkill for what I need. What would you use to implement a bulked flow behavior?</p> <p>Note that I would like to get code that is exactly like what I wrote (simple to understand &amp; debug), so solutions that involve yield or configuration in order to connect flows to one another are inadequate for my purpose. Also, <a href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern" rel="nofollow noreferrer">chaining</a> is not what I'm looking for - I don't want to first build a chain and then run it, I want code that looks as if it is a simple flow ("Do A, Do B, if C then do D").</p>
[ { "answer_id": 88169, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>I don't know if this is what you need, because it's sqlserver based, but have you tried taking a look to <a href=\"http://en.wikipedia.org/wiki/SQL_Server_Integration_Services\" rel=\"nofollow noreferrer\">SSIS</a> and or <a href=\"http://en.wikipedia.org/wiki/Data_Transformation_Services\" rel=\"nofollow noreferrer\">DTS</a>?</p>\n" }, { "answer_id": 794619, "author": "JohnIdol", "author_id": 1311500, "author_profile": "https://Stackoverflow.com/users/1311500", "pm_score": 1, "selected": false, "text": "<p>Common problem - instead of calling Persist I usually load up commands (or smt along those lines) into a Persistor class then after the loop is finished I call Persistor.Persist to persist the batch. </p>\n\n<p>Just a few pointers - If you're generating sql the commands you add to the persistor can represent your queries somehow (with built-in objects, custom objects or just query strings). If you're calling stored procedures you can use the commands to append stuff to a piece of xml tha will be passed down to the SP when you call the persist method. </p>\n\n<p>hope it helps - Pretty sure there's a pattern for this but dunno the name :)</p>\n" }, { "answer_id": 816162, "author": "Khurram Aziz", "author_id": 96966, "author_profile": "https://Stackoverflow.com/users/96966", "pm_score": 0, "selected": false, "text": "<p>One simple thing that you can do is to create a MemoryBuffer where you push the messages which simply add them to a list and returns. This MemoryBuffer has a System.Timers.Timer which gets invoked periodically and do the \"actual\" updates.</p>\n\n<p>One such implementation can be found in a Syslog Server (C#) at <a href=\"http://www.fantail.net.nz/wordpress/?p=5\" rel=\"nofollow noreferrer\">http://www.fantail.net.nz/wordpress/?p=5</a> in which the syslog messages gets logged to a SQL Server periodically in a batch.</p>\n\n<p>This approach might not be good if the info being pushed to database is important, as if something goes wrong, you will lose the messages in MemoryBuffer.</p>\n" }, { "answer_id": 873821, "author": "Robin", "author_id": 108040, "author_profile": "https://Stackoverflow.com/users/108040", "pm_score": 0, "selected": false, "text": "<p>How about using the <code>BackgroundWorker</code> class to persist each item asynchronously on a separate thread? For example:</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Threading;\n\nclass PersistenceManager\n{\n public void Persist(ICollection persistable)\n {\n // initialize a list of background workers\n var backgroundWorkers = new List&lt;BackgroundWorker&gt;();\n\n // launch each persistable item in a background worker on a separate thread\n foreach (var persistableItem in persistable)\n {\n var worker = new BackgroundWorker();\n worker.DoWork += new DoWorkEventHandler(worker_DoWork);\n backgroundWorkers.Add(worker);\n worker.RunWorkerAsync(persistableItem);\n }\n\n // wait for all the workers to finish\n while (true)\n {\n // sleep a little bit to give the workers a chance to finish\n Thread.Sleep(100);\n\n // continue looping until all workers are done processing\n if (backgroundWorkers.Exists(w =&gt; w.IsBusy)) continue;\n\n break;\n }\n\n // dispose all the workers\n foreach (var w in backgroundWorkers) w.Dispose();\n }\n\n void worker_DoWork(object sender, DoWorkEventArgs e)\n {\n var persistableItem = e.Argument;\n // TODO: add logic here to save the persistableItem to the database\n }\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
I am working on a project with peek performance requirements, so we need to bulk (batch?) several operations (for example persisting the data to a database) for efficiency. However, I want our code to maintain an easy to understand flow, like: ``` input = Read(); parsed = Parse(input); if (parsed.Count > 10) { status = Persist(parsed); ReportSuccess(status); return; } ReportFailure(); ``` The feature I'm looking for here is automatically have Persist() happen in bulks (and ergo asynchronously), but behave to its user as if it's synchronous (user should block until the bulk action completes). I want the implementor to be able to implement Persist(ICollection). I looked into flow-based programming, with which I am not highly familiar. I saw one library for fbp in C# [here](http://www.jpaulmorrison.com/fbp/), and played a bit with Microsoft's Workflow Foundation, but my impression is that both are overkill for what I need. What would you use to implement a bulked flow behavior? Note that I would like to get code that is exactly like what I wrote (simple to understand & debug), so solutions that involve yield or configuration in order to connect flows to one another are inadequate for my purpose. Also, [chaining](http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern) is not what I'm looking for - I don't want to first build a chain and then run it, I want code that looks as if it is a simple flow ("Do A, Do B, if C then do D").
Common problem - instead of calling Persist I usually load up commands (or smt along those lines) into a Persistor class then after the loop is finished I call Persistor.Persist to persist the batch. Just a few pointers - If you're generating sql the commands you add to the persistor can represent your queries somehow (with built-in objects, custom objects or just query strings). If you're calling stored procedures you can use the commands to append stuff to a piece of xml tha will be passed down to the SP when you call the persist method. hope it helps - Pretty sure there's a pattern for this but dunno the name :)
88,235
<p>Recently I ran into this error in my web application:</p> <blockquote> <p>java.lang.OutOfMemoryError: PermGen space</p> </blockquote> <p>It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6. Apparently this can occur after redeploying an application a few times.</p> <p>What causes it and what can be done to avoid it? How do I fix the problem?</p>
[ { "answer_id": 88262, "author": "Chris", "author_id": 16907, "author_profile": "https://Stackoverflow.com/users/16907", "pm_score": 10, "selected": true, "text": "<p>The solution was to add these flags to JVM command line when Tomcat is started:</p>\n<pre><code>-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled\n</code></pre>\n<p>You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the &quot;Java&quot; tab, add the arguments to the &quot;Java Options&quot; box. Click &quot;OK&quot; and then restart the service.</p>\n<p>If you get an error <em>the specified service does not exist as an installed service</em> you should run:</p>\n<pre><code>tomcat6w //ES//servicename\n</code></pre>\n<p>where <em><strong>servicename</strong></em> is the name of the server as viewed in services.msc</p>\n<p>Source: orx's comment on <a href=\"https://web.archive.org/web/20160124133922/http://www.jroller.com/agileanswers/entry/preventing_java_s_java_lang\" rel=\"noreferrer\">Eric's Agile Answers</a>.</p>\n" }, { "answer_id": 88307, "author": "Jeremy", "author_id": 4419, "author_profile": "https://Stackoverflow.com/users/4419", "pm_score": 4, "selected": false, "text": "<p>Alternatively, you can switch to JRockit which handling permgen differently then sun's jvm. It generally has better performance as well.</p>\n\n<p><a href=\"http://www.oracle.com/technetwork/middleware/jrockit/overview/index.html\" rel=\"noreferrer\">http://www.oracle.com/technetwork/middleware/jrockit/overview/index.html</a></p>\n" }, { "answer_id": 89392, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 2, "selected": false, "text": "<p><a href=\"/questions/tagged/jrockit\" class=\"post-tag\" title=\"show questions tagged &#39;jrockit&#39;\" rel=\"tag\">jrockit</a> resolved this for me as well; however, I noticed that the servlet restart times were much worse, so while it was better in production, it was kind of a drag in development.</p>\n" }, { "answer_id": 89748, "author": "user17163", "author_id": 17163, "author_profile": "https://Stackoverflow.com/users/17163", "pm_score": 5, "selected": false, "text": "<p>Use the command line parameter <code>-XX:MaxPermSize=128m</code> for a Sun JVM (obviously substituting 128 for whatever size you need).</p>\n" }, { "answer_id": 343595, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<p>App server PermGen errors that happen after multiple deployments are most likely caused by references held by the container into your old apps' classloaders. For example, using a custom log level class will cause references to be held by the app server's classloader. You can detect these inter-classloader leaks by using modern (JDK6+) JVM analysis tools such as jmap and jhat to look at which classes continue to be held in your app, and redesigning or eliminating their use. Usual suspects are databases, loggers, and other base-framework-level libraries.</p>\n\n<p>See <a href=\"http://frankkieviet.blogspot.ca/2006/10/classloader-leaks-dreaded-permgen-space.html\" rel=\"noreferrer\">Classloader leaks: the dreaded \"java.lang.OutOfMemoryError: PermGen space\" exception</a>, and especially its <a href=\"http://frankkieviet.blogspot.ca/2006/10/how-to-fix-dreaded-permgen-space.html\" rel=\"noreferrer\">followup post</a>.</p>\n" }, { "answer_id": 636607, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Try <code>-XX:MaxPermSize=256m</code> and if it persists, try <code>-XX:MaxPermSize=512m</code></p>\n" }, { "answer_id": 636623, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": "<p>The configuration of the memory depends on the nature of your app.</p>\n\n<p>What are you doing?</p>\n\n<p>What's the amount of transactions precessed?</p>\n\n<p>How much data are you loading?</p>\n\n<p>etc.</p>\n\n<p>etc.</p>\n\n<p>etc</p>\n\n<p>Probably you could profile your app and start cleaning up some modules from your app. </p>\n\n<blockquote>\n <p><em>Apparently this can occur after redeploying an application a few times</em></p>\n</blockquote>\n\n<p>Tomcat has hot deploy but it consumes memory. Try restarting your container once in a while. Also you will need to know the amount of memory needed to run in production mode, this seems a good time for that research. </p>\n" }, { "answer_id": 835269, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>You better try <strong><code>-XX:MaxPermSize=128M</code></strong> rather than <code>-XX:MaxPermGen=128M</code>. </p>\n\n<p>I can not tell the precise use of this memory pool, but it have to do with the number of classes loaded into the JVM. (Thus enabling class unloading for tomcat can resolve the problem.) If your applications generates and compiles classes on the run it is more likely to need a memory pool bigger than the default. </p>\n" }, { "answer_id": 1067325, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I have a combination of Hibernate+Eclipse RCP, tried using <code>-XX:MaxPermSize=512m</code> and <code>-XX:PermSize=512m</code> and it seems to be working for me.</p>\n" }, { "answer_id": 2726885, "author": "sandeep", "author_id": 327487, "author_profile": "https://Stackoverflow.com/users/327487", "pm_score": 2, "selected": false, "text": "<p>Set <code>-XX:PermSize=64m -XX:MaxPermSize=128m</code>. Later on you may also try increasing <code>MaxPermSize</code>. Hope it'll work. The same works for me. Setting only <code>MaxPermSize</code> didn't worked for me.</p>\n" }, { "answer_id": 3745669, "author": "Tony Ennis", "author_id": 449693, "author_profile": "https://Stackoverflow.com/users/449693", "pm_score": 2, "selected": false, "text": "<p>They Say that the latest rev of Tomcat (6.0.28 or 6.0.29) handles the task of redeploying servlets <strong>much</strong> better.</p>\n" }, { "answer_id": 3753934, "author": "Ross Peoples", "author_id": 156588, "author_profile": "https://Stackoverflow.com/users/156588", "pm_score": 2, "selected": false, "text": "<p>\"They\" are wrong because I'm running 6.0.29 and have the same problem even after setting all of the options. As Tim Howland said above, these options only put off the inevitable. They allow me to redeploy 3 times before hitting the error instead of every time I redeploy.</p>\n" }, { "answer_id": 4214895, "author": "Hrishikesh Kumar", "author_id": 512126, "author_profile": "https://Stackoverflow.com/users/512126", "pm_score": 2, "selected": false, "text": "<p>In case you are getting this in the eclipse IDE, even after setting the parameters \n<code>--launcher.XXMaxPermSize</code>, <code>-XX:MaxPermSize</code>, etc, still if you are getting the same error, it most likely is that the eclipse is using a buggy version of JRE which would have been installed by some third party applications and set to default. These buggy versions do not pick up the PermSize parameters and so no matter whatever you set, you still keep getting these memory errors. So, in your eclipse.ini add the following parameters: </p>\n\n<pre><code>-vm &lt;path to the right JRE directory&gt;/&lt;name of javaw executable&gt;\n</code></pre>\n\n<p>Also make sure you set the default JRE in the preferences in the eclipse to the correct version of java.</p>\n" }, { "answer_id": 4307335, "author": "Daniel", "author_id": 524291, "author_profile": "https://Stackoverflow.com/users/524291", "pm_score": 2, "selected": false, "text": "<p>The only way that worked for me was with the JRockit JVM. I have MyEclipse 8.6.</p>\n\n<p>The JVM's heap stores all the objects generated by a running Java program. Java uses the <code>new</code> operator to create objects, and memory for new objects is allocated on the heap at run time. Garbage collection is the mechanism of automatically freeing up the memory contained by the objects that are no longer referenced by the program.</p>\n" }, { "answer_id": 4350922, "author": "Hugo Mendoza", "author_id": 530019, "author_profile": "https://Stackoverflow.com/users/530019", "pm_score": 4, "selected": false, "text": "<p>I had the problem we are talking about here, my scenario is eclipse-helios + tomcat + jsf and what you were doing is making a deploy a simple application to tomcat. I was showing the same problem here, solved it as follows. </p>\n\n<p>In eclipse go to <strong>servers</strong> tab double click on the registered server in my case tomcat 7.0, it opens my file server General registration information. On the section <strong>\"General Information\"</strong> click on the link <strong>\"Open launch configuration\"</strong> , this opens the execution of server options in the Arguments tab in VM arguments added in the end these two entries</p>\n\n<pre><code>-XX: MaxPermSize = 512m\n-XX: PermSize = 512m\n</code></pre>\n\n<p>and ready.</p>\n" }, { "answer_id": 5361829, "author": "Maze", "author_id": 549635, "author_profile": "https://Stackoverflow.com/users/549635", "pm_score": 2, "selected": false, "text": "<p>I run into exactly the same problem, but unfortunately none of the suggested solutions really worked for me. The problem did not happen during deployment, and I was neither doing any hot deployments.</p>\n\n<p>In my case the problem occurred every time at the same point during the execution of my web-application, while connecting (via hibernate) to the database.</p>\n\n<p><a href=\"http://jroller.com/agileanswers/entry/preventing_java_s_java_lang\" rel=\"nofollow\">This link</a> (also mentioned earlier) did provide enough insides to resolve the problem. Moving the jdbc-(mysql)-driver out of the WEB-INF and into the jre/lib/ext/ folder seems to have solved the problem. This is not the ideal solution, since upgrading to a newer JRE would require you to reinstall the driver.\nAnother candidate that could cause similar problems is log4j, so you might want to move that one as well</p>\n" }, { "answer_id": 6249914, "author": "Ioannis Sermetziadis", "author_id": 785622, "author_profile": "https://Stackoverflow.com/users/785622", "pm_score": 3, "selected": false, "text": "<p>Also if you are using log4j in your webapp, check this paragraph in log4j <a href=\"http://logging.apache.org/log4j/1.2/faq.html#a3.6\" rel=\"nofollow\">documentation</a>.</p>\n\n<p>It seems that if you are using <code>PropertyConfigurator.configureAndWatch(\"log4j.properties\")</code>, you cause memory leaks when you undeploy your webapp. </p>\n" }, { "answer_id": 6290834, "author": "Edward Torbett", "author_id": 1506341, "author_profile": "https://Stackoverflow.com/users/1506341", "pm_score": 5, "selected": false, "text": "<p>I've been butting my head against this problem while deploying and undeploying a complex web application too, and thought I'd add an explanation and my solution.</p>\n\n<p>When I deploy an application on Apache Tomcat, a new ClassLoader is created for that app. The ClassLoader is then used to load all the application's classes, and on undeploy, everything's supposed to go away nicely. However, in reality it's not quite as simple.</p>\n\n<p>One or more of the classes created during the web application's life holds a static reference which, somewhere along the line, references the ClassLoader. As the reference is originally static, no amount of garbage collecting will clean this reference up - the ClassLoader, and all the classes it's loaded, are here to stay.</p>\n\n<p>And after a couple of redeploys, we encounter the OutOfMemoryError.</p>\n\n<p>Now this has become a fairly serious problem. I could make sure that Tomcat is restarted after each redeploy, but that takes down the entire server, rather than just the application being redeployed, which is often not feasible. </p>\n\n<p>So instead I've put together a solution in code, which works on Apache Tomcat 6.0. I've not tested on any other application servers, and must stress that <strong>this is very likely not to work without modification on any other application server</strong>.</p>\n\n<p>I'd also like to say that personally I hate this code, and that <strong>nobody should be using this as a \"quick fix\" if the existing code can be changed to use proper shutdown and cleanup methods</strong>. The only time this should be used is if there's an external library your code is dependent on (In my case, it was a RADIUS client) that doesn't provide a means to clean up its own static references.</p>\n\n<p>Anyway, on with the code. This should be called at the point where the application is undeploying - such as a servlet's destroy method or (the better approach) a ServletContextListener's contextDestroyed method.</p>\n\n<pre><code>//Get a list of all classes loaded by the current webapp classloader\nWebappClassLoader classLoader = (WebappClassLoader) getClass().getClassLoader();\nField classLoaderClassesField = null;\nClass clazz = WebappClassLoader.class;\nwhile (classLoaderClassesField == null &amp;&amp; clazz != null) {\n try {\n classLoaderClassesField = clazz.getDeclaredField(\"classes\");\n } catch (Exception exception) {\n //do nothing\n }\n clazz = clazz.getSuperclass();\n}\nclassLoaderClassesField.setAccessible(true);\n\nList classes = new ArrayList((Vector)classLoaderClassesField.get(classLoader));\n\nfor (Object o : classes) {\n Class c = (Class)o;\n //Make sure you identify only the packages that are holding references to the classloader.\n //Allowing this code to clear all static references will result in all sorts\n //of horrible things (like java segfaulting).\n if (c.getName().startsWith(\"com.whatever\")) {\n //Kill any static references within all these classes.\n for (Field f : c.getDeclaredFields()) {\n if (Modifier.isStatic(f.getModifiers())\n &amp;&amp; !Modifier.isFinal(f.getModifiers())\n &amp;&amp; !f.getType().isPrimitive()) {\n try {\n f.setAccessible(true);\n f.set(null, null);\n } catch (Exception exception) {\n //Log the exception\n }\n }\n }\n }\n}\n\nclasses.clear();\n</code></pre>\n" }, { "answer_id": 8432825, "author": "kiwilisk", "author_id": 1087971, "author_profile": "https://Stackoverflow.com/users/1087971", "pm_score": 2, "selected": false, "text": "<p>I tried several answers and the only thing what finally did the job was this configuration for the compiler plugin in the pom:</p>\n\n<pre><code>&lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;\n &lt;version&gt;2.3.2&lt;/version&gt;\n &lt;configuration&gt;\n &lt;fork&gt;true&lt;/fork&gt;\n &lt;meminitial&gt;128m&lt;/meminitial&gt;\n &lt;maxmem&gt;512m&lt;/maxmem&gt;\n &lt;source&gt;1.6&lt;/source&gt;\n &lt;target&gt;1.6&lt;/target&gt;\n &lt;!-- prevent PermGen space out of memory exception --&gt;\n &lt;!-- &lt;argLine&gt;-Xmx512m -XX:MaxPermSize=512m&lt;/argLine&gt; --&gt;\n &lt;/configuration&gt;\n&lt;/plugin&gt;\n</code></pre>\n\n<p>hope this one helps.</p>\n" }, { "answer_id": 8721314, "author": "Peter", "author_id": 1129061, "author_profile": "https://Stackoverflow.com/users/1129061", "pm_score": 6, "selected": false, "text": "<p>Common mistakes people make is thinking that heap space and permgen space are same, which is not at all true. You could have lot of space remaining in the heap but still can run out of memory in permgen. </p>\n\n<p>Common causes of OutofMemory in PermGen is ClassLoader. Whenever a class is loaded into JVM, all its meta data, along with Classloader, is kept on PermGen area and they will be garbage collected when the Classloader which loaded them is ready for garbage collection. In Case Classloader has a memory leak than all classes loaded by it will remain in memory and cause permGen outofmemory once you repeat it a couple of times. The classical example is <a href=\"http://javarevisited.blogspot.com/2012/01/tomcat-javalangoutofmemoryerror-permgen.html\" rel=\"noreferrer\">Java.lang.OutOfMemoryError:PermGen Space in Tomcat</a>. </p>\n\n<p>Now there are two ways to solve this:<br>\n1. Find the cause of Memory Leak or if there is any memory leak.<br>\n2. Increase size of PermGen Space by using JVM param <code>-XX:MaxPermSize</code> and <code>-XX:PermSize</code>.</p>\n\n<p>You can also check <a href=\"http://javarevisited.blogspot.com/2011/09/javalangoutofmemoryerror-permgen-space.html\" rel=\"noreferrer\">2 Solution of Java.lang.OutOfMemoryError</a> in Java for more details.</p>\n" }, { "answer_id": 11452196, "author": "Nikem", "author_id": 301650, "author_profile": "https://Stackoverflow.com/users/301650", "pm_score": 3, "selected": false, "text": "<p>Increasing Permanent Generation size or tweaking GC parameters will NOT help if you have a real memory leak. If your application or some 3rd party library it uses, leaks class loaders the only real and permanent solution is to find this leak and fix it. There are number of tools that can help you, one of the recent is <a href=\"http://plumbr.eu\" rel=\"noreferrer\">Plumbr</a>, which has just released a new version with the required capabilities.</p>\n" }, { "answer_id": 12225849, "author": "dev", "author_id": 80286, "author_profile": "https://Stackoverflow.com/users/80286", "pm_score": 1, "selected": false, "text": "<p>You can also solve this problem by doing a:</p>\n\n<pre><code>rm -rf &lt;tomcat-dir&gt;/work/* &lt;tomcat-dir&gt;/temp/*\n</code></pre>\n\n<p>Clearing out the <em>work</em> and <em>temp</em> directories makes Tomcat do a clean startup.</p>\n" }, { "answer_id": 15184546, "author": "prayagupa", "author_id": 432903, "author_profile": "https://Stackoverflow.com/users/432903", "pm_score": 5, "selected": false, "text": "<p>I <a href=\"https://stackoverflow.com/a/835269/432903\">added</a> <code>-XX: MaxPermSize = 128m</code> (you can experiment which works best) to <strong>VM Arguments</strong> as I'm using eclipse ide. In most of JVM, <a href=\"http://javarevisited.blogspot.com/2011/09/javalangoutofmemoryerror-permgen-space.html\" rel=\"noreferrer\">default PermSize</a> is around <strong>64MB</strong> which runs out of memory if there are too many classes or huge number of Strings in the project.</p>\n\n<p>For eclipse, it is also described at <a href=\"https://stackoverflow.com/a/4350922/432903\">answer</a>.</p>\n\n<p><strong>STEP 1</strong> : Double Click on the tomcat server at <strong>Servers</strong> Tab</p>\n\n<p><img src=\"https://i.stack.imgur.com/l6N8V.png\" alt=\"enter image description here\"></p>\n\n<p><strong>STEP 2</strong> : <strong>Open launch Conf</strong> and add <code>-XX: MaxPermSize = 128m</code> to the end of existing <strong>VM arguements</strong>. </p>\n\n<p><img src=\"https://i.stack.imgur.com/wiImH.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 15520565, "author": "Lucky", "author_id": 1793718, "author_profile": "https://Stackoverflow.com/users/1793718", "pm_score": 3, "selected": false, "text": "<ol>\n<li>Open tomcat7w from Tomcat's bin directory or type Monitor Tomcat in start menu \n(a tabbed window opens with various service information).</li>\n<li><p>In the Java Options text area append this line:</p>\n\n<pre><code>-XX:MaxPermSize=128m\n</code></pre></li>\n<li>Set Initial Memory Pool to 1024 (optional).</li>\n<li>Set Maximum Memory Pool to 1024 (optional).</li>\n<li>Click Ok.</li>\n<li>Restart the Tomcat service.</li>\n</ol>\n" }, { "answer_id": 25119311, "author": "Edwin Buck", "author_id": 302139, "author_profile": "https://Stackoverflow.com/users/302139", "pm_score": 4, "selected": false, "text": "<p>The simplest answer these days is to use Java 8. </p>\n\n<p>It no longer reserves memory exclusively for PermGen space, allowing the PermGen memory to co-mingle with the regular memory pool.</p>\n\n<p>Keep in mind that you will have to remove all non-standard <code>-XXPermGen...=...</code> JVM startup parameters if you don't want Java 8 to complain that they don't do anything.</p>\n" }, { "answer_id": 25647363, "author": "faisalbhagat", "author_id": 1851358, "author_profile": "https://Stackoverflow.com/users/1851358", "pm_score": 4, "selected": false, "text": "<h2>1) Increasing the PermGen Memory Size</h2>\n\n<p>The first thing one can do is to make the size of the permanent generation heap space bigger. This cannot be done with the usual –Xms(set initial heap size) and –Xmx(set maximum heap size) JVM arguments, since as mentioned, the permanent generation heap space is entirely separate from the regular Java Heap space, \nand these arguments set the space for this regular Java heap space. However, there are similar arguments which can be used(at least with the Sun/OpenJDK jvms) to make the size of the permanent generation heap bigger:</p>\n\n<pre><code> -XX:MaxPermSize=128m\n</code></pre>\n\n<p>Default is 64m.</p>\n\n<h2>2) Enable Sweeping</h2>\n\n<p>Another way to take care of that for good is to allow classes to be unloaded so your PermGen never runs out:</p>\n\n<pre><code>-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled\n</code></pre>\n\n<p>Stuff like that worked magic for me in the past. One thing though, there’s a significant performance trade off in using those, since permgen sweeps will make like an extra 2 requests for every request you make or something along those lines. You’ll need to balance your use with the tradeoffs.</p>\n\n<p>You can find the details of this error.</p>\n\n<p><a href=\"http://faisalbhagat.blogspot.com/2014/09/java-outofmemoryerror-permgen.html\" rel=\"noreferrer\">http://faisalbhagat.blogspot.com/2014/09/java-outofmemoryerror-permgen.html</a></p>\n" }, { "answer_id": 25841574, "author": "Darshan", "author_id": 3828400, "author_profile": "https://Stackoverflow.com/users/3828400", "pm_score": 3, "selected": false, "text": "<p>Perm gen space error occurs due to the use of large space rather then jvm provided space to executed the code. </p>\n\n<p>The best solution for this problem in UNIX operating systems is to change some configuration on the bash file. The following steps solve the problem.</p>\n\n<p>Run command <code>gedit .bashrc</code> on terminal.</p>\n\n<p>Create <code>JAVA_OTPS</code> variable with following value:</p>\n\n<pre><code>export JAVA_OPTS=\"-XX:PermSize=256m -XX:MaxPermSize=512m\"\n</code></pre>\n\n<p>Save the bash file. Run command exec bash on the terminal. Restart the server.</p>\n\n<p>I hope this approach will work on your problem. If you use a Java version lower than 8 this issue occurs sometimes. But if you use Java 8 the problem never occurs.</p>\n" }, { "answer_id": 32394678, "author": "NIKHIL CHAURASIA", "author_id": 3927323, "author_profile": "https://Stackoverflow.com/users/3927323", "pm_score": 2, "selected": false, "text": "<p>I was having similar issue.\nMine is JDK 7 + Maven 3.0.2 + Struts 2.0 + Google GUICE dependency injection based project.</p>\n\n<p>Whenever i tried running <strong><code>mvn clean package</code></strong> command, it was showing following error and <strong>\"BUILD FAILURE\"</strong> occured </p>\n\n<blockquote>\n <p><strong>org.apache.maven.surefire.util.SurefireReflectionException: java.lang.reflect.InvocationTargetException; nested exception is java.lang.reflect.InvocationTargetException: null\n java.lang.reflect.InvocationTargetException \n Caused by: java.lang.OutOfMemoryError: PermGen space</strong></p>\n</blockquote>\n\n<p>I tried all the above useful tips and tricks but unfortunately none worked for me.\nWhat worked for me is described step by step below :=></p>\n\n<ol>\n<li>Go to your pom.xml</li>\n<li>Search for <code>&lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;</code></li>\n<li>Add a new <code>&lt;configuration&gt;</code> element and then <code>&lt;argLine&gt;</code> sub element in which pass <code>-Xmx512m -XX:MaxPermSize=256m</code> as shown below => </li>\n</ol>\n\n<p><strong><em><code>&lt;configuration&gt;\n &lt;argLine&gt;-Xmx512m -XX:MaxPermSize=256m&lt;/argLine&gt;\n &lt;/configuration&gt;</code></em></strong></p>\n\n<p>Hope it helps, happy programming :)</p>\n" }, { "answer_id": 34602657, "author": "sendon1982", "author_id": 2680640, "author_profile": "https://Stackoverflow.com/users/2680640", "pm_score": 2, "selected": false, "text": "<p>First step in such case is to check whether the GC is allowed to unload classes from PermGen. The standard JVM is rather conservative in this regard – classes are born to live forever. So once loaded, classes stay in memory even if no code is using them anymore. This can become a problem when the application creates lots of classes dynamically and the generated classes are not needed for longer periods. In such a case, allowing the JVM to unload class definitions can be helpful. This can be achieved by adding just one configuration parameter to your startup scripts:</p>\n\n<pre><code>-XX:+CMSClassUnloadingEnabled\n</code></pre>\n\n<p>By default this is set to false and so to enable this you need to explicitly set the following option in Java options. If you enable CMSClassUnloadingEnabled, GC will sweep PermGen too and remove classes which are no longer used. Keep in mind that this option will work only when UseConcMarkSweepGC is also enabled using the below option. So when running ParallelGC or, God forbid, Serial GC, make sure you have set your GC to CMS by specifying:</p>\n\n<pre><code>-XX:+UseConcMarkSweepGC\n</code></pre>\n" }, { "answer_id": 36148243, "author": "Santosh Jadi", "author_id": 3805521, "author_profile": "https://Stackoverflow.com/users/3805521", "pm_score": 4, "selected": false, "text": "<p>The <code>java.lang.OutOfMemoryError: PermGen</code> space message indicates that the Permanent Generation’s area in memory is exhausted. </p>\n\n<p>Any Java applications is allowed to use a limited amount of memory. The exact amount of memory your particular application can use is specified during application startup.</p>\n\n<p><strong>Java memory is separated into different regions which can be seen in the following image:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/AkDxx.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/AkDxx.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Metaspace: A new memory space is born</strong></p>\n\n<p>The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace; similar to the Oracle JRockit and IBM JVM's.</p>\n\n<p><strong>The good news is that it means no more <code>java.lang.OutOfMemoryError: PermGen</code> space problems and no need for you to tune and monitor this memory space anymore using <a href=\"http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html\" rel=\"noreferrer\">Java_8_Download</a> or higher.</strong></p>\n" }, { "answer_id": 36846957, "author": "Alejandro Pablo Tkachuk", "author_id": 4987783, "author_profile": "https://Stackoverflow.com/users/4987783", "pm_score": 2, "selected": false, "text": "<p>Assigning Tomcat more memory is NOT the proper solution.</p>\n\n<p>The correct solution is to do a cleanup after the context is destroyed and recreated (the hot deploy). The solution is to stop the memory leaks.</p>\n\n<p>If your Tomcat/Webapp Server is telling you that failed to unregister drivers (JDBC), then unregister them. This will stop the memory leaks. </p>\n\n<p>You can create a ServletContextListener and configure it in your web.xml. Here is a sample ServletContextListener:</p>\n\n<pre><code>import java.sql.Driver;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.util.Enumeration;\n\nimport javax.servlet.ServletContextEvent;\nimport javax.servlet.ServletContextListener;\n\nimport org.apache.log4j.Logger;\n\nimport com.mysql.jdbc.AbandonedConnectionCleanupThread;\n\n/**\n * \n * @author alejandro.tkachuk / calculistik.com\n *\n */\npublic class AppContextListener implements ServletContextListener {\n\n private static final Logger logger = Logger.getLogger(AppContextListener.class);\n\n @Override\n public void contextInitialized(ServletContextEvent arg0) {\n logger.info(\"AppContextListener started\");\n }\n\n @Override\n public void contextDestroyed(ServletContextEvent arg0) {\n logger.info(\"AppContextListener destroyed\");\n\n // manually unregister the JDBC drivers\n Enumeration&lt;Driver&gt; drivers = DriverManager.getDrivers();\n while (drivers.hasMoreElements()) {\n Driver driver = drivers.nextElement();\n try {\n DriverManager.deregisterDriver(driver);\n logger.info(String.format(\"Unregistering jdbc driver: %s\", driver));\n } catch (SQLException e) {\n logger.info(String.format(\"Error unregistering driver %s\", driver), e);\n }\n\n }\n\n // manually shutdown clean up threads\n try {\n AbandonedConnectionCleanupThread.shutdown();\n logger.info(\"Shutting down AbandonedConnectionCleanupThread\");\n } catch (InterruptedException e) {\n logger.warn(\"SEVERE problem shutting down AbandonedConnectionCleanupThread: \", e);\n e.printStackTrace();\n } \n }\n}\n</code></pre>\n\n<p>And here you configure it in your web.xml:</p>\n\n<pre><code>&lt;listener&gt;\n &lt;listener-class&gt;\n com.calculistik.mediweb.context.AppContextListener \n &lt;/listener-class&gt;\n&lt;/listener&gt; \n</code></pre>\n" }, { "answer_id": 39818539, "author": "kittu", "author_id": 1800583, "author_profile": "https://Stackoverflow.com/users/1800583", "pm_score": 0, "selected": false, "text": "<p>If any one is struggling with the same error in netbeans, then here is how I fixed it.</p>\n\n<p><strong>In Netbeans:</strong></p>\n\n<p>Go to services tab --> Right on server -->Choose properties --> go to platform tab -->Inside vm options type -Xms1024m</p>\n\n<p>In my case, I have given -Xms4096m</p>\n\n<p>Here is the screenshot:</p>\n\n<p><a href=\"https://i.stack.imgur.com/PrpdN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PrpdN.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 70596932, "author": "Douglas Silva", "author_id": 10141464, "author_profile": "https://Stackoverflow.com/users/10141464", "pm_score": 0, "selected": false, "text": "<p>To who is getting this same problem in IntelliJ when trying to debug JBoss Application:\nI just added this <code>-XX: MaxPermSize = 128m</code> to the VM Options In Run/Debug COnfigurations. You can increase it to 256m to be more guaranteed that will work.</p>\n" }, { "answer_id": 71465370, "author": "Abd Abughazaleh", "author_id": 8370334, "author_profile": "https://Stackoverflow.com/users/8370334", "pm_score": 0, "selected": false, "text": "<p>Increase Tomcat Memory</p>\n<p><code>C:\\Program Files\\Apache Software Foundation\\Tomcat 9.0\\bin</code></p>\n<p>or anywhere you used tomcat. and run <code>tomcat9w</code> or any version you used.</p>\n<p>after that follow the picture</p>\n<p><a href=\"https://i.stack.imgur.com/Cs5k5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Cs5k5.png\" alt=\"enter image description here\" /></a></p>\n<p>Change 128 to 1024 and also max change it to 1024 or more as you want.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16907/" ]
Recently I ran into this error in my web application: > > java.lang.OutOfMemoryError: PermGen space > > > It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6. Apparently this can occur after redeploying an application a few times. What causes it and what can be done to avoid it? How do I fix the problem?
The solution was to add these flags to JVM command line when Tomcat is started: ``` -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled ``` You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the "Java" tab, add the arguments to the "Java Options" box. Click "OK" and then restart the service. If you get an error *the specified service does not exist as an installed service* you should run: ``` tomcat6w //ES//servicename ``` where ***servicename*** is the name of the server as viewed in services.msc Source: orx's comment on [Eric's Agile Answers](https://web.archive.org/web/20160124133922/http://www.jroller.com/agileanswers/entry/preventing_java_s_java_lang).
88,269
<p>In certain unknown situations selenium does not detect that a page has loaded when using the open method. I am using the Java API. For example (This code will not produce this error. I don't know of an externally visible page that will.):</p> <pre><code>Selenium browser = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com"); browser.start(); browser.open("http://www.google.com/webhp?hl=en"); browser.type("q", "hello world"); </code></pre> <p>When the error occurs, the call to 'open' times out, even though you can clearly see that the page has loaded successfully before the timeout occurs. Increasing the timeout does not help. The call to 'type' never occurs, no progress is made.</p> <p>How do you get selenium to recognize that the page has loaded when this error occurs?</p>
[ { "answer_id": 88315, "author": "Jim Deville", "author_id": 1591, "author_profile": "https://Stackoverflow.com/users/1591", "pm_score": 1, "selected": false, "text": "<p>When I do Selenium testing, I wait to see if a certain element is visible (waitForVisible), then I do my action. I usually try to use an element after the one I'm typing in.</p>\n" }, { "answer_id": 88320, "author": "Matthew Jaskula", "author_id": 4356, "author_profile": "https://Stackoverflow.com/users/4356", "pm_score": 0, "selected": false, "text": "<p>Enabling the 'multiWindow' feature solved the issue, though I am not clear why.</p>\n\n<p>SeleniumServer(int port, boolean slowResources, boolean multiWindow)</p>\n\n<pre><code>SeleniumServer server = new SeleniumServer(4444, false, true);\n</code></pre>\n\n<p>Any clarification would be helpful.</p>\n" }, { "answer_id": 92179, "author": "Peter Bernier", "author_id": 6112, "author_profile": "https://Stackoverflow.com/users/6112", "pm_score": 0, "selected": false, "text": "<p>I've run into similar issues when using Selenium to test an application with iFrames. Basically, it seemed that once the primary page (the page containing the iframes) was loaded, Selenium was unable to determine when the iframe content had finished loading.</p>\n\n<p>From looking at the source for the link you're trying to load, it looks like there's some Javascript that's creating additional page elements once the page has loaded. I can't be sure, but it's possible that this is what's causing the problem since it seems similar to the situation that I've encountered above.</p>\n\n<p>Do you get the same sort of errors loading a static page? (ie, something with straight html)</p>\n\n<p>If you're unable to get a better answer, try the selenium forums, they're usually quite active and the Selenium devs do respond to good questions.</p>\n\n<p><a href=\"http://clearspace.openqa.org/community/selenium_remote_control\" rel=\"nofollow noreferrer\">http://clearspace.openqa.org/community/selenium_remote_control</a></p>\n\n<p>Also, if you haven't already tried it, add a call to browser.WaitForPageToLoad(\"15000\") after the call to open. I've found that doing this after every page transition makes my tests a little more solid, even though it shouldn't technically be required. (When Selenium detects that the page actually has loaded, it continues, so the actual timeout variable isn't really a concern..</p>\n" }, { "answer_id": 96178, "author": "Lawrence", "author_id": 17621, "author_profile": "https://Stackoverflow.com/users/17621", "pm_score": 1, "selected": false, "text": "<p>Using 'openAndWait' in place of 'open' will do the trick.</p>\n\n<p>From the <a href=\"http://www.openqa.org/\" rel=\"nofollow noreferrer\">website</a>: </p>\n\n<blockquote>\n <p>Many Actions can be called with the \"AndWait\" suffix, e.g. \"clickAndWait\". This suffix tells Selenium that the action will cause the browser to make a call to the server, and that Selenium should wait for a new page to load.</p>\n</blockquote>\n" }, { "answer_id": 8079103, "author": "Timur Evdokimov", "author_id": 656559, "author_profile": "https://Stackoverflow.com/users/656559", "pm_score": 2, "selected": false, "text": "<p>I faced this problem quite recently.</p>\n\n<p>All JS-based solutions didn't quite fit ICEFaces 2.x + Selenium 2.x/Webdriver combination I have.</p>\n\n<p>What I did and what worked for me is the following:</p>\n\n<p>In the corner of the screen, there's connection activity indicator.</p>\n\n<pre><code> &lt;ice:outputConnectionStatus id=\"connectStat\"\n showPopupOnDisconnect=\"true\"/&gt;\n</code></pre>\n\n<p>In my Java unit test, I wait until its 'idle' image comes back again:</p>\n\n<pre><code>private void waitForAjax() throws InterruptedException {\n for (int second = 0;; second++) {\n if (second &gt;= 60) fail(\"timeout\");\n try { \n if (\"visibility: visible;\".equals(\n selenium.getAttribute(\"top_right_form:connectStat:connection-idle@style\"))) { \n break;\n }\n } catch (Exception e) {\n\n }\n Thread.sleep(1000);\n }\n}\n</code></pre>\n\n<p>You can disable rendering of this indicator in production build, if showing it at the page is unnecessary, or use empty 1x1 gifs as its images.</p>\n\n<p>Works 100% (with popups, pushed messages etc.) and relieves you from the hell of specifying waitForElement(...) for each element separately. </p>\n\n<p>Hope this helps someone.</p>\n" }, { "answer_id": 16129677, "author": "dav", "author_id": 932473, "author_profile": "https://Stackoverflow.com/users/932473", "pm_score": 0, "selected": false, "text": "<p>Not a perfect solution, but I am using this method</p>\n\n<pre><code>$t1 = time(); // current timestamp\n$this-&gt;selenium-&gt;waitForPageToLoad(30);\n$t2 = time();\n\nif ($t2 - $t1 &gt;= 28) {\n // page was not loaded\n}\n</code></pre>\n\n<p>So, it is kind of checking if the page was not loaded during the specified time, so it is not loaded.</p>\n" }, { "answer_id": 18870766, "author": "someman", "author_id": 2791217, "author_profile": "https://Stackoverflow.com/users/2791217", "pm_score": 0, "selected": false, "text": "<p>If you page has no AJAX, try to seek footer of page (I also use Junit <code>fail(\"\")</code>, you may use <code>System.err.println()</code> instead):</p>\n\n<pre><code> element.click();\n int timeout =120; \n // one loop = 0.5 sec, co it will be one minute \n WebElement myFooter = null;\n\n for(int i=0; i&lt;timeout; i++){\n myFooter = driver.findElement(By.id(\"footer\"));\n if(myFooter!= null){\n break;\n }\n else{\n timeout--;\n }\n}\nif(timeout==0 &amp;&amp; myFooter == null){\n fail(\"ERROR! PAGE TIMEOUT\");\n}\n</code></pre>\n" }, { "answer_id": 18870910, "author": "someman", "author_id": 2791217, "author_profile": "https://Stackoverflow.com/users/2791217", "pm_score": 0, "selected": false, "text": "<p>another idea is to modify AJAX API (to add some text after AJAX actions).\nAfter ajax action was finished, before return, set invisible field to TRUE, selenium will find it and read as green-light</p>\n\n<p>in html:</p>\n\n<pre><code>&lt;input type='hidden' id=\"greenlight\"&gt;\n</code></pre>\n\n<p>in selenium</p>\n\n<pre><code>if(driver.findElement(By.id(\"greenlight\")).getAttr(\"value\").equals(\"TRUE\")){\n // do something after page loading\n}\n</code></pre>\n" }, { "answer_id": 25195600, "author": "Prabu Ananthakrishnan", "author_id": 2888917, "author_profile": "https://Stackoverflow.com/users/2888917", "pm_score": 2, "selected": false, "text": "<p>Maybe this will help you....</p>\n\n<p>Consider the following method is in page called Functions.java</p>\n\n<pre><code>public static void waitForPageLoaded(WebDriver driver) {\n\n ExpectedCondition&lt;Boolean&gt; expectation = new\n ExpectedCondition&lt;Boolean&gt;() {\n public Boolean apply(WebDriver driver) {\n return ((JavascriptExecutor)driver).executeScript(\"return document.readyState\").equals(\"complete\");\n }\n };\n\n WebDriverWait wait = new WebDriverWait(driver,30);\n try {\n wait.until(expectation);\n } catch(Throwable error) {\n Assert.assertFalse(true, \"Timeout waiting for Page Load Request to complete.\");\n }\n } \n</code></pre>\n\n<p>And you can call this method into your function. Since it is a static method, you can directly call with the class name.</p>\n\n<pre><code>public class Test(){\n WebDriver driver;\n\n @Test\n public void testing(){\n driver = new FirefoxDriver();\n driver.get(\"http://www.gmail.com\");\n Functions.waitForPageLoaded(driver);\n }\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4356/" ]
In certain unknown situations selenium does not detect that a page has loaded when using the open method. I am using the Java API. For example (This code will not produce this error. I don't know of an externally visible page that will.): ``` Selenium browser = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com"); browser.start(); browser.open("http://www.google.com/webhp?hl=en"); browser.type("q", "hello world"); ``` When the error occurs, the call to 'open' times out, even though you can clearly see that the page has loaded successfully before the timeout occurs. Increasing the timeout does not help. The call to 'type' never occurs, no progress is made. How do you get selenium to recognize that the page has loaded when this error occurs?
I faced this problem quite recently. All JS-based solutions didn't quite fit ICEFaces 2.x + Selenium 2.x/Webdriver combination I have. What I did and what worked for me is the following: In the corner of the screen, there's connection activity indicator. ``` <ice:outputConnectionStatus id="connectStat" showPopupOnDisconnect="true"/> ``` In my Java unit test, I wait until its 'idle' image comes back again: ``` private void waitForAjax() throws InterruptedException { for (int second = 0;; second++) { if (second >= 60) fail("timeout"); try { if ("visibility: visible;".equals( selenium.getAttribute("top_right_form:connectStat:connection-idle@style"))) { break; } } catch (Exception e) { } Thread.sleep(1000); } } ``` You can disable rendering of this indicator in production build, if showing it at the page is unnecessary, or use empty 1x1 gifs as its images. Works 100% (with popups, pushed messages etc.) and relieves you from the hell of specifying waitForElement(...) for each element separately. Hope this helps someone.
88,276
<p>I've been trying to figure this out for about two weeks. I'm able to create email items in people's folders, read the folders, all that stuff but for the life of me I can not get anything to work with the calendars.</p> <p>I can provide examples of the XML I'm sending to WebDav but hoping someone out there has done this and has an example?</p>
[ { "answer_id": 92523, "author": "Robert Sanders", "author_id": 16952, "author_profile": "https://Stackoverflow.com/users/16952", "pm_score": 2, "selected": false, "text": "<p>I did this in a Java program a few years back, and the way I did it was to PUT a VCALENDAR document into the folder. One quirk is that the VCALENDAR had to be enclosed within an RFC822 message. It's a bizarre combination of WebDAV, email, and iCAL/VCAL, but it worked at the time on Exchange 2003 hosted at Link2Exchange.</p>\n\n<p>I'm sure there is an easier way, but this is what worked for me. Below I show a tcpdump packet trace of what happened. You should probably use ngrep/tcpdump on your own Outlook/Entourage client to see what it does.</p>\n\n<p>Note that \"Cal2\" is the name of my test calendar folder. You'd use \"Calendar\" for the main calendar folder.</p>\n\n<pre><code>T 10.0.1.95:59741 -&gt; 66.211.136.9:80 [AP]\nPUT /exchange/yourname.domainname.com/Cal2/CC1.1163646061548.0.eml HTTP/1.1.\ntranslate: f.\nContent-Type: message/rfc822.\nPragma: no-cache.\nAccept: */*.\nCache-Control: no-cache.\nAuthorization: Basic NOYOUCANTSEEMYPASSWORDYOUBASTARDS.\nUser-Agent: Jakarta Commons-HttpClient/2.0final.\nHost: e1.exmx.net.\nCookie: sessionid=29486b50-d398-4f76-9604-8421950c7dcd:0x0.\nContent-Length: 478.\nExpect: 100-continue.\n.\n\n\nT 66.211.136.9:80 -&gt; 10.0.1.95:59741 [AP]\nHTTP/1.1 100 Continue.\n.\n\n\nT 10.0.1.95:59741 -&gt; 66.211.136.9:80 [AP]\ncontent-class: urn:content-classes:appointment.\nContent-Type: text/calendar;.\n.method=REQUEST;.\n.charset=\"utf-8\".\nContent-Transfer-Encoding: 8bit.\n.\nBEGIN:VCALENDAR.\nBEGIN:VEVENT.\nUID:E1+1382+1014+495066799@I1+1382+1014+6+495066799.\nSUMMARY:Voice Architecture Leads Meeting.\nPRIORITY:5.\nLOCATION:x44444 pc:6879.\nDTSTART:20061122T193000Z.\nDTEND:20061122T203000Z.\nDTSTAMP:20061110T074856Z.\nDESCRIPTION:this is a description.\nSUMMARY:this is a summary.\nEND:VEVENT.\nEND:VCALENDAR.\n\n\n\nT 66.211.136.9:80 -&gt; 10.0.1.95:59741 [AP]\nHTTP/1.1 201 Created.\nDate: Thu, 16 Nov 2006 03:00:16 GMT.\nServer: Microsoft-IIS/6.0.\nX-Powered-By: ASP.NET.\nMS-Exchange-Permanent-URL: http://e1.exmx.net/exchange/yourname.yourdomain.com/-FlatUrlSpace-/122cda661de1da48936f9\n44bda4dde6e-3af8a8/122cda661de1da48936f944bda4dde6e-3f3383.\nLocation: http://e1.exmx.net/exchange/yourname.yourdomain.com/Cal2/CC1.1163646061548.0.eml.\nRepl-UID: &lt;rid:122cda661de1da48936f944bda4dde6e0000003f3383&gt;.\nContent-Type: text/html.\nContent-Length: 110.\nAllow: OPTIONS, TRACE, GET, HEAD, DELETE, PUT, COPY, MOVE, PROPFIND, PROPPATCH, SEARCH, SUBSCRIBE, UNSUBSCRIBE, PO\nLL, BDELETE, BCOPY, BMOVE, BPROPPATCH, BPROPFIND, LOCK, UNLOCK.\nResourceTag: &lt;rt:122cda661de1da48936f944bda4dde6e0000003f3383122cda661de1da48936f944bda4dde6e0000003f4671&gt;.\nGetETag: \"122cda661de1da48936f944bda4dde6e0000003f4671\".\nMS-WebStorage: 6.5.7638.\nCache-Control: no-cache.\n</code></pre>\n\n<p>.</p>\n\n<pre><code>T 66.211.136.9:80 -&gt; 10.0.1.95:59741 [AP]\n&lt;body&gt;&lt;h1&gt;/exchange/yourname.yourdomain.com/Cal2/CC1.1163646061548.0.eml was created successfully&lt;/h1&gt;&lt;/body&gt;.\n</code></pre>\n\n<p>You can verify that it worked using something like Cadaver to query the object's properties via WebDAV like so:</p>\n\n<pre><code>dav:/exchange/[email protected]/Cal2/&gt; propget CC1.1163646061548.0.eml\n Fetching properties for `CC1.1163646061548.0.eml':\n textdescription = this is a description\n contentclass = urn:content-classes:appointment\n supportedlock = &lt;lockentry&gt;&lt;locktype&gt;&lt;transaction&gt;&lt;groupoperation&gt;&lt;/groupoperation&gt;&lt;/transaction&gt;&lt;/locktype&gt;&lt;locks\n cope&gt;&lt;local&gt;&lt;/local&gt;&lt;/lockscope&gt;&lt;/lockentry&gt;\n permanenturl = http://e1.exmx.net/exchange/[email protected]/-FlatUrlSpace-/122cda661de1da48936f944bda4dde6e-\n 3af8a8/122cda661de1da48936f944bda4dde6e-3f3383\n getcontenttype = message/rfc822\n id = AQEAAAAAOvioAQAAAAA/M4MAAAAA\n mid = -8992774761696198655\n uid = E1+1382+1014+495066799@I1+1382+1014+6+495066799\n isfolder = 0\n resourcetype = \n method = PUBLISH\n getetag = \"122cda661de1da48936f944bda4dde6e0000003f4671\"\n lockdiscovery = \n outlookmessageclass = IPM.Appointment\n creationdate = 2006-11-16T03:00:16.549Z\n outlookmessageclass = IPM.Appointment\n creationdate = 2006-11-16T03:00:16.549Z\n ntsecuritydescriptor = CAAEAAAAAAABAC+MMAAAAEwAAAAAAAAAFAAAAAIAHAABAAAAARAUAL8PHwABAQAAAAAABQcAAAABBQAAAAAABRUAAAC\n nkePD6LEa8iIT/+gqDAAAAQUAAAAAAAUVAAAAp5Hjw+ixGvIiE//oAQIAAA==\n dtstamp = 2006-11-10T07:48:56.000Z\n lastmodified = 2006-11-16T03:00:16.565Z\n dtstart = 2006-11-22T19:30:00.000Z\n location = x44444 pc:6879\n duration = 3600\n htmldescription = &lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\"&gt;\n &lt;HTML&gt;\n &lt;HEAD&gt;\n\n &lt;META NAME=\"Generator\" CONTENT=\"MS Exchange Server version 6.5.7638.1\"&gt;\n &lt;TITLE&gt;this is a summary&lt;/TITLE&gt;\n &lt;/HEAD&gt;\n &lt;BODY&gt;\n &lt;!-- Converted from text/plain format --&gt;\n\n &lt;P&gt;&lt;FONT SIZE=2&gt;this is a description&lt;/FONT&gt;\n &lt;/P&gt;\n\n &lt;/BODY&gt;\n &lt;/HTML&gt;\n ishidden = 0\n parentname = http://e1.exmx.net/exchange/[email protected]/Cal2/\n meetingstatus = TENTATIVE\n subject = this is a summary\n getcontentlength = 631\n normalizedsubject = this is a summary\n isstructureddocument = 0\n repl-uid = rid:122cda661de1da48936f944bda4dde6e0000003f3383\n timezoneid = 0\n displayname = CC1.1163646061548.0.eml\n href = http://e1.exmx.net/exchange/[email protected]/Cal2/CC1.1163646061548.0.eml\n nomodifyexceptions = 1\n patternend = 2006-11-22T20:30:00.000Z\n isreadonly = 0\n instancetype = 0\n uid = AQEAAAAAPzODAAAAAAAAAAAAAAAA\n getlastmodified = 2006-11-16T03:00:16.565Z\n created = 2006-11-16T03:00:16.549Z\n sensitivity = 0\n dtend = 2006-11-22T20:30:00.000Z\n hasattachment = 0\n iscollection = 0\n read = 1\n resourcetag = rt:122cda661de1da48936f944bda4dde6e0000003f3383122cda661de1da48936f944bda4dde6e0000003f4671\n patternstart = 2006-11-22T19:30:00.000Z\n priority = 0\n sequence = 0\n</code></pre>\n" }, { "answer_id": 1418135, "author": "golemwashere", "author_id": 172779, "author_profile": "https://Stackoverflow.com/users/172779", "pm_score": 0, "selected": false, "text": "<p>have a look at this\n<a href=\"http://golemlab.wordpress.com/2009/09/13/php-owa-2003-calendar-fun/\" rel=\"nofollow noreferrer\">http://golemlab.wordpress.com/2009/09/13/php-owa-2003-calendar-fun/</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've been trying to figure this out for about two weeks. I'm able to create email items in people's folders, read the folders, all that stuff but for the life of me I can not get anything to work with the calendars. I can provide examples of the XML I'm sending to WebDav but hoping someone out there has done this and has an example?
I did this in a Java program a few years back, and the way I did it was to PUT a VCALENDAR document into the folder. One quirk is that the VCALENDAR had to be enclosed within an RFC822 message. It's a bizarre combination of WebDAV, email, and iCAL/VCAL, but it worked at the time on Exchange 2003 hosted at Link2Exchange. I'm sure there is an easier way, but this is what worked for me. Below I show a tcpdump packet trace of what happened. You should probably use ngrep/tcpdump on your own Outlook/Entourage client to see what it does. Note that "Cal2" is the name of my test calendar folder. You'd use "Calendar" for the main calendar folder. ``` T 10.0.1.95:59741 -> 66.211.136.9:80 [AP] PUT /exchange/yourname.domainname.com/Cal2/CC1.1163646061548.0.eml HTTP/1.1. translate: f. Content-Type: message/rfc822. Pragma: no-cache. Accept: */*. Cache-Control: no-cache. Authorization: Basic NOYOUCANTSEEMYPASSWORDYOUBASTARDS. User-Agent: Jakarta Commons-HttpClient/2.0final. Host: e1.exmx.net. Cookie: sessionid=29486b50-d398-4f76-9604-8421950c7dcd:0x0. Content-Length: 478. Expect: 100-continue. . T 66.211.136.9:80 -> 10.0.1.95:59741 [AP] HTTP/1.1 100 Continue. . T 10.0.1.95:59741 -> 66.211.136.9:80 [AP] content-class: urn:content-classes:appointment. Content-Type: text/calendar;. .method=REQUEST;. .charset="utf-8". Content-Transfer-Encoding: 8bit. . BEGIN:VCALENDAR. BEGIN:VEVENT. UID:E1+1382+1014+495066799@I1+1382+1014+6+495066799. SUMMARY:Voice Architecture Leads Meeting. PRIORITY:5. LOCATION:x44444 pc:6879. DTSTART:20061122T193000Z. DTEND:20061122T203000Z. DTSTAMP:20061110T074856Z. DESCRIPTION:this is a description. SUMMARY:this is a summary. END:VEVENT. END:VCALENDAR. T 66.211.136.9:80 -> 10.0.1.95:59741 [AP] HTTP/1.1 201 Created. Date: Thu, 16 Nov 2006 03:00:16 GMT. Server: Microsoft-IIS/6.0. X-Powered-By: ASP.NET. MS-Exchange-Permanent-URL: http://e1.exmx.net/exchange/yourname.yourdomain.com/-FlatUrlSpace-/122cda661de1da48936f9 44bda4dde6e-3af8a8/122cda661de1da48936f944bda4dde6e-3f3383. Location: http://e1.exmx.net/exchange/yourname.yourdomain.com/Cal2/CC1.1163646061548.0.eml. Repl-UID: <rid:122cda661de1da48936f944bda4dde6e0000003f3383>. Content-Type: text/html. Content-Length: 110. Allow: OPTIONS, TRACE, GET, HEAD, DELETE, PUT, COPY, MOVE, PROPFIND, PROPPATCH, SEARCH, SUBSCRIBE, UNSUBSCRIBE, PO LL, BDELETE, BCOPY, BMOVE, BPROPPATCH, BPROPFIND, LOCK, UNLOCK. ResourceTag: <rt:122cda661de1da48936f944bda4dde6e0000003f3383122cda661de1da48936f944bda4dde6e0000003f4671>. GetETag: "122cda661de1da48936f944bda4dde6e0000003f4671". MS-WebStorage: 6.5.7638. Cache-Control: no-cache. ``` . ``` T 66.211.136.9:80 -> 10.0.1.95:59741 [AP] <body><h1>/exchange/yourname.yourdomain.com/Cal2/CC1.1163646061548.0.eml was created successfully</h1></body>. ``` You can verify that it worked using something like Cadaver to query the object's properties via WebDAV like so: ``` dav:/exchange/[email protected]/Cal2/> propget CC1.1163646061548.0.eml Fetching properties for `CC1.1163646061548.0.eml': textdescription = this is a description contentclass = urn:content-classes:appointment supportedlock = <lockentry><locktype><transaction><groupoperation></groupoperation></transaction></locktype><locks cope><local></local></lockscope></lockentry> permanenturl = http://e1.exmx.net/exchange/[email protected]/-FlatUrlSpace-/122cda661de1da48936f944bda4dde6e- 3af8a8/122cda661de1da48936f944bda4dde6e-3f3383 getcontenttype = message/rfc822 id = AQEAAAAAOvioAQAAAAA/M4MAAAAA mid = -8992774761696198655 uid = E1+1382+1014+495066799@I1+1382+1014+6+495066799 isfolder = 0 resourcetype = method = PUBLISH getetag = "122cda661de1da48936f944bda4dde6e0000003f4671" lockdiscovery = outlookmessageclass = IPM.Appointment creationdate = 2006-11-16T03:00:16.549Z outlookmessageclass = IPM.Appointment creationdate = 2006-11-16T03:00:16.549Z ntsecuritydescriptor = CAAEAAAAAAABAC+MMAAAAEwAAAAAAAAAFAAAAAIAHAABAAAAARAUAL8PHwABAQAAAAAABQcAAAABBQAAAAAABRUAAAC nkePD6LEa8iIT/+gqDAAAAQUAAAAAAAUVAAAAp5Hjw+ixGvIiE//oAQIAAA== dtstamp = 2006-11-10T07:48:56.000Z lastmodified = 2006-11-16T03:00:16.565Z dtstart = 2006-11-22T19:30:00.000Z location = x44444 pc:6879 duration = 3600 htmldescription = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <HTML> <HEAD> <META NAME="Generator" CONTENT="MS Exchange Server version 6.5.7638.1"> <TITLE>this is a summary</TITLE> </HEAD> <BODY> <!-- Converted from text/plain format --> <P><FONT SIZE=2>this is a description</FONT> </P> </BODY> </HTML> ishidden = 0 parentname = http://e1.exmx.net/exchange/[email protected]/Cal2/ meetingstatus = TENTATIVE subject = this is a summary getcontentlength = 631 normalizedsubject = this is a summary isstructureddocument = 0 repl-uid = rid:122cda661de1da48936f944bda4dde6e0000003f3383 timezoneid = 0 displayname = CC1.1163646061548.0.eml href = http://e1.exmx.net/exchange/[email protected]/Cal2/CC1.1163646061548.0.eml nomodifyexceptions = 1 patternend = 2006-11-22T20:30:00.000Z isreadonly = 0 instancetype = 0 uid = AQEAAAAAPzODAAAAAAAAAAAAAAAA getlastmodified = 2006-11-16T03:00:16.565Z created = 2006-11-16T03:00:16.549Z sensitivity = 0 dtend = 2006-11-22T20:30:00.000Z hasattachment = 0 iscollection = 0 read = 1 resourcetag = rt:122cda661de1da48936f944bda4dde6e0000003f3383122cda661de1da48936f944bda4dde6e0000003f4671 patternstart = 2006-11-22T19:30:00.000Z priority = 0 sequence = 0 ```
88,306
<p>I'm making a small web application in Seaside. I have a login component, and after the user logs in I want to send along a cookie when the next component renders itself. Is there a way to get at the object handling the response so I can add something to the headers it will output?</p> <p>I'm trying to avoid using WASession>>redirectWithCookies since it seems pretty kludgey to redirect only because I want to set a cookie.</p> <p>Is there another way that already exist to add a cookie that will go out on the next response?</p>
[ { "answer_id": 90665, "author": "Avi", "author_id": 9983, "author_profile": "https://Stackoverflow.com/users/9983", "pm_score": 2, "selected": false, "text": "<p>I've just looked into this in depth, and the answer seems to be no. Specifically, there's no way to get at the response from the WARenderCanvas or anything it can access (it holds onto the WARenderingContext, which holds onto the WAHtmlStreamDocument, which holds onto the response's <em>stream</em> but not the response itself). I think it would be reasonable to give the context access to the current response, precisely to be able to set headers on it, but you asked if there was already a way, so: no.</p>\n\n<p>That said, Seaside does a lot of extra redirecting, and it doesn't seem to have much impact on the user experience, so maybe the thing to do is to stop worrying about it seeming kludgey and go with the flow of the API that's already there :)</p>\n" }, { "answer_id": 90695, "author": "Julian", "author_id": 11526, "author_profile": "https://Stackoverflow.com/users/11526", "pm_score": 4, "selected": true, "text": "<p>There is currently no built-in way to add cookies during the action/callback phase of request processing. This is most likely a defect and is noted in this issue: <a href=\"http://code.google.com/p/seaside/issues/detail?id=48\" rel=\"nofollow noreferrer\">http://code.google.com/p/seaside/issues/detail?id=48</a></p>\n\n<p>This is currently slated to be fixed for Seaside 2.9 but I don't know if it will even be backported to 2.8 or not.</p>\n\n<p>Keep in mind that there is already (by default) a redirection between the action and rendering phases to prevent a Refresh from re-triggering the callbacks, so in the grand scheme of things, one more redirect in this case isn't <em>so</em> bad.</p>\n\n<p>If you still want to dig further, have a look at WARenderContinuation>>handleRequest:. That's where callback processing is triggered and the redirect or rendering phase begun.</p>\n\n<p><strong>Edited to add:</strong></p>\n\n<p>The issue has now been fixed and (in the latest development code) you can now properly add cookies to the current response at any time. Simply access the response object in the current request context and add the cookie. For example, you might do something like:</p>\n\n<pre><code>self requestContext response addCookie: aCookie\n</code></pre>\n\n<p>This is unlikely to be backported to Seaside 2.8 as it required a fairly major shift in the way responses are handled.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2766176/" ]
I'm making a small web application in Seaside. I have a login component, and after the user logs in I want to send along a cookie when the next component renders itself. Is there a way to get at the object handling the response so I can add something to the headers it will output? I'm trying to avoid using WASession>>redirectWithCookies since it seems pretty kludgey to redirect only because I want to set a cookie. Is there another way that already exist to add a cookie that will go out on the next response?
There is currently no built-in way to add cookies during the action/callback phase of request processing. This is most likely a defect and is noted in this issue: <http://code.google.com/p/seaside/issues/detail?id=48> This is currently slated to be fixed for Seaside 2.9 but I don't know if it will even be backported to 2.8 or not. Keep in mind that there is already (by default) a redirection between the action and rendering phases to prevent a Refresh from re-triggering the callbacks, so in the grand scheme of things, one more redirect in this case isn't *so* bad. If you still want to dig further, have a look at WARenderContinuation>>handleRequest:. That's where callback processing is triggered and the redirect or rendering phase begun. **Edited to add:** The issue has now been fixed and (in the latest development code) you can now properly add cookies to the current response at any time. Simply access the response object in the current request context and add the cookie. For example, you might do something like: ``` self requestContext response addCookie: aCookie ``` This is unlikely to be backported to Seaside 2.8 as it required a fairly major shift in the way responses are handled.
88,311
<p>I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":</p> <pre><code>value = ""; 8.times{value &lt;&lt; (65 + rand(25)).chr} </code></pre> <p>but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to:</p> <pre><code>value = ""; 8.times{value &lt;&lt; ((rand(2)==1?65:97) + rand(25)).chr} </code></pre> <p>but it looks like trash.</p> <p>Does anyone have a better method?</p>
[ { "answer_id": 88338, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 0, "selected": false, "text": "<p>To make your first into one statement:</p>\n\n<pre><code>(0...8).collect { |n| value &lt;&lt; (65 + rand(25)).chr }.join()\n</code></pre>\n" }, { "answer_id": 88341, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 11, "selected": true, "text": "<pre><code>(0...8).map { (65 + rand(26)).chr }.join\n</code></pre>\n<p>I spend too much time golfing.</p>\n<pre><code>(0...50).map { ('a'..'z').to_a[rand(26)] }.join\n</code></pre>\n<p>And a last one that's even more confusing, but more flexible and wastes fewer cycles:</p>\n<pre><code>o = [('a'..'z'), ('A'..'Z')].map(&amp;:to_a).flatten\nstring = (0...50).map { o[rand(o.length)] }.join\n</code></pre>\n<p>If you want to generate some random text then use the following:</p>\n<pre><code>50.times.map { (0...(rand(10))).map { ('a'..'z').to_a[rand(26)] }.join }.join(&quot; &quot;)\n</code></pre>\n<p>this code generates 50 random word string with words length less than 10 characters and then join with space</p>\n" }, { "answer_id": 88347, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": -1, "selected": false, "text": "<p>I don't know ruby, so I can't give you the exact syntax, but I would set a constant string with the list of acceptable characters, then use the substring operator to pick a random character out of it.</p>\n\n<p>The advantage here is that if the string is supposed to be user-enterable, then you can exclude easily confused characters like l and 1 and i, 0 and O, 5 and S, etc.</p>\n" }, { "answer_id": 88371, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": -1, "selected": false, "text": "<p>This is almost as ugly but perhaps as step in right direction?</p>\n\n<pre><code> (1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join\n</code></pre>\n" }, { "answer_id": 88422, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>require 'sha1'\nsrand\nseed = \"--#{rand(10000)}--#{Time.now}--\"\nDigest::SHA1.hexdigest(seed)[0,8]\n</code></pre>\n" }, { "answer_id": 88470, "author": "Carlos Villela", "author_id": 16944, "author_profile": "https://Stackoverflow.com/users/16944", "pm_score": 2, "selected": false, "text": "<p>We've been using this on our code:</p>\n\n<pre><code>class String\n\n def self.random(length=10)\n ('a'..'z').sort_by {rand}[0,length].join\n end\n\nend\n</code></pre>\n\n<p>The maximum length supported is 25 (we're only using it with the default anyway, so hasn't been a problem).</p>\n\n<p>Someone mentioned that 'a'..'z' is suboptimal if you want to completely avoid generating offensive words. One of the ideas we had was removing vowels, but you still end up with WTFBBQ etc.</p>\n" }, { "answer_id": 89042, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 2, "selected": false, "text": "<p>With this method you can pass in an abitrary length. It's set as a default as 6.</p>\n\n<pre><code>def generate_random_string(length=6)\n string = \"\"\n chars = (\"A\"..\"Z\").to_a\n length.times do\n string &lt;&lt; chars[rand(chars.length-1)]\n end\n string\nend\n</code></pre>\n" }, { "answer_id": 89514, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 2, "selected": false, "text": "<p>I like Radar's answer best, so far, I think. I'd tweak a bit like this:</p>\n\n<pre><code>CHARS = ('a'..'z').to_a + ('A'..'Z').to_a\ndef rand_string(length=8)\n s=''\n length.times{ s &lt;&lt; CHARS[rand(CHARS.length)] }\n s\nend\n</code></pre>\n" }, { "answer_id": 493230, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<p>This solution generates a string of easily readable characters for activation codes; I didn't want people confusing 8 with B, 1 with I, 0 with O, L with 1, etc.</p>\n\n<pre><code># Generates a random string from a set of easily readable characters\ndef generate_activation_code(size = 6)\n charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z}\n (0...size).map{ charset.to_a[rand(charset.size)] }.join\nend\n</code></pre>\n" }, { "answer_id": 1117003, "author": "Travis Reeder", "author_id": 105562, "author_profile": "https://Stackoverflow.com/users/105562", "pm_score": 5, "selected": false, "text": "<p>I can't remember where I found this, but it seems like the best and the least process intensive to me:</p>\n\n<pre><code>def random_string(length=10)\n chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789'\n password = ''\n length.times { password &lt;&lt; chars[rand(chars.size)] }\n password\nend\n</code></pre>\n" }, { "answer_id": 1157293, "author": "maykeye", "author_id": 141770, "author_profile": "https://Stackoverflow.com/users/141770", "pm_score": -1, "selected": false, "text": "<p>In ruby 1.9 one can use Array's choice method which returns random element from array</p>\n" }, { "answer_id": 1619602, "author": "christopherstyles", "author_id": 131852, "author_profile": "https://Stackoverflow.com/users/131852", "pm_score": 10, "selected": false, "text": "<p>Why not use SecureRandom?</p>\n\n<pre><code>require 'securerandom'\nrandom_string = SecureRandom.hex\n\n# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81 (i.e. 32 chars of 0..9, a..f)\n</code></pre>\n\n<p>SecureRandom also has methods for:</p>\n\n<ul>\n<li>base64</li>\n<li>random_bytes</li>\n<li>random_number</li>\n</ul>\n\n<p>see: <a href=\"http://ruby-doc.org/stdlib-1.9.2/libdoc/securerandom/rdoc/SecureRandom.html\" rel=\"noreferrer\">http://ruby-doc.org/stdlib-1.9.2/libdoc/securerandom/rdoc/SecureRandom.html</a></p>\n" }, { "answer_id": 2031464, "author": "user163365", "author_id": 163365, "author_profile": "https://Stackoverflow.com/users/163365", "pm_score": 3, "selected": false, "text": "<p>Another method I like to use:</p>\n\n<pre><code> rand(2**256).to_s(36)[0..7]\n</code></pre>\n\n<p>Add <code>ljust</code> if you are really paranoid about the correct string length:</p>\n\n<pre><code> rand(2**256).to_s(36).ljust(8,'a')[0..7]\n</code></pre>\n" }, { "answer_id": 2908081, "author": "Nathan L Smith", "author_id": 161787, "author_profile": "https://Stackoverflow.com/users/161787", "pm_score": 0, "selected": false, "text": "<pre><code>`pwgen 8 1`.chomp\n</code></pre>\n" }, { "answer_id": 3326909, "author": "Ragmaanir", "author_id": 323733, "author_profile": "https://Stackoverflow.com/users/323733", "pm_score": 4, "selected": false, "text": "<p>Ruby 1.9+:</p>\n\n<pre><code>ALPHABET = ('a'..'z').to_a\n#=&gt; [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]\n\n10.times.map { ALPHABET.sample }.join\n#=&gt; \"stkbssowre\"\n\n# or\n\n10.times.inject('') { |s| s + ALPHABET.sample }\n#=&gt; \"fdgvacnxhc\"\n</code></pre>\n" }, { "answer_id": 3431889, "author": "erik", "author_id": 414025, "author_profile": "https://Stackoverflow.com/users/414025", "pm_score": 2, "selected": false, "text": "<p>I was doing something like this recently to generate an 8 byte random string from 62 characters. The characters were 0-9,a-z,A-Z. I had an array of them as was looping 8 times and picking a random value out of the array. This was inside a Rails app.</p>\n\n<pre><code>str = ''\n8.times {|i| str &lt;&lt; ARRAY_OF_POSSIBLE_VALUES[rand(SIZE_OF_ARRAY_OF_POSSIBLE_VALUES)] }\n</code></pre>\n\n<p>The weird thing is that I got good number of duplicates. Now randomly this should pretty much never happen. 62^8 is huge, but out of 1200 or so codes in the db i had a good number of duplicates. I noticed them happening on hour boundaries of each other. In other words I might see a duple at 12:12:23 and 2:12:22 or something like that...not sure if time is the issue or not.</p>\n\n<p>This code was in the before create of an ActiveRecord object. Before the record was created this code would run and generate the 'unique' code. Entries in the DB were always produced reliably, but the code (<code>str</code> in the above line) was being duplicated much too often.</p>\n\n<p>I created a script to run through 100000 iterations of this above line with small delay so it would take 3-4 hours hoping to see some kind of repeat pattern on an hourly basis, but saw nothing. I have no idea why this was happening in my Rails app.</p>\n" }, { "answer_id": 3572953, "author": "Christoffer Möller", "author_id": 431562, "author_profile": "https://Stackoverflow.com/users/431562", "pm_score": 8, "selected": false, "text": "<p>I use this for generating random URL friendly strings with a guaranteed maximum length:</p>\n<pre><code>string_length = 8\nrand(36**string_length).to_s(36)\n</code></pre>\n<p>It generates random strings of lowercase a-z and 0-9. It's not very customizable but it's short and clean.</p>\n" }, { "answer_id": 5073878, "author": "Manuel A. Guilamo", "author_id": 627682, "author_profile": "https://Stackoverflow.com/users/627682", "pm_score": 2, "selected": false, "text": "<p>try this out</p>\n\n<pre><code>def rand_name(len=9)\n ary = [('0'..'9').to_a, ('a'..'z').to_a, ('A'..'Z').to_a]\n name = ''\n\n len.times do\n name &lt;&lt; ary.choice.choice\n end\n name\nend\n</code></pre>\n\n<p>I love the answers of the thread, have been very helpful, indeed!, but if I may say, none of them satisfies my ayes, maybe is the rand() method. it's just doesn't seems right to me, since we've got the Array#choice method for that matter.</p>\n" }, { "answer_id": 5735905, "author": "Tim James", "author_id": 17055, "author_profile": "https://Stackoverflow.com/users/17055", "pm_score": 2, "selected": false, "text": "<p>Given:</p>\n\n<pre><code>chars = [*('a'..'z'),*('0'..'9')].flatten\n</code></pre>\n\n<p>Single expression, can be passed as an argument, allows duplicate characters:</p>\n\n<pre><code>Array.new(len) { chars.sample }.join\n</code></pre>\n" }, { "answer_id": 6412228, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 3, "selected": false, "text": "<p>I think this is a nice balance of conciseness, clarity and ease of modification.</p>\n<pre><code>characters = ('a'..'z').to_a + ('A'..'Z').to_a\n# Prior to 1.9, use .choice, not .sample\n(0..8).map{characters.sample}.join\n</code></pre>\n<h3>Easily modified</h3>\n<p>For example, including digits:</p>\n<pre><code>characters = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a\n</code></pre>\n<p>Uppercase hexadecimal:</p>\n<pre><code>characters = ('A'..'F').to_a + (0..9).to_a\n</code></pre>\n<p>For a truly impressive array of characters:</p>\n<pre><code>characters = (32..126).to_a.pack('U*').chars.to_a\n</code></pre>\n" }, { "answer_id": 7173336, "author": "Evgenii", "author_id": 297131, "author_profile": "https://Stackoverflow.com/users/297131", "pm_score": 2, "selected": false, "text": "<p>Here is another method:</p>\n\n<ul>\n<li>It uses the secure random number generator instead of rand()</li>\n<li>Can be used in URLs and file names</li>\n<li>Contains uppercase, lowercase characters and numbers</li>\n<li>Has an option not to include ambiguous characters I0l01</li>\n</ul>\n\n<p>Needs <code>require \"securerandom\"</code></p>\n\n<pre><code>def secure_random_string(length = 32, non_ambiguous = false)\n characters = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a\n\n %w{I O l 0 1}.each{ |ambiguous_character| \n characters.delete ambiguous_character \n } if non_ambiguous\n\n (0...length).map{\n characters[ActiveSupport::SecureRandom.random_number(characters.size)]\n }.join\nend\n</code></pre>\n" }, { "answer_id": 7222962, "author": "Travis Reeder", "author_id": 105562, "author_profile": "https://Stackoverflow.com/users/105562", "pm_score": 7, "selected": false, "text": "<p>Others have mentioned something similar, but this uses the URL safe function.</p>\n\n<pre><code>require 'securerandom'\np SecureRandom.urlsafe_base64(5) #=&gt; \"UtM7aa8\"\np SecureRandom.urlsafe_base64 #=&gt; \"UZLdOkzop70Ddx-IJR0ABg\"\np SecureRandom.urlsafe_base64(nil, true) #=&gt; \"i0XQ-7gglIsHGV2_BNPrdQ==\"\n</code></pre>\n\n<p>The result may contain A-Z, a-z, 0-9, “-” and “_”. “=” is also used if padding is true.</p>\n" }, { "answer_id": 7653318, "author": "eric", "author_id": 979198, "author_profile": "https://Stackoverflow.com/users/979198", "pm_score": 2, "selected": false, "text": "<pre><code>''.tap {|v| 4.times { v &lt;&lt; ('a'..'z').to_a.sample} }\n</code></pre>\n" }, { "answer_id": 8730431, "author": "Shai Coleman", "author_id": 891862, "author_profile": "https://Stackoverflow.com/users/891862", "pm_score": 6, "selected": false, "text": "<pre><code>[*('A'..'Z')].sample(8).join\n</code></pre>\n\n<p>Generate a random 8 letter string (e.g. NVAYXHGR)</p>\n\n<pre><code>([*('A'..'Z'),*('0'..'9')]-%w(0 1 I O)).sample(8).join\n</code></pre>\n\n<p>Generate a random 8 character string (e.g. 3PH4SWF2), excludes 0/1/I/O. Ruby 1.9</p>\n" }, { "answer_id": 9234645, "author": "peter", "author_id": 923315, "author_profile": "https://Stackoverflow.com/users/923315", "pm_score": 2, "selected": false, "text": "<p>2 solutions for a random string consisting of 3 ranges:</p>\n\n<pre><code>(('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a).sample(8).join\n\n([*(48..57),*(65..90),*(97..122)]).sample(8).collect(&amp;:chr)*\"\"\n</code></pre>\n\n<h3>One Character from each Range.</h3>\n\n<p>And if you need at least one character from each range, such as creating a random password that has one uppercase, one lowercase letter and one digit, you can do something like this: </p>\n\n<pre><code>( ('a'..'z').to_a.sample(8) + ('A'..'Z').to_a.sample(8) + (0..9).to_a.sample(8) ).shuffle.join \n#=&gt; \"Kc5zOGtM0H796QgPp8u2Sxo1\"\n</code></pre>\n" }, { "answer_id": 10220012, "author": "Teej", "author_id": 37532, "author_profile": "https://Stackoverflow.com/users/37532", "pm_score": 3, "selected": false, "text": "<pre><code>SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')\n</code></pre>\n\n<p>Something from Devise</p>\n" }, { "answer_id": 10292347, "author": "Chris Bloom", "author_id": 83743, "author_profile": "https://Stackoverflow.com/users/83743", "pm_score": 1, "selected": false, "text": "<p>This is based on a few other answers, but it adds a bit more complexity:</p>\n\n<pre><code>def random_password\n specials = ((32..47).to_a + (58..64).to_a + (91..96).to_a + (123..126).to_a).pack('U*').chars.to_a\n numbers = (0..9).to_a\n alpha = ('a'..'z').to_a + ('A'..'Z').to_a\n %w{i I l L 1 O o 0}.each{ |ambiguous_character| \n alpha.delete ambiguous_character \n }\n characters = (alpha + specials + numbers)\n password = Random.new.rand(8..18).times.map{characters.sample}\n password &lt;&lt; specials.sample unless password.join =~ Regexp.new(Regexp.escape(specials.join))\n password &lt;&lt; numbers.sample unless password.join =~ Regexp.new(Regexp.escape(numbers.join))\n password.shuffle.join\nend\n</code></pre>\n\n<p>Essentially it ensures a password that is 8 - 20 characters in length, and which contains at least one number and one special character.</p>\n" }, { "answer_id": 10434882, "author": "tybro0103", "author_id": 202875, "author_profile": "https://Stackoverflow.com/users/202875", "pm_score": 2, "selected": false, "text": "<p>My 2 cents:</p>\n\n<pre><code> def token(length=16)\n chars = [*('A'..'Z'), *('a'..'z'), *(0..9)]\n (0..length).map {chars.sample}.join\n end\n</code></pre>\n" }, { "answer_id": 10773250, "author": "pdu", "author_id": 92096, "author_profile": "https://Stackoverflow.com/users/92096", "pm_score": 3, "selected": false, "text": "<p>Just adding my cents here...</p>\n\n<pre><code>def random_string(length = 8)\n rand(32**length).to_s(32)\nend\n</code></pre>\n" }, { "answer_id": 11313001, "author": "lzap", "author_id": 299204, "author_profile": "https://Stackoverflow.com/users/299204", "pm_score": 2, "selected": false, "text": "<p>If you are on a UNIX and you still must use Ruby 1.8 (no SecureRandom) without Rails, you can also use this:</p>\n\n<pre><code>random_string = `openssl rand -base64 24`\n</code></pre>\n\n<p>Note this spawns new shell, this is very slow and it can only be recommended for scripts.</p>\n" }, { "answer_id": 11462624, "author": "LENZCOM", "author_id": 1055573, "author_profile": "https://Stackoverflow.com/users/1055573", "pm_score": 5, "selected": false, "text": "<pre><code>require 'securerandom'\nSecureRandom.urlsafe_base64(9)\n</code></pre>\n" }, { "answer_id": 12890596, "author": "Thaha kp", "author_id": 1465460, "author_profile": "https://Stackoverflow.com/users/1465460", "pm_score": 3, "selected": false, "text": "<p>Here is one simple code for random password with length 8:</p>\n\n<pre><code>rand_password=('0'..'z').to_a.shuffle.first(8).join\n</code></pre>\n" }, { "answer_id": 15719632, "author": "pencil", "author_id": 933424, "author_profile": "https://Stackoverflow.com/users/933424", "pm_score": 3, "selected": false, "text": "<p>Be aware: <code>rand</code> is predictable for an attacker and therefore probably insecure. You should definitely use SecureRandom if this is for generating passwords. I use something like this:</p>\n\n<pre><code>length = 10\ncharacters = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a\n\npassword = SecureRandom.random_bytes(length).each_char.map do |char|\n characters[(char.ord % characters.length)]\nend.join\n</code></pre>\n" }, { "answer_id": 15789933, "author": "Ghazi", "author_id": 1114817, "author_profile": "https://Stackoverflow.com/users/1114817", "pm_score": 0, "selected": false, "text": "<p>Create an empty string or a pre-fix if require:</p>\n\n<pre><code>myStr = \"OID-\"\n</code></pre>\n\n<p>Use this code to populate the string with random numbers:</p>\n\n<pre><code>begin; n = ((rand * 43) + 47).ceil; myStr &lt;&lt; n.chr if !(58..64).include?(n); end while(myStr.length &lt; 12)\n</code></pre>\n\n<p>Notes:</p>\n\n<pre><code>(rand * 43) + 47).ceil\n</code></pre>\n\n<p>It will generate random numbers from 48-91 (0,1,2..Y,Z)</p>\n\n<pre><code>!(58..64).include?(n)\n</code></pre>\n\n<p>It is used to skip special characters (as I am not interested to include them)</p>\n\n<pre><code>while(myStr.length &lt; 12)\n</code></pre>\n\n<p>It will generate total 12 characters long string including prefix.</p>\n\n<p>Sample Output:</p>\n\n<pre><code>\"OID-XZ2J32XM\"\n</code></pre>\n" }, { "answer_id": 17596273, "author": "Srikanta Mahapatro", "author_id": 889340, "author_profile": "https://Stackoverflow.com/users/889340", "pm_score": 5, "selected": false, "text": "<p>If you want a string of specified length, use:</p>\n\n<pre><code>require 'securerandom'\nrandomstring = SecureRandom.hex(n)\n</code></pre>\n\n<p>It will generate a random string of length <code>2n</code> containing <code>0-9</code> and <code>a-f</code></p>\n" }, { "answer_id": 17949884, "author": "Abdo", "author_id": 226255, "author_profile": "https://Stackoverflow.com/users/226255", "pm_score": 0, "selected": false, "text": "<p>Here's a solution that is flexible and allows dups:</p>\n\n<pre><code>class String\n # generate a random string of length n using current string as the source of characters\n def random(n)\n return \"\" if n &lt;= 0\n (chars * (n / length + 1)).shuffle[0..n-1].join \n end\nend\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>\"ATCG\".random(8) =&gt; \"CGTGAAGA\"\n</code></pre>\n\n<p>You can also allow a certain character to appear more frequently:</p>\n\n<pre><code>\"AAAAATCG\".random(10) =&gt; \"CTGAAAAAGC\"\n</code></pre>\n\n<p>Explanation:\nThe method above takes the chars of a given string and generates a big enough array. It then shuffles it, takes the first n items, then joins them.</p>\n" }, { "answer_id": 20272585, "author": "Josh", "author_id": 1193216, "author_profile": "https://Stackoverflow.com/users/1193216", "pm_score": 2, "selected": false, "text": "<p>My favorite is <code>(:A..:Z).to_a.shuffle[0,8].join</code>. Note that shuffle requires Ruby > 1.9.</p>\n" }, { "answer_id": 20342630, "author": "Sibevin Wang", "author_id": 232710, "author_profile": "https://Stackoverflow.com/users/232710", "pm_score": 2, "selected": false, "text": "<p>I just write a small gem <code>random_token</code> to generate random tokens for most use case, enjoy ~</p>\n\n<p><a href=\"https://github.com/sibevin/random_token\" rel=\"nofollow\">https://github.com/sibevin/random_token</a></p>\n" }, { "answer_id": 23310810, "author": "Automatico", "author_id": 741850, "author_profile": "https://Stackoverflow.com/users/741850", "pm_score": 0, "selected": false, "text": "<pre><code>Array.new(8).inject(\"\"){|r|r&lt;&lt;('0'..'z').to_a.shuffle[0]} # 57\n(1..8).inject(\"\"){|r|r&lt;&lt;('0'..'z').to_a.shuffle[0]} # 51\ne=\"\";8.times{e&lt;&lt;('0'..'z').to_a.shuffle[0]};e # 45\n(1..8).map{('0'..'z').to_a.shuffle[0]}.join # 43\n(1..8).map{rand(49..122).chr}.join # 34\n</code></pre>\n" }, { "answer_id": 25358706, "author": "lzap", "author_id": 299204, "author_profile": "https://Stackoverflow.com/users/299204", "pm_score": 2, "selected": false, "text": "<p>Another trick that works with Ruby 1.8+ and is fast is:</p>\n\n<pre><code>&gt;&gt; require \"openssl\"\n&gt;&gt; OpenSSL::Random.random_bytes(20).unpack('H*').join\n=&gt; \"2f3ff53dd712ba2303a573d9f9a8c1dbc1942d28\"\n</code></pre>\n\n<p>It get's you random hex string. Similar way you should be able to generate base64 string ('M*').</p>\n" }, { "answer_id": 25456667, "author": "Tilo", "author_id": 677684, "author_profile": "https://Stackoverflow.com/users/677684", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"https://github.com/rubyworks/facets/blob/126a619fd766bc45588cac18d09c4f1927538e33/lib/core/facets/string/random.rb\" rel=\"nofollow noreferrer\"><code>String#random</code></a> from the Facets of Ruby Gem <code>facets</code>.</p>\n\n<p>It basically does this:</p>\n\n<pre><code>class String\n def self.random(len=32, character_set = [\"A\"..\"Z\", \"a\"..\"z\", \"0\"..\"9\"])\n characters = character_set.map { |i| i.to_a }.flatten\n characters_len = characters.length\n (0...len).map{ characters[rand(characters_len)] }.join\n end\nend\n</code></pre>\n" }, { "answer_id": 26107751, "author": "gr8scott06", "author_id": 2760406, "author_profile": "https://Stackoverflow.com/users/2760406", "pm_score": 4, "selected": false, "text": "<p><code>Array.new(n){[*\"0\"..\"9\"].sample}.join</code>,\nwhere <code>n=8</code> in your case.</p>\n\n<p>Generalized: <code>Array.new(n){[*\"A\"..\"Z\", *\"0\"..\"9\"].sample}.join</code>, etc. </p>\n\n<p>From: \"<a href=\"https://stackoverflow.com/questions/26076011/rails-generate-pseudo-random-string-a-z-0-9/26076063#26076063\">Generate pseudo random string A-Z, 0-9</a>\".</p>\n" }, { "answer_id": 27010181, "author": "Awais", "author_id": 2561638, "author_profile": "https://Stackoverflow.com/users/2561638", "pm_score": 4, "selected": false, "text": "<p>Here is one line simple code for random string with length 8:</p>\n\n<pre><code> random_string = ('0'..'z').to_a.shuffle.first(8).join\n</code></pre>\n\n<p>You can also use it for random password having length 8:</p>\n\n<pre><code>random_password = ('0'..'z').to_a.shuffle.first(8).join\n</code></pre>\n" }, { "answer_id": 32656602, "author": "Alex Antonov", "author_id": 2926641, "author_profile": "https://Stackoverflow.com/users/2926641", "pm_score": 3, "selected": false, "text": "<p>This solution needs external dependency, but seems prettier than another.</p>\n\n<ol>\n<li>Install gem <a href=\"https://github.com/stympy/faker\" rel=\"noreferrer\">faker</a></li>\n<li><code>Faker::Lorem.characters(10) # =&gt; \"ang9cbhoa8\"</code></li>\n</ol>\n" }, { "answer_id": 35601419, "author": "DDD", "author_id": 2665844, "author_profile": "https://Stackoverflow.com/users/2665844", "pm_score": 1, "selected": false, "text": "<pre><code>10.times do \n alphabet = ('a'..'z').to_a\n string += alpha[rand(alpha.length)]\nend\n</code></pre>\n" }, { "answer_id": 37333123, "author": "shiva kumar", "author_id": 2400485, "author_profile": "https://Stackoverflow.com/users/2400485", "pm_score": 1, "selected": false, "text": "<p>For devise secure_validatable you can use this</p>\n<pre class=\"lang-rb prettyprint-override\"><code>(0...8).map { ([65, 97].sample + rand(26)).chr }.push(rand(99)).join\n</code></pre>\n" }, { "answer_id": 39246466, "author": "Minski", "author_id": 5308822, "author_profile": "https://Stackoverflow.com/users/5308822", "pm_score": 0, "selected": false, "text": "<pre><code>a='';8.times{a&lt;&lt;[*'a'..'z'].sample};p a\n</code></pre>\n\n<p>or</p>\n\n<pre><code>8.times.collect{[*'a'..'z'].sample}.join\n</code></pre>\n" }, { "answer_id": 48521297, "author": "Markus", "author_id": 590761, "author_profile": "https://Stackoverflow.com/users/590761", "pm_score": 7, "selected": false, "text": "<p>Since Ruby 2.5, it's really easy with <code>SecureRandom.alphanumeric</code>:</p>\n\n<pre><code>len = 8\nSecureRandom.alphanumeric(len)\n=&gt; \"larHSsgL\"\n</code></pre>\n\n<p>It generates random strings containing A-Z, a-z and 0-9 and therefore should be applicable in most use-cases. And they are generated randomly secure, which might be a benefit, too.</p>\n\n<hr>\n\n<p>This is a benchmark to compare it with the solution having the most upvotes:</p>\n\n<pre><code>require 'benchmark'\nrequire 'securerandom'\n\nlen = 10\nn = 100_000\n\nBenchmark.bm(12) do |x|\n x.report('SecureRandom') { n.times { SecureRandom.alphanumeric(len) } }\n x.report('rand') do\n o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&amp;:to_a).flatten\n n.times { (0...len).map { o[rand(o.length)] }.join }\n end\nend\n</code></pre>\n\n<hr>\n\n<pre><code> user system total real\nSecureRandom 0.429442 0.002746 0.432188 ( 0.432705)\nrand 0.306650 0.000716 0.307366 ( 0.307745)\n</code></pre>\n\n<p>So the <code>rand</code> solution only takes about 3/4 of the time of <code>SecureRandom</code>. That might matter if you generate a lot of strings, but if you just create some random string from time to time I'd always go with the more secure implementation since it is also easier to call and more explicit.</p>\n" }, { "answer_id": 51750404, "author": "Lucas Andrade", "author_id": 7390929, "author_profile": "https://Stackoverflow.com/users/7390929", "pm_score": 1, "selected": false, "text": "<p>Here is a improve of @Travis R answer:</p>\n\n<pre><code> def random_string(length=5)\n chars = 'abdefghjkmnpqrstuvwxyzABDEFGHJKLMNPQRSTUVWXYZ'\n numbers = '0123456789'\n random_s = ''\n (length/2).times { random_s &lt;&lt; numbers[rand(numbers.size)] }\n (length - random_s.length).times { random_s &lt;&lt; chars[rand(chars.size)] }\n random_s.split('').shuffle.join\n end\n</code></pre>\n\n<p>At @Travis R answer chars and numbers were together, so sometimes <code>random_string</code> could return only numbers or only characters. With this improve at least half of <code>random_string</code> will be characters and the rest are numbers. Just in case if you need a random string with numbers and characters</p>\n" }, { "answer_id": 53171700, "author": "Rubyist", "author_id": 386455, "author_profile": "https://Stackoverflow.com/users/386455", "pm_score": 0, "selected": false, "text": "<p>Use 'SafeRandom' Gem <a href=\"https://github.com/rpatil/safe_random\" rel=\"nofollow noreferrer\">GithubLink</a></p>\n\n<p>It will provide the easiest way to generate random values for Rails2, Rails 3, Rails 4, Rails 5 compatible. </p>\n" }, { "answer_id": 71507399, "author": "Tareq Saif", "author_id": 3981013, "author_profile": "https://Stackoverflow.com/users/3981013", "pm_score": 0, "selected": false, "text": "<p>The following worked well for me</p>\n<pre><code>def generate_random_password(min_length, max_length)\n length = SecureRandom.random_number(max_length - min_length) + min_length\n character_sets = [ \n ('a'..'z').to_a,\n ('A'..'Z').to_a,\n ('0'..'9').to_a,\n &quot;~!@^&amp;*()_-+=[]|:;&lt;,&gt;.?&quot;.split('')\n ] \n retval = []\n # \n # Add one character from each set\n # \n character_sets.each do |character_set|\n character = character_set[SecureRandom.random_number(character_set.count)]\n retval.push character\n end \n # \n # Fill the rest of the password with a random character from a random set\n # \n i = character_sets.count - 1 \n while i &lt; length\n character_set = character_sets[SecureRandom.random_number(character_sets.count)]\n character = character_set[SecureRandom.random_number(character_set.count)]\n retval.push character\n i += 1\n end\n retval.shuffle.join\n end\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10157/" ]
I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z": ``` value = ""; 8.times{value << (65 + rand(25)).chr} ``` but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to: ``` value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr} ``` but it looks like trash. Does anyone have a better method?
``` (0...8).map { (65 + rand(26)).chr }.join ``` I spend too much time golfing. ``` (0...50).map { ('a'..'z').to_a[rand(26)] }.join ``` And a last one that's even more confusing, but more flexible and wastes fewer cycles: ``` o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten string = (0...50).map { o[rand(o.length)] }.join ``` If you want to generate some random text then use the following: ``` 50.times.map { (0...(rand(10))).map { ('a'..'z').to_a[rand(26)] }.join }.join(" ") ``` this code generates 50 random word string with words length less than 10 characters and then join with space
88,325
<p>I have a class:</p> <pre><code>class MyClass: def __init__(self, foo): if foo != 1: raise Error("foo is not equal to 1!") </code></pre> <p>and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error:</p> <pre><code>def testInsufficientArgs(self): foo = 0 self.assertRaises((Error), myClass = MyClass(Error, foo)) </code></pre> <p>But I get...</p> <pre><code>NameError: global name 'Error' is not defined </code></pre> <p>Why? Where should I be defining this Error object? I thought it was built-in as a default exception type, no?</p>
[ { "answer_id": 88346, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 6, "selected": true, "text": "<p>'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metasyntatic placeholder to mean, \"The Appropriate Exception Class\".</p>\n\n<p>The baseclass of all exceptions is called 'Exception', and most of its subclasses are descriptive names of the type of error involved, such as 'OSError', 'ValueError', 'NameError', 'TypeError'.</p>\n\n<p>In this case, the appropriate error is 'ValueError' (the value of foo was wrong, therefore a ValueError). I would recommend replacing 'Error' with 'ValueError' in your script.</p>\n\n<p>Here is a complete version of the code you are trying to write, I'm duplicating everything because you have a weird keyword argument in your original example that you seem to be conflating with an assignment, and I'm using the 'failUnless' function name because that's the non-aliased name of the function:</p>\n\n<pre><code>class MyClass:\n def __init__(self, foo):\n if foo != 1:\n raise ValueError(\"foo is not equal to 1!\")\n\nimport unittest\nclass TestFoo(unittest.TestCase):\n def testInsufficientArgs(self):\n foo = 0\n self.failUnlessRaises(ValueError, MyClass, foo)\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>.\n----------------------------------------------------------------------\nRan 1 test in 0.007s\n\nOK\n</code></pre>\n\n<p>There is a flaw in the unit testing library 'unittest' that other unit testing frameworks fix. You'll note that it is impossible to gain access to the exception object from the calling context. If you want to fix this, you'll have to redefine that method in a subclass of UnitTest:</p>\n\n<p>This is an example of it in use:</p>\n\n<pre><code>class TestFoo(unittest.TestCase):\n def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):\n try:\n callableObj(*args, **kwargs)\n except excClass, excObj:\n return excObj # Actually return the exception object\n else:\n if hasattr(excClass,'__name__'): excName = excClass.__name__\n else: excName = str(excClass)\n raise self.failureException, \"%s not raised\" % excName\n\n def testInsufficientArgs(self):\n foo = 0\n excObj = self.failUnlessRaises(ValueError, MyClass, foo)\n self.failUnlessEqual(excObj[0], 'foo is not equal to 1!')\n</code></pre>\n\n<p>I have copied the failUnlessRaises function from unittest.py from python2.5 and modified it slightly.</p>\n" }, { "answer_id": 88357, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 1, "selected": false, "text": "<p>I think you're thinking of <a href=\"http://docs.python.org/lib/module-exceptions.html\" rel=\"nofollow noreferrer\">Exception</a>s. Replace the word Error in your description with Exception and you should be good to go :-)</p>\n" }, { "answer_id": 88369, "author": "Terhorst", "author_id": 8062, "author_profile": "https://Stackoverflow.com/users/8062", "pm_score": 3, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>class MyClass:\n def __init__(self, foo):\n if foo != 1:\n raise Exception(\"foo is not equal to 1!\")\n\nimport unittest\n\nclass Tests(unittest.TestCase):\n def testSufficientArgs(self):\n foo = 1\n MyClass(foo)\n\n def testInsufficientArgs(self):\n foo = 2\n self.assertRaises(Exception, MyClass, foo)\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
I have a class: ``` class MyClass: def __init__(self, foo): if foo != 1: raise Error("foo is not equal to 1!") ``` and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error: ``` def testInsufficientArgs(self): foo = 0 self.assertRaises((Error), myClass = MyClass(Error, foo)) ``` But I get... ``` NameError: global name 'Error' is not defined ``` Why? Where should I be defining this Error object? I thought it was built-in as a default exception type, no?
'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metasyntatic placeholder to mean, "The Appropriate Exception Class". The baseclass of all exceptions is called 'Exception', and most of its subclasses are descriptive names of the type of error involved, such as 'OSError', 'ValueError', 'NameError', 'TypeError'. In this case, the appropriate error is 'ValueError' (the value of foo was wrong, therefore a ValueError). I would recommend replacing 'Error' with 'ValueError' in your script. Here is a complete version of the code you are trying to write, I'm duplicating everything because you have a weird keyword argument in your original example that you seem to be conflating with an assignment, and I'm using the 'failUnless' function name because that's the non-aliased name of the function: ``` class MyClass: def __init__(self, foo): if foo != 1: raise ValueError("foo is not equal to 1!") import unittest class TestFoo(unittest.TestCase): def testInsufficientArgs(self): foo = 0 self.failUnlessRaises(ValueError, MyClass, foo) if __name__ == '__main__': unittest.main() ``` The output is: ``` . ---------------------------------------------------------------------- Ran 1 test in 0.007s OK ``` There is a flaw in the unit testing library 'unittest' that other unit testing frameworks fix. You'll note that it is impossible to gain access to the exception object from the calling context. If you want to fix this, you'll have to redefine that method in a subclass of UnitTest: This is an example of it in use: ``` class TestFoo(unittest.TestCase): def failUnlessRaises(self, excClass, callableObj, *args, **kwargs): try: callableObj(*args, **kwargs) except excClass, excObj: return excObj # Actually return the exception object else: if hasattr(excClass,'__name__'): excName = excClass.__name__ else: excName = str(excClass) raise self.failureException, "%s not raised" % excName def testInsufficientArgs(self): foo = 0 excObj = self.failUnlessRaises(ValueError, MyClass, foo) self.failUnlessEqual(excObj[0], 'foo is not equal to 1!') ``` I have copied the failUnlessRaises function from unittest.py from python2.5 and modified it slightly.
88,326
<p>Does <a href="http://elmah.github.io/" rel="nofollow noreferrer">ELMAH</a> logged exceptions even when they do not bubble up to the application? I'd like to pop up a message when an exception occurs and still log the exception. Currently I've been putting everything in try catch blocks and spitting out messages, but this gets tedious.</p>
[ { "answer_id": 841426, "author": "Michael La Voie", "author_id": 65843, "author_profile": "https://Stackoverflow.com/users/65843", "pm_score": 7, "selected": false, "text": "<p>ELMAH has been updated to support a new feature called <a href=\"https://code.google.com/p/elmah/wiki/DotNetSlackersArticle#Error_Signaling\" rel=\"noreferrer\">Signaling</a>.</p>\n\n<p>This allows you to handle exceptions how you want, while still logging them to ELMAH.</p>\n\n<pre><code>try\n{\n int i = 5;\n int j = 0;\n i = i / j; //Throws exception\n}\ncatch (Exception ex)\n{\n MyPersonalHandlingCode(ex);\n ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling\n}\n</code></pre>\n\n<p>Re-throwing exceptions can be a bad practice as it makes it difficult to trace the flow of an application. Using Signaling is a much better approach if you intended to handle the error in some fashion and simply want to document it.</p>\n\n<p>Please check out this excellent guide by <a href=\"http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx\" rel=\"noreferrer\">DotNetSlackers on ELMAH</a></p>\n" }, { "answer_id": 13851034, "author": "Josh C", "author_id": 965935, "author_profile": "https://Stackoverflow.com/users/965935", "pm_score": 3, "selected": false, "text": "<p>A filter is the cleanest way to handle this problem. Check this solution here <a href=\"https://stackoverflow.com/a/5936867/965935\">https://stackoverflow.com/a/5936867/965935</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16891/" ]
Does [ELMAH](http://elmah.github.io/) logged exceptions even when they do not bubble up to the application? I'd like to pop up a message when an exception occurs and still log the exception. Currently I've been putting everything in try catch blocks and spitting out messages, but this gets tedious.
ELMAH has been updated to support a new feature called [Signaling](https://code.google.com/p/elmah/wiki/DotNetSlackersArticle#Error_Signaling). This allows you to handle exceptions how you want, while still logging them to ELMAH. ``` try { int i = 5; int j = 0; i = i / j; //Throws exception } catch (Exception ex) { MyPersonalHandlingCode(ex); ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling } ``` Re-throwing exceptions can be a bad practice as it makes it difficult to trace the flow of an application. Using Signaling is a much better approach if you intended to handle the error in some fashion and simply want to document it. Please check out this excellent guide by [DotNetSlackers on ELMAH](http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx)
88,399
<p>I saw <a href="https://stackoverflow.com/questions/73319/duplicate-a-whole-line-in-vim#73357">this same question for VIM</a> and it has been something that I myself wanted to know how to do for Emacs. In ReSharper I use CTRL-D for this action. What is the least number of commands to perform this in Emacs?</p>
[ { "answer_id": 88408, "author": "Arthur Thomas", "author_id": 14009, "author_profile": "https://Stackoverflow.com/users/14009", "pm_score": -1, "selected": false, "text": "<p>well ive usually used:</p>\n\n<pre>Ctl-Space (set the mark)\nmove to end of line\nCtl-K kill line\nCtl-Y * 2 (yank the line back)</pre>\n\n<p>there may be a much better way though :P</p>\n" }, { "answer_id": 88409, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 2, "selected": false, "text": "<p>because i don't know, i'll start this round of golf with a slowball:</p>\n\n<p>ctrl-k, y, y</p>\n" }, { "answer_id": 88427, "author": "CJP", "author_id": 13152, "author_profile": "https://Stackoverflow.com/users/13152", "pm_score": 2, "selected": false, "text": "<p><kbd>ctrl</kbd>-<kbd>k</kbd>, <kbd>ctrl</kbd>-<kbd>k</kbd>, (position to new location) <kbd>ctrl</kbd>-<kbd>y</kbd></p>\n\n<p>Add a <kbd>ctrl</kbd>-<kbd>a</kbd> if you're not starting at the beginning of the line. And the 2nd <kbd>ctrl</kbd>-<kbd>k</kbd> is to grab the newline character. It can be removed if you just want the text.</p>\n" }, { "answer_id": 88440, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 6, "selected": false, "text": "<p>Place cursor on line, if not at beginning do a <kbd>CTRL</kbd>-<kbd>A</kbd>, then:</p>\n\n<p><kbd>CTRL</kbd>-<kbd>K</kbd></p>\n\n<p><kbd>CTRL</kbd>-<kbd>K</kbd></p>\n\n<p><kbd>CTRL</kbd>-<kbd>Y</kbd></p>\n\n<p><kbd>CTRL</kbd>-<kbd>Y</kbd></p>\n" }, { "answer_id": 88468, "author": "Allen", "author_id": 6043, "author_profile": "https://Stackoverflow.com/users/6043", "pm_score": 2, "selected": false, "text": "<p>@[Kevin Conner]: Pretty close, so far as I know. The only other thing to consider is turning on <code>kill-whole-line</code> to include the newline in the C-k.</p>\n" }, { "answer_id": 88588, "author": "sverrejoh", "author_id": 473, "author_profile": "https://Stackoverflow.com/users/473", "pm_score": 2, "selected": false, "text": "<pre><code>C-a C-k C-k C-y C-y\n</code></pre>\n" }, { "answer_id": 88737, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 8, "selected": true, "text": "<p>I use </p>\n\n<pre><code>C-a C-SPACE C-n M-w C-y\n</code></pre>\n\n<p>which breaks down to</p>\n\n<ul>\n<li><code>C-a</code>: move cursor to start of line</li>\n<li><code>C-SPACE</code>: begin a selection (\"set mark\")</li>\n<li><code>C-n</code>: move cursor to next line</li>\n<li><code>M-w</code>: copy region</li>\n<li><code>C-y</code>: paste (\"yank\")</li>\n</ul>\n\n<p>The aforementioned</p>\n\n<pre><code>C-a C-k C-k C-y C-y\n</code></pre>\n\n<p>amounts to the same thing (TMTOWTDI)</p>\n\n<ul>\n<li><code>C-a</code>: move cursor to start of line</li>\n<li><code>C-k</code>: cut (\"kill\") the line</li>\n<li><code>C-k</code>: cut the newline</li>\n<li><code>C-y</code>: paste (\"yank\") (we're back at square one)</li>\n<li><code>C-y</code>: paste again (now we've got two copies of the line)</li>\n</ul>\n\n<p>These are both embarrassingly verbose compared to <code>C-d</code> in your editor, but in Emacs there's always a customization. <code>C-d</code> is bound to <code>delete-char</code> by default, so how about <code>C-c C-d</code>? Just add the following to your <code>.emacs</code>:</p>\n\n<pre><code>(global-set-key \"\\C-c\\C-d\" \"\\C-a\\C- \\C-n\\M-w\\C-y\")\n</code></pre>\n\n<p>(@Nathan's elisp version is probably preferable, because it won't break if any of the key bindings are changed.)</p>\n\n<p>Beware: some Emacs modes may reclaim <code>C-c C-d</code> to do something else.</p>\n" }, { "answer_id": 88828, "author": "Nate", "author_id": 17009, "author_profile": "https://Stackoverflow.com/users/17009", "pm_score": 7, "selected": false, "text": "<p>In addition to the previous answers you can also define your own function to duplicate a line. For example, putting the following in your .emacs file will make C-d duplicate the current line.</p>\n\n<pre><code>(defun duplicate-line()\n (interactive)\n (move-beginning-of-line 1)\n (kill-line)\n (yank)\n (open-line 1)\n (next-line 1)\n (yank)\n)\n(global-set-key (kbd \"C-d\") 'duplicate-line)\n</code></pre>\n" }, { "answer_id": 167972, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 3, "selected": false, "text": "<p>I have <code>copy-from-above-command</code> bound to a key and use that. It's provided with XEmacs, but I don't know about GNU Emacs.</p>\n\n<blockquote>\n <p>`copy-from-above-command' is an\n interactive compiled Lisp function<br>\n -- loaded from \"/usr/share/xemacs/21.4.15/lisp/misc.elc\"\n (copy-from-above-command &amp;optional\n ARG)</p>\n \n <p>Documentation: <strong>Copy characters from\n previous nonblank line</strong>, starting just\n above point. Copy ARG characters, but\n not past the end of that line. If no\n argument given, copy the entire rest\n of the line. The characters copied are\n inserted in the buffer before point.</p>\n</blockquote>\n" }, { "answer_id": 551053, "author": "pw.", "author_id": 66574, "author_profile": "https://Stackoverflow.com/users/66574", "pm_score": 4, "selected": false, "text": "<p>Nathan's addition to your .emacs file is the way to go but it could be simplified slightly by replacing </p>\n\n<pre><code> (open-line 1)\n (next-line 1)\n</code></pre>\n\n<p>with</p>\n\n<pre><code> (newline)\n</code></pre>\n\n<p>yielding</p>\n\n<pre><code>(defun duplicate-line()\n (interactive)\n (move-beginning-of-line 1)\n (kill-line)\n (yank)\n (newline)\n (yank)\n)\n(global-set-key (kbd \"C-d\") 'duplicate-line)\n</code></pre>\n" }, { "answer_id": 551290, "author": "polyglot", "author_id": 45383, "author_profile": "https://Stackoverflow.com/users/45383", "pm_score": 2, "selected": false, "text": "<p>something you might want to have in your .emacs is </p>\n\n<pre><code>(setq kill-whole-line t)\n</code></pre>\n\n<p>Which basically kills the entire line plus the newline whenever you invoke kill-line (i.e. via C-k). Then without extra code, you can just do C-a C-k C-y C-y to duplicate the line. It breaks down to </p>\n\n<pre><code>C-a go to beginning of line\nC-k kill-line (i.e. cut the line into clipboard)\nC-y yank (i.e. paste); the first time you get the killed line back; \n second time gives the duplicated line.\n</code></pre>\n\n<p>But if you use this often then maybe a dedicated key binding might be a better idea, but the advantage of just using C-a C-k C-y C-y is you can duplicate the line elsewhere, instead of just below the current line.</p>\n" }, { "answer_id": 890279, "author": "Marius Andersen", "author_id": 110198, "author_profile": "https://Stackoverflow.com/users/110198", "pm_score": 2, "selected": false, "text": "<p>The defaults are horrible for this. However, you can extend Emacs to work like SlickEdit and TextMate, that is, copy/cut the current line when no text is selected:</p>\n\n<pre><code>(transient-mark-mode t)\n(defadvice kill-ring-save (before slick-copy activate compile)\n \"When called interactively with no active region, copy a single line instead.\"\n (interactive\n (if mark-active (list (region-beginning) (region-end))\n (message \"Copied line\")\n (list (line-beginning-position)\n (line-beginning-position 2)))))\n(defadvice kill-region (before slick-cut activate compile)\n \"When called interactively with no active region, kill a single line instead.\"\n (interactive\n (if mark-active (list (region-beginning) (region-end))\n (list (line-beginning-position)\n (line-beginning-position 2)))))\n</code></pre>\n\n<p>Place the above in <code>.emacs</code>. Then, to copy a line, <code>M-w</code>. To delete a line, <code>C-w</code>. To duplicate a line, <code>C-a M-w C-y C-y C-y ...</code>.</p>\n" }, { "answer_id": 959435, "author": "mk-fg", "author_id": 1646435, "author_profile": "https://Stackoverflow.com/users/1646435", "pm_score": 3, "selected": false, "text": "<p>I don't quite remember how line duplication works anywhere else, but as a former SciTE user I liked one thing about SciTE-way: it doesn't touch the cursor position!\nSo all the recipies above weren't good enough for me, here's my hippie-version:</p>\n\n<pre><code>(defun duplicate-line ()\n \"Clone line at cursor, leaving the latter intact.\"\n (interactive)\n (save-excursion\n (let ((kill-read-only-ok t) deactivate-mark)\n (toggle-read-only 1)\n (kill-whole-line)\n (toggle-read-only 0)\n (yank))))\n</code></pre>\n\n<p>Note that nothing gets actually killed in process, leaving marks and current selection intact.</p>\n\n<p>BTW, why you guys so fond of jerking cursor around when there's this nice'n'clean kill-whole-line thingy (C-S-backspace)?</p>\n" }, { "answer_id": 998472, "author": "pesche", "author_id": 3686, "author_profile": "https://Stackoverflow.com/users/3686", "pm_score": 6, "selected": false, "text": "<p>My version of a function to duplicate a line that works nice with undo and doesn't mess with the cursor position. It was the result of a <a href=\"http://groups.google.com/group/gnu.emacs.sources/browse_thread/thread/c5f2992c108abd76/2810ac8f4fca534c?lnk=gst&amp;q=steiner#2810ac8f4fca534c\" rel=\"noreferrer\">discussion in gnu.emacs.sources from November 1997</a>.</p>\n\n<pre><code>(defun duplicate-line (arg)\n \"Duplicate current line, leaving point in lower line.\"\n (interactive \"*p\")\n\n ;; save the point for undo\n (setq buffer-undo-list (cons (point) buffer-undo-list))\n\n ;; local variables for start and end of line\n (let ((bol (save-excursion (beginning-of-line) (point)))\n eol)\n (save-excursion\n\n ;; don't use forward-line for this, because you would have\n ;; to check whether you are at the end of the buffer\n (end-of-line)\n (setq eol (point))\n\n ;; store the line and disable the recording of undo information\n (let ((line (buffer-substring bol eol))\n (buffer-undo-list t)\n (count arg))\n ;; insert the line arg times\n (while (&gt; count 0)\n (newline) ;; because there is no newline in 'line'\n (insert line)\n (setq count (1- count)))\n )\n\n ;; create the undo information\n (setq buffer-undo-list (cons (cons eol (point)) buffer-undo-list)))\n ) ; end-of-let\n\n ;; put the point in the lowest line and return\n (next-line arg))\n</code></pre>\n\n<p>Then you can define CTRL-D to call this function:</p>\n\n<pre><code>(global-set-key (kbd \"C-d\") 'duplicate-line)\n</code></pre>\n" }, { "answer_id": 1062326, "author": "Joyer", "author_id": 126671, "author_profile": "https://Stackoverflow.com/users/126671", "pm_score": 2, "selected": false, "text": "<p>' I wrote my own version of <code>duplicate-line</code>, cause I don't want to screw up the killing ring.</p>\n\n<pre><code> (defun jr-duplicate-line ()\n \"EASY\"\n (interactive)\n (save-excursion\n (let ((line-text (buffer-substring-no-properties\n (line-beginning-position)\n (line-end-position))))\n (move-end-of-line 1)\n (newline)\n (insert line-text))))\n (global-set-key \"\\C-cd\" 'jr-duplicate-line)\n</code></pre>\n" }, { "answer_id": 3206650, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 6, "selected": false, "text": "<p>Instead of <code>kill-line</code> (<code>C-k</code>) as in <code>C-a</code> <code>C-k</code> <code>C-k</code> <code>C-y</code> <code>C-y</code> use the <a href=\"http://www.gnu.org/software/emacs/manual/html_node/emacs/Killing-by-Lines.html\" rel=\"noreferrer\"><code>kill-whole-line</code></a> command:</p>\n\n<pre><code>C-S-Backspace\nC-y\nC-y\n</code></pre>\n\n<p>The advantages over <code>C-k</code> include that it does not matter where point is on the line (unlike <code>C-k</code> which requires being at start of the line) and it also kills the newline (again something <code>C-k</code> does not do).</p>\n" }, { "answer_id": 3208345, "author": "phils", "author_id": 324105, "author_profile": "https://Stackoverflow.com/users/324105", "pm_score": 2, "selected": false, "text": "<p>I liked FraGGod's version, except for two things: (1) It doesn't check whether the buffer is already read-only with <code>(interactive \"*\")</code>, and (2) it fails on the last line of the buffer if that last line is empty (as you cannot kill the line in that case), leaving your buffer read-only.</p>\n\n<p>I made the following changes to resolve that:</p>\n\n<pre><code>(defun duplicate-line ()\n \"Clone line at cursor, leaving the latter intact.\"\n (interactive \"*\")\n (save-excursion\n ;; The last line of the buffer cannot be killed\n ;; if it is empty. Instead, simply add a new line.\n (if (and (eobp) (bolp))\n (newline)\n ;; Otherwise kill the whole line, and yank it back.\n (let ((kill-read-only-ok t)\n deactivate-mark)\n (toggle-read-only 1)\n (kill-whole-line)\n (toggle-read-only 0)\n (yank)))))\n</code></pre>\n" }, { "answer_id": 3446738, "author": "Karthik", "author_id": 394835, "author_profile": "https://Stackoverflow.com/users/394835", "pm_score": 0, "selected": false, "text": "<p>With prefix arguments, and what is (I hope) intuitive behaviour:</p>\n\n<pre><code>(defun duplicate-line (&amp;optional arg)\n \"Duplicate it. With prefix ARG, duplicate ARG times.\"\n (interactive \"p\")\n (next-line \n (save-excursion \n (let ((beg (line-beginning-position))\n (end (line-end-position)))\n (copy-region-as-kill beg end)\n (dotimes (num arg arg)\n (end-of-line) (newline)\n (yank))))))\n</code></pre>\n\n<p>The cursor will remain on the last line.\nAlternatively, you might want to specify a prefix to duplicate the next few lines at once:</p>\n\n<pre><code>(defun duplicate-line (&amp;optional arg)\n \"Duplicate it. With prefix ARG, duplicate ARG times.\"\n (interactive \"p\")\n (save-excursion \n (let ((beg (line-beginning-position))\n (end \n (progn (forward-line (1- arg)) (line-end-position))))\n (copy-region-as-kill beg end)\n (end-of-line) (newline)\n (yank)))\n (next-line arg))\n</code></pre>\n\n<p>I find myself using both often, using a wrapper function to switch the behavior of the prefix argument.</p>\n\n<p>And a keybinding:\n<code>(global-set-key (kbd \"C-S-d\") 'duplicate-line)</code></p>\n" }, { "answer_id": 4717026, "author": "qmega", "author_id": 416571, "author_profile": "https://Stackoverflow.com/users/416571", "pm_score": 5, "selected": false, "text": "<p>Here's yet another function for doing this. My version doesn't touch the kill ring, and the cursor ends up on the new line where it was on the original. It will duplicate the region if it's active (transient mark mode), or default to duplicating the line otherwise. It will also make multiple copies if given a prefix arg, and comment out the original line if given a negative prefix arg (this is useful for testing a different version of a command/statement while keeping the old one).</p>\n\n<pre><code>(defun duplicate-line-or-region (&amp;optional n)\n \"Duplicate current line, or region if active.\nWith argument N, make N copies.\nWith negative N, comment out original line and use the absolute value.\"\n (interactive \"*p\")\n (let ((use-region (use-region-p)))\n (save-excursion\n (let ((text (if use-region ;Get region if active, otherwise line\n (buffer-substring (region-beginning) (region-end))\n (prog1 (thing-at-point 'line)\n (end-of-line)\n (if (&lt; 0 (forward-line 1)) ;Go to beginning of next line, or make a new one\n (newline))))))\n (dotimes (i (abs (or n 1))) ;Insert N times, or once if not specified\n (insert text))))\n (if use-region nil ;Only if we're working with a line (not a region)\n (let ((pos (- (point) (line-beginning-position)))) ;Save column\n (if (&gt; 0 n) ;Comment out original with negative arg\n (comment-region (line-beginning-position) (line-end-position)))\n (forward-line 1)\n (forward-char pos)))))\n</code></pre>\n\n<p>I have it bound to <code>C-c d</code>:</p>\n\n<pre><code>(global-set-key [?\\C-c ?d] 'duplicate-line-or-region)\n</code></pre>\n\n<p>This should never be re-assigned by a mode or anything because <code>C-c</code> followed by a single (unmodified) letter is reserved for user bindings.</p>\n" }, { "answer_id": 12119106, "author": "WisdomFusion", "author_id": 191071, "author_profile": "https://Stackoverflow.com/users/191071", "pm_score": 0, "selected": false, "text": "<pre><code>;; http://www.emacswiki.org/emacs/WholeLineOrRegion#toc2\n;; cut, copy, yank\n(defadvice kill-ring-save (around slick-copy activate)\n \"When called interactively with no active region, copy a single line instead.\"\n (if (or (use-region-p) (not (called-interactively-p)))\n ad-do-it\n (kill-new (buffer-substring (line-beginning-position)\n (line-beginning-position 2))\n nil '(yank-line))\n (message \"Copied line\")))\n(defadvice kill-region (around slick-copy activate)\n \"When called interactively with no active region, kill a single line instead.\"\n (if (or (use-region-p) (not (called-interactively-p)))\n ad-do-it\n (kill-new (filter-buffer-substring (line-beginning-position)\n (line-beginning-position 2) t)\n nil '(yank-line))))\n(defun yank-line (string)\n \"Insert STRING above the current line.\"\n (beginning-of-line)\n (unless (= (elt string (1- (length string))) ?\\n)\n (save-excursion (insert \"\\n\")))\n (insert string))\n\n(global-set-key (kbd \"&lt;f2&gt;\") 'kill-region) ; cut.\n(global-set-key (kbd \"&lt;f3&gt;\") 'kill-ring-save) ; copy.\n(global-set-key (kbd \"&lt;f4&gt;\") 'yank) ; paste.\n</code></pre>\n\n<p>add the elisp above to you init.el, and you get cut/copy whole line function now, then you can F3 F4 to duplicate a line.</p>\n" }, { "answer_id": 19916232, "author": "linbianxiaocao", "author_id": 2956795, "author_profile": "https://Stackoverflow.com/users/2956795", "pm_score": 0, "selected": false, "text": "<p>The simplest way is Chris Conway's method. </p>\n\n<pre><code>C-a C-SPACE C-n M-w C-y\n</code></pre>\n\n<p>That's the default way mandated by EMACS. In my opinion, it's better to use the standard. I am always careful towards customization one's own key-binding in EMACS. EMACS is already powerful enough, I think we should try our best to adapt to its own key-bindings. </p>\n\n<p>Though it's a bit lengthy, but when you are used to it, you can do fast and will find this is fun!</p>\n" }, { "answer_id": 20248584, "author": "Louis Kottmann", "author_id": 677014, "author_profile": "https://Stackoverflow.com/users/677014", "pm_score": 2, "selected": false, "text": "<p>With recent emacs, you can use M-w anywhere in the line to copy it. So it becomes:</p>\n\n<pre><code>M-w C-a RET C-y\n</code></pre>\n" }, { "answer_id": 24105783, "author": "kuanyui", "author_id": 1244729, "author_profile": "https://Stackoverflow.com/users/1244729", "pm_score": 1, "selected": false, "text": "<p>I write one for my preference.</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun duplicate-line ()\n \"Duplicate current line.\"\n (interactive)\n (let ((text (buffer-substring-no-properties (point-at-bol) (point-at-eol)))\n (cur-col (current-column)))\n (end-of-line) (insert \"\\n\" text)\n (beginning-of-line) (right-char cur-col)))\n(global-set-key (kbd \"C-c d l\") 'duplicate-line)\n</code></pre>\n\n<p>But I found this would have some problem when current line contains multi-byte characters (e.g. CJK characters). If you encounter this issue, try this instead:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun duplicate-line ()\n \"Duplicate current line.\"\n (interactive)\n (let* ((text (buffer-substring-no-properties (point-at-bol) (point-at-eol)))\n (cur-col (length (buffer-substring-no-properties (point-at-bol) (point)))))\n (end-of-line) (insert \"\\n\" text)\n (beginning-of-line) (right-char cur-col)))\n(global-set-key (kbd \"C-c d l\") 'duplicate-line)\n</code></pre>\n" }, { "answer_id": 26070201, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>install duplicate-thing from melpa:</p>\n\n<p>M-x package-install RET duplicate-thing</p>\n\n<p>and add this keybinding to <a href=\"https://www.gnu.org/software/emacs/manual/html_node/elisp/Init-File.html#Init-File\" rel=\"nofollow noreferrer\">init file</a> :</p>\n\n<p>(global-set-key (kbd \"M-c\") 'duplicate-thing)</p>\n" }, { "answer_id": 30977209, "author": "yPhil", "author_id": 1729094, "author_profile": "https://Stackoverflow.com/users/1729094", "pm_score": 2, "selected": false, "text": "<p>When called interactively with no active region, COPY (M-w) a single line instead :</p>\n<pre><code>(defadvice kill-ring-save (before slick-copy activate compile)\n &quot;When called interactively with no active region, COPY a single line instead.&quot;\n (interactive\n (if mark-active (list (region-beginning) (region-end))\n (message &quot;Copied line&quot;)\n (list (line-beginning-position)\n (line-beginning-position 2)))))\n</code></pre>\n<p>When called interactively with no active region, KILL (C-w) a single line instead.</p>\n<pre><code>(defadvice kill-region (before slick-cut activate compile)\n &quot;When called interactively with no active region, KILL a single line instead.&quot;\n (interactive\n (if mark-active (list (region-beginning) (region-end))\n (message &quot;Killed line&quot;)\n (list (line-beginning-position)\n (line-beginning-position 2)))))\n</code></pre>\n<p>Also, on a related note:</p>\n<pre><code>(defun move-line-up ()\n &quot;Move the current line up.&quot;\n (interactive)\n (transpose-lines 1)\n (forward-line -2)\n (indent-according-to-mode))\n\n(defun move-line-down ()\n &quot;Move the current line down.&quot;\n (interactive)\n (forward-line 1)\n (transpose-lines 1)\n (forward-line -1)\n (indent-according-to-mode))\n\n(global-set-key [(meta shift up)] 'move-line-up)\n(global-set-key [(meta shift down)] 'move-line-down)\n</code></pre>\n" }, { "answer_id": 38338217, "author": "user6581334", "author_id": 6581334, "author_profile": "https://Stackoverflow.com/users/6581334", "pm_score": 2, "selected": false, "text": "<p>I saw very complex solutions, anyway...</p>\n\n<pre><code>(defun duplicate-line ()\n \"Duplicate current line\"\n (interactive)\n (kill-whole-line)\n (yank)\n (yank))\n(global-set-key (kbd \"C-x M-d\") 'duplicate-line)\n</code></pre>\n" }, { "answer_id": 39643342, "author": "AesopHimself", "author_id": 3648760, "author_profile": "https://Stackoverflow.com/users/3648760", "pm_score": 2, "selected": false, "text": "<p>This functionality should match up with JetBrains' implementation in terms of duplicating both by line or region, and then leaving the point and/ or active region as expected:</p>\n\n<p>Just a wrapper to around the interactive form:</p>\n\n<pre><code>(defun wrx/duplicate-line-or-region (beg end)\n \"Implements functionality of JetBrains' `Command-d' shortcut for `duplicate-line'.\n BEG &amp; END correspond point &amp; mark, smaller first\n `use-region-p' explained: \n http://emacs.stackexchange.com/questions/12334/elisp-for-applying-command-to-only-the-selected-region#answer-12335\"\n (interactive \"r\")\n (if (use-region-p)\n (wrx/duplicate-region-in-buffer beg end)\n (wrx/duplicate-line-in-buffer)))\n</code></pre>\n\n<p>Which calls this,</p>\n\n<pre><code>(defun wrx/duplicate-region-in-buffer (beg end)\n \"copy and duplicate context of current active region\n |------------------------+----------------------------|\n | before | after |\n |------------------------+----------------------------|\n | first &lt;MARK&gt;line here | first line here |\n | second item&lt;POINT&gt; now | second item&lt;MARK&gt;line here |\n | | second item&lt;POINT&gt; now |\n |------------------------+----------------------------|\n TODO: Acts funky when point &lt; mark\"\n (set-mark-command nil)\n (insert (buffer-substring beg end))\n (setq deactivate-mark nil))\n</code></pre>\n\n<p>Or this</p>\n\n<pre><code>(defun wrx/duplicate-line-in-buffer ()\n \"Duplicate current line, maintaining column position.\n |--------------------------+--------------------------|\n | before | after |\n |--------------------------+--------------------------|\n | lorem ipsum&lt;POINT&gt; dolor | lorem ipsum dolor |\n | | lorem ipsum&lt;POINT&gt; dolor |\n |--------------------------+--------------------------|\n TODO: Save history for `Cmd-Z'\n Context: \n http://stackoverflow.com/questions/88399/how-do-i-duplicate-a-whole-line-in-emacs#answer-551053\"\n (setq columns-over (current-column))\n (save-excursion\n (kill-whole-line)\n (yank)\n (yank))\n (let (v)\n (dotimes (n columns-over v)\n (right-char)\n (setq v (cons n v))))\n (next-line))\n</code></pre>\n\n<p>And then I have this bound to meta+shift+d</p>\n\n<pre><code>(global-set-key (kbd \"M-D\") 'wrx/duplicate-line-or-region)\n</code></pre>\n" }, { "answer_id": 40905708, "author": "teksturi", "author_id": 7235121, "author_profile": "https://Stackoverflow.com/users/7235121", "pm_score": 2, "selected": false, "text": "<p>There is package called <a href=\"https://github.com/abo-abo/avy\" rel=\"nofollow noreferrer\">Avy</a> It has command avy-copy-line. When you use that command, every line in your window gets letter combination. Then you just have to type combination and you get that line. This also works for region. Then you just have to type two combination.</p>\n\n<p>Here you can see interface: </p>\n\n<p><a href=\"https://i.stack.imgur.com/63mnV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/63mnV.png\" alt=\"enter image description here\"></a>\n</p>\n" }, { "answer_id": 48330087, "author": "Dodgie", "author_id": 1851813, "author_profile": "https://Stackoverflow.com/users/1851813", "pm_score": 2, "selected": false, "text": "<p>Here's a function for duplicating current line. With prefix arguments, it will duplicate the line multiple times. E.g., <code>C-3 C-S-o</code> will duplicate the current line three times. Doesn't change kill ring.</p>\n<pre><code>(defun duplicate-lines (arg)\n (interactive &quot;P&quot;)\n (let* ((arg (if arg arg 1))\n (beg (save-excursion (beginning-of-line) (point)))\n (end (save-excursion (end-of-line) (point)))\n (line (buffer-substring-no-properties beg end)))\n (save-excursion\n (end-of-line)\n (open-line arg)\n (setq num 0)\n (while (&lt; num arg)\n (setq num (1+ num))\n (forward-line 1)\n (insert line))\n )))\n\n(global-set-key (kbd &quot;C-S-o&quot;) 'duplicate-lines)\n</code></pre>\n" }, { "answer_id": 52565378, "author": "Andy", "author_id": 1028665, "author_profile": "https://Stackoverflow.com/users/1028665", "pm_score": 1, "selected": false, "text": "<p>I cannot believe all these complicated solutions. This is two keystrokes:</p>\n\n<p><code>&lt;C-S-backspace&gt;</code> runs the command kill-whole-line</p>\n\n<p><code>C-/</code> runs the command undo</p>\n\n<p>So <code>&lt;C-S-backspace&gt; C-/</code> to \"copy\" a whole line (kill and undo).</p>\n\n<p>You can, of course, combine this with numeric and negative args to kill multiple lines either forward or backward.</p>\n" }, { "answer_id": 53071175, "author": "Shim Kporku", "author_id": 406569, "author_profile": "https://Stackoverflow.com/users/406569", "pm_score": 0, "selected": false, "text": "<p>This feels more natural, with respect to the selected answer by Chris Conway.</p>\n\n<p>(global-set-key \"\\C-c\\C-d\" \"\\C-a\\C- \\C-n\\M-w\\C-y\\C-p\\C-e\")</p>\n\n<p>This allows you to duplicate a line multiple times by simply repeating the \\C-c\\C-d key strokes.</p>\n" }, { "answer_id": 53670517, "author": "krsoni", "author_id": 3504244, "author_profile": "https://Stackoverflow.com/users/3504244", "pm_score": 1, "selected": false, "text": "<p>As mentioned in other answers, binding key strokes to lisp code is a better idea than binding them to another key strokes. With @mw's answer, code duplicates the line and moves the mark to end of new line. This modification keeps the mark position at same column on the new line:</p>\n\n<pre><code>fun duplicate-line ()\n (interactive)\n (let ((col (current-column)))\n (move-beginning-of-line 1)\n (kill-line)\n (yank)\n (newline)\n (yank)\n (move-to-column col)))\n</code></pre>\n" }, { "answer_id": 58221106, "author": "Dan Garland", "author_id": 875138, "author_profile": "https://Stackoverflow.com/users/875138", "pm_score": 2, "selected": false, "text": "<p>If you're using Spacemacs, you can simply use <code>duplicate-line-or-region</code>, bound to:</p>\n\n<pre><code>SPC x l d \n</code></pre>\n" }, { "answer_id": 63765602, "author": "Y.H Wong", "author_id": 226114, "author_profile": "https://Stackoverflow.com/users/226114", "pm_score": 2, "selected": false, "text": "<p>There's a package called 'move-dup' on Melpa that can help you with that.</p>\n<p>Disclaimer: I'm the author of that package.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
I saw [this same question for VIM](https://stackoverflow.com/questions/73319/duplicate-a-whole-line-in-vim#73357) and it has been something that I myself wanted to know how to do for Emacs. In ReSharper I use CTRL-D for this action. What is the least number of commands to perform this in Emacs?
I use ``` C-a C-SPACE C-n M-w C-y ``` which breaks down to * `C-a`: move cursor to start of line * `C-SPACE`: begin a selection ("set mark") * `C-n`: move cursor to next line * `M-w`: copy region * `C-y`: paste ("yank") The aforementioned ``` C-a C-k C-k C-y C-y ``` amounts to the same thing (TMTOWTDI) * `C-a`: move cursor to start of line * `C-k`: cut ("kill") the line * `C-k`: cut the newline * `C-y`: paste ("yank") (we're back at square one) * `C-y`: paste again (now we've got two copies of the line) These are both embarrassingly verbose compared to `C-d` in your editor, but in Emacs there's always a customization. `C-d` is bound to `delete-char` by default, so how about `C-c C-d`? Just add the following to your `.emacs`: ``` (global-set-key "\C-c\C-d" "\C-a\C- \C-n\M-w\C-y") ``` (@Nathan's elisp version is probably preferable, because it won't break if any of the key bindings are changed.) Beware: some Emacs modes may reclaim `C-c C-d` to do something else.
88,434
<p>I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on.</p> <p>Is this possible? And if so I'd like to have it detected before the client types their first letter.</p> <p>Is there a non-platform specific way to do this?</p>
[ { "answer_id": 88456, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 6, "selected": true, "text": "<p>Try this, from java.awt.Toolkit, returns a boolean:</p>\n\n<pre><code>Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)\n</code></pre>\n" }, { "answer_id": 88462, "author": "Arthur Thomas", "author_id": 14009, "author_profile": "https://Stackoverflow.com/users/14009", "pm_score": 1, "selected": false, "text": "<p>here is some info on the class\n<a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Toolkit.html#getLockingKeyState(int)\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Toolkit.html#getLockingKeyState(int)</a></p>\n" }, { "answer_id": 6574268, "author": "StephMW", "author_id": 93673, "author_profile": "https://Stackoverflow.com/users/93673", "pm_score": 1, "selected": false, "text": "<p>In addition to Nick's answer, to react to this condition before the user presses a key, you can listen to the focus event of your text entry component and test the caps-lock as the component receives focus.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on. Is this possible? And if so I'd like to have it detected before the client types their first letter. Is there a non-platform specific way to do this?
Try this, from java.awt.Toolkit, returns a boolean: ``` Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK) ```
88,454
<p>Most of the MVC samples I have seen pass an instance of the view to the controller like this</p> <pre><code>public class View { Controller controller = new Controller(this); } </code></pre> <p>Is there any advantage to passing a class which provides access to just the the properties and events the controller is interested in, like this:</p> <pre><code>public class UIWrapper { private TextBox textBox; public TextBox TextBox { get {return textBox;} } public UIWrapper(ref TextBox textBox) { this.textBox = textBox; } public class View { UIWrapper wrapper = new UIWrapper(this); Controller controller = new Controller(wrapper) } </code></pre>
[ { "answer_id": 90767, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 0, "selected": false, "text": "<p>This is probably not the solution you want, but just to help you with the log parsing, you can use this to get counts for each from the logs (assuming you're on a linux server) :</p>\n\n<pre><code>grep -c \\.swz web_log_dir/* \ngrep -c \\.swf web_log_dir/*\n</code></pre>\n" }, { "answer_id": 194582, "author": "James Fassett", "author_id": 27081, "author_profile": "https://Stackoverflow.com/users/27081", "pm_score": 2, "selected": false, "text": "<p>My advice is to use the cached framework regardless of your user-base. The fact is, you won't be alone in doing so and it will only be a matter of time before it pays off (even if it is on return visits).</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35031/" ]
Most of the MVC samples I have seen pass an instance of the view to the controller like this ``` public class View { Controller controller = new Controller(this); } ``` Is there any advantage to passing a class which provides access to just the the properties and events the controller is interested in, like this: ``` public class UIWrapper { private TextBox textBox; public TextBox TextBox { get {return textBox;} } public UIWrapper(ref TextBox textBox) { this.textBox = textBox; } public class View { UIWrapper wrapper = new UIWrapper(this); Controller controller = new Controller(wrapper) } ```
My advice is to use the cached framework regardless of your user-base. The fact is, you won't be alone in doing so and it will only be a matter of time before it pays off (even if it is on return visits).
88,460
<p>I'm trying to use libvirt with virsh to manage my kvm/qemu vms. The problem I have is with getting it to work with public IPs. The server is running ubuntu 8.04.</p> <p>libvirt keeps trying to run it as:</p> <pre><code>/usr/bin/kvm -M pc -m 256 -smp 3 -monitor pty -no-acpi \ -drive file=/opt/virtual-machines/calculon/root.qcow2,if=ide,boot=on \ -net nic,vlan=0,model=virtio -net tap,fd=10,vlan=0 -usb -vnc 127.0.0.1:0 </code></pre> <p>Which boots, but does not have any network access (pings go nowhere). Running it without fd=10 makes it work right, with kvm creating the necessary TAP device for me and networking functioning inside the host. All the setup guides I've seen focus on setting up masquerading, while I just want a simple bridge and unfiltered access to the net (both the guests and host must use public IPs). </p> <p>Running ifconfig on the host gives this, the bridge is manually setup in my /etc/network/interfaces file. :</p> <pre><code>br0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8 inet addr:12.34.56.78 Bcast:12.34.56.79 Mask:255.255.255.240 inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:3359 errors:0 dropped:0 overruns:0 frame:0 TX packets:3025 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:180646 (176.4 KB) TX bytes:230908 (225.4 KB) eth0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8 inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:6088386 errors:0 dropped:0 overruns:0 frame:0 TX packets:3058 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:680236624 (648.7 MB) TX bytes:261696 (255.5 KB) Interrupt:33 </code></pre> <p>Any help would be greatly appreciated.</p>
[ { "answer_id": 90689, "author": "AgentK", "author_id": 14868, "author_profile": "https://Stackoverflow.com/users/14868", "pm_score": 4, "selected": true, "text": "<p>I followed the bridged networking guide at <a href=\"https://help.ubuntu.com/community/KVM\" rel=\"noreferrer\">https://help.ubuntu.com/community/KVM</a> and have the following in /etc/network/interfaces:</p>\n\n<pre><code>auto eth0\niface eth0 inet manual\n\nauto br0\niface br0 inet static\n address 192.168.0.10\n network 192.168.0.0\n netmask 255.255.255.0\n broadcast 192.168.0.255\n gateway 192.168.0.1\n bridge_ports eth0\n bridge_fd 9\n bridge_hello 2\n bridge_maxage 12\n bridge_stp off\n</code></pre>\n\n<p>I have not changed any libvirt network settings and my kvm images are booted like:</p>\n\n<pre><code>/usr/bin/kvm -M pc -no-kqemu -m 256 -smp 1 -monitor pty -boot c -hda \\\n /libvirt/apt.img -net nic,macaddr=00:16:3e:77:32:1d,vlan=0 -net \\\n tap,fd=11,script=,vlan=0 -usb -vnc 127.0.0.1:0\n</code></pre>\n\n<p>I then specify the static network settings in the kvm image as normal. Has all worked ok since I followed the guide.</p>\n\n<p>I do have the following settings in my xml files in /etc/libvirt/qemu/ though under devices:</p>\n\n<pre><code>&lt;interface type='bridge'&gt;\n &lt;mac address='00:16:3e:77:32:1d'/&gt;\n &lt;source bridge='br0'/&gt;\n&lt;/interface&gt;\n</code></pre>\n" }, { "answer_id": 224727, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>i guess your tap device should be shown in ifconfig.</p>\n\n<p>run \"brctl show \"</p>\n\n<p>it will show bridge and tunnel device connection.</p>\n\n<p>you may have to put iptable entry show that all the packets will be routed through bridge</p>\n\n<p>iptables -I INPUT -i br0 -j ACCEPT</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11105/" ]
I'm trying to use libvirt with virsh to manage my kvm/qemu vms. The problem I have is with getting it to work with public IPs. The server is running ubuntu 8.04. libvirt keeps trying to run it as: ``` /usr/bin/kvm -M pc -m 256 -smp 3 -monitor pty -no-acpi \ -drive file=/opt/virtual-machines/calculon/root.qcow2,if=ide,boot=on \ -net nic,vlan=0,model=virtio -net tap,fd=10,vlan=0 -usb -vnc 127.0.0.1:0 ``` Which boots, but does not have any network access (pings go nowhere). Running it without fd=10 makes it work right, with kvm creating the necessary TAP device for me and networking functioning inside the host. All the setup guides I've seen focus on setting up masquerading, while I just want a simple bridge and unfiltered access to the net (both the guests and host must use public IPs). Running ifconfig on the host gives this, the bridge is manually setup in my /etc/network/interfaces file. : ``` br0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8 inet addr:12.34.56.78 Bcast:12.34.56.79 Mask:255.255.255.240 inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:3359 errors:0 dropped:0 overruns:0 frame:0 TX packets:3025 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:180646 (176.4 KB) TX bytes:230908 (225.4 KB) eth0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8 inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:6088386 errors:0 dropped:0 overruns:0 frame:0 TX packets:3058 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:680236624 (648.7 MB) TX bytes:261696 (255.5 KB) Interrupt:33 ``` Any help would be greatly appreciated.
I followed the bridged networking guide at <https://help.ubuntu.com/community/KVM> and have the following in /etc/network/interfaces: ``` auto eth0 iface eth0 inet manual auto br0 iface br0 inet static address 192.168.0.10 network 192.168.0.0 netmask 255.255.255.0 broadcast 192.168.0.255 gateway 192.168.0.1 bridge_ports eth0 bridge_fd 9 bridge_hello 2 bridge_maxage 12 bridge_stp off ``` I have not changed any libvirt network settings and my kvm images are booted like: ``` /usr/bin/kvm -M pc -no-kqemu -m 256 -smp 1 -monitor pty -boot c -hda \ /libvirt/apt.img -net nic,macaddr=00:16:3e:77:32:1d,vlan=0 -net \ tap,fd=11,script=,vlan=0 -usb -vnc 127.0.0.1:0 ``` I then specify the static network settings in the kvm image as normal. Has all worked ok since I followed the guide. I do have the following settings in my xml files in /etc/libvirt/qemu/ though under devices: ``` <interface type='bridge'> <mac address='00:16:3e:77:32:1d'/> <source bridge='br0'/> </interface> ```
88,473
<p>Does anybody know how to apply a "where in values" type condition using LINQ-to-Entities? I've tried the following but it doesn't work:</p> <pre><code>var values = new[] { "String1", "String2" }; // some string values var foo = model.entitySet.Where(e =&gt; values.Contains(e.Name)); </code></pre> <p>I believe this works in LINQ-to-SQL though? Any thoughts?</p>
[ { "answer_id": 88486, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>Yes it does translate to SQL, it generates a standard IN statement like this:</p>\n\n<pre><code>SELECT [t0].[col1]\nFROM [table] [t0]\nWHERE [col1] IN ( 'Value 1', 'Value 2')\n</code></pre>\n" }, { "answer_id": 88495, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Using the where method doesn't alway work</p>\n\n<pre><code>var results = from p in db.Products\n\n where p.Name == nameTextBox.Text\n\n select p;\n</code></pre>\n" }, { "answer_id": 88645, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 4, "selected": false, "text": "<p><strong>Update:</strong> found out how to do this. And EF will generate the appropriate SQL on the database. I'm not sure if this is for EF4 only but I got the tip from Entity Framework 4.0 Recipes</p>\n\n<hr>\n\n<pre><code>var listOfIds=GetAListOfIds();\nvar context=CreateEntityFrameworkObjectContext();\nvar results = from item in context.Items\n where listOfIds.Contains(item.Category.Id)\n select item;\n//results contains the items with matching category Ids\n</code></pre>\n\n<p>This query generates the correct in clause on the server side. I haven't tested it with EF 3.5 but it does work with EF4.</p>\n\n<p><strong>NB:</strong> The values passed into the in clause are NOT parameters so make sure you validate your inputs.</p>\n" }, { "answer_id": 89769, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": true, "text": "<p>It is somewhat of a shame that <a href=\"http://msdn.microsoft.com/en-us/library/bb738638.aspx\" rel=\"nofollow noreferrer\">Contains is not supported in Linq to Entities</a>.</p>\n\n<p>IN and JOIN are not the same operator (Filtering by IN never changes the cardinality of the query).</p>\n" }, { "answer_id": 96350, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 1, "selected": false, "text": "<p>Contains is not supported in EF at this time.</p>\n" }, { "answer_id": 2543363, "author": "Changgyu Oh", "author_id": 304851, "author_profile": "https://Stackoverflow.com/users/304851", "pm_score": 1, "selected": false, "text": "<p>FYI:</p>\n\n<p>If you are using ESql you are able to use in operation.\nI don't have VS 2008 With me but code should be something like following:</p>\n\n<pre><code>var ids = \"12, 34, 35\";\nusing (context = new Entites())\n{\n var selectedProducts = context.CreateQuery&lt;Products&gt;(\n String.Format(\"select value p from [Entities].Products as p \n where p.productId in {{{0}}}\", ids)).ToList();\n ...\n}\n</code></pre>\n" }, { "answer_id": 4759633, "author": "Lucian", "author_id": 158246, "author_profile": "https://Stackoverflow.com/users/158246", "pm_score": 1, "selected": false, "text": "<p>For the cases when you want to use expressions when querying your data, you can use the following extension method (adapted after <a href=\"http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/095745fe-dcf0-4142-b684-b7e4a1ab59f0/\" rel=\"nofollow\">http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/095745fe-dcf0-4142-b684-b7e4a1ab59f0/</a>):</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Data.Objects;\n\nnamespace Sample {\n public static class Extensions {\n public static IQueryable&lt;T&gt; ExtWhereIn&lt;T, TValue&gt;(this ObjectQuery&lt;T&gt; query,\n Expression&lt;Func&lt;T, TValue&gt;&gt; valueSelector,\n IEnumerable&lt;TValue&gt; values) {\n return query.Where(BuildContainsExpression&lt;T, TValue&gt;(valueSelector, values));\n }\n public static IQueryable&lt;T&gt; ExtWhereIn&lt;T, TValue&gt;(this IQueryable&lt;T&gt; query,\n Expression&lt;Func&lt;T, TValue&gt;&gt; valueSelector,\n IEnumerable&lt;TValue&gt; values) {\n return query.Where(BuildContainsExpression&lt;T, TValue&gt;(valueSelector, values));\n }\n private static Expression&lt;Func&lt;TElement, bool&gt;&gt; BuildContainsExpression&lt;TElement, TValue&gt;(\n Expression&lt;Func&lt;TElement, TValue&gt;&gt; valueSelector, IEnumerable&lt;TValue&gt; values) {\n if (null == valueSelector) { throw new ArgumentNullException(\"valueSelector\"); }\n if (null == values) { throw new ArgumentNullException(\"values\"); }\n ParameterExpression p = valueSelector.Parameters.Single();\n // p =&gt; valueSelector(p) == values[0] || valueSelector(p) == ...\n if (!values.Any()) {\n return e =&gt; false;\n }\n var equals = values.Select(value =&gt; (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));\n var body = equals.Aggregate&lt;Expression&gt;((accumulate, equal) =&gt; Expression.Or(accumulate, equal));\n return Expression.Lambda&lt;Func&lt;TElement, bool&gt;&gt;(body, p);\n }\n }\n class Program {\n static void Main(string[] args) {\n List&lt;int&gt; fullList = new List&lt;int&gt;();\n for (int i = 0; i &lt; 20; i++) {\n fullList.Add(i);\n }\n\n List&lt;int&gt; filter = new List&lt;int&gt;();\n filter.Add(2);\n filter.Add(5);\n filter.Add(10);\n\n List&lt;int&gt; results = fullList.AsQueryable().ExtWhereIn&lt;int, int&gt;(item =&gt; item, filter).ToList();\n foreach (int result in results) {\n Console.WriteLine(result);\n }\n }\n } \n}\n</code></pre>\n\n<p>Using the extensions is really easy (as you can see in the sample). To use it on a database object, assuming you are filtering a table called \"Product\" by more than one id, you could do something like that:</p>\n\n<pre><code>class Product {\n public int Id { get; set; }\n /// ... other properties\n}\n\n\nList&lt;Product&gt; GetProducts(List&lt;int&gt; productIds) { \n using (MyEntities context = new MyEntities()) {\n return context.Products.ExtWhereIn&lt;Product, int&gt;(product =&gt; product.Id, productIds).ToList();\n }\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16948/" ]
Does anybody know how to apply a "where in values" type condition using LINQ-to-Entities? I've tried the following but it doesn't work: ``` var values = new[] { "String1", "String2" }; // some string values var foo = model.entitySet.Where(e => values.Contains(e.Name)); ``` I believe this works in LINQ-to-SQL though? Any thoughts?
It is somewhat of a shame that [Contains is not supported in Linq to Entities](http://msdn.microsoft.com/en-us/library/bb738638.aspx). IN and JOIN are not the same operator (Filtering by IN never changes the cardinality of the query).
88,481
<p>I see that Adobe AIR uses WebKit as its render and I see that WebKit (at least the most current build) has some SVG support. Does this mean (and has anyone specifically tried) that an Adobe AIR application could render SVG on an HTML page?</p>
[ { "answer_id": 88513, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Adobe AIR can only support SVG once Adobe updates their version of WebKit (AIR's HTML rendering engine) and enables the SVG support within their version of WebKit. Might be a business decision not to (ie Flash).</p>\n" }, { "answer_id": 227999, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 2, "selected": false, "text": "<p>On the offchance that it's helpful (and that you don't already know), Flex can embed SVG at <s>runtime</s> compile time, which effectively converts it to SWF format and embeds it as a resource.</p>\n\n<pre><code>[Embed(source=\"assets/frog.svg\")]\n[Bindable]\npublic var SvgAsset:Class;\n</code></pre>\n\n<p>More info at Adobe's <a href=\"http://www.adobe.com/devnet/flex/quickstart/embedding_assets/#EmbeddingSvgFiles\" rel=\"nofollow noreferrer\">embedding assets article</a>.</p>\n" }, { "answer_id": 339209, "author": "Robin Rodricks", "author_id": 41021, "author_profile": "https://Stackoverflow.com/users/41021", "pm_score": 2, "selected": false, "text": "<p>If ActionScript 2: use the <strong>com.itechnica.svg</strong> (PathToArray) library to load SVGs at SWF runtime and display them <em>(uses XML for SVG parsing)</em>: </p>\n\n<p><a href=\"http://flash-creations.com/notes/sample_svgtoflash.php\" rel=\"nofollow noreferrer\">Using <strong>SVG Path Data</strong> in Flash</a>, Download button on the <strong>right pane.</strong></p>\n\n<hr>\n\n<p>If ActionScript 3: use the <strong>com.zavoo.svg</strong> (SvgPath) library to load SVGs at SWF runtime and display them <em>(uses RegExp for SVG parsing)</em>: </p>\n\n<p><a href=\"http://labs.zavoo.com/content/flex/DrawSvg/srcview/index.html\" rel=\"nofollow noreferrer\">Source code for <strong>SvgLoad</strong> and <strong>SvgDraw</strong></a>, Download button on the <strong>bottom-left.</strong></p>\n" }, { "answer_id": 4700534, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 2, "selected": false, "text": "<p><strong>No</strong>, according to the Adobe AIR Developer Center article <a href=\"http://www.adobe.com/devnet/air/ajax/articles/air_and_webkit.html\" rel=\"nofollow\">What's new about HTML, HTML5, CSS, and JavaScript in AIR 2.5?</a>.</p>\n\n<blockquote>\n <p><strong>SVG</strong> </p>\n \n <p>Another feature that has received\n a great deal of interest lately is\n support for SVG. While present in\n WebKit, the current version of Adobe\n AIR does not support SVG.</p>\n \n <p>The main reason for not including it\n was runtime size concerns (adding it\n would have increased the runtime size\n by 15 to 20 percent). Initially, the\n main pain-points regarding AIR were\n the size of the runtime, integration\n with the operating system and native\n APIs, support for the tag and\n new CSS properties, and JavaScript\n performance. These priorities, coupled\n with a trend toward reduced interest\n in SVG graphics, led to SVG support\n not being included in the current\n version of Adobe AIR.</p>\n \n <p>However, the renewed interest in rich\n JavaScript applications powered by\n HTML5 canvas and faster JavaScript\n engines increased the number of\n requests for scriptable vector\n graphics via SVG. Thus, adding support\n for SVG graphics may be considered for\n the next version of AIR.</p>\n</blockquote>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8256/" ]
I see that Adobe AIR uses WebKit as its render and I see that WebKit (at least the most current build) has some SVG support. Does this mean (and has anyone specifically tried) that an Adobe AIR application could render SVG on an HTML page?
On the offchance that it's helpful (and that you don't already know), Flex can embed SVG at ~~runtime~~ compile time, which effectively converts it to SWF format and embeds it as a resource. ``` [Embed(source="assets/frog.svg")] [Bindable] public var SvgAsset:Class; ``` More info at Adobe's [embedding assets article](http://www.adobe.com/devnet/flex/quickstart/embedding_assets/#EmbeddingSvgFiles).
88,485
<p>This is a follow up question to <a href="https://stackoverflow.com/questions/85815/how-to-tell-if-a-javascript-function-is-defined">This Question</a>. </p> <p>I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used:</p> <pre><code>function exist(sFN) { if(self[sFN]) return true; return false; } </code></pre> <p>It seems to work fine, although I don't understand how. Does it work? How? What are minuses of this approach? Should I switch to solution from the other question?</p>
[ { "answer_id": 88498, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 2, "selected": false, "text": "<p>just use <code>typeof</code>.</p>\n\n<pre><code>typeof(foobar) // -&gt; undefined\ntypeof(alert) // -&gt; function\n</code></pre>\n\n<p>You can't, however, defined a function based on typeof, because you'd need to pass an identifier which might not exist. So if you define <code>function isfun(sym) { return typeof(sym) }</code>, and then tried calling <code>isfun(inexistent)</code>, your code would throw.</p>\n\n<p>The fun thing about <code>typeof</code> is that it's an operator, not a function. So you can use it to check a symbol that's not defined without throwing.</p>\n\n<hr>\n\n<p>if you assume a function in the global scope (i.e., not within a closure), you can define a function to check it as follows:</p>\n\n<pre><code>function isfun(identifier) {\n return typeof(window[identifier]) == 'function';\n}\n</code></pre>\n\n<p>Here you pass an string for the identifier, so:</p>\n\n<pre><code>isfun('alert'); // -&gt; true\nisfun('foobar'); // -&gt; false\n</code></pre>\n\n<hr>\n\n<h3>closure?</h3>\n\n<p>Here's an example of a function defined within a closure. Here, the printed value would be <strong><code>false</code></strong>, which is wrong.</p>\n\n<pre><code>(function closure() { \n function enclosed() {}\n print(isfun('enclosed'))\n})()\n</code></pre>\n" }, { "answer_id": 88499, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>function exist(sFN) {\n return (typeof sFN == 'function');\n}\n</code></pre>\n" }, { "answer_id": 88523, "author": "Glenn", "author_id": 11814, "author_profile": "https://Stackoverflow.com/users/11814", "pm_score": 4, "selected": true, "text": "<p>Your condition is checking the existence of the \"sFN\" property in the \"self\" object. Anything that isn't null, undefined, 0, and \"\" will evaluate to true. </p>\n\n<p>As others have said, you can use typeof, or instanceof to see if it's actually a function. </p>\n\n<p>Looking at your linked example, you should read up on the difference between ==/!= and ===/!== in javascript. Short answer: (\"\" == null) is true, (\"\" === null) is false.</p>\n" }, { "answer_id": 88576, "author": "Tim Booker", "author_id": 10046, "author_profile": "https://Stackoverflow.com/users/10046", "pm_score": 0, "selected": false, "text": "<p>You can't really wrap this in a method, but it's so simple there is really no need.</p>\n\n<pre><code>function bob()\n{}\n\nif( typeof bob == \"function\" )\n alert( \"bob exists\" );\n\nif( typeof dave != \"function\" )\n alert( \"dave doesn't\" );\n</code></pre>\n" }, { "answer_id": 89471, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 1, "selected": false, "text": "<p>FYI: There is (or was) a nice pitfall for typeof.</p>\n\n<p>FF2 returns 'function' for typeof(/pattern/).\nFF3, IE7, and Chrome all return 'object' for the same code.\n(I can't verify other browsers.)</p>\n\n<p>Assuming everyone that used FF2 has upgraded, you're in the clear.\nBut, that's probably a far-fetched assumption.</p>\n" }, { "answer_id": 228703, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": -1, "selected": false, "text": "<p>I read somewhere (<a href=\"http://www.electrictoolbox.com/check-javascript-function-exists/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://bytes.com/forum/thread90633.html\" rel=\"nofollow noreferrer\">here</a>) that functions are properties of the window object, so you can do the following:</p>\n\n<pre><code>if (window.my_func_name) {\n my_func_name('tester!');\n}\n</code></pre>\n\n<p>or for popups:</p>\n\n<pre><code>if (window.opener.my_func_name) {\n my_func_name('tester!');\n}\n</code></pre>\n\n<p>A complete solution then:</p>\n\n<pre><code>function function_exists(func_name) {\n var eval_string;\n if (window.opener) {\n eval_string = 'window.opener.' + func_name;\n } else {\n eval_string = 'window.' + func_name;\n }\n return eval(eval_string + ' ? true : false');\n}\n</code></pre>\n" }, { "answer_id": 237798, "author": "Shaun", "author_id": 11627, "author_profile": "https://Stackoverflow.com/users/11627", "pm_score": 0, "selected": false, "text": "<p>Object.prototype.toString.apply(value) === '[object Function]'</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2515/" ]
This is a follow up question to [This Question](https://stackoverflow.com/questions/85815/how-to-tell-if-a-javascript-function-is-defined). I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used: ``` function exist(sFN) { if(self[sFN]) return true; return false; } ``` It seems to work fine, although I don't understand how. Does it work? How? What are minuses of this approach? Should I switch to solution from the other question?
Your condition is checking the existence of the "sFN" property in the "self" object. Anything that isn't null, undefined, 0, and "" will evaluate to true. As others have said, you can use typeof, or instanceof to see if it's actually a function. Looking at your linked example, you should read up on the difference between ==/!= and ===/!== in javascript. Short answer: ("" == null) is true, ("" === null) is false.
88,518
<p>I'm a complete perl novice, am running a perl script using perl 5.10 and getting this warning: </p> <pre><code>$* is no longer supported at migrate.pl line 380. </code></pre> <p>Can anyone describe what $* did and what the recommended replacement of it is now? Alternatively if you could point me to documentation that describes this that would be great.</p> <p>The script I'm running is to migrate a source code database from vss to svn and can be found here: <a href="http://www.x2systems.com/files/migrate.pl.txt" rel="noreferrer">http://www.x2systems.com/files/migrate.pl.txt</a></p> <p>The two snippets of code that use it are: </p> <pre><code> $* = 1; $/ = ':'; $cmd = $SSCMD . " Dir -I- \"$proj\""; $_ = `$cmd`; # what this next expression does is to merge wrapped lines like: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/excep # tion: # into: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/exception: s/\n((\w*\-*\.*\w*\/*)+\:)/$1/g; $* = 0; </code></pre> <p>and then some ways later on: </p> <pre><code> $cmd = $SSCMD . " get -GTM -W -I-Y -GL\"$localdir\" -V$version \"$file\" 2&gt;&amp;1"; $out = `$cmd`; # get rid of stupid VSS warning messages $* = 1; $out =~ s/\n?Project.*rebuilt\.//g; $out =~ s/\n?File.*rebuilt\.//g; $out =~ s/\n.*was moved out of this project.*rebuilt\.//g; $out =~ s/\nContinue anyway.*Y//g; $* = 0; </code></pre> <p>many thanks, </p> <ul> <li>Rory</li> </ul>
[ { "answer_id": 88528, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 1, "selected": false, "text": "<p>It turns on multi-line mode. Since perl 5.0 (from 1994), the correct way to do that is adding a <em><code>m</code></em> and/or the <em><code>s</code></em> modifier to your regexps, like this</p>\n\n<pre><code> s/\\n?Project.*rebuilt\\.//msg\n</code></pre>\n" }, { "answer_id": 88540, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://perldoc.perl.org/5.8.8/perlvar.html\" rel=\"nofollow noreferrer\">Perl 5.8 version of perlvar</a>:</p>\n\n<blockquote>\n <p>Set to a non-zero integer value to do\n multi-line matching within a string\n [...] Use of $* is deprecated in\n modern Perl, supplanted by the /s and\n /m modifiers on pattern matching.</p>\n</blockquote>\n\n<p>While using /s and /m is much better, you need to set the modifiers (appropriately!) for each regular expression.</p>\n\n<p>perlvar also says <em>\"This variable influences the interpretation of only ^ and $.\"</em> which gives the impression that it's equivalent to /m only and not /s.</p>\n\n<p>Note that <code>$*</code> is a global variable. Because the change to it is not made local with the <code>local</code> keyword, it will affect <strong>all</strong> regular expressions in the program, not just those that follow it in the block. This will make it more difficult to update the script correctly.</p>\n" }, { "answer_id": 88544, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 5, "selected": true, "text": "<p>From <a href=\"http://perldoc.perl.org/perlvar.html#%24*\" rel=\"nofollow noreferrer\">perlvar</a>:</p>\n\n<blockquote>\n <p>Use of $* is deprecated in modern Perl, supplanted by the /s and /m modifiers on pattern matching.</p>\n</blockquote>\n\n<p>If you have access to the place where it's being matched just add it to the end:</p>\n\n<pre><code> $haystack =~ m/.../sm;\n</code></pre>\n\n<p>If you only have access to the string, you can surround the expression with </p>\n\n<pre><code> qr/(?ms-ix:$expr)/;\n</code></pre>\n\n<p>Or in your case: </p>\n\n<pre><code>s/\\n((\\w*\\-*\\.*\\w*\\/*)+\\:)/$1/gsm;\n</code></pre>\n" }, { "answer_id": 88559, "author": "Alex", "author_id": 12204, "author_profile": "https://Stackoverflow.com/users/12204", "pm_score": 1, "selected": false, "text": "<p>It was basically a way of saying that in subsequent regexes (s/// or m//), the ^ or $ assertions should be able to match before or after newlines embedded in the string.</p>\n\n<p>The recommended equivalent is the m modifier at the end of your regex (e.g., s/\\n((\\w*-*.*\\w*/*)+:)/$1/gm;).</p>\n" }, { "answer_id": 88578, "author": "Notitze", "author_id": 9411, "author_profile": "https://Stackoverflow.com/users/9411", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://perldoc.perl.org/5.8.8/perlvar.html#%24%2a\" rel=\"nofollow noreferrer\">perldoc perlvar</a>:</p>\n<blockquote>\n<h3><code>$*</code></h3>\n<p>Set to a non-zero integer value to do multi-line matching within a string, 0 (or undefined) to tell Perl that it can assume that strings contain a single line, for the purpose of optimizing pattern matches. Pattern matches on strings containing multiple newlines can produce confusing results when <code>$*</code> is 0 or undefined. Default is undefined. (Mnemonic: <code>*</code> matches multiple things.) This variable influences the interpretation of only <code>^</code> and <code>$</code>. A literal newline can be searched for even when <code>$* == 0</code>.</p>\n<p>Use of <code>$*</code> is deprecated in modern Perl, supplanted by the <code>/s</code> and <code>/m</code> modifiers on pattern matching.</p>\n<p>Assigning a non-numerical value to <code>$*</code> triggers a warning (and makes <code>$*</code> act as if <code>$* == 0</code>), while assigning a numerical value to <code>$*</code> makes that an implicit int is applied on the value.</p>\n</blockquote>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8479/" ]
I'm a complete perl novice, am running a perl script using perl 5.10 and getting this warning: ``` $* is no longer supported at migrate.pl line 380. ``` Can anyone describe what $\* did and what the recommended replacement of it is now? Alternatively if you could point me to documentation that describes this that would be great. The script I'm running is to migrate a source code database from vss to svn and can be found here: <http://www.x2systems.com/files/migrate.pl.txt> The two snippets of code that use it are: ``` $* = 1; $/ = ':'; $cmd = $SSCMD . " Dir -I- \"$proj\""; $_ = `$cmd`; # what this next expression does is to merge wrapped lines like: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/excep # tion: # into: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/exception: s/\n((\w*\-*\.*\w*\/*)+\:)/$1/g; $* = 0; ``` and then some ways later on: ``` $cmd = $SSCMD . " get -GTM -W -I-Y -GL\"$localdir\" -V$version \"$file\" 2>&1"; $out = `$cmd`; # get rid of stupid VSS warning messages $* = 1; $out =~ s/\n?Project.*rebuilt\.//g; $out =~ s/\n?File.*rebuilt\.//g; $out =~ s/\n.*was moved out of this project.*rebuilt\.//g; $out =~ s/\nContinue anyway.*Y//g; $* = 0; ``` many thanks, * Rory
From [perlvar](http://perldoc.perl.org/perlvar.html#%24*): > > Use of $\* is deprecated in modern Perl, supplanted by the /s and /m modifiers on pattern matching. > > > If you have access to the place where it's being matched just add it to the end: ``` $haystack =~ m/.../sm; ``` If you only have access to the string, you can surround the expression with ``` qr/(?ms-ix:$expr)/; ``` Or in your case: ``` s/\n((\w*\-*\.*\w*\/*)+\:)/$1/gsm; ```
88,522
<p>I wanting to show prices for my products in my online store. I'm currently doing:</p> <pre><code>&lt;span class="ourprice"&gt; &lt;%=GetPrice().ToString("C")%&gt; &lt;/span&gt; </code></pre> <p>Where GetPrice() returns a decimal. So this currently returns a value e.g. "£12.00"</p> <p>I think the correct HTML for an output of "£12.00" is "<code>&amp;pound;12.00</code>", so although this is rendering fine in most browsers, some browsers (Mozilla) show this as $12.00. </p> <p>(The server is in the UK, with localisation is set appropriately in web.config).</p> <p>Is the below an improvement, or is there a better way?</p> <pre><code>&lt;span class="ourprice"&gt; &lt;%=GetPrice().ToString("C").Replace("£","&amp;pound;")%&gt; &lt;/span&gt; </code></pre>
[ { "answer_id": 88535, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 2, "selected": false, "text": "<p>Try this, it'll use your locale set for the application:</p>\n\n<pre><code>&lt;%=String.Format(\"{0:C}\",GetPrice())%&gt;\n</code></pre>\n" }, { "answer_id": 88553, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>If you need to explicity state the localisation you can use the CultureInfo and pass that to the string formatter.</p>\n" }, { "answer_id": 88555, "author": "Claus Thomsen", "author_id": 15555, "author_profile": "https://Stackoverflow.com/users/15555", "pm_score": 2, "selected": false, "text": "<p>Use </p>\n\n<pre><code>GetPrice().ToString(\"C\", CultureInfo.CreateSpecificCulture(\"en-GB\"))\n</code></pre>\n" }, { "answer_id": 88560, "author": "Peter Stuifzand", "author_id": 1633, "author_profile": "https://Stackoverflow.com/users/1633", "pm_score": 1, "selected": false, "text": "<p>You could write a function which would perform the conversion from price to string. This way you have a lot of control over the output. </p>\n\n<p>The problem with locale is that it's web server dependent and not web browser dependent.</p>\n" }, { "answer_id": 88759, "author": "typemismatch", "author_id": 13714, "author_profile": "https://Stackoverflow.com/users/13714", "pm_score": 0, "selected": false, "text": "<p>just use the ToString(\"C2\") property of a decimal value. Set your globalization in the web.config - keep it simple.</p>\n" }, { "answer_id": 91463, "author": "martin", "author_id": 8421, "author_profile": "https://Stackoverflow.com/users/8421", "pm_score": 3, "selected": true, "text": "<p>The £ symbol (U+00A3), and the html entities &amp; #163; and &amp; pound; should all render the same in a browser. </p>\n\n<p>If the browser doesn't recognise £, it probably won't recognise the entity versions.\nIt's in ISO 8859-1 (Latin-1), so I'd be surprised if a Mozilla browser can't render it (my FF certainly can).</p>\n\n<p>If you see a $ sign, it's likely you have two things:\n1. The browser default language is en-us\n2. Asp.net is doing automatic locale switching. The default web.config setting is something like</p>\n\n<pre><code>&lt;globalization culture=\"auto:en-us\" uiCulture=\"auto:en-US\" /&gt;\n</code></pre>\n\n<p>As you (almost certainly) want UK-only prices, simply specify the locale in web.config:</p>\n\n<pre><code> &lt;globalization culture=\"us\" uiCulture=\"en-gb\" /&gt;\n</code></pre>\n\n<p>(or on page level:)</p>\n\n<pre><code> &lt;%@Page Culture=\"en-gb\" UICulture=\"en-gb\" ..etc... %&gt;\n</code></pre>\n\n<p>Thereafter the string formats such as String.Format(\"{0:C}\",GetPrice()) and GetPrice().ToString(\"C\") will use the en-GB locale as asp.net will have set the currentCulture for you</p>\n\n<p>(although you can specify the en-gb culture in the overloads if you're paranoid).</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11538/" ]
I wanting to show prices for my products in my online store. I'm currently doing: ``` <span class="ourprice"> <%=GetPrice().ToString("C")%> </span> ``` Where GetPrice() returns a decimal. So this currently returns a value e.g. "£12.00" I think the correct HTML for an output of "£12.00" is "`&pound;12.00`", so although this is rendering fine in most browsers, some browsers (Mozilla) show this as $12.00. (The server is in the UK, with localisation is set appropriately in web.config). Is the below an improvement, or is there a better way? ``` <span class="ourprice"> <%=GetPrice().ToString("C").Replace("£","&pound;")%> </span> ```
The £ symbol (U+00A3), and the html entities & #163; and & pound; should all render the same in a browser. If the browser doesn't recognise £, it probably won't recognise the entity versions. It's in ISO 8859-1 (Latin-1), so I'd be surprised if a Mozilla browser can't render it (my FF certainly can). If you see a $ sign, it's likely you have two things: 1. The browser default language is en-us 2. Asp.net is doing automatic locale switching. The default web.config setting is something like ``` <globalization culture="auto:en-us" uiCulture="auto:en-US" /> ``` As you (almost certainly) want UK-only prices, simply specify the locale in web.config: ``` <globalization culture="us" uiCulture="en-gb" /> ``` (or on page level:) ``` <%@Page Culture="en-gb" UICulture="en-gb" ..etc... %> ``` Thereafter the string formats such as String.Format("{0:C}",GetPrice()) and GetPrice().ToString("C") will use the en-GB locale as asp.net will have set the currentCulture for you (although you can specify the en-gb culture in the overloads if you're paranoid).
88,546
<p>In Perl, a conditional can be expressed either as</p> <pre><code>if (condition) { do something } </code></pre> <p>or as</p> <pre><code>(condition) and do { do something } </code></pre> <p>Interestingly, the second way seems to be about 10% faster. Does anyone know why?</p>
[ { "answer_id": 88611, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": false, "text": "<p>I've deparsed it, and it really shouldn't be faster. The opcode tree for the first is</p>\n\n<pre><code>LISTOP (0x8177a18) leave [1] \n OP (0x8176590) enter \n COP (0x8177a40) nextstate \n LISTOP (0x8177b20) scope \n OP (0x81779b8) null [174] \n UNOP (0x8177c40) dofile \n SVOP (0x8177b58) const [1] PV (0x81546e4) \"something\" \n</code></pre>\n\n<p>The opcode tree for the second is </p>\n\n<pre><code>LISTOP (0x8177b28) leave [1] \n OP (0x8176598) enter \n COP (0x8177a48) nextstate \n UNOP (0x8177980) null \n LISTOP (0x8177ca0) scope \n OP (0x81779c0) null [174] \n UNOP (0x8177c48) dofile \n SVOP (0x8177b60) const [1] PV (0x81546e4) \"something\"\n</code></pre>\n\n<p>I really don't see how the latter could be faster. It does an opcode more!</p>\n" }, { "answer_id": 88937, "author": "shelfoo", "author_id": 3444, "author_profile": "https://Stackoverflow.com/users/3444", "pm_score": 2, "selected": false, "text": "<p>According to Benchmark, the second is slightly slower. Possibly it has something to do with the condition, but here's results for a very simple case:</p>\n\n<pre>\n<code>\nuse Benchmark;\n\ntimethese(10000000, {\n 'if' =&gt; '$m=5;if($m &gt; 4){my $i=0;}',\n 'and' => '$m=5; $m &gt; 4 and do {my $i =0}',\n});\n</code>\n</pre>\n\n<p>Results:</p>\n\n<pre>\n<code>\nBenchmark: timing 10000000 iterations of Name1, Name2...\n if: 3 wallclock secs ( 2.94 usr + 0.01 sys = 2.95 CPU) @ 3389830.51/s (n=10000000)\n and: 3 wallclock secs ( 3.01 usr + 0.01 sys = 3.02 CPU) @ 3311258.28/s (n=10000000)\n</code>\n</pre>\n" }, { "answer_id": 89848, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 4, "selected": false, "text": "<p>Which just goes to show, if you don't know how to do proper code profiling, don't be doing this stuff. The speed difference of these two methods are within the same Big O() speed (As proven by @Leon Timmermans opcode analyisis) - the benchmarks are just going to show differences based on other local conditions, not necessarily your code.</p>\n\n<p>@Svante said the \"and\" was faster, and @shelfoo said \"if\" was faster. </p>\n\n<p>I mean really... 7 hundredths of a second change for 10 million loops? That's not faster or slower, statistically.... that's equal.</p>\n\n<p>Instead of looking at miniscule timings like this, learn about code refactoring and Big O() notation... how to reduce the number of loops in your code... and most of all, how to use code profilers to see where the real bottlenecks are. Don't worry about the statistically insignificant stuff. ;)</p>\n" }, { "answer_id": 89857, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 2, "selected": false, "text": "<p>How many tests did you do before you averaged? Very, very small deviations are statistically insignificant! There are plenty of reasons for speed to vary slightly between tests.</p>\n" }, { "answer_id": 91147, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 4, "selected": false, "text": "<p>Some comments about the deparse below:</p>\n\n<p>First, don't use B::Terse, it's obsolete. B::Concise gives you much better information once you are used to it.</p>\n\n<p>Second, you've run it using the literal code given, so condition was taken as a bareword that happens to be true, so the boolean check was optimized away in both cases, which kind of defeats the purpose.</p>\n\n<p>Third, there isn't an extra opcode - the \"null\" indicates an opcode that's been optimized away (completely out of the execution tree, though still in the parse tree.)</p>\n\n<p>Here's the Concise execution tree for the two cases, which shows them as identical:</p>\n\n<pre><code>$ perl -MO=Concise,-exec -e'($condition) and do { do something }'\n1 &lt;0&gt; enter \n2 &lt;;&gt; nextstate(main 2 -e:1) v\n3 &lt;#&gt; gvsv[*condition] s\n4 &lt;|&gt; and(other-&gt;5) vK/1\n5 &lt;$&gt; const[PV \"something\"] s/BARE\n6 &lt;1&gt; dofile vK/1\n7 &lt;@&gt; leave[1 ref] vKP/REFC\n-e syntax OK\n$ perl -MO=Concise,-exec -e'if ($condition) { do something }'\n1 &lt;0&gt; enter \n2 &lt;;&gt; nextstate(main 3 -e:1) v\n3 &lt;#&gt; gvsv[*condition] s\n4 &lt;|&gt; and(other-&gt;5) vK/1\n5 &lt;$&gt; const[PV \"something\"] s/BARE\n6 &lt;1&gt; dofile vK/1\n7 &lt;@&gt; leave[1 ref] vKP/REFC\n-e syntax OK\n</code></pre>\n" }, { "answer_id": 93630, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 0, "selected": false, "text": "<p>It also could depend on the version of Perl. Which you haven't mentioned. And the difference is not enough to worry about anyway. So use whatever makes more sense.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In Perl, a conditional can be expressed either as ``` if (condition) { do something } ``` or as ``` (condition) and do { do something } ``` Interestingly, the second way seems to be about 10% faster. Does anyone know why?
I've deparsed it, and it really shouldn't be faster. The opcode tree for the first is ``` LISTOP (0x8177a18) leave [1] OP (0x8176590) enter COP (0x8177a40) nextstate LISTOP (0x8177b20) scope OP (0x81779b8) null [174] UNOP (0x8177c40) dofile SVOP (0x8177b58) const [1] PV (0x81546e4) "something" ``` The opcode tree for the second is ``` LISTOP (0x8177b28) leave [1] OP (0x8176598) enter COP (0x8177a48) nextstate UNOP (0x8177980) null LISTOP (0x8177ca0) scope OP (0x81779c0) null [174] UNOP (0x8177c48) dofile SVOP (0x8177b60) const [1] PV (0x81546e4) "something" ``` I really don't see how the latter could be faster. It does an opcode more!
88,554
<p>In <em>C++</em>, I can have take input like this: </p> <pre><code>cin &gt;&gt; a &gt;&gt; b &gt;&gt; c; </code></pre> <p>And <code>a</code> can be <code>int</code>, <code>b</code> can be <code>float</code>, and <code>c</code> can be whatever... How do I do the same in <em>python</em>?</p> <p><code>input()</code> and <code>raw_input()</code>, the way I'm using them, don't seem to be giving me the desired results.</p>
[ { "answer_id": 88587, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You generally shouldn't use <code>input()</code> in production code. If you want an <code>int</code> and then a <code>float</code>, try this:</p>\n\n<pre><code>&gt;&gt;&gt; line = raw_input().split()\n&gt;&gt;&gt; a = int(line[0])\n&gt;&gt;&gt; b = float(line[1])\n&gt;&gt;&gt; c = \" \".join(line[2:])\n</code></pre>\n\n<p>It all depends on what exactly you're trying to accomplish, but remember that readability counts. Obscure one-liners may seem cool but in the face of maintainability, try to choose something sensible :)</p>\n\n<p>(P.S.: Don't forget to check for errors with <code>try: ... except (ValueError, IndexError):</code>)</p>\n" }, { "answer_id": 88589, "author": "Paul Wicks", "author_id": 85, "author_profile": "https://Stackoverflow.com/users/85", "pm_score": 0, "selected": false, "text": "<p>Depending upon what you are doing, something like the <a href=\"http://docs.python.org/lib/module-getopt.html\" rel=\"nofollow noreferrer\">getopt</a> module could be useful, but only in certain situations and I'm not sure if it would apply in yours.</p>\n" }, { "answer_id": 88714, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>Since the C++ cin reads from sys.stdin, you'll often do something more like the following.</p>\n\n<pre><code>import sys\ntokens= sys.stdin.read().split()\ntry:\n a= int(token[0])\n b= float(token[1])\nexcept ValueError, e:\n print e # handle the invalid input\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10096/" ]
In *C++*, I can have take input like this: ``` cin >> a >> b >> c; ``` And `a` can be `int`, `b` can be `float`, and `c` can be whatever... How do I do the same in *python*? `input()` and `raw_input()`, the way I'm using them, don't seem to be giving me the desired results.
You generally shouldn't use `input()` in production code. If you want an `int` and then a `float`, try this: ``` >>> line = raw_input().split() >>> a = int(line[0]) >>> b = float(line[1]) >>> c = " ".join(line[2:]) ``` It all depends on what exactly you're trying to accomplish, but remember that readability counts. Obscure one-liners may seem cool but in the face of maintainability, try to choose something sensible :) (P.S.: Don't forget to check for errors with `try: ... except (ValueError, IndexError):`)
88,558
<p>I am making a game in C++ and am having problems with my derived class. I have a base class called GameScreen which has a vitrual void draw() function with no statements. I also have a derived class called MenuScreen which also has a virtual void draw() function and a derived class from MenuScreen called TestMenu which also has a void draw() function. In my program I have a list of GameScreens that I have a GameScreen iterator pass through calling each GameScreens draw() function.</p> <p>The issue is that I have placed a TestMenu object on the GameScreen list. Instead of the iterator calling the draw() function of TestMenu it is calling the draw() function of the GameScreen class. Does anyone know how I could call the draw() function of TestMenu instead of the one in GameScreen.</p> <p>Here is the function:</p> <pre><code>// Tell each screen to draw itself. //gsElement is a GameScreen iterator //gsScreens is a list of type GameScreen void Draw() { for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++) { /*if (gsElement-&gt;ssState == Hidden) continue;*/ gsElement-&gt;Draw(); } } </code></pre> <p>Here are a copy of my classes:</p> <pre><code>class GameScreen { public: string strName; bool bIsPopup; bool bOtherScreenHasFocus; ScreenState ssState; //ScreenManager smScreenManager; GameScreen(string strName){ this-&gt;strName = strName; } //Determine if the screen should be drawn or not bool IsActive(){ return !bOtherScreenHasFocus &amp;&amp; (ssState == Active); } //------------------------------------ //Load graphics content for the screen //------------------------------------ virtual void LoadContent(){ } //------------------------------------ //Unload content for the screen //------------------------------------ virtual void UnloadContent(){ } //------------------------------------------------------------------------- //Update changes whether the screen should be updated or not and sets //whether the screen should be drawn or not. // //Input: // bOtherScreenHasFocus - is used set whether the screen should update // bCoveredByOtherScreen - is used to set whether the screen is drawn or not //------------------------------------------------------------------------- virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ this-&gt;bOtherScreenHasFocus = bOtherScreenHasFocus; //if the screen is covered by another than change the screen state to hidden //else set the screen state to active if(bCoveredByOtherScreen){ ssState = Hidden; } else{ ssState = Active; } } //----------------------------------------------------------- //Takes input from the mouse and calls appropriate actions //----------------------------------------------------------- virtual void HandleInput(){ } //---------------------- //Draw content on screen //---------------------- virtual void Draw(){ } //-------------------------------------- //Deletes screen from the screen manager //-------------------------------------- void ExitScreen(){ //smScreenManager.RemoveScreen(*this); } }; class MenuScreen: public GameScreen{ public: vector &lt;BUTTON&gt; vbtnMenuEntries; MenuScreen(string strName):GameScreen(strName){ } virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ GameScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); for(unsigned int i = 0; i &lt; vbtnMenuEntries.size(); i++){ vbtnMenuEntries[i].IsPressed(); } } virtual void Draw(){ GameScreen::Draw(); for(unsigned int i = 0; i &lt; vbtnMenuEntries.size(); i++) vbtnMenuEntries[i].Draw(); } }; class testMenu : public MenuScreen{ public: vector&lt;OBJECT&gt; test; //OBJECT background3(); // OBJECT testPic(512, 384, buttonHover.png, 100, 40, 100, 40); // BUTTON x(256, 384, buttonNormal.png, buttonHover.png, buttonPressed.png, 100, 40, test()); bool draw; testMenu():MenuScreen("testMenu"){ OBJECT background3(1, 1, 0, TEXT("background.png"), 1, 1, 1024, 768); OBJECT testPic(512, 384,0, TEXT("buttonHover.png"), 1, 1, 100, 40); test.push_back(background3); test.push_back(testPic); //background3.Init(int xLoc, int yLoc, int zLoc, LPCTSTR filePath, int Rows, int Cols, int Width, int Height) //test.push_back(background3); // vbtnMenuEntries.push_back(x); draw = false; } void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ MenuScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); //cout &lt;&lt; "X" &lt;&lt; endl; /*if(MouseLButton == true){ testMenu2 t; smManager.AddScreen(t); }*/ } void Draw(){ //background3.Draw(); test[0].Draw(); test[1].Draw(); MenuScreen::Draw(); ///*if(draw){*/ // testPic.Draw(); //} } /*void test(){ draw = true; }*/ }; </code></pre>
[ { "answer_id": 88620, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 3, "selected": false, "text": "<p>If gsScreens is a list of objects instead of a list of pointers (as your code suggests), then you're not storing what you think you're storing in it.</p>\n\n<p>What's happening is that -- instead of putting a TestMenu into the list, you're actually constructing a new MenuScreen using the compiler-generated copy constructor and putting this MenuScreen into the list.</p>\n\n<p>C++ is polymorphic through pointers, so if you don't have a pointer you won't get polymorphic behavior.</p>\n" }, { "answer_id": 90612, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 1, "selected": false, "text": "<p>To get the polymorphic behavior you're after and at the same time use a <code>std::vector&lt;&gt;</code>, you must store <em>pointers</em> to the base class type in the vector, instead of storing <em>values</em>. Also, you must remember to free their memory before the vector goes out of scope.</p>\n\n<p>For instance:</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n\nstruct Base\n{\n virtual void Foo() = 0;\n virtual ~Base() { }\n};\n\nstruct Derived1 : public Base\n{\n void Foo() { }\n};\n\nstruct Derived2 : public Base\n{\n void Foo() { }\n};\n\nstruct delete_ptr\n{\n template &lt;typename T&gt;\n void operator()(T&amp; p)\n {\n delete p;\n p = 0;\n }\n};\n\nint wmain(int, wchar_t*[])\n{\n std::vector&lt;Base*&gt; items;\n items.push_back(new Derived1);\n items.push_back(new Derived2);\n\n Base&amp; first = items.front();\n first.Foo(); // Will boil down to Derived1::Foo().\n\n Base&amp; last = items.back();\n last.Foo(); // Will boil down to Derived2::Foo().\n\n std::for_each(items.begin(), items.end(), delete_ptr())\n};\n</code></pre>\n" }, { "answer_id": 90634, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/88558/c-derived-class-problems#88620\">Curt</a> is absolutely correct, but I'd just like to throw a little more information at it.</p>\n\n<p>This problem (storing base-class objects, rather than pointers) is sometimes called \"slicing\".</p>\n\n<p>Also, I tend to make use of the following macro:</p>\n\n<pre><code>#define DISALLOW_COPYING(X) \\\n private: \\\n X(const X &amp;); \\\n const X&amp; operator= (const X&amp; x)\n</code></pre>\n\n<p>Then you put this somewhere in your class definition:</p>\n\n<pre><code>class Foo {\n // ...\n DISALLOW_COPYING(Foo);\n};\n</code></pre>\n\n<p>If another class attempts to copy the object, you'll get a compiler error (because the methods are declared private). If the class itself attempts to copy the object, you'll get a linker error (because the methods have no implementation).</p>\n" }, { "answer_id": 94389, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 0, "selected": false, "text": "<p>Boost (www.boost.org, a library I would recommend anyone coding in C++ use) provides a noncopyable base class that does exactly that; you don't need an ugly macro that way.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am making a game in C++ and am having problems with my derived class. I have a base class called GameScreen which has a vitrual void draw() function with no statements. I also have a derived class called MenuScreen which also has a virtual void draw() function and a derived class from MenuScreen called TestMenu which also has a void draw() function. In my program I have a list of GameScreens that I have a GameScreen iterator pass through calling each GameScreens draw() function. The issue is that I have placed a TestMenu object on the GameScreen list. Instead of the iterator calling the draw() function of TestMenu it is calling the draw() function of the GameScreen class. Does anyone know how I could call the draw() function of TestMenu instead of the one in GameScreen. Here is the function: ``` // Tell each screen to draw itself. //gsElement is a GameScreen iterator //gsScreens is a list of type GameScreen void Draw() { for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++) { /*if (gsElement->ssState == Hidden) continue;*/ gsElement->Draw(); } } ``` Here are a copy of my classes: ``` class GameScreen { public: string strName; bool bIsPopup; bool bOtherScreenHasFocus; ScreenState ssState; //ScreenManager smScreenManager; GameScreen(string strName){ this->strName = strName; } //Determine if the screen should be drawn or not bool IsActive(){ return !bOtherScreenHasFocus && (ssState == Active); } //------------------------------------ //Load graphics content for the screen //------------------------------------ virtual void LoadContent(){ } //------------------------------------ //Unload content for the screen //------------------------------------ virtual void UnloadContent(){ } //------------------------------------------------------------------------- //Update changes whether the screen should be updated or not and sets //whether the screen should be drawn or not. // //Input: // bOtherScreenHasFocus - is used set whether the screen should update // bCoveredByOtherScreen - is used to set whether the screen is drawn or not //------------------------------------------------------------------------- virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ this->bOtherScreenHasFocus = bOtherScreenHasFocus; //if the screen is covered by another than change the screen state to hidden //else set the screen state to active if(bCoveredByOtherScreen){ ssState = Hidden; } else{ ssState = Active; } } //----------------------------------------------------------- //Takes input from the mouse and calls appropriate actions //----------------------------------------------------------- virtual void HandleInput(){ } //---------------------- //Draw content on screen //---------------------- virtual void Draw(){ } //-------------------------------------- //Deletes screen from the screen manager //-------------------------------------- void ExitScreen(){ //smScreenManager.RemoveScreen(*this); } }; class MenuScreen: public GameScreen{ public: vector <BUTTON> vbtnMenuEntries; MenuScreen(string strName):GameScreen(strName){ } virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ GameScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++){ vbtnMenuEntries[i].IsPressed(); } } virtual void Draw(){ GameScreen::Draw(); for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++) vbtnMenuEntries[i].Draw(); } }; class testMenu : public MenuScreen{ public: vector<OBJECT> test; //OBJECT background3(); // OBJECT testPic(512, 384, buttonHover.png, 100, 40, 100, 40); // BUTTON x(256, 384, buttonNormal.png, buttonHover.png, buttonPressed.png, 100, 40, test()); bool draw; testMenu():MenuScreen("testMenu"){ OBJECT background3(1, 1, 0, TEXT("background.png"), 1, 1, 1024, 768); OBJECT testPic(512, 384,0, TEXT("buttonHover.png"), 1, 1, 100, 40); test.push_back(background3); test.push_back(testPic); //background3.Init(int xLoc, int yLoc, int zLoc, LPCTSTR filePath, int Rows, int Cols, int Width, int Height) //test.push_back(background3); // vbtnMenuEntries.push_back(x); draw = false; } void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ MenuScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); //cout << "X" << endl; /*if(MouseLButton == true){ testMenu2 t; smManager.AddScreen(t); }*/ } void Draw(){ //background3.Draw(); test[0].Draw(); test[1].Draw(); MenuScreen::Draw(); ///*if(draw){*/ // testPic.Draw(); //} } /*void test(){ draw = true; }*/ }; ```
If gsScreens is a list of objects instead of a list of pointers (as your code suggests), then you're not storing what you think you're storing in it. What's happening is that -- instead of putting a TestMenu into the list, you're actually constructing a new MenuScreen using the compiler-generated copy constructor and putting this MenuScreen into the list. C++ is polymorphic through pointers, so if you don't have a pointer you won't get polymorphic behavior.
88,570
<p>Does anyone know if it's possible to use regex capture within Apache's DirectoryMatch directive? I'd like to do something like the following:</p> <pre><code>&lt;DirectoryMatch ^/home/www/(.*)&gt; AuthType Basic AuthName $1 AuthUserFile /etc/apache2/svn.passwd Require group $1 admin &lt;/DirectoryMatch&gt; </code></pre> <p>but so far I've had no success.</p> <p>Specifically, I'm trying to create a group-based HTTP Auth for individual directories/vhosts on a server in Apache 2.0. </p> <p>For example, Site A, pointing to /home/www/a will be available to all users in group admin and group a, site b at /home/www/b will be available to all users in group admin and group b, etc. I'd like to keep everything based on the directory name so I can easily script adding htpasswd users to the correct groups and automate this as much as possible, but other suggestions for solving the problem are certainly welcome.</p>
[ { "answer_id": 88704, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>What you are trying to do looks very similar to <a href=\"http://httpd.apache.org/docs/2.0/howto/public_html.html\" rel=\"nofollow noreferrer\">per-user home directories</a>. The way Apache handles these is through file system permissions and <a href=\"http://httpd.apache.org/docs/1.3/howto/htaccess.html\" rel=\"nofollow noreferrer\">.htaccess files</a>. I don't believe there is any way to use regex capture in the enclosed directives (AuthName, etc).</p>\n" }, { "answer_id": 91535, "author": "innaM", "author_id": 7498, "author_profile": "https://Stackoverflow.com/users/7498", "pm_score": 3, "selected": true, "text": "<p>You could tackle the problem from a completely different angle: enable the perl module and you can include a little perl script in your httpd.conf. You could then do something like this:</p>\n\n<pre><code>&lt;Perl&gt;\nmy @groups = qw/ foo bar baz /;\nforeach ( @groups ) {\n push @PerlConfig, qq| &lt;Directory /home/www/$_&gt; blah &lt;/Directory&gt; |;\n}\n&lt;/Perl&gt;\n</code></pre>\n\n<p>That way, you could even read your groups and other information from a database or by simply globbing /home/www or whatever else tickles your fancy.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16960/" ]
Does anyone know if it's possible to use regex capture within Apache's DirectoryMatch directive? I'd like to do something like the following: ``` <DirectoryMatch ^/home/www/(.*)> AuthType Basic AuthName $1 AuthUserFile /etc/apache2/svn.passwd Require group $1 admin </DirectoryMatch> ``` but so far I've had no success. Specifically, I'm trying to create a group-based HTTP Auth for individual directories/vhosts on a server in Apache 2.0. For example, Site A, pointing to /home/www/a will be available to all users in group admin and group a, site b at /home/www/b will be available to all users in group admin and group b, etc. I'd like to keep everything based on the directory name so I can easily script adding htpasswd users to the correct groups and automate this as much as possible, but other suggestions for solving the problem are certainly welcome.
You could tackle the problem from a completely different angle: enable the perl module and you can include a little perl script in your httpd.conf. You could then do something like this: ``` <Perl> my @groups = qw/ foo bar baz /; foreach ( @groups ) { push @PerlConfig, qq| <Directory /home/www/$_> blah </Directory> |; } </Perl> ``` That way, you could even read your groups and other information from a database or by simply globbing /home/www or whatever else tickles your fancy.
88,573
<p>In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example:</p> <pre><code>void foo() throw(); // guaranteed not to throw an exception void bar() throw(int); // may throw an exception of type int void baz() throw(...); // may throw an exception of some unspecified type </code></pre> <p>I'm doubtful about actually using them because of the following:</p> <ol> <li>The compiler doesn't really enforce exception specifiers in any rigorous way, so the benefits are not great. Ideally, you would like to get a compile error.</li> <li>If a function violates an exception specifier, I think the standard behaviour is to terminate the program.</li> <li>In VS.Net, it treats throw(X) as throw(...), so adherence to the standard is not strong.</li> </ol> <p>Do you think exception specifiers should be used?<br> Please answer with "yes" or "no" and provide some reasons to justify your answer.</p>
[ { "answer_id": 88591, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 2, "selected": false, "text": "<p>Generally I would not use exception specifiers. However, in cases where if any other exception were to come from the function in question that the program would definitively be unable to <em>correct</em>, then it can be useful. In all cases, make sure to document clearly what exceptions could be expected from that function.</p>\n\n<p>Yes, the expected behavior of a non-specified exception being thrown from a function with exception specifiers is to call terminate().</p>\n\n<p>I will also note that Scott Meyers addresses this subject in More Effective C++. His Effective C++ and More Effective C++ are highly recommended books.</p>\n" }, { "answer_id": 88599, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 2, "selected": false, "text": "<p>If you're writing code that will be used by people that would rather look at the function declaration than any comments around it, then a specification will tell them which exceptions they might want to catch.</p>\n\n<p>Otherwise I don't find it particularly useful to use anything but <code>throw()</code> to indicate that it doesn't throw any exceptions.</p>\n" }, { "answer_id": 88614, "author": "user10392", "author_id": 10392, "author_profile": "https://Stackoverflow.com/users/10392", "pm_score": 2, "selected": false, "text": "<p>Yes, if you're into internal documentation. Or maybe writing a libary that others will use, so that they can tell what happens without consulting the documentation. Throwing or not throwing can be considered part of the API, almost like the return value.</p>\n\n<p>I agree, they are not really useful for enforcing correctness Java style in the compiler, but it's better than nothing or haphazard comments.</p>\n" }, { "answer_id": 88637, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": false, "text": "<p>Avoid exception specifications in C++. The reasons you give in your question are a pretty good start for why.</p>\n\n<p>See Herb Sutter's <a href=\"http://www.gotw.ca/publications/mill22.htm\" rel=\"noreferrer\">\"A Pragmatic Look at Exception Specifications\"</a>.</p>\n" }, { "answer_id": 88669, "author": "Odd", "author_id": 11908, "author_profile": "https://Stackoverflow.com/users/11908", "pm_score": 2, "selected": false, "text": "<p>They can be useful for unit testing so that when writing tests you know what to expect the function to throw when it fails, but there is no enforcement surrounding them in the compiler. I think that they are extra code that is not necessary in C++. Which ever you choose all that you should be sure of is that you follow the same coding standard across the project and the team members so that your code remains readable.</p>\n" }, { "answer_id": 88905, "author": "Christopher", "author_id": 3186, "author_profile": "https://Stackoverflow.com/users/3186", "pm_score": 8, "selected": true, "text": "<p>No.</p>\n\n<p>Here are several examples why:</p>\n\n<ol>\n<li><p>Template code is impossible to write with exception specifications,</p>\n\n<pre><code>template&lt;class T&gt;\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\n</code></pre>\n\n<p>The copies might throw, the parameter passing might throw, and <code>x()</code> might throw some unknown exception.</p></li>\n<li><p>Exception-specifications tend to prohibit extensibility.</p>\n\n<pre><code>virtual void open() throw( FileNotFound );\n</code></pre>\n\n<p>might evolve into</p>\n\n<pre><code>virtual void open() throw( FileNotFound, SocketNotReady, InterprocessObjectNotImplemented, HardwareUnresponsive );\n</code></pre>\n\n<p>You could really write that as</p>\n\n<pre><code>throw( ... )\n</code></pre>\n\n<p>The first is not extensible, the second is overambitious and the third is really what you mean, when you write virtual functions.</p></li>\n<li><p>Legacy code</p>\n\n<p>When you write code which relies on another library, you don't really know what it might do when something goes horribly wrong.</p>\n\n<pre><code>int lib_f();\n\nvoid g() throw( k_too_small_exception )\n{ \n int k = lib_f();\n if( k &lt; 0 ) throw k_too_small_exception();\n}\n</code></pre>\n\n<p><code>g</code> will terminate, when <code>lib_f()</code> throws. This is (in most cases) not what you really want. <code>std::terminate()</code> should never be called. It is always better to let the application crash with an unhandled exception, from which you can retrieve a stack-trace, than to silently/violently die.</p></li>\n<li><p>Write code that returns common errors and throws on exceptional occasions.</p>\n\n<pre><code>Error e = open( \"bla.txt\" );\nif( e == FileNotFound )\n MessageUser( \"File bla.txt not found\" );\nif( e == AccessDenied )\n MessageUser( \"Failed to open bla.txt, because we don't have read rights ...\" );\nif( e != Success )\n MessageUser( \"Failed due to some other error, error code = \" + itoa( e ) );\n\ntry\n{\n std::vector&lt;TObj&gt; k( 1000 );\n // ...\n}\ncatch( const bad_alloc&amp; b )\n{ \n MessageUser( \"out of memory, exiting process\" );\n throw;\n}\n</code></pre></li>\n</ol>\n\n<p>Nevertheless, when your library just throws your own exceptions, you can use exception specifications to state your intent.</p>\n" }, { "answer_id": 89735, "author": "Jeremy", "author_id": 3657, "author_profile": "https://Stackoverflow.com/users/3657", "pm_score": 3, "selected": false, "text": "<p>gcc will emit warnings when you violate exception specifications. What I do is to use macros to use the exception specifications only in a \"lint\" mode compile expressly for checking to make sure the exceptions agree with my documentation.</p>\n" }, { "answer_id": 89790, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 4, "selected": false, "text": "<p>I think the standardly except convention (for C++)<br>\nException specifiers were an experiment in the C++ standard that mostly failed.<br>\nThe exception being that the no throw specifier is useful but you should also add the appropriate try catch block internally to make sure the code matches the specifier. Herb Sutter has a page on the subject. <a href=\"http://www.gotw.ca/gotw/082.htm\" rel=\"noreferrer\">Gotch 82</a></p>\n<p>In a addition I think it is worth describing Exception Guarantees.</p>\n<p>These are basically documentation on how the state of an object is affected by exceptions escaping a method on that object. Unfortunately they are not enforced or otherwise mentioned by the compiler.<br>\n<a href=\"http://www.boost.org/community/exception_safety.html\" rel=\"noreferrer\">Boost and Exceptions</a></p>\n<h2>Exception Guarantees</h2>\n<h3>No Guarantee:</h3>\n<blockquote>\n<p>There is no guarantee about the state of the object after an exception escapes a method<br>\nIn these situations the object should no longer be used.</p>\n</blockquote>\n<h3>Basic Guarantee:</h3>\n<blockquote>\n<p>In nearly all situations this should be the minimum guarantee a method provides.<br>\nThis guarantees the object's state is well defined and can still be consistently used.</p>\n</blockquote>\n<h3>Strong Guarantee: (aka Transactional Guarantee)</h3>\n<blockquote>\n<p>This guarantees that the method will complete successfully<br>\nOr an Exception will be thrown and the objects state will not change.</p>\n</blockquote>\n<h3>No Throw Guarantee:</h3>\n<blockquote>\n<p>The method guarantees that no exceptions are allowed to propagate out of the method.<br>\nAll destructors should make this guarantee.<br>\n| N.B. If an exception escapes a destructor while an exception is already propagating<br>\n| the application will terminate</p>\n</blockquote>\n" }, { "answer_id": 96564, "author": "Harold Ekstrom", "author_id": 8429, "author_profile": "https://Stackoverflow.com/users/8429", "pm_score": 3, "selected": false, "text": "<p>The only useful exception specifier is \"throw()\", as in \"doesn't throw\".</p>\n" }, { "answer_id": 98766, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "<p>No. If you use them and an exception is thrown that you did not specify, either by your code or code called by your code, then the default behavior is to promptly terminate your program.</p>\n\n<p>Also, I believe their use has been deprecated in current drafts of the C++0x standard.</p>\n" }, { "answer_id": 219544, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "<p>Exception specifications are not wonderfully useful tools in C++. However, there /is/ a good use for them, if combined with std::unexpected.</p>\n\n<p>What I do in some projects is code with exception specifications, and then call set_unexpected() with a function that will throw a special exception of my own design. This exception, upon construction, gets a backtrace (in a platform-specific manner) and is derived from std::bad_exception (to allow it to be propagated if desired). If it causes a terminate() call, as it usually does, the backtrace is printed by what() (as well as the original exception that caused it; not to hard to find that) and so I get information of where my contract was violated, such as what unexpected library exception was thrown.</p>\n\n<p>If I do this, I never allow propagation of library exceptions (except std ones) and derive all my exceptions from std::exception. If a library decides to throw, I will catch and convert into my own hierarchy, allowing for me to always control the code. Templated functions that call dependent functions should avoid exception specifications for obvious reasons; but it's rare to have a templated function interface with library code anyway (and few libraries really use templates in a useful manner).</p>\n" }, { "answer_id": 219552, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": -1, "selected": false, "text": "<p>Exception specifications = rubbish, ask any Java developer over the age of 30</p>\n" }, { "answer_id": 1941372, "author": "Marius", "author_id": 174650, "author_profile": "https://Stackoverflow.com/users/174650", "pm_score": 0, "selected": false, "text": "<p>From the article:</p>\n\n<p><a href=\"http://www.boost.org/community/exception_safety.html\" rel=\"nofollow noreferrer\">http://www.boost.org/community/exception_safety.html</a></p>\n\n<blockquote>\n <p>“It is well known to be impossible to\n write an exception-safe generic\n container.” This claim is often heard\n with reference to an article by Tom\n Cargill [4] in which he explores the\n problem of exception-safety for a\n generic stack template. In his\n article, Cargill raises many useful\n questions, but unfortunately fails to\n present a solution to his problem.1 He\n concludes by suggesting that a\n solution may not be possible.\n Unfortunately, his article was read by\n many as “proof” of that speculation.\n Since it was published there have been\n many examples of exception-safe\n generic components, among them the C++\n standard library containers.</p>\n</blockquote>\n\n<p>And indeed I can think of ways to make template classes exception safe. Unless you don't have control over all the sub-classes then you may have a problem anyway. To do this one could create typedefs in your classes that define the exceptions thrown by various template classes. This think the problem is as always tacking it on afterwards as opposed to designing it in from the start, and I think it's this overhead that's the real hurdle.</p>\n" }, { "answer_id": 2356721, "author": "TheJuice", "author_id": 105344, "author_profile": "https://Stackoverflow.com/users/105344", "pm_score": 2, "selected": false, "text": "<p>A \"throw()\" specification allows the compiler to perform some optimisations when doing code flow analysis if it know that function will never throw an exception (or at least promises to never throw an exception). Larry Osterman talks about this briefly here:</p>\n\n<p><a href=\"http://blogs.msdn.com/larryosterman/archive/2006/03/22/558390.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/larryosterman/archive/2006/03/22/558390.aspx</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example: ``` void foo() throw(); // guaranteed not to throw an exception void bar() throw(int); // may throw an exception of type int void baz() throw(...); // may throw an exception of some unspecified type ``` I'm doubtful about actually using them because of the following: 1. The compiler doesn't really enforce exception specifiers in any rigorous way, so the benefits are not great. Ideally, you would like to get a compile error. 2. If a function violates an exception specifier, I think the standard behaviour is to terminate the program. 3. In VS.Net, it treats throw(X) as throw(...), so adherence to the standard is not strong. Do you think exception specifiers should be used? Please answer with "yes" or "no" and provide some reasons to justify your answer.
No. Here are several examples why: 1. Template code is impossible to write with exception specifications, ``` template<class T> void f( T k ) { T x( k ); x.x(); } ``` The copies might throw, the parameter passing might throw, and `x()` might throw some unknown exception. 2. Exception-specifications tend to prohibit extensibility. ``` virtual void open() throw( FileNotFound ); ``` might evolve into ``` virtual void open() throw( FileNotFound, SocketNotReady, InterprocessObjectNotImplemented, HardwareUnresponsive ); ``` You could really write that as ``` throw( ... ) ``` The first is not extensible, the second is overambitious and the third is really what you mean, when you write virtual functions. 3. Legacy code When you write code which relies on another library, you don't really know what it might do when something goes horribly wrong. ``` int lib_f(); void g() throw( k_too_small_exception ) { int k = lib_f(); if( k < 0 ) throw k_too_small_exception(); } ``` `g` will terminate, when `lib_f()` throws. This is (in most cases) not what you really want. `std::terminate()` should never be called. It is always better to let the application crash with an unhandled exception, from which you can retrieve a stack-trace, than to silently/violently die. 4. Write code that returns common errors and throws on exceptional occasions. ``` Error e = open( "bla.txt" ); if( e == FileNotFound ) MessageUser( "File bla.txt not found" ); if( e == AccessDenied ) MessageUser( "Failed to open bla.txt, because we don't have read rights ..." ); if( e != Success ) MessageUser( "Failed due to some other error, error code = " + itoa( e ) ); try { std::vector<TObj> k( 1000 ); // ... } catch( const bad_alloc& b ) { MessageUser( "out of memory, exiting process" ); throw; } ``` Nevertheless, when your library just throws your own exceptions, you can use exception specifications to state your intent.
88,613
<p>How do I tokenize the string:</p> <pre><code>&quot;2+24*48/32&quot; </code></pre> <p>Into a list:</p> <pre><code>['2', '+', '24', '*', '48', '/', '32'] </code></pre>
[ { "answer_id": 88639, "author": "Cristian", "author_id": 680, "author_profile": "https://Stackoverflow.com/users/680", "pm_score": 2, "selected": false, "text": "<p>Regular expressions:</p>\n\n<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; splitter = re.compile(r'([+*/])')\n&gt;&gt;&gt; splitter.split(\"2+24*48/32\")\n</code></pre>\n\n<p>You can expand the regular expression to include any other characters you want to split on.</p>\n" }, { "answer_id": 88661, "author": "Jiayao Yu", "author_id": 10289, "author_profile": "https://Stackoverflow.com/users/10289", "pm_score": 3, "selected": false, "text": "<blockquote>\n <blockquote>\n <blockquote>\n <p>s = \"2+24*48/32\"</p>\n \n <p>p = re.compile(r'(\\W+)')</p>\n \n <p>p.split(s)</p>\n </blockquote>\n </blockquote>\n</blockquote>\n" }, { "answer_id": 88663, "author": "readonly", "author_id": 4883, "author_profile": "https://Stackoverflow.com/users/4883", "pm_score": 5, "selected": false, "text": "<p>You can use <code>split</code> from the <code>re</code> module. </p>\n\n<p><a href=\"http://docs.python.org/library/re.html#re.split\" rel=\"noreferrer\">re.split(pattern, string, maxsplit=0, flags=0)</a></p>\n\n<blockquote>\n <p>Split string by the occurrences of pattern. If capturing parentheses\n are used in pattern, then the text of all groups in the pattern are\n also returned as part of the resulting list.</p>\n</blockquote>\n\n<p>Example code:</p>\n\n<pre><code>import re\ndata = re.split(r'(\\D)', '2+24*48/32')\n</code></pre>\n\n<hr>\n\n<p>\\D</p>\n\n<blockquote>\n <p>When the UNICODE flag is not specified, \\D matches any non-digit\n character; this is equivalent to the set [^0-9].</p>\n</blockquote>\n" }, { "answer_id": 88783, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "<p>This looks like a parsing problem, and thus I am compelled to present a solution based on parsing techniques.</p>\n\n<p>While it may seem that you want to 'split' this string, I think what you actually want to do is 'tokenize' it. Tokenization or lexxing is the compilation step before parsing. I have amended my original example in an edit to implement a proper recursive decent parser here. This is the easiest way to implement a parser by hand.</p>\n\n<pre><code>import re\n\npatterns = [\n ('number', re.compile('\\d+')),\n ('*', re.compile(r'\\*')),\n ('/', re.compile(r'\\/')),\n ('+', re.compile(r'\\+')),\n ('-', re.compile(r'\\-')),\n]\nwhitespace = re.compile('\\W+')\n\ndef tokenize(string):\n while string:\n\n # strip off whitespace\n m = whitespace.match(string)\n if m:\n string = string[m.end():]\n\n for tokentype, pattern in patterns:\n m = pattern.match(string)\n if m:\n yield tokentype, m.group(0)\n string = string[m.end():]\n\ndef parseNumber(tokens):\n tokentype, literal = tokens.pop(0)\n assert tokentype == 'number'\n return int(literal)\n\ndef parseMultiplication(tokens):\n product = parseNumber(tokens)\n while tokens and tokens[0][0] in ('*', '/'):\n tokentype, literal = tokens.pop(0)\n if tokentype == '*':\n product *= parseNumber(tokens)\n elif tokentype == '/':\n product /= parseNumber(tokens)\n else:\n raise ValueError(\"Parse Error, unexpected %s %s\" % (tokentype, literal))\n\n return product\n\ndef parseAddition(tokens):\n total = parseMultiplication(tokens)\n while tokens and tokens[0][0] in ('+', '-'):\n tokentype, literal = tokens.pop(0)\n if tokentype == '+':\n total += parseMultiplication(tokens)\n elif tokentype == '-':\n total -= parseMultiplication(tokens)\n else:\n raise ValueError(\"Parse Error, unexpected %s %s\" % (tokentype, literal))\n\n return total\n\ndef parse(tokens):\n tokenlist = list(tokens)\n returnvalue = parseAddition(tokenlist)\n if tokenlist:\n print 'Unconsumed data', tokenlist\n return returnvalue\n\ndef main():\n string = '2+24*48/32'\n for tokentype, literal in tokenize(string):\n print tokentype, literal\n\n print parse(tokenize(string))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Implementation of handling of brackets is left as an exercise for the reader. This example will correctly do multiplication before addition.</p>\n" }, { "answer_id": 89003, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>i'm sure Tim meant </p>\n\n<pre><code>splitter = re.compile(r'([\\D])'). \n</code></pre>\n\n<p>if you copy exactly what he has down you only get the <code>digits</code> not the <code>operators</code>.</p>\n" }, { "answer_id": 89534, "author": "molasses", "author_id": 11293, "author_profile": "https://Stackoverflow.com/users/11293", "pm_score": 4, "selected": false, "text": "<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; re.findall(r'\\d+|\\D+', '2+24*48/32=10')\n\n['2', '+', '24', '*', '48', '/', '32', '=', '10']\n</code></pre>\n\n<p>Matches consecutive digits or consecutive non-digits.</p>\n\n<p>Each match is returned as a new element in the list.</p>\n\n<p>Depending on the usage, you may need to alter the regular expression. Such as if you need to match numbers with a decimal point.</p>\n\n<pre><code>&gt;&gt;&gt; re.findall(r'[0-9\\.]+|[^0-9\\.]+', '2+24*48/32=10.1')\n\n['2', '+', '24', '*', '48', '/', '32', '=', '10.1']\n</code></pre>\n" }, { "answer_id": 89666, "author": "habnabit", "author_id": 10999, "author_profile": "https://Stackoverflow.com/users/10999", "pm_score": 2, "selected": false, "text": "<p>Another solution to this would be to avoid writing a calculator like that altogether. Writing an RPN parser is much simpler, and doesn't have any of the ambiguity inherent in writing math with infix notation.</p>\n\n<pre><code>import operator, math\ncalc_operands = {\n '+': (2, operator.add),\n '-': (2, operator.sub),\n '*': (2, operator.mul),\n '/': (2, operator.truediv),\n '//': (2, operator.div),\n '%': (2, operator.mod),\n '^': (2, operator.pow),\n '**': (2, math.pow),\n 'abs': (1, operator.abs),\n 'ceil': (1, math.ceil),\n 'floor': (1, math.floor),\n 'round': (2, round),\n 'trunc': (1, int),\n 'log': (2, math.log),\n 'ln': (1, math.log),\n 'pi': (0, lambda: math.pi),\n 'e': (0, lambda: math.e),\n}\n\ndef calculate(inp):\n stack = []\n for tok in inp.split():\n if tok in self.calc_operands:\n n_pops, func = self.calc_operands[tok]\n args = [stack.pop() for x in xrange(n_pops)]\n args.reverse()\n stack.append(func(*args))\n elif '.' in tok:\n stack.append(float(tok))\n else:\n stack.append(int(tok))\n if not stack:\n raise ValueError('no items on the stack.')\n return stack.pop()\n if stack:\n raise ValueError('%d item(s) left on the stack.' % len(stack))\n\ncalculate('24 38 * 32 / 2 +')\n</code></pre>\n" }, { "answer_id": 100283, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 3, "selected": false, "text": "<p>This is a parsing problem, so neither regex not split() are the \"good\" solution. Use a parser generator instead.</p>\n\n<p>I would look closely at <a href=\"http://pyparsing.wikispaces.com/\" rel=\"noreferrer\">pyparsing</a>. There have also been some decent articles about pyparsing in the <a href=\"http://pymag.phparch.com/\" rel=\"noreferrer\">Python Magazine</a>.</p>\n" }, { "answer_id": 111355, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 6, "selected": false, "text": "<p>It just so happens that the tokens you want split are already Python tokens, so you can use the built-in <code>tokenize</code> module. It's almost a one-liner; this program:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from io import StringIO\nfrom tokenize import generate_tokens\n\nSTRING = 1\nprint(\n list(\n token[STRING]\n for token in generate_tokens(StringIO(&quot;2+24*48/32&quot;).readline)\n if token[STRING]\n )\n)\n</code></pre>\n<p>produces this output:</p>\n<pre class=\"lang-py prettyprint-override\"><code>['2', '+', '24', '*', '48', '/', '32']\n</code></pre>\n" }, { "answer_id": 3517872, "author": "Timotheos", "author_id": 423481, "author_profile": "https://Stackoverflow.com/users/423481", "pm_score": 0, "selected": false, "text": "<p>This doesn't answer the question exactly, but I believe it solves what you're trying to achieve. I would add it as a comment, but I don't have permission to do so yet.</p>\n\n<p>I personally would take advantage of Python's maths functionality directly with exec:</p>\n\n<blockquote>\n <p>expression = \"2+24*48/32\"<br>\n <strong>exec</strong> \"result = \" + expression<br>\n <strong>print</strong> result<br>\n 38</p>\n</blockquote>\n" }, { "answer_id": 8863507, "author": "jbchichoko", "author_id": 1126747, "author_profile": "https://Stackoverflow.com/users/1126747", "pm_score": 1, "selected": false, "text": "<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; my_string = \"2+24*48/32\"\n&gt;&gt;&gt; my_list = re.findall(r\"-?\\d+|\\S\", my_string)\n&gt;&gt;&gt; print my_list\n\n['2', '+', '24', '*', '48', '/', '32']\n</code></pre>\n\n<p>This will do the trick. I have encountered this kind of problem before.</p>\n" }, { "answer_id": 72064350, "author": "Xinyue Zhang", "author_id": 18994381, "author_profile": "https://Stackoverflow.com/users/18994381", "pm_score": 0, "selected": false, "text": "<p>Here is a good way that I always use when splitting str with different special characters. However, this code does not work with _, if there is a _ in the str you want to split, you might need to do another split one more time.</p>\n<pre><code>import re\n \n \n# initializing string \ndata = &quot;2+24*48/32&quot;\n \n# printing original string \nprint(&quot;The original string is : &quot; + data) \n \n# Using re.findall() \n# Splitting characters in String \nres = re.findall(r&quot;[\\w']+&quot;, data)\n \n# printing result \nprint(&quot;The list after performing split functionality : &quot; + str(res)) \n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I tokenize the string: ``` "2+24*48/32" ``` Into a list: ``` ['2', '+', '24', '*', '48', '/', '32'] ```
It just so happens that the tokens you want split are already Python tokens, so you can use the built-in `tokenize` module. It's almost a one-liner; this program: ```py from io import StringIO from tokenize import generate_tokens STRING = 1 print( list( token[STRING] for token in generate_tokens(StringIO("2+24*48/32").readline) if token[STRING] ) ) ``` produces this output: ```py ['2', '+', '24', '*', '48', '/', '32'] ```
88,651
<p>Is it possible to get notifications using <a href="http://www.microsoft.com/sql/technologies/reporting/default.mspx" rel="nofollow noreferrer">SQL Server Reporting Services</a>? Say for example I have a report that I want by mail if has for example suddenly shows more than 10 rows or if a specific value drop below 100 000. Do I need to tie Notification Services into it and how do I do that?</p> <p>Please provide as much technical details as possible as I've never used <a href="http://www.microsoft.com/sql/technologies/notification/default.mspx" rel="nofollow noreferrer">Notification Services</a> before.</p> <p>Someone also told me that Notifications Services is replaced by new functionality in Reporting Services in Sql Server 2008 - is this the case?</p>
[ { "answer_id": 90762, "author": "Simon Munro", "author_id": 3893, "author_profile": "https://Stackoverflow.com/users/3893", "pm_score": 0, "selected": false, "text": "<p>I wouldn't go down the ntofications services route - it is pretty much a deprecated feature of SQL Server and even if it is around in future it will stagnate. So don't build a dependency on it.</p>\n" }, { "answer_id": 211006, "author": "Booji Boy", "author_id": 1433, "author_profile": "https://Stackoverflow.com/users/1433", "pm_score": 0, "selected": false, "text": "<p>Depending on your needs a data driven SSRS subscription to e-mail you the report would probably work. \n<a href=\"http://msdn.microsoft.com/en-us/library/ms159150(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms159150(SQL.90).aspx</a></p>\n" }, { "answer_id": 220505, "author": "balaweblog", "author_id": 22162, "author_profile": "https://Stackoverflow.com/users/22162", "pm_score": 0, "selected": false, "text": "<p>Sending mail using SSRS subscription to your data driven report</p>\n" }, { "answer_id": 239482, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 3, "selected": true, "text": "<p>I'd agree with Simon re Notification Services</p>\n\n<p>Also, data driven SSRS Subscriptions are not available unless you use Enterprise Edition (and isn't available if you use SharePoint Integrated Mode).</p>\n\n<p>An alternate way would be to create an Agent job that runs a proc. The proc could check the conditions you require and kick off the subscription if they are met using: </p>\n\n<pre><code>exec ReportServer.dbo.AddEvent @EventType='TimedSubscription', @EventData='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx'\n</code></pre>\n\n<p>Where the @EventData is the ID of the subscription in dbo.Subscriptions.</p>\n\n<p>This will drop a row in [dbo].[Event]. The Service polls this table a few times a minute to kick off subscriptions.</p>\n\n<p>Really, this isn't far from what happens when you set up a new Subscription, might even be easier to create a Subscription in the Report Server site, find which agent job was created (the ones with GUID names) and edit the T-SQL.</p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 12324264, "author": "Kumar Manish", "author_id": 1051234, "author_profile": "https://Stackoverflow.com/users/1051234", "pm_score": 0, "selected": false, "text": "<p>A data-driven subscription is composed of multiple parts. The fixed aspects of a data-driven subscription are defined when you create the subscription, and these include the following:</p>\n\n<p>The report for which the subscription is defined (a subscription is always associated with a single report).\nThe delivery extension used to distribute the report. You can specify report server e-mail delivery, file share delivery, the null delivery provider used for preloading the cache, or a custom delivery extension. You cannot specify multiple delivery extensions within a single subscription.\nThe subscriber data source. You must specify a connection string to the data source that contains subscriber data when you define the subscription. The subscriber data source cannot be specified dynamically at run time.\nThe query that you use to select subscriber data must be specified when you define the subscription. You cannot change the query at run time.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298/" ]
Is it possible to get notifications using [SQL Server Reporting Services](http://www.microsoft.com/sql/technologies/reporting/default.mspx)? Say for example I have a report that I want by mail if has for example suddenly shows more than 10 rows or if a specific value drop below 100 000. Do I need to tie Notification Services into it and how do I do that? Please provide as much technical details as possible as I've never used [Notification Services](http://www.microsoft.com/sql/technologies/notification/default.mspx) before. Someone also told me that Notifications Services is replaced by new functionality in Reporting Services in Sql Server 2008 - is this the case?
I'd agree with Simon re Notification Services Also, data driven SSRS Subscriptions are not available unless you use Enterprise Edition (and isn't available if you use SharePoint Integrated Mode). An alternate way would be to create an Agent job that runs a proc. The proc could check the conditions you require and kick off the subscription if they are met using: ``` exec ReportServer.dbo.AddEvent @EventType='TimedSubscription', @EventData='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx' ``` Where the @EventData is the ID of the subscription in dbo.Subscriptions. This will drop a row in [dbo].[Event]. The Service polls this table a few times a minute to kick off subscriptions. Really, this isn't far from what happens when you set up a new Subscription, might even be easier to create a Subscription in the Report Server site, find which agent job was created (the ones with GUID names) and edit the T-SQL. Hope this helps
88,682
<p>What's the best way to serialize a HashTable (or a data best navigated through a string indexer) with SOAP/XML?</p> <p>Let's say I have a <code>Foo</code> that has an property <code>Bar[] Bars</code>. A <code>Bar</code> object has a key and a value. By default, this serializes to the following XML:</p> <pre><code>&lt;Foo&gt; &lt;Bars&gt; &lt;Bar key="key0" value="value0"/&gt; ... &lt;/Bars&gt; &lt;/Foo&gt; </code></pre> <p>For JSON, this serializes to:</p> <pre><code>{"Foo":["Bars":[{"Key":"key0","Value":"key1} ... ]}]} </code></pre> <p>What I'd really like to have is this serialize to better reflect the underlying relationship. E.g., </p> <pre><code>&lt;Foo&gt; &lt;Bars&gt; &lt;Key0 value="value0"/&gt; &lt;Key1 value="value1"/&gt; ... &lt;/Bars&gt; &lt;/Foo&gt; </code></pre> <p>I realize there are some challenges with serializing to SOAP in this way, but what's the best approach to providing a schema that better reflects this? </p> <p>I've tried creating a BarsCollection object and defining custom serialization on that, but it doesn't seem to actually invoke the serialization on that object. E.g.</p> <pre><code>void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { foreach (Bar bar in Bars){ info.AddValue(bar.Key. bar); } } </code></pre> <p>Any suggestions? What's the best practice here? </p>
[ { "answer_id": 88707, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>ISerializable isn't used for xml serialization; its used for binary serialization. You would be better implementing IXmlSerializable.</p>\n\n<p>But I think that the KeyedCollection serializes more like you're thinking. Except you'll never get &lt;key0 ... /> &lt;key1 ... /> since the elements map to classes.</p>\n" }, { "answer_id": 88760, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 0, "selected": false, "text": "<p>You could pass the hashtable in a SOAP Extension. That way, you can serialize it whichever way you would like. Although there is custom code for this that has to be on the client and server.</p>\n" }, { "answer_id": 88899, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": true, "text": "<p>I really don't think that what you want reflects the structure better. To define a schema (think XSD) for this you would have to know all of the potential keys in advance since you indicate that you want each one to be a separate custom type. Conceptually Bars would be an array of objects holding objects of type Key0, Key1, with each of the KeyN class containing a value property. I believe that the first serialization actually is the best reflection of the underlying structure. The reason it \"works\" more like you want in JSON is that you lose the typing -- everything is just an object. If you don't care about the types why not just use JSON?</p>\n" }, { "answer_id": 92659, "author": "jsmith", "author_id": 17658, "author_profile": "https://Stackoverflow.com/users/17658", "pm_score": 0, "selected": false, "text": "<p>I think you're missing a fundamental key of the SOAP protocol.</p>\n\n<p>One of the things I really like about the SOAP protocol is that you can define arbitrary objects (along with methods) in your WSDL file and pass these objects around from one end to the other using the SOAP protocol. You don't have to serialize the data on one end and then unserialize it on the other end.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242/" ]
What's the best way to serialize a HashTable (or a data best navigated through a string indexer) with SOAP/XML? Let's say I have a `Foo` that has an property `Bar[] Bars`. A `Bar` object has a key and a value. By default, this serializes to the following XML: ``` <Foo> <Bars> <Bar key="key0" value="value0"/> ... </Bars> </Foo> ``` For JSON, this serializes to: ``` {"Foo":["Bars":[{"Key":"key0","Value":"key1} ... ]}]} ``` What I'd really like to have is this serialize to better reflect the underlying relationship. E.g., ``` <Foo> <Bars> <Key0 value="value0"/> <Key1 value="value1"/> ... </Bars> </Foo> ``` I realize there are some challenges with serializing to SOAP in this way, but what's the best approach to providing a schema that better reflects this? I've tried creating a BarsCollection object and defining custom serialization on that, but it doesn't seem to actually invoke the serialization on that object. E.g. ``` void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { foreach (Bar bar in Bars){ info.AddValue(bar.Key. bar); } } ``` Any suggestions? What's the best practice here?
I really don't think that what you want reflects the structure better. To define a schema (think XSD) for this you would have to know all of the potential keys in advance since you indicate that you want each one to be a separate custom type. Conceptually Bars would be an array of objects holding objects of type Key0, Key1, with each of the KeyN class containing a value property. I believe that the first serialization actually is the best reflection of the underlying structure. The reason it "works" more like you want in JSON is that you lose the typing -- everything is just an object. If you don't care about the types why not just use JSON?
88,710
<p>I need to create a repeatable process for deploying SQL Server Reporting Services reports. I am not in favor of using Visual Studio and or Business Development Studio to do this. The rs.exe method of scripting deployments also seems rather clunky. Does anyone have a very elegant way that they have been able to deploy reports. The key here is that I want the process to be completely automated.</p>
[ { "answer_id": 88722, "author": "cori", "author_id": 8151, "author_profile": "https://Stackoverflow.com/users/8151", "pm_score": 0, "selected": false, "text": "<p>I know you say that you're not in favor of the Business Development Studio to do this, but I've found the built-in tools to be very reliable and easy to use.</p>\n" }, { "answer_id": 88735, "author": "Ray", "author_id": 233, "author_profile": "https://Stackoverflow.com/users/233", "pm_score": 1, "selected": false, "text": "<p>Well not really elegant. We created our own tool that uses the reportingservices2005 web service. We found this to be the most reliable way of getting what we want.</p>\n\n<p>It's not really that difficult and lets you expand it to do other things like creating data sources and folders as required.</p>\n" }, { "answer_id": 88873, "author": "Vyrotek", "author_id": 10941, "author_profile": "https://Stackoverflow.com/users/10941", "pm_score": 0, "selected": false, "text": "<p>Have you looked into any Continuous Integration solutions such as CruiseControl.NET? If you are able to deploy Reports using rs.exe then you can setup an automated process in CruiseControl to build and deploy your Reports on a timer or whenever a report is modified.</p>\n" }, { "answer_id": 91077, "author": "Lukáš Rampa", "author_id": 10560, "author_profile": "https://Stackoverflow.com/users/10560", "pm_score": 6, "selected": true, "text": "<p>We use rs.exe, once we developed the script we have not needed to touch it anymore, it just works.</p>\n\n<p>Here is the source (I slightly modified it by hand to remove sensitive data without a chance to test it, hope I did not brake anything), it deploys reports and associated images from subdirectories for various languages. Also datasource is created.</p>\n\n<pre><code>'=====================================================================\n' File: PublishReports.rss\n'\n' Summary: Script that can be used with RS.exe to \n' publish the reports.\n'\n' Rss file spans from beginnig of this comment to end of module\n' (except of \"End Module\").\n'=====================================================================\n\nDim langPaths As String() = {\"en\", \"cs\", \"pl\", \"de\"}\nDim filePath As String = Environment.CurrentDirectory\n\nPublic Sub Main()\n\n rs.Credentials = System.Net.CredentialCache.DefaultCredentials\n\n 'Create parent folder\n Try\n rs.CreateFolder(parentFolder, \"/\", Nothing)\n Console.WriteLine(\"Parent folder created: {0}\", parentFolder)\n Catch e As Exception\n Console.WriteLine(e.Message)\n End Try\n\n PublishLanguagesFromFolder(filePath)\n\nEnd Sub\n\nPublic Sub PublishLanguagesFromFolder(ByVal folder As String)\n Dim Lang As Integer\n Dim langPath As String\n\n For Lang = langPaths.GetLowerBound(0) To langPaths.GetUpperBound(0)\n langPath = langPaths(Lang)\n\n 'Create the lang folder\n Try\n rs.CreateFolder(langPath, \"/\" + parentFolder, Nothing)\n Console.WriteLine(\"Parent lang folder created: {0}\", parentFolder + \"/\" + langPath)\n Catch e As Exception\n Console.WriteLine(e.Message)\n End Try\n\n 'Create the shared data source\n CreateDataSource(\"/\" + parentFolder + \"/\" + langPath)\n\n 'Publish reports and images\n PublishFolderContents(folder + \"\\\" + langPath, \"/\" + parentFolder + \"/\" + langPath)\n Next 'Lang\nEnd Sub\n\nPublic Sub CreateDataSource(ByVal targetFolder As String)\n Dim name As String = \"data source\"\n\n 'Data source definition.\n Dim definition As New DataSourceDefinition\n definition.CredentialRetrieval = CredentialRetrievalEnum.Store\n definition.ConnectString = \"data source=\" + dbServer + \";initial catalog=\" + db\n definition.Enabled = True\n definition.EnabledSpecified = True\n definition.Extension = \"SQL\"\n definition.ImpersonateUser = False\n definition.ImpersonateUserSpecified = True\n 'Use the default prompt string.\n definition.Prompt = Nothing\n definition.WindowsCredentials = False\n 'Login information\n definition.UserName = \"user\"\n definition.Password = \"password\"\n\n Try\n 'name, folder, overwrite, definition, properties \n rs.CreateDataSource(name, targetFolder, True, definition, Nothing)\n Catch e As Exception\n Console.WriteLine(e.Message)\n End Try\n\nEnd Sub\n\nPublic Sub PublishFolderContents(ByVal sourceFolder As String, ByVal targetFolder As String)\n Dim di As New DirectoryInfo(sourceFolder)\n Dim fis As FileInfo() = di.GetFiles()\n Dim fi As FileInfo\n\n Dim fileName As String\n\n For Each fi In fis\n fileName = fi.Name\n Select Case fileName.Substring(fileName.Length - 4).ToUpper\n Case \".RDL\"\n PublishReport(sourceFolder, fileName, targetFolder)\n Case \".JPG\", \".JPEG\"\n PublishResource(sourceFolder, fileName, \"image/jpeg\", targetFolder)\n Case \".GIF\", \".PNG\", \".BMP\"\n PublishResource(sourceFolder, fileName, \"image/\" + fileName.Substring(fileName.Length - 3).ToLower, targetFolder)\n End Select\n Next fi\nEnd Sub\n\nPublic Sub PublishReport(ByVal sourceFolder As String, ByVal reportName As String, ByVal targetFolder As String)\n Dim definition As [Byte]() = Nothing\n Dim warnings As Warning() = Nothing\n\n Try\n Dim stream As FileStream = File.OpenRead(sourceFolder + \"\\\" + reportName)\n definition = New [Byte](stream.Length) {}\n stream.Read(definition, 0, CInt(stream.Length))\n stream.Close()\n Catch e As IOException\n Console.WriteLine(e.Message)\n End Try\n\n Try\n 'name, folder, overwrite, definition, properties \n warnings = rs.CreateReport(reportName.Substring(0, reportName.Length - 4), targetFolder, True, definition, Nothing)\n\n If Not (warnings Is Nothing) Then\n Dim warning As Warning\n For Each warning In warnings\n Console.WriteLine(warning.Message)\n Next warning\n Else\n Console.WriteLine(\"Report: {0} published successfully with no warnings\", targetFolder + \"/\" + reportName)\n End If\n Catch e As Exception\n Console.WriteLine(e.Message)\n End Try\nEnd Sub\n\nPublic Sub PublishResource(ByVal sourceFolder As String, ByVal resourceName As String, ByVal resourceMIME As String, ByVal targetFolder As String)\n Dim definition As [Byte]() = Nothing\n Dim warnings As Warning() = Nothing\n\n Try\n Dim stream As FileStream = File.OpenRead(sourceFolder + \"\\\" + resourceName)\n definition = New [Byte](stream.Length) {}\n stream.Read(definition, 0, CInt(stream.Length))\n stream.Close()\n Catch e As IOException\n Console.WriteLine(e.Message)\n End Try\n\n Try\n 'name, folder, overwrite, definition, MIME, properties \n rs.CreateResource(resourceName, targetFolder, True, definition, resourceMIME, Nothing)\n Console.WriteLine(\"Resource: {0} with MIME {1} created successfully\", targetFolder + \"/\" + resourceName, resourceMIME)\n Catch e As Exception\n Console.WriteLine(e.Message)\n End Try\nEnd Sub\n</code></pre>\n\n<p>Here is the batch to call the rs.exe:</p>\n\n<pre><code>SET ReportServer=%1\nSET DBServer=%2\nSET DBName=%3\nSET ReportFolder=%4\n\nrs -i PublishReports.rss -s %ReportServer% -v dbServer=\"%DBServer%\" -v db=\"%DBName%\" -v parentFolder=\"%ReportFolder%\" &gt;PublishReports.log 2&gt;&amp;1\n\npause\n</code></pre>\n" }, { "answer_id": 2651242, "author": "rafek", "author_id": 3182, "author_profile": "https://Stackoverflow.com/users/3182", "pm_score": 1, "selected": false, "text": "<p>I strongly recommend <a href=\"http://www.sqldbatips.com/showarticle.asp?ID=62\" rel=\"nofollow noreferrer\">RSScripter</a>. As noted in the overview: </p>\n\n<blockquote>\n <p>Reporting Services Scripter is a .NET\n Windows Forms application that enables\n scripting and transfer of all\n Microsoft SQL Server Reporting\n Services catalog items to aid in\n transferring them from one server to\n another. It can also be used to easily\n move items on mass from one Reporting\n Services folder to another on the same\n server. Depending on the scripting\n options chosen, Reporting Services\n Scripter can also transfer all catalog\n item properties such as Descriptions,\n History options, Execution options\n (including report specific and shared\n schedules), Subscriptions (normal and\n data driven) and server side report\n parameters.</p>\n</blockquote>\n" }, { "answer_id": 2759212, "author": "fretje", "author_id": 101371, "author_profile": "https://Stackoverflow.com/users/101371", "pm_score": 3, "selected": false, "text": "<p>I used the script <a href=\"https://stackoverflow.com/questions/88710/reporting-services-deployment/91077#91077\">@David</a> supplied but I had to add some code (I'm typing this up as an answer, as this would be too long for a comment.</p>\n\n<p>The problem is: if there is already a \"shared datasource\" attached to a report in the report definition, this is never the same datasource as the one that is created in the script. </p>\n\n<p>This also becomes apparent from the warning emitted by the \"CreateReport\" method:</p>\n\n<blockquote>\n <p>The data set '' refers to the shared data source '', which is not published on the report server.</p>\n</blockquote>\n\n<p>So the data source has to be set explicitly afterwards. I've made the following code changes:</p>\n\n<p>I added a global variable:</p>\n\n<pre><code>Dim dataSourceRefs(0) As DataSource\n</code></pre>\n\n<p>At the end of the CreateDataSource method, that variable gets filled:</p>\n\n<pre><code>Dim dsr As New DataSourceReference\ndsr.Reference = \"/\" + parentFolder + \"/\" + db\nDim ds As New DataSource\nds.Item = CType(dsr, DataSourceDefinitionOrReference)\nds.Name = db\ndataSourceRefs(0) = ds\n</code></pre>\n\n<p>And in the PublishReport method, that data source gets explicitly set (after CreateReport has been called):</p>\n\n<pre><code>rs.SetItemDataSources(targetFolder + \"/\" + reportName.Substring(0, reportName.Length - 4), dataSourceRefs)\n</code></pre>\n\n<p>Note that this last call is only RS 2005 or higher. If you want to load your reports onto a RS 2000 server, you have to use Set<i>Report</i>DataSources in stead:</p>\n\n<pre><code>rs.SetReportDataSources(targetFolder + \"/\" + reportName.Substring(0, reportName.Length - 4), dataSourceRefs)\n</code></pre>\n" }, { "answer_id": 52931504, "author": "SherlockSpreadsheets", "author_id": 5335644, "author_profile": "https://Stackoverflow.com/users/5335644", "pm_score": 0, "selected": false, "text": "<p>In our environment, we develop in VS with version control then deploy to DEV SSRS. Once the report is validated, we use ReportSync program to deploy reports from <code>ReportServer DEV</code> to <code>ReportServer PROD</code>. The RS.EXE scripts still have their place, but I have found ReportSync to be a much simpler and agile way to promote a report. </p>\n\n<p><strong>ReportSync:</strong> </p>\n\n<p><strong><code>ReportSync</code></strong> is an open source program free to download and use. It works great for downloading reports in bulk, and it can even push a report from one server to another server. </p>\n\n<hr>\n\n<p>How to get download the program?</p>\n\n<ul>\n<li><p>Download the source code files from <a href=\"http://github.com/phires/reportsync\" rel=\"nofollow noreferrer\">Github: Phires/ReportSynch</a>, Run VS, Open the solution file (.SLN), compile the program, find the executable file (.EXE) from the <em>C:\\Temp\\reportsync-master\\bin\\Release</em> folder. Finally, saved the .EXE somewhere for you to use regularly</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/5336576/how-do-i-copy-ssrs-reports-to-a-new-server-if-i-am-not-the-owner-of-the-reports\">How do I copy SSRS reports to a new server if I am not the owner of the reports</a> --> ReportSync answer by nunespascal</p></li>\n</ul>\n\n<p>How to deploy a report? </p>\n\n<ol>\n<li>Run the executable and the interface will launch.</li>\n<li>Use the <code>SOURCE</code> and <code>DESTINATION</code> dialogues to choose a <code>single report</code>, <code>multiple reports</code>, or an <code>entire folder of reports</code>. You can any target folder you would like. (HINT: You can even target the same server if you are wanting to duplicate a report on the same server.)</li>\n<li>After making your selections press the <code>Sync button</code></li>\n<li>Go to the target server, and validate the change took effect by reviewing the Changed By Date. </li>\n</ol>\n\n<p>This tool has been very convenient, but I have noticed some quirks. For example <code>when I want to update just one report that already exists in the destination</code>, here is what I have to select-- [<code>Source:Report&gt; Target:Folder&gt; Sync</code>]. WARNING: You might think you would select the target server report to update it, but I have tried this and the report does not get updated. </p>\n\n<hr>\n\n<p>What else can ReportSync do?</p>\n\n<ul>\n<li><p>There is also an <code>Export</code> feature, which works marvelously for simply dumping all the RDL files to a folder for me to access. This is helpful in the event you need to migrate the server, add the files to to a VS Solution Project, or do anything else will all the files. </p></li>\n<li><p>In my testing this program <strong>does not</strong> migrate other content-- subscriptions, shared data sources, shared data sets. It is just applicable to the report files. </p></li>\n</ul>\n\n<p>I know this post is old, but I came across it when researching RS.EXE scripts, so I thought I would provide an answer this question. </p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16980/" ]
I need to create a repeatable process for deploying SQL Server Reporting Services reports. I am not in favor of using Visual Studio and or Business Development Studio to do this. The rs.exe method of scripting deployments also seems rather clunky. Does anyone have a very elegant way that they have been able to deploy reports. The key here is that I want the process to be completely automated.
We use rs.exe, once we developed the script we have not needed to touch it anymore, it just works. Here is the source (I slightly modified it by hand to remove sensitive data without a chance to test it, hope I did not brake anything), it deploys reports and associated images from subdirectories for various languages. Also datasource is created. ``` '===================================================================== ' File: PublishReports.rss ' ' Summary: Script that can be used with RS.exe to ' publish the reports. ' ' Rss file spans from beginnig of this comment to end of module ' (except of "End Module"). '===================================================================== Dim langPaths As String() = {"en", "cs", "pl", "de"} Dim filePath As String = Environment.CurrentDirectory Public Sub Main() rs.Credentials = System.Net.CredentialCache.DefaultCredentials 'Create parent folder Try rs.CreateFolder(parentFolder, "/", Nothing) Console.WriteLine("Parent folder created: {0}", parentFolder) Catch e As Exception Console.WriteLine(e.Message) End Try PublishLanguagesFromFolder(filePath) End Sub Public Sub PublishLanguagesFromFolder(ByVal folder As String) Dim Lang As Integer Dim langPath As String For Lang = langPaths.GetLowerBound(0) To langPaths.GetUpperBound(0) langPath = langPaths(Lang) 'Create the lang folder Try rs.CreateFolder(langPath, "/" + parentFolder, Nothing) Console.WriteLine("Parent lang folder created: {0}", parentFolder + "/" + langPath) Catch e As Exception Console.WriteLine(e.Message) End Try 'Create the shared data source CreateDataSource("/" + parentFolder + "/" + langPath) 'Publish reports and images PublishFolderContents(folder + "\" + langPath, "/" + parentFolder + "/" + langPath) Next 'Lang End Sub Public Sub CreateDataSource(ByVal targetFolder As String) Dim name As String = "data source" 'Data source definition. Dim definition As New DataSourceDefinition definition.CredentialRetrieval = CredentialRetrievalEnum.Store definition.ConnectString = "data source=" + dbServer + ";initial catalog=" + db definition.Enabled = True definition.EnabledSpecified = True definition.Extension = "SQL" definition.ImpersonateUser = False definition.ImpersonateUserSpecified = True 'Use the default prompt string. definition.Prompt = Nothing definition.WindowsCredentials = False 'Login information definition.UserName = "user" definition.Password = "password" Try 'name, folder, overwrite, definition, properties rs.CreateDataSource(name, targetFolder, True, definition, Nothing) Catch e As Exception Console.WriteLine(e.Message) End Try End Sub Public Sub PublishFolderContents(ByVal sourceFolder As String, ByVal targetFolder As String) Dim di As New DirectoryInfo(sourceFolder) Dim fis As FileInfo() = di.GetFiles() Dim fi As FileInfo Dim fileName As String For Each fi In fis fileName = fi.Name Select Case fileName.Substring(fileName.Length - 4).ToUpper Case ".RDL" PublishReport(sourceFolder, fileName, targetFolder) Case ".JPG", ".JPEG" PublishResource(sourceFolder, fileName, "image/jpeg", targetFolder) Case ".GIF", ".PNG", ".BMP" PublishResource(sourceFolder, fileName, "image/" + fileName.Substring(fileName.Length - 3).ToLower, targetFolder) End Select Next fi End Sub Public Sub PublishReport(ByVal sourceFolder As String, ByVal reportName As String, ByVal targetFolder As String) Dim definition As [Byte]() = Nothing Dim warnings As Warning() = Nothing Try Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + reportName) definition = New [Byte](stream.Length) {} stream.Read(definition, 0, CInt(stream.Length)) stream.Close() Catch e As IOException Console.WriteLine(e.Message) End Try Try 'name, folder, overwrite, definition, properties warnings = rs.CreateReport(reportName.Substring(0, reportName.Length - 4), targetFolder, True, definition, Nothing) If Not (warnings Is Nothing) Then Dim warning As Warning For Each warning In warnings Console.WriteLine(warning.Message) Next warning Else Console.WriteLine("Report: {0} published successfully with no warnings", targetFolder + "/" + reportName) End If Catch e As Exception Console.WriteLine(e.Message) End Try End Sub Public Sub PublishResource(ByVal sourceFolder As String, ByVal resourceName As String, ByVal resourceMIME As String, ByVal targetFolder As String) Dim definition As [Byte]() = Nothing Dim warnings As Warning() = Nothing Try Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + resourceName) definition = New [Byte](stream.Length) {} stream.Read(definition, 0, CInt(stream.Length)) stream.Close() Catch e As IOException Console.WriteLine(e.Message) End Try Try 'name, folder, overwrite, definition, MIME, properties rs.CreateResource(resourceName, targetFolder, True, definition, resourceMIME, Nothing) Console.WriteLine("Resource: {0} with MIME {1} created successfully", targetFolder + "/" + resourceName, resourceMIME) Catch e As Exception Console.WriteLine(e.Message) End Try End Sub ``` Here is the batch to call the rs.exe: ``` SET ReportServer=%1 SET DBServer=%2 SET DBName=%3 SET ReportFolder=%4 rs -i PublishReports.rss -s %ReportServer% -v dbServer="%DBServer%" -v db="%DBName%" -v parentFolder="%ReportFolder%" >PublishReports.log 2>&1 pause ```
88,717
<p>I want to load one or more DLLs dynamically so that they run with a different security or basepath than my main application. How do I load these DLLs into a separate AppDomain and instantiate objects from them?</p>
[ { "answer_id": 88758, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/44s54yc4.aspx\" rel=\"nofollow noreferrer\">AppDomain.CreateInstance</a> method to do this. You'll need to call the Unwrap method of the ObjectHandle that is returned to get at the actual object.</p>\n" }, { "answer_id": 88767, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If you're targeting 3.5, you can take advantage of the new <a href=\"http://code.msdn.microsoft.com/mef\" rel=\"nofollow noreferrer\">managed extensibility framework</a> to handle all the heavy lifting for you.</p>\n" }, { "answer_id": 88769, "author": "Min", "author_id": 14461, "author_profile": "https://Stackoverflow.com/users/14461", "pm_score": 0, "selected": false, "text": "<p>Create a new Appdomain with AppDomain.Create( ... ).\nAfter creating the AppDomain load the DLLs into that AppDomain.</p>\n\n<p>Look into all the methods that Appdomain has with Create*. There are certain things like CreateInstanceAndUnwrap, etc.</p>\n" }, { "answer_id": 88906, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 0, "selected": false, "text": "<p>As previously stated, use AppDomain.CreateDomain to create a new app domain. You can then load an assembly into it using the Load method, or even execute an assembly using the ExecuteAssembly method. You can use GetAssemblies to see if an assembly has already been loaded. Be aware too that you cannot unload an assembly once it's loaded. You will need to unload the domain.</p>\n" }, { "answer_id": 93045, "author": "Jon Turner", "author_id": 16979, "author_profile": "https://Stackoverflow.com/users/16979", "pm_score": 6, "selected": true, "text": "<p>More specifically</p>\n\n<pre><code>AppDomain domain = AppDomain.CreateDomain(\"New domain name\");\n//Do other things to the domain like set the security policy\n\nstring pathToDll = @\"C:\\myDll.dll\"; //Full path to dll you want to load\nType t = typeof(TypeIWantToLoad);\nTypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName);\n</code></pre>\n\n<p>If all that goes properly (no exceptions thrown) you now have an instance of TypeIWantToLoad loaded into your new domain. The instance you have is actually a proxy (since the actual object is in the new domain) but you can use it just like your normal object.</p>\n\n<p>Note: As far as I know TypeIWantToLoad has to inherit from MarshalByRefObject.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16979/" ]
I want to load one or more DLLs dynamically so that they run with a different security or basepath than my main application. How do I load these DLLs into a separate AppDomain and instantiate objects from them?
More specifically ``` AppDomain domain = AppDomain.CreateDomain("New domain name"); //Do other things to the domain like set the security policy string pathToDll = @"C:\myDll.dll"; //Full path to dll you want to load Type t = typeof(TypeIWantToLoad); TypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName); ``` If all that goes properly (no exceptions thrown) you now have an instance of TypeIWantToLoad loaded into your new domain. The instance you have is actually a proxy (since the actual object is in the new domain) but you can use it just like your normal object. Note: As far as I know TypeIWantToLoad has to inherit from MarshalByRefObject.
88,743
<p>I'm using jmockit for unit testing (with TestNG), and I'm having trouble using the Expectations class to mock out a method that takes a primitive type (boolean) as a parameter, using a matcher. Here's some sample code that illustrates the problem.</p> <pre><code>/******************************************************/ import static org.hamcrest.Matchers.is; import mockit.Expectations; import org.testng.annotations.Test; public class PrimitiveMatcherTest { private MyClass obj; @Test public void testPrimitiveMatcher() { new Expectations(true) { MyClass c; { obj = c; invokeReturning(c.getFoo(with(is(false))), "bas"); } }; assert "bas".equals(obj.getFoo(false)); Expectations.assertSatisfied(); } public static class MyClass { public String getFoo(boolean arg) { if (arg) { return "foo"; } else { return "bar"; } } } } /******************************************************/ </code></pre> <p>The line containing the call to invokeReturning(...) throws a NullPointerException.</p> <p>If I change this call to not use a matcher, as in:</p> <pre><code>invokeReturning(c.getFoo(false), "bas"); </code></pre> <p>it works just fine. This is no good for me, because in my real code I'm actually mocking a multi-parameter method and I need to use a matcher on another argument. In this case, the Expectations class requires that <strong>all</strong> arguments use a matcher.</p> <p>I'm pretty sure this is a bug, or perhaps it's not possible to use Matchers with primitive types (that would make me sad). Has anyone encountered this issue, and know how to get around it?</p>
[ { "answer_id": 89215, "author": "DJ.", "author_id": 10638, "author_profile": "https://Stackoverflow.com/users/10638", "pm_score": 1, "selected": false, "text": "<p>the issue is the combination of Expectation usage and that Matchers does not support primitive type.</p>\n\n<p>The Matchers code rely on Generic which basically does not support primitive type. Typically the usage of Matchers is more for matching value; with the auto-boxing/unboxing feater in Java 5, this is usually not a problem.</p>\n\n<p>But JMockit's Expectation is not using it for matching value, it uses it for some kind of parsing to determine the method call signature type..which in this case the Matchers will resulted in Boolean type while your method is primitive type..so it fails to mock it properly.</p>\n\n<p>I'm sorry that I can not tell you any workaround for this. Maybe somebody else can help.</p>\n" }, { "answer_id": 90136, "author": "Kris Pruden", "author_id": 16977, "author_profile": "https://Stackoverflow.com/users/16977", "pm_score": 3, "selected": true, "text": "<p>So the problem appears to be in Expectations.with():</p>\n\n<pre><code> protected final &lt;T&gt; T with(Matcher&lt;T&gt; argumentMatcher)\n {\n argMatchers.add(argumentMatcher);\n\n TypeVariable&lt;?&gt; typeVariable = argumentMatcher.getClass().getTypeParameters()[0];\n\n return (T) Utilities.defaultValueForType(typeVariable.getClass());\n }\n</code></pre>\n\n<p>The call to typeVariable.getClass() does not do what the author expects, and the call to Utilities.defaultValueFor type returns null. The de-autoboxing back the the primitive boolean value is where the NPE comes from.</p>\n\n<p>I fixed it by changing the invokeReturning(...) call to:</p>\n\n<pre><code>invokeReturning(withEqual(false)), \"bas\");\n</code></pre>\n\n<p>I'm no longer using a matcher here, but it's good enough for what I need.</p>\n" }, { "answer_id": 1009688, "author": "Rogério", "author_id": 2326914, "author_profile": "https://Stackoverflow.com/users/2326914", "pm_score": 1, "selected": false, "text": "<p>I changed JMockit (release 0.982) so that \"with(is(false))\" and other similar variations now work as expected (it no longer returns null, but the actual argument value inside the inner matcher).</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16977/" ]
I'm using jmockit for unit testing (with TestNG), and I'm having trouble using the Expectations class to mock out a method that takes a primitive type (boolean) as a parameter, using a matcher. Here's some sample code that illustrates the problem. ``` /******************************************************/ import static org.hamcrest.Matchers.is; import mockit.Expectations; import org.testng.annotations.Test; public class PrimitiveMatcherTest { private MyClass obj; @Test public void testPrimitiveMatcher() { new Expectations(true) { MyClass c; { obj = c; invokeReturning(c.getFoo(with(is(false))), "bas"); } }; assert "bas".equals(obj.getFoo(false)); Expectations.assertSatisfied(); } public static class MyClass { public String getFoo(boolean arg) { if (arg) { return "foo"; } else { return "bar"; } } } } /******************************************************/ ``` The line containing the call to invokeReturning(...) throws a NullPointerException. If I change this call to not use a matcher, as in: ``` invokeReturning(c.getFoo(false), "bas"); ``` it works just fine. This is no good for me, because in my real code I'm actually mocking a multi-parameter method and I need to use a matcher on another argument. In this case, the Expectations class requires that **all** arguments use a matcher. I'm pretty sure this is a bug, or perhaps it's not possible to use Matchers with primitive types (that would make me sad). Has anyone encountered this issue, and know how to get around it?
So the problem appears to be in Expectations.with(): ``` protected final <T> T with(Matcher<T> argumentMatcher) { argMatchers.add(argumentMatcher); TypeVariable<?> typeVariable = argumentMatcher.getClass().getTypeParameters()[0]; return (T) Utilities.defaultValueForType(typeVariable.getClass()); } ``` The call to typeVariable.getClass() does not do what the author expects, and the call to Utilities.defaultValueFor type returns null. The de-autoboxing back the the primitive boolean value is where the NPE comes from. I fixed it by changing the invokeReturning(...) call to: ``` invokeReturning(withEqual(false)), "bas"); ``` I'm no longer using a matcher here, but it's good enough for what I need.
88,773
<p>There must be a generic way to transform some hierachical XML such as:</p> <pre><code>&lt;element1 A="AValue" B="BValue"&gt; &lt;element2 C="DValue" D="CValue"&gt; &lt;element3 E="EValue1" F="FValue1"/&gt; &lt;element3 E="EValue2" F="FValue2"/&gt; &lt;/element2&gt; ... &lt;/element1&gt; </code></pre> <p>into the flattened XML (html) picking up selected attributes along the way and providing different labels for the attributes that become column headers.</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;th&gt;A_Label&lt;/th&gt; &lt;th&gt;D_Label&lt;/th&gt; &lt;th&gt;E_Label&lt;/th&gt; &lt;th&gt;F_Label&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;AValue&lt;/td&gt; &lt;td&gt;DValue&lt;/td&gt; &lt;td&gt;EValue1&lt;/td&gt; &lt;td&gt;FValue1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;AValue&lt;/td&gt; &lt;td&gt;DValue&lt;/td&gt; &lt;td&gt;EValue2&lt;/td&gt; &lt;td&gt;FValue2&lt;/td&gt; &lt;/tr&gt; &lt;table&gt; </code></pre> <p>OK, so there's not generic solution due to the attribute re-labelling but you get what I mean hopefully. I've just started on all the XSLT/XPATH stuff so I'll work it out in good time but any clues would be useful.</p>
[ { "answer_id": 88867, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>We already have a Pro*C program reading from an Oracle database, it calls a perl script which in turn executes some Java to extract data in XML format from the aforementioned database for calling a batch file to execute some vbscript FTPing the file to some other server. I was really hoping for something in Fortran.</p>\n" }, { "answer_id": 88875, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 4, "selected": true, "text": "<p>I'm not 100% sure of what you are trying to do but this solution may work if your element1, element2 and element3 are nested consistently.</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" exclude-result-prefixes=\"msxsl\"&gt;\n &lt;xsl:output method=\"xml\" indent=\"yes\"/&gt;\n\n &lt;xsl:template match=\"/\"&gt;\n &lt;table&gt;\n &lt;xsl:apply-templates select=\"//element3\"&gt;&lt;/xsl:apply-templates&gt;\n &lt;/table&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"element3\"&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"../../@A\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"../../@B\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"../@C\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"../@D\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"@E\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"@F\"/&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;xsl:apply-templates select=\"*\"&gt;&lt;/xsl:apply-templates&gt;\n &lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" }, { "answer_id": 90389, "author": "GerG", "author_id": 17249, "author_profile": "https://Stackoverflow.com/users/17249", "pm_score": 0, "selected": false, "text": "<p>The original question needs to be clarified:</p>\n\n<ul>\n<li>What happens with BValue and CValue in the original question? Is there a reason why they shouldn't be part of the flattened structure?</li>\n<li>Do all of the elements in the XML doc have 2 attributes or is this completely arbitrary?</li>\n<li>Are there only 3 types of elements and are they always nested as shown in the example?</li>\n<li>Can your element1 be repeated itself or is this the root element of your doc?</li>\n</ul>\n\n<p>In XSLT it is possible to write very generic transformers but it is often much easier to write a stylesheet to transform a document when you can take any known restrictions into account.</p>\n" }, { "answer_id": 91278, "author": "Confusion", "author_id": 16784, "author_profile": "https://Stackoverflow.com/users/16784", "pm_score": 0, "selected": false, "text": "<p>I have used an expanded version of the template below to flatten structured XML. Warning: There was some case-specific code in the original version (it actually turned the XML into CSV) that I just stripped and I didn't test this version. </p>\n\n<p>The basic way it works should be clear: it prints everything that doesn't have node children and otherwise recursively calls the template on the node() that does have children. I don't think it handles attributes and comments correctly as it is now, but that should not be hard to fix.</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n\n&lt;!-- XSL template to flatten structured XML, before converting to CSV. --&gt;\n&lt;xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n\n &lt;xsl:output method=\"xml\" indent=\"yes\" encoding=\"UTF-8\"/&gt;\n\n &lt;xsl:strip-space elements=\"*\" /&gt; \n\n &lt;xsl:template match=\"/\"&gt;\n &lt;xsl:apply-templates select=\"//yourElementsToFlatten\"/&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"//yourElementsToFlatten\"&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"@*|node()\"&gt;\n &lt;xsl:choose&gt;\n &lt;!-- If the element has multiple childs, call this template \n on its children to flatten it--&gt;\n &lt;xsl:when test=\"count(child::*) &gt; 0\"&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:when&gt;\n &lt;xsl:otherwise&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:value-of select=\"text()\" /&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:otherwise&gt;\n &lt;/xsl:choose&gt;\n &lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" }, { "answer_id": 11780518, "author": "Édouard Lopez", "author_id": 802365, "author_profile": "https://Stackoverflow.com/users/802365", "pm_score": 1, "selected": false, "text": "<p>I needed a similar XSLT but with unknown depth, here is how I did it.</p>\n\n<p>First, add a wrapper for the resulting HTML table/def list and call the template mode=\"puke\" to flatten our XML tree :</p>\n\n<pre><code>&lt;xsl:element name=\"div\"&gt;\n &lt;xsl:attribute name=\"class\" select=\"puke\" /&gt;\n &lt;xsl:apply-templates select=\"$notice\" mode=\"puke\" /&gt;\n&lt;/xsl:element&gt; \n</code></pre>\n\n<p>Here we match each node to display its content (e.g. text()) and its attributes. We do this recursively. I used dl/dt/dd because my source tree was a complex tree that can't be flatten as a .</p>\n\n<pre><code>&lt;!-- @description: \n Display all field from the notice so the customer can tell what he want\n--&gt;\n&lt;xsl:template match=\"node()\" mode=\"puke\"&gt;\n&lt;xsl:message&gt;\n puking : &lt;xsl:value-of select=\"local-name( . )\" /&gt;\n&lt;/xsl:message&gt;\n &lt;xsl:element name=\"dl\"&gt;\n &lt;xsl:element name=\"dt\"&gt;\n &lt;xsl:attribute name=\"class\"&gt;tagName&lt;/xsl:attribute&gt; \n &lt;xsl:value-of select=\"local-name( . )\" /&gt;\n &lt;/xsl:element&gt;\n &lt;xsl:element name=\"dd\"&gt;\n &lt;xsl:attribute name=\"class\"&gt;tagText&lt;/xsl:attribute&gt;\n &lt;xsl:value-of select=\"text()\" /&gt;&lt;/xsl:element&gt; \n &lt;xsl:element name=\"dl\"&gt;\n &lt;xsl:attribute name=\"class\"&gt;attr&lt;/xsl:attribute&gt;\n &lt;!-- display attribute --&gt;\n &lt;xsl:apply-templates select=\"@*\" /&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:element&gt;\n &lt;!-- recursive call on node() --&gt;\n &lt;xsl:apply-templates select=\"./*\" mode=\"puke\" /&gt; \n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>Match attribute of a given node and display them.\n \n \n \n \n <br>\n \n \n \n </p>\n\n<p>The CSS use in to format the resulting HTML :</p>\n\n<pre><code>&lt;style&gt;\n.puke {\n background-color: #BDD6DE;\n clear: both;\n}\n.tagName, .attrName {\n float: left;\n}\n.tagText, .attrText {\n clear: right;\n}\n&lt;/style&gt;\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There must be a generic way to transform some hierachical XML such as: ``` <element1 A="AValue" B="BValue"> <element2 C="DValue" D="CValue"> <element3 E="EValue1" F="FValue1"/> <element3 E="EValue2" F="FValue2"/> </element2> ... </element1> ``` into the flattened XML (html) picking up selected attributes along the way and providing different labels for the attributes that become column headers. ``` <table> <tr> <th>A_Label</th> <th>D_Label</th> <th>E_Label</th> <th>F_Label</th> </tr> <tr> <td>AValue</td> <td>DValue</td> <td>EValue1</td> <td>FValue1</td> </tr> <tr> <td>AValue</td> <td>DValue</td> <td>EValue2</td> <td>FValue2</td> </tr> <table> ``` OK, so there's not generic solution due to the attribute re-labelling but you get what I mean hopefully. I've just started on all the XSLT/XPATH stuff so I'll work it out in good time but any clues would be useful.
I'm not 100% sure of what you are trying to do but this solution may work if your element1, element2 and element3 are nested consistently. ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <table> <xsl:apply-templates select="//element3"></xsl:apply-templates> </table> </xsl:template> <xsl:template match="element3"> <tr> <td><xsl:value-of select="../../@A"/></td> <td><xsl:value-of select="../../@B"/></td> <td><xsl:value-of select="../@C"/></td> <td><xsl:value-of select="../@D"/></td> <td><xsl:value-of select="@E"/></td> <td><xsl:value-of select="@F"/></td> </tr> <xsl:apply-templates select="*"></xsl:apply-templates> </xsl:template> </xsl:stylesheet> ```
88,775
<p>I work at a college and have been developing an ASP.NET site with many, many reports about students, attendance stats... The basis for the data is an MSSQL server DB which is the back end to our student management system. This has a regular maintenance period on Thursday mornings for an unknown length of time (dependent on what has to be done). </p> <p>Most of the staff are aware of this but the less regular users seem to be forever ringing me up. What is the easiest way to disable the site during maintenance obviously I can just try a DB query to test if it is up but am unsure of the best way to for instance redirect all users to a "The website is down for maintenance" message, bearing in mind they could have started a session prior to the website going down.</p> <p>Hopefully, something can be implemented globally rather than per page.</p>
[ { "answer_id": 88782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Drop an html file called \"app_offline.htm\" into the root of your virtual directory. Simple as that.</p>\n\n<p><a href=\"http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx\" rel=\"nofollow noreferrer\">Scott Guthrie</a> on the subject and friendly errors.</p>\n" }, { "answer_id": 88792, "author": "Charles Ma", "author_id": 11708, "author_profile": "https://Stackoverflow.com/users/11708", "pm_score": 1, "selected": false, "text": "<p>You could display a message to people who have logged in saying \"the site will be down for maintenance in xxx minutes\" then run a service to log everyone out after xxx minutes. Then set a flag somewhere that every page can access, and at the top of every page(or just the template page) you test if that flag is set, if it is, send a redirect header to a site is down for maintenance page.</p>\n" }, { "answer_id": 88806, "author": "ckarras", "author_id": 5688, "author_profile": "https://Stackoverflow.com/users/5688", "pm_score": 1, "selected": false, "text": "<p>The \"offline.html\" page won't work if the user was already navigating within the site, or if he's accessing the site from a bookmark/external link to a specific page.</p>\n\n<p>The solution I use is to create a second web site with the same address (IP or host header(s)), but have it disabled by default. When the website is down, a script deactivates the \"real\" web site and enables the \"maintenance\" website instead. When it comes back online, another script switches back to the \"real\" web site.</p>\n\n<p>The \"maintenance\" web site is located in a different root directory, with a single page with the message (and any required images/css files)</p>\n\n<p>To have the same message shown on any page, the \"maintenance\" web site is set up with a 404 error handler that will redirect any request to the same \"website is down for maintenance\" page.</p>\n" }, { "answer_id": 88854, "author": "Matt Blaine", "author_id": 16272, "author_profile": "https://Stackoverflow.com/users/16272", "pm_score": 1, "selected": false, "text": "<p>What happens now when the site is down and someone tries to hit it? Does ADO.NET throw a specific exception you could catch and then redirect to the \"website down\" page?</p>\n\n<p>You could add a \"Global.asax\" file to the project, and in its code-behind add an \"Application_Error\" event handler. It would fire whenever an exception is thrown and goes uncaught, from anywhere in your web app. For example, in C#:</p>\n\n<pre><code>protected void Application_Error(object sender, EventArgs e)\n{\n Exception e = Server.GetLastError().GetBaseException();\n if(e is SqlException)\n { \n Server.ClearError();\n Server.Transfer(\"~/offline.aspx\");\n }\n} \n</code></pre>\n\n<p>You could also check the Number property on the exception, though I'm not sure which number(s) would indicate it was unable to connect to the database server. You could test this while it's down, find the SQL error number and look it up online to see if it's specifically what you really want to be checking for.</p>\n\n<p><strong>EDIT:</strong> I see what you're saying, petebob.</p>\n" }, { "answer_id": 88894, "author": "PeteT", "author_id": 16989, "author_profile": "https://Stackoverflow.com/users/16989", "pm_score": 0, "selected": false, "text": "<p>Thanks for the replies so far I should point out I'm not the one that does the maintenance nor does I have access all the time to IIS. Also, I prefer options where I do nothing as like all programmers I am a bit lazy.</p>\n\n<p>I know one way is to check a flag on every page but I'm hoping to avoid it. Could I not do something with the global.asax page, in fact, I think posting has engaged my brain:</p>\n\n<p>Think I could put in Application_BeginRequest a bit of code to check the SQL state then redirect:</p>\n\n<pre><code>HttpContext context = HttpContext.Current;\n if (!isOnline())\n {\n context.Response.ClearContent();\n context.Response.Write(\"&lt;script language='javascript'&gt;\" + \n\"top.location='\" + Request.ApplicationPath + \"/public/Offline.aspx';&lt;/scr\" + \"ipt&gt;\");\n } \n</code></pre>\n\n<p>Or something like that may not be perfect not tested yet as I'm not at work. Comments appreciated.</p>\n" }, { "answer_id": 88958, "author": "James", "author_id": 2719, "author_profile": "https://Stackoverflow.com/users/2719", "pm_score": 2, "selected": true, "text": "<p>I would suggest doing it in Application_PreRequestHandlerExecute instead of after an error occurs. Generally, it'd be best not to enter normal processing if you know your database isn't available. I typically use something like below</p>\n\n<pre><code>void Application_PreRequestHandlerExecute(Object sender, EventArgs e)\n{\n string sPage = Request.ServerVariables[\"SCRIPT_NAME\"];\n if (!sPage.EndsWith(\"Maintenance.aspx\", StringComparison.OrdinalIgnoreCase))\n {\n //test the database connection\n //if it fails then redirect the user to Maintenance.aspx\n string connStr = ConfigurationManager.ConnectionString[\"ConnectionString\"].ConnectionString;\n SqlConnection conn = new SqlConnection(connStr);\n try\n {\n conn.Open();\n }\n catch(Exception ex)\n {\n Session[\"DBException\"] = ex;\n Response.Redirect(\"Maintenance.aspx\");\n }\n finally\n {\n conn.Close();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 88970, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 0, "selected": false, "text": "<p>A slightly more elegant version of the DB check on every page would be to do the check in the Global.asax file or to create a master page that all the other pages inherit from.</p>\n\n<p>The suggestion of having an online site and an offline site is really good, but only really applicable if you have a limited number of sites to manage on the server.</p>\n\n<p><strong>EDIT:</strong> Damn, the other answers with these suggestions came up after I loaded the page. I need to remember to refresh before replying :)</p>\n" }, { "answer_id": 89001, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 0, "selected": false, "text": "<p>James code forgets to close the connection, should probably be:</p>\n\n<pre><code>try\n{\n conn.Open();\n}\ncatch(Exception ex)\n{\n Session[\"DBException\"] = ex;\n Response.Redirect(\"Maintenance.aspx\");\n}\nfinally\n{\n conn.Close();\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
I work at a college and have been developing an ASP.NET site with many, many reports about students, attendance stats... The basis for the data is an MSSQL server DB which is the back end to our student management system. This has a regular maintenance period on Thursday mornings for an unknown length of time (dependent on what has to be done). Most of the staff are aware of this but the less regular users seem to be forever ringing me up. What is the easiest way to disable the site during maintenance obviously I can just try a DB query to test if it is up but am unsure of the best way to for instance redirect all users to a "The website is down for maintenance" message, bearing in mind they could have started a session prior to the website going down. Hopefully, something can be implemented globally rather than per page.
I would suggest doing it in Application\_PreRequestHandlerExecute instead of after an error occurs. Generally, it'd be best not to enter normal processing if you know your database isn't available. I typically use something like below ``` void Application_PreRequestHandlerExecute(Object sender, EventArgs e) { string sPage = Request.ServerVariables["SCRIPT_NAME"]; if (!sPage.EndsWith("Maintenance.aspx", StringComparison.OrdinalIgnoreCase)) { //test the database connection //if it fails then redirect the user to Maintenance.aspx string connStr = ConfigurationManager.ConnectionString["ConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); try { conn.Open(); } catch(Exception ex) { Session["DBException"] = ex; Response.Redirect("Maintenance.aspx"); } finally { conn.Close(); } } } ```
88,791
<p>I was wondering what people thought of using properties as object initializers in C#. For some reason it seems to break the fundamentals of what constructors are used for.</p> <p>An example...</p> <pre><code>public class Person { string firstName; string lastName; public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName= value; } } } </code></pre> <p>Then doing object intialization with.....</p> <pre><code>Person p = new Person{ FirstName = "Joe", LastName = "Smith" }; Person p = new Person{ FirstName = "Joe" }; </code></pre>
[ { "answer_id": 88802, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>IMHO its sweet. Most objects are newed up with the default constructor, and must have some properties set before they are ready to run; so the object initializers make it easier to code against most objects out there.</p>\n" }, { "answer_id": 88807, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": true, "text": "<p>What you see here is some syntatic sugar provided by the compiler. Under the hood what it really does is something like:</p>\n\n<p><strong>Person p = new Person( FirstName = \"Joe\", LastName = \"Smith\" );</strong></p>\n\n<pre><code>Person _p$1 = new Person();\n_p$1.FirstName = \"Joe\";\n_p$1.LastName = \"Smith\";\nPerson p = _p$1;\n</code></pre>\n\n<p>So IMHO you are not really breaking any constructor fundamentals but using a nice language artifact in order to ease readability and maintainability.</p>\n" }, { "answer_id": 88819, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 1, "selected": false, "text": "<p>I think overall it is useful, especially when used with automatic properties.\nIt can be confusing when properties are doing more than get/set.\nHopefully this will lead to more methods, and reduce the abuse of properties.</p>\n" }, { "answer_id": 88821, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 0, "selected": false, "text": "<p>It's also quite necessary for projected classes returned from a language integrated query (linq) </p>\n\n<pre><code>var qry = from something in listofsomething\n select new {\n Firstname = something.FirstName,\n Lastname = something.Surname\n }\n</code></pre>\n" }, { "answer_id": 88841, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": false, "text": "<p>Object initializers does in no way replace constructors. The constructor defines the contract that you have to adhere to in order to create a instance of a class.</p>\n\n<p>The main motivation for object initializers in the C# language is to support <a href=\"http://msdn.microsoft.com/en-us/library/bb397696.aspx\" rel=\"noreferrer\">Anonymous Types</a>.</p>\n\n<pre><code>var v = new { Foo = 1, Bar = \"Hi\" };\nConsole.WriteLine(v.Bar);\n</code></pre>\n" }, { "answer_id": 88843, "author": "Jeromy Irvine", "author_id": 8223, "author_profile": "https://Stackoverflow.com/users/8223", "pm_score": 0, "selected": false, "text": "<p>Object Initializers help to reduce coding complexity in that you don't need to create a half dozen different constructors in order to provide initial values for properties. Anything that reduces redundant code is a positive, in my book.</p>\n\n<p>I believe the primary reason the feature was added to the language is to support <a href=\"http://msdn.microsoft.com/en-us/library/bb397696.aspx\" rel=\"nofollow noreferrer\">anonymous types</a> for LINQ.</p>\n" }, { "answer_id": 88853, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 0, "selected": false, "text": "<p>Adding to Nescio's thoughts - I'd suggest in code reviews actively hunting down expensive transparent operations in property accessors e.g. DB round tripping.</p>\n" }, { "answer_id": 88857, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 2, "selected": false, "text": "<p>Since you're already using the new C# syntax, might as well use automatic properties as well, just to sweeten up your code a drop more:</p>\n\n<p>instead of this:</p>\n\n<pre><code>string firstName;\n\npublic string FirstName\n{\n get { return firstName; }\n set { firstName = value; }\n}\n</code></pre>\n\n<p>use this:</p>\n\n<pre><code>public string FirstName { get; set; }\n</code></pre>\n" }, { "answer_id": 88860, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 2, "selected": false, "text": "<p>Constructors should only really have arguments that are <em>required</em> to construct the object. Object initialisers are just a convenient way to assign values to properties. I use object initialisers whenever I can as I think it's a tidier syntax.</p>\n" }, { "answer_id": 88908, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>If you want to enforce the use of a constructor, you could set your object's default parameterless constructor to private, and leave public only some enforced constructors:</p>\n\n<pre><code>public class SomeObject\n{\n private SomeObject()\n {}\n\n public SomeObject(string someString) //enforced constructor\n {}\n\n public string MyProperty { get; set; }\n }\n</code></pre>\n\n<p>Using the above definition, this throws an error:</p>\n\n<pre><code>var myObject = new SomeObject { MyProperty = \"foo\" } //no method accepts zero arguments for constructor\n</code></pre>\n\n<p>Of course this can't be done for all cases. Serialization, for example, requires that you have a non-private default constructor.</p>\n" }, { "answer_id": 88967, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 1, "selected": false, "text": "<p>Not your original question, but still...</p>\n\n<p>Your class declaration can be written as:</p>\n\n<pre><code>public class Person\n{\n public string FirstName { get; set; }\n public string LastName {get; set; }\n}\n</code></pre>\n\n<p>and if it were my code, I'd probably have an object for Name with fields First and Last.</p>\n" }, { "answer_id": 105532, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I for one am not happy with them. I don't think they have a place in the constructor, or MS should got back and refactor them to allow you to use them in a private fasion. If I construct an object I want to pass in some PRIVATE data. I want it set from the outside world once and that's it. With Object Initializers you allow the values passed into the constructor to be modifiable. </p>\n\n<p>Maybe in the future they will change this.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342514/" ]
I was wondering what people thought of using properties as object initializers in C#. For some reason it seems to break the fundamentals of what constructors are used for. An example... ``` public class Person { string firstName; string lastName; public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName= value; } } } ``` Then doing object intialization with..... ``` Person p = new Person{ FirstName = "Joe", LastName = "Smith" }; Person p = new Person{ FirstName = "Joe" }; ```
What you see here is some syntatic sugar provided by the compiler. Under the hood what it really does is something like: **Person p = new Person( FirstName = "Joe", LastName = "Smith" );** ``` Person _p$1 = new Person(); _p$1.FirstName = "Joe"; _p$1.LastName = "Smith"; Person p = _p$1; ``` So IMHO you are not really breaking any constructor fundamentals but using a nice language artifact in order to ease readability and maintainability.
88,831
<p>Anyone has ever programmed a PHP (or Perl) function to get the ceiling value Excel style?</p>
[ { "answer_id": 88837, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 2, "selected": false, "text": "<p>Sorry, not quite clear what 'Excel style' is, but PHP has a <a href=\"http://us3.php.net/ceil\" rel=\"nofollow noreferrer\">ceil</a> function.</p>\n" }, { "answer_id": 88888, "author": "Jacob", "author_id": 8119, "author_profile": "https://Stackoverflow.com/users/8119", "pm_score": 3, "selected": false, "text": "<p><em>\"Microsoft Excel's ceiling function does not follow the mathematical definition, but rather as with (int) operator in C, it is a mixture of the floor and ceiling function: for x ≥ 0 it returns ceiling(x), and for x &lt; 0 it returns floor(x). This has followed through to the Office Open XML file format. For example, CEILING(-4.5) returns -5. A mathematical ceiling function can be emulated in Excel by using the formula \"-INT(-value)\" (please note that this is not a general rule, as it depends on Excel's INT function, which behaves differently that most programming languages).\"</em> - from <a href=\"http://en.wikipedia.org/wiki/Ceiling_function\" rel=\"noreferrer\">wikipedia</a></p>\n\n<p>If php's built in ceil function isn't working right you could make a new function like</p>\n\n<pre><code>function excel_ceil($num){\n return ($num&gt;0)?ceil($num):floor($num);\n}\n</code></pre>\n\n<p>Hope that helps</p>\n" }, { "answer_id": 10091498, "author": "Superbiji", "author_id": 1305919, "author_profile": "https://Stackoverflow.com/users/1305919", "pm_score": 3, "selected": false, "text": "<p>This should be the answer, from php.net comments:</p>\n\n<pre><code>// MS Excel function: Ceiling( number, significance ) \n\n\n// duplicates m$ excel's ceiling function\nif( !function_exists('ceiling') )\n{\n function ceiling($number, $significance = 1)\n {\n return ( is_numeric($number) &amp;&amp; is_numeric($significance) ) ? (ceil($number/$significance)*$significance) : false;\n }\n}\n\necho ceiling(0, 1000); // 0\necho ceiling(1, 1); // 1000\necho ceiling(1001, 1000); // 2000\necho ceiling(1.27, 0.05); // 1.30\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/88831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Anyone has ever programmed a PHP (or Perl) function to get the ceiling value Excel style?
*"Microsoft Excel's ceiling function does not follow the mathematical definition, but rather as with (int) operator in C, it is a mixture of the floor and ceiling function: for x ≥ 0 it returns ceiling(x), and for x < 0 it returns floor(x). This has followed through to the Office Open XML file format. For example, CEILING(-4.5) returns -5. A mathematical ceiling function can be emulated in Excel by using the formula "-INT(-value)" (please note that this is not a general rule, as it depends on Excel's INT function, which behaves differently that most programming languages)."* - from [wikipedia](http://en.wikipedia.org/wiki/Ceiling_function) If php's built in ceil function isn't working right you could make a new function like ``` function excel_ceil($num){ return ($num>0)?ceil($num):floor($num); } ``` Hope that helps
88,838
<p>In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions?</p>
[ { "answer_id": 88847, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": false, "text": "<pre><code>String original = \"hello world\";\nbyte[] utf8Bytes = original.getBytes(\"UTF-8\");\n</code></pre>\n" }, { "answer_id": 88863, "author": "mcherm", "author_id": 14570, "author_profile": "https://Stackoverflow.com/users/14570", "pm_score": 10, "selected": true, "text": "<p>Convert from <code>String</code> to <code>byte[]</code>:</p>\n<pre><code>String s = &quot;some text here&quot;;\nbyte[] b = s.getBytes(StandardCharsets.UTF_8);\n</code></pre>\n<p>Convert from <code>byte[]</code> to <code>String</code>:</p>\n<pre><code>byte[] b = {(byte) 99, (byte)97, (byte)116};\nString s = new String(b, StandardCharsets.US_ASCII);\n</code></pre>\n<p>You should, of course, use the correct encoding name. My examples used US-ASCII and UTF-8, two commonly-used encodings.</p>\n" }, { "answer_id": 91774, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 4, "selected": false, "text": "<p>You can convert directly via the <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/String.html\" rel=\"noreferrer\">String(byte[], String)</a> constructor and getBytes(String) method. Java exposes available character sets via the <a href=\"http://java.sun.com/javase/6/docs/api/java/nio/charset/Charset.html\" rel=\"noreferrer\">Charset</a> class. The JDK documentation <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html\" rel=\"noreferrer\">lists supported encodings</a>.</p>\n\n<p>90% of the time, such conversions are performed on streams, so you'd use the <a href=\"http://java.sun.com/javase/6/docs/api/java/io/InputStreamReader.html\" rel=\"noreferrer\">Reader</a>/<a href=\"http://java.sun.com/javase/6/docs/api/java/io/OutputStreamWriter.html\" rel=\"noreferrer\">Writer</a> classes. You would not incrementally decode using the String methods on arbitrary byte streams - you would leave yourself open to bugs involving multibyte characters.</p>\n" }, { "answer_id": 2293195, "author": "savio", "author_id": 276570, "author_profile": "https://Stackoverflow.com/users/276570", "pm_score": -1, "selected": false, "text": "<p>terribly late but i just encountered this issue and this is my fix:</p>\n\n<pre><code>private static String removeNonUtf8CompliantCharacters( final String inString ) {\n if (null == inString ) return null;\n byte[] byteArr = inString.getBytes();\n for ( int i=0; i &lt; byteArr.length; i++ ) {\n byte ch= byteArr[i]; \n // remove any characters outside the valid UTF-8 range as well as all control characters\n // except tabs and new lines\n if ( !( (ch &gt; 31 &amp;&amp; ch &lt; 253 ) || ch == '\\t' || ch == '\\n' || ch == '\\r') ) {\n byteArr[i]=' ';\n }\n }\n return new String( byteArr );\n}\n</code></pre>\n" }, { "answer_id": 3386646, "author": "M. Leonhard", "author_id": 1736338, "author_profile": "https://Stackoverflow.com/users/1736338", "pm_score": 7, "selected": false, "text": "<p>Here's a solution that avoids performing the Charset lookup for every conversion:</p>\n\n<pre><code>import java.nio.charset.Charset;\n\nprivate final Charset UTF8_CHARSET = Charset.forName(\"UTF-8\");\n\nString decodeUTF8(byte[] bytes) {\n return new String(bytes, UTF8_CHARSET);\n}\n\nbyte[] encodeUTF8(String string) {\n return string.getBytes(UTF8_CHARSET);\n}\n</code></pre>\n" }, { "answer_id": 11488296, "author": "Pacerier", "author_id": 632951, "author_profile": "https://Stackoverflow.com/users/632951", "pm_score": 1, "selected": false, "text": "<p>If you are using 7-bit ASCII or ISO-8859-1 (an amazingly common format) then you don't have to create a new <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html\" rel=\"nofollow\">java.lang.String</a> at all. It's much much more performant to simply cast the byte into char:</p>\n\n<p>Full working example:</p>\n\n<pre><code>for (byte b : new byte[] { 43, 45, (byte) 215, (byte) 247 }) {\n char c = (char) b;\n System.out.print(c);\n}\n</code></pre>\n\n<p>If you are <strong>not</strong> using <em>extended-characters</em> like Ä, Æ, Å, Ç, Ï, Ê <strong>and</strong> can be sure that the only transmitted values are of the first 128 Unicode characters, then this code will also work for UTF-8 and extended ASCII (like cp-1252).</p>\n" }, { "answer_id": 17401223, "author": "Ran Adler", "author_id": 2447599, "author_profile": "https://Stackoverflow.com/users/2447599", "pm_score": -1, "selected": false, "text": "<pre><code>//query is your json \n\n DefaultHttpClient httpClient = new DefaultHttpClient();\n HttpPost postRequest = new HttpPost(\"http://my.site/test/v1/product/search?qy=\");\n\n StringEntity input = new StringEntity(query, \"UTF-8\");\n input.setContentType(\"application/json\");\n postRequest.setEntity(input); \n HttpResponse response=response = httpClient.execute(postRequest);\n</code></pre>\n" }, { "answer_id": 19470896, "author": "paiego", "author_id": 491066, "author_profile": "https://Stackoverflow.com/users/491066", "pm_score": 4, "selected": false, "text": "<p>My tomcat7 implementation is accepting strings as ISO-8859-1; despite the content-type of the HTTP request. The following solution worked for me when trying to correctly interpret characters like 'é' .</p>\n\n<pre><code>byte[] b1 = szP1.getBytes(\"ISO-8859-1\");\nSystem.out.println(b1.toString());\n\nString szUT8 = new String(b1, \"UTF-8\");\nSystem.out.println(szUT8);\n</code></pre>\n\n<p>When trying to interpret the string as US-ASCII, the byte info wasn't correctly interpreted.</p>\n\n<pre><code>b1 = szP1.getBytes(\"US-ASCII\");\nSystem.out.println(b1.toString());\n</code></pre>\n" }, { "answer_id": 30170431, "author": "vtor", "author_id": 1534407, "author_profile": "https://Stackoverflow.com/users/1534407", "pm_score": 3, "selected": false, "text": "<p>As an alternative, <a href=\"https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/StringUtils.html\" rel=\"noreferrer\">StringUtils</a> from Apache Commons can be used.</p>\n\n<pre><code> byte[] bytes = {(byte) 1};\n String convertedString = StringUtils.newStringUtf8(bytes);\n</code></pre>\n\n<p>or</p>\n\n<pre><code> String myString = \"example\";\n byte[] convertedBytes = StringUtils.getBytesUtf8(myString);\n</code></pre>\n\n<p>If you have non-standard charset, you can use <a href=\"https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/StringUtils.html#getBytesUnchecked(java.lang.String,%20java.lang.String)\" rel=\"noreferrer\">getBytesUnchecked()</a> or <a href=\"https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/StringUtils.html#newString(byte[],%20java.lang.String)\" rel=\"noreferrer\">newString()</a> accordingly.</p>\n" }, { "answer_id": 30190990, "author": "Макс Даниленко", "author_id": 2200271, "author_profile": "https://Stackoverflow.com/users/2200271", "pm_score": 0, "selected": false, "text": "<pre><code>Reader reader = new BufferedReader(\n new InputStreamReader(\n new ByteArrayInputStream(\n string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));\n</code></pre>\n" }, { "answer_id": 30198440, "author": "jschober", "author_id": 1610193, "author_profile": "https://Stackoverflow.com/users/1610193", "pm_score": 3, "selected": false, "text": "<p>I can't comment but don't want to start a new thread. But this isn't working. A simple round trip:</p>\n\n<pre><code>byte[] b = new byte[]{ 0, 0, 0, -127 }; // 0x00000081\nString s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000, 0x0000, 0xfffd\nb = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081\n</code></pre>\n\n<p>I'd need b[] the same array before and after encoding which it isn't (this referrers to the first answer).</p>\n" }, { "answer_id": 34810953, "author": "Nitish Raj", "author_id": 2598888, "author_profile": "https://Stackoverflow.com/users/2598888", "pm_score": 1, "selected": false, "text": "<pre><code>Charset UTF8_CHARSET = Charset.forName(\"UTF-8\");\nString strISO = \"{\\\"name\\\":\\\"א\\\"}\";\nSystem.out.println(strISO);\nbyte[] b = strISO.getBytes();\nfor (byte c: b) {\n System.out.print(\"[\" + c + \"]\");\n}\nString str = new String(b, UTF8_CHARSET);\nSystem.out.println(str);\n</code></pre>\n" }, { "answer_id": 38139228, "author": "Bouke Woudstra", "author_id": 3184700, "author_profile": "https://Stackoverflow.com/users/3184700", "pm_score": 2, "selected": false, "text": "<p>For decoding a series of bytes to a normal string message I finally got it working with UTF-8 encoding with this code:</p>\n\n<pre><code>/* Convert a list of UTF-8 numbers to a normal String\n * Usefull for decoding a jms message that is delivered as a sequence of bytes instead of plain text\n */\npublic String convertUtf8NumbersToString(String[] numbers){\n int length = numbers.length;\n byte[] data = new byte[length];\n\n for(int i = 0; i&lt; length; i++){\n data[i] = Byte.parseByte(numbers[i]);\n }\n return new String(data, Charset.forName(\"UTF-8\"));\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/88838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14570/" ]
In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions?
Convert from `String` to `byte[]`: ``` String s = "some text here"; byte[] b = s.getBytes(StandardCharsets.UTF_8); ``` Convert from `byte[]` to `String`: ``` byte[] b = {(byte) 99, (byte)97, (byte)116}; String s = new String(b, StandardCharsets.US_ASCII); ``` You should, of course, use the correct encoding name. My examples used US-ASCII and UTF-8, two commonly-used encodings.
88,918
<p>This is my first experience using the Zend Framework. I am attempting to follow the <a href="http://framework.zend.com/docs/quickstart/introduction" rel="nofollow noreferrer">Quick Start</a> tutorial. Everything was working as expected until I reached the section on the <a href="http://framework.zend.com/docs/quickstart/create-an-error-controller-and-view" rel="nofollow noreferrer">Error Controller and View</a>. When I navigate to a page that does not exist, instead of receiving the error page I get the Fatal Error screen dump (in all it's glory):</p> <blockquote> <p>Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (error)' in /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Dispatcher/Standard.php:249 Stack trace: #0 /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Front.php(946): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http)) #1 /home/.fantasia/bcnewman/foo.com/public/index.php(42): Zend_Controller_Front->dispatch() #2 {main} thrown in /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Dispatcher/Standard.php on line 249</p> </blockquote> <p>I do not believe this is caused by a syntax error on my part (a copied and pasted the example file's content from the tutorial) and I believe I have the application directory structure correct:</p> <pre><code>./application ./application/controllers ./application/controllers/IndexController.php ./application/controllers/ErrorHandler.php ./application/views ./application/views/scripts ./application/views/scripts/index ./application/views/scripts/index/index.phtml ./application/views/scripts/error ./application/views/scripts/error/error.phtml ./application/bootstrap.php ./public ./public/index.php </code></pre> <p>And finally, the <code>IndexController</code> and <code>index.phtml</code> view does work.</p>
[ { "answer_id": 89347, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 2, "selected": false, "text": "<p>Assuming that you have the ErrorController plugin loaded into your front controller, make sure that in your bootstrap that you do not have the following set:</p>\n\n<pre><code>$frontController-&gt;throwExceptions(true);\n</code></pre>\n\n<p>If this is set then Exceptions will <em>always</em> be thrown, regardless of whether or not you have an error controller set.</p>\n" }, { "answer_id": 89550, "author": "rg88", "author_id": 11252, "author_profile": "https://Stackoverflow.com/users/11252", "pm_score": 3, "selected": true, "text": "<p>You have ErrorHandler.php. It should be ErrorController.php. Controllers all need to be named following the format of NameController.php. Since you don't have it named properly the dispatcher cannot find it.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/88918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3210/" ]
This is my first experience using the Zend Framework. I am attempting to follow the [Quick Start](http://framework.zend.com/docs/quickstart/introduction) tutorial. Everything was working as expected until I reached the section on the [Error Controller and View](http://framework.zend.com/docs/quickstart/create-an-error-controller-and-view). When I navigate to a page that does not exist, instead of receiving the error page I get the Fatal Error screen dump (in all it's glory): > > Fatal error: Uncaught exception 'Zend\_Controller\_Dispatcher\_Exception' > with message 'Invalid controller specified (error)' in > /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Dispatcher/Standard.php:249 > Stack trace: #0 > /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Front.php(946): > Zend\_Controller\_Dispatcher\_Standard->dispatch(Object(Zend\_Controller\_Request\_Http), > Object(Zend\_Controller\_Response\_Http)) #1 > /home/.fantasia/bcnewman/foo.com/public/index.php(42): > Zend\_Controller\_Front->dispatch() #2 {main} thrown in > /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Dispatcher/Standard.php > on line 249 > > > I do not believe this is caused by a syntax error on my part (a copied and pasted the example file's content from the tutorial) and I believe I have the application directory structure correct: ``` ./application ./application/controllers ./application/controllers/IndexController.php ./application/controllers/ErrorHandler.php ./application/views ./application/views/scripts ./application/views/scripts/index ./application/views/scripts/index/index.phtml ./application/views/scripts/error ./application/views/scripts/error/error.phtml ./application/bootstrap.php ./public ./public/index.php ``` And finally, the `IndexController` and `index.phtml` view does work.
You have ErrorHandler.php. It should be ErrorController.php. Controllers all need to be named following the format of NameController.php. Since you don't have it named properly the dispatcher cannot find it.
88,929
<p>Is there a command that would allow me to check if the string <code>"xyz"</code> was ever in file <code>foo.c</code> in the repository and print which revisions they were found in? </p>
[ { "answer_id": 89008, "author": "CaptainPicard", "author_id": 15203, "author_profile": "https://Stackoverflow.com/users/15203", "pm_score": 6, "selected": true, "text": "<p>This will print any commits where the diff contains xyz</p>\n\n<pre><code>git log -Sxyz foo.c\n</code></pre>\n" }, { "answer_id": 51486627, "author": "Nwyfiant", "author_id": 9020923, "author_profile": "https://Stackoverflow.com/users/9020923", "pm_score": 3, "selected": false, "text": "<p>This will print any commits where the diff contains xyz. Note the <code>--</code> separating the filename from the rest of the command.</p>\n\n<pre><code>git log -Sxyz -- foo.c\n</code></pre>\n\n<p>Without the <code>--</code>, I get this error:</p>\n\n<pre><code>fatal: ambiguous argument 'foo.c': unknown revision or path not in the working tree.\nUse '--' to separate paths from revisions, like this:\n'git &lt;command&gt; [&lt;revision&gt;...] -- [&lt;file&gt;...]'\n</code></pre>\n\n<p>I originally wanted to comment on <a href=\"https://stackoverflow.com/a/89008/9020923\">CaptainPicard's answer</a> to add a correction, but I don't have sufficient reputation yet. If someone would like to edit that answer to mention this correction I'll be happy to take this answer down.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/88929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
Is there a command that would allow me to check if the string `"xyz"` was ever in file `foo.c` in the repository and print which revisions they were found in?
This will print any commits where the diff contains xyz ``` git log -Sxyz foo.c ```
88,931
<p>When defining or calling functions with enough arguments to span multiple lines, I want vim to line them up. For example,</p> <pre><code>def myfunction(arg1, arg2, arg, ... argsN-1, argN) </code></pre> <p>The idea is for argsN-1 to have its 'a' lined up with args1.</p> <p>Does anyone have a way to have this happen automatically in vim? I've seen the align plugin for lining equal signs (in assignment statements) and such, but I'm not sure if it can be made to solve this problem?</p>
[ { "answer_id": 89119, "author": "solinent", "author_id": 13852, "author_profile": "https://Stackoverflow.com/users/13852", "pm_score": 3, "selected": false, "text": "<p>I believe you have to issue the command:</p>\n\n<pre><code>:set cino=(0\n</code></pre>\n\n<p>This is when using cindent of course.</p>\n\n<p>edit: I missed \"set\"</p>\n" }, { "answer_id": 89169, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 4, "selected": false, "text": "<p>The previous poster had it, but forgot the <code>set</code></p>\n\n<pre><code>:set cino=(0&lt;Enter&gt;\n</code></pre>\n\n<p>From <code>:help cinoptions-values</code></p>\n\n<pre><code>The 'cinoptions' option sets how Vim performs indentation. In the list below,\n\"N\" represents a number of your choice (the number can be negative). When\nthere is an 's' after the number, Vim multiplies the number by 'shiftwidth':\n\"1s\" is 'shiftwidth', \"2s\" is two times 'shiftwidth', etc. You can use a\ndecimal point, too: \"-0.5s\" is minus half a 'shiftwidth'. The examples below\nassume a 'shiftwidth' of 4.\n\n...\n\n (N When in unclosed parentheses, indent N characters from the line\n with the unclosed parentheses. Add a 'shiftwidth' for every\n unclosed parentheses. When N is 0 or the unclosed parentheses\n is the first non-white character in its line, line up with the\n next non-white character after the unclosed parentheses.\n (default 'shiftwidth' * 2).\n\n cino= cino=(0 &gt;\n if (c1 &amp;&amp; (c2 || if (c1 &amp;&amp; (c2 ||\n c3)) c3))\n foo; foo;\n if (c1 &amp;&amp; if (c1 &amp;&amp;\n (c2 || c3)) (c2 || c3))\n { {\n</code></pre>\n" }, { "answer_id": 93026, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Try the Align <a href=\"http://www.vim.org/scripts/script.php?script_id=294\" rel=\"nofollow noreferrer\">http://www.vim.org/scripts/script.php?script_id=294</a> and AutoAlign <a href=\"http://www.vim.org/scripts/script.php?script_id=884\" rel=\"nofollow noreferrer\">http://www.vim.org/scripts/script.php?script_id=884</a> scripts.</p>\n" }, { "answer_id": 97527, "author": "hakamadare", "author_id": 17597, "author_profile": "https://Stackoverflow.com/users/17597", "pm_score": 1, "selected": false, "text": "<p>you might get some good mileage out of using a language-specific external tool as a Vim filter. for example, if you can write a <a href=\"http://perltidy.sf.net\" rel=\"nofollow noreferrer\">Perltidy</a> config file to generate the formatting you want (it looks like you would want the <strong>-lp -vtc=2</strong> flags), you can then pipe your existing Vim buffer through it with</p>\n\n<pre><code>:!/path/to/tidy -config /path/to/configfile\n</code></pre>\n\n<p>if you're going to be running this sort of command frequently, you can define an command by putting something like the following in your .vimrc:</p>\n\n<pre><code>command -range=% Tidy &lt;line1&gt;,&lt;line2&gt;!/path/to/tidy -config /path/to/configfile\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/88931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7706/" ]
When defining or calling functions with enough arguments to span multiple lines, I want vim to line them up. For example, ``` def myfunction(arg1, arg2, arg, ... argsN-1, argN) ``` The idea is for argsN-1 to have its 'a' lined up with args1. Does anyone have a way to have this happen automatically in vim? I've seen the align plugin for lining equal signs (in assignment statements) and such, but I'm not sure if it can be made to solve this problem?
The previous poster had it, but forgot the `set` ``` :set cino=(0<Enter> ``` From `:help cinoptions-values` ``` The 'cinoptions' option sets how Vim performs indentation. In the list below, "N" represents a number of your choice (the number can be negative). When there is an 's' after the number, Vim multiplies the number by 'shiftwidth': "1s" is 'shiftwidth', "2s" is two times 'shiftwidth', etc. You can use a decimal point, too: "-0.5s" is minus half a 'shiftwidth'. The examples below assume a 'shiftwidth' of 4. ... (N When in unclosed parentheses, indent N characters from the line with the unclosed parentheses. Add a 'shiftwidth' for every unclosed parentheses. When N is 0 or the unclosed parentheses is the first non-white character in its line, line up with the next non-white character after the unclosed parentheses. (default 'shiftwidth' * 2). cino= cino=(0 > if (c1 && (c2 || if (c1 && (c2 || c3)) c3)) foo; foo; if (c1 && if (c1 && (c2 || c3)) (c2 || c3)) { { ```
88,957
<p>When <code>{0}</code> is used to initialize an object, what does it mean? I can't find any references to <code>{0}</code> anywhere, and because of the curly braces Google searches are not helpful.</p> <p>Example code:</p> <pre><code>SHELLEXECUTEINFO sexi = {0}; // what does this do? sexi.cbSize = sizeof(SHELLEXECUTEINFO); sexi.hwnd = NULL; sexi.fMask = SEE_MASK_NOCLOSEPROCESS; sexi.lpFile = lpFile.c_str(); sexi.lpParameters = args; sexi.nShow = nShow; if(ShellExecuteEx(&amp;sexi)) { DWORD wait = WaitForSingleObject(sexi.hProcess, INFINITE); if(wait == WAIT_OBJECT_0) GetExitCodeProcess(sexi.hProcess, &amp;returnCode); } </code></pre> <p>Without it, the above code will crash on runtime.</p>
[ { "answer_id": 88960, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 9, "selected": true, "text": "<p>What's happening here is called <strong>aggregate</strong> initialization. Here is the (abbreviated) definition of an aggregate from section 8.5.1 of the ISO spec:</p>\n\n<blockquote>\n <p>An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions.</p>\n</blockquote>\n\n<p>Now, using <code>{0}</code> to initialize an aggregate like this is basically a trick to <code>0</code> the entire thing. This is because when using aggregate initialization <strong>you don't have to specify all the members</strong> and the spec requires that all unspecified members be default initialized, which means set to <code>0</code> for simple types.</p>\n\n<p>Here is the relevant quote from the spec:</p>\n\n<blockquote>\n <p>If there are fewer initializers in the list than there are members in the\n aggregate, then each member not\n explicitly initialized shall be\n default-initialized.\n Example:</p>\n\n<pre><code>struct S { int a; char* b; int c; };\nS ss = { 1, \"asdf\" };\n</code></pre>\n \n <p>initializes <code>ss.a</code> with <code>1</code>, <code>ss.b</code> with\n <code>\"asdf\"</code>, and <code>ss.c</code> with the value of an\n expression of the form <code>int()</code>, that is,\n <code>0</code>.</p>\n</blockquote>\n\n<p>You can find the complete spec on this topic <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf#page=207\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 88983, "author": "µBio", "author_id": 9796, "author_profile": "https://Stackoverflow.com/users/9796", "pm_score": 2, "selected": false, "text": "<p>It's been awhile since I worked in c/c++ but IIRC, the same shortcut can be used for arrays as well.</p>\n" }, { "answer_id": 89093, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": false, "text": "<p>I also use it to initialize strings eg.</p>\n\n<pre><code>char mytext[100] = {0};\n</code></pre>\n" }, { "answer_id": 89462, "author": "Harold Ekstrom", "author_id": 8429, "author_profile": "https://Stackoverflow.com/users/8429", "pm_score": 7, "selected": false, "text": "<p>One thing to be aware of is that this technique will not set padding bytes to zero. For example:</p>\n\n<pre><code>struct foo\n{\n char c;\n int i;\n};\n\nfoo a = {0};\n</code></pre>\n\n<p>Is not the same as:</p>\n\n<pre><code>foo a;\nmemset(&amp;a,0,sizeof(a));\n</code></pre>\n\n<p>In the first case, pad bytes between c and i are uninitialized. Why would you care? Well, if you're saving this data to disk or sending it over a network or whatever, you could have a security issue.</p>\n" }, { "answer_id": 153599, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 4, "selected": false, "text": "<p>Note that an empty aggregate initializer also works:</p>\n\n<pre><code>SHELLEXECUTEINFO sexi = {};\nchar mytext[100] = {};\n</code></pre>\n" }, { "answer_id": 734171, "author": "snowcrash09", "author_id": 89036, "author_profile": "https://Stackoverflow.com/users/89036", "pm_score": 4, "selected": false, "text": "<p>In answer to why <code>ShellExecuteEx()</code> is crashing: your <code>SHELLEXECUTEINFO</code> \"sexi\" struct has many members and you're only initializing some of them. </p>\n\n<p>For example, the member <code>sexi.lpDirectory</code> could be pointing anywhere, but <code>ShellExecuteEx()</code> will still try to use it, hence you'll get a memory access violation. </p>\n\n<p>When you include the line:</p>\n\n<pre><code>SHELLEXECUTEINFO sexi = {0};\n</code></pre>\n\n<p>before the rest of your structure setup, you're telling the compiler to zero out <strong>all</strong> structure members before you initialize the specific ones you're interested in. <code>ShellExecuteEx()</code> knows that if <code>sexi.lpDirectory</code> is zero, it should ignore it.</p>\n" }, { "answer_id": 16534600, "author": "Ingo Blackman", "author_id": 1917520, "author_profile": "https://Stackoverflow.com/users/1917520", "pm_score": 2, "selected": false, "text": "<p>I have always wondered, <strong>why</strong> you should use something like </p>\n\n<pre><code>struct foo bar = { 0 };\n</code></pre>\n\n<p>Here is a test case to explain: </p>\n\n<p>check.c</p>\n\n<pre><code>struct f {\n int x;\n char a;\n} my_zero_struct;\n\nint main(void)\n{\n return my_zero_struct.x;\n}\n</code></pre>\n\n<p>I compile with <code>gcc -O2 -o check check.c</code> and then output the symbol table with <code>readelf -s check | sort -k 2</code> (this is with gcc 4.6.3 on ubuntu 12.04.2 on a x64 system). Excerpt:</p>\n\n<pre><code>59: 0000000000601018 0 NOTYPE GLOBAL DEFAULT ABS __bss_start\n48: 0000000000601018 0 NOTYPE GLOBAL DEFAULT ABS _edata\n25: 0000000000601018 0 SECTION LOCAL DEFAULT 25 \n33: 0000000000601018 1 OBJECT LOCAL DEFAULT 25 completed.6531\n34: 0000000000601020 8 OBJECT LOCAL DEFAULT 25 dtor_idx.6533\n62: 0000000000601028 8 OBJECT GLOBAL DEFAULT 25 my_zero_struct\n57: 0000000000601030 0 NOTYPE GLOBAL DEFAULT ABS _end\n</code></pre>\n\n<p>The important part here is, that <code>my_zero_struct</code> is after <code>__bss_start</code>. The \".bss\" section in a C program is the section of memory which is set to zero <strong>before</strong> <code>main</code> is called see <a href=\"http://en.wikipedia.org/wiki/.bss\" rel=\"nofollow\">wikipedia on .bss</a>.</p>\n\n<p>If you change the code above to:</p>\n\n<pre><code>} my_zero_struct = { 0 };\n</code></pre>\n\n<p>Then the resulting \"check\" executable looks <strong>exactly</strong> the same at least with the gcc 4.6.3 compiler on ubuntu 12.04.2; the <code>my_zero_struct</code> is still in the <code>.bss</code> section and thus it will be automatically initialized to zero, before <code>main</code> is called.</p>\n\n<p>Hints in the comments, that a <code>memset</code> might initialize the \"full\" structure is also not an improvement, because the <code>.bss</code> section is cleared fully which also means the \"full\" structure is set to zero.</p>\n\n<p>It <strong>might</strong> be that the C language standard does not mention any of this, but in a real world C compiler I have never seen a different behaviour.</p>\n" }, { "answer_id": 25693018, "author": "nitin prajapati", "author_id": 4012858, "author_profile": "https://Stackoverflow.com/users/4012858", "pm_score": -1, "selected": false, "text": "<p>{0} is an <strong>anonymous array</strong> containing its element as 0.</p>\n\n<p>This is used to <strong>initialize one or all elements of array with 0.</strong></p>\n\n<p>e.g. int arr[8] = {0};</p>\n\n<p>In this case all the elements of arr will be initialized as 0.</p>\n" }, { "answer_id": 25693435, "author": "Keith Thompson", "author_id": 827263, "author_profile": "https://Stackoverflow.com/users/827263", "pm_score": 3, "selected": false, "text": "<p><code>{0}</code> is a valid initializer for any (complete object) type, in both C and C++. It's a common idiom used to initialize an object to <em>zero</em> (read on to see what that means).</p>\n\n<p>For scalar types (arithmetic and pointer types), the braces are unnecessary, but they're explicitly allowed. Quoting the <a href=\"http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf\" rel=\"noreferrer\">N1570 draft</a> of the ISO C standard, section 6.7.9:</p>\n\n<blockquote>\n <p>The initializer for a scalar shall be a single expression, optionally enclosed in braces.</p>\n</blockquote>\n\n<p>It initializes the object to zero (<code>0</code> for integers, <code>0.0</code> for floating-point, a null pointer for pointers).</p>\n\n<p>For non-scalar types (structures, arrays, unions), <code>{0}</code> specifies that the <em>first</em> element of the object is initialized to zero. For structures containing structures, arrays of structures, and so on, this is applied recursively, so the first scalar element is set to the zero, as appropriate for the type. As in any initializer, any elements not specified are set to zero.</p>\n\n<p>Intermediate braces (<code>{</code>, <code>}</code>) may be omitted; for example both these are valid and equivalent:</p>\n\n<pre><code>int arr[2][2] = { { 1, 2 }, {3, 4} };\n\nint arr[2][2] = { 1, 2, 3, 4 };\n</code></pre>\n\n<p>which is why you don't have to write, for example, <code>{ { 0 } }</code> for a type whose first element is non-scalar.</p>\n\n<p>So this:</p>\n\n<pre><code>some_type obj = { 0 };\n</code></pre>\n\n<p>is a shorthand way of initializing <code>obj</code> to zero, meaning that each scalar sub-object of <code>obj</code> is set to <code>0</code> if it's an integer, <code>0.0</code> if it's floating-point, or a null pointer if it's a pointer.</p>\n\n<p>The rules are similar for C++.</p>\n\n<p>In your particular case, since you're assigning values to <code>sexi.cbSize</code> and so forth, it's clear that <code>SHELLEXECUTEINFO</code> is a struct or class type (or possibly a union, but probably not), so not all of this applies, but as I said <code>{ 0 }</code> is a common idiom that can be used in more general situations.</p>\n\n<p>This is <em>not</em> (necessarily) equivalent to using <code>memset</code> to set the object's representation to all-bits-zero. Neither floating-point <code>0.0</code> nor a null pointer is necessarily represented as all-bits-zero, and a <code>{ 0 }</code> initializer doesn't necessarily set padding bytes to any particular value. On most systems, though, it's likely to have the same effect.</p>\n" }, { "answer_id": 62515907, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 0, "selected": false, "text": "<p>It's syntatic sugar to initialize your entire structure to empty/zero/null values.</p>\n<p><strong>Long version</strong></p>\n<pre><code>SHELLEXECUTEINFO sexi;\nsexi.cbSize = 0;\nsexi.fMask = 0;\nsexi.hwnd = NULL;\nsexi.lpVerb = NULL;\nsexi.lpFile = NULL;\nsexi.lpParameters = NULL;\nsexi.lpDirectory = NULL;\nsexi.nShow = nShow;\nsexi.hInstApp = 0;\nsexi.lpIDList = NULL;\nsexi.lpClass = NULL;\nsexi.hkeyClass = 0;\nsexi.dwHotKey = 0;\nsexi.hMonitor = 0;\nsexi.hProcess = 0;\n</code></pre>\n<p><strong>Short version</strong></p>\n<pre><code>SHELLEXECUTEINFO sexi = {0};\n</code></pre>\n<p>Wasn't that much easier?</p>\n<p>It's also nice because:</p>\n<ul>\n<li>you don't have to hunt down every member and initialize it</li>\n<li>you don't have to worry that you might not initialize new members when they're added later</li>\n<li>you don't have have to <a href=\"https://devblogs.microsoft.com/oldnewthing/20050628-07/?p=35183\" rel=\"nofollow noreferrer\">call <code>ZeroMemory</code></a></li>\n</ul>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/88957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17027/" ]
When `{0}` is used to initialize an object, what does it mean? I can't find any references to `{0}` anywhere, and because of the curly braces Google searches are not helpful. Example code: ``` SHELLEXECUTEINFO sexi = {0}; // what does this do? sexi.cbSize = sizeof(SHELLEXECUTEINFO); sexi.hwnd = NULL; sexi.fMask = SEE_MASK_NOCLOSEPROCESS; sexi.lpFile = lpFile.c_str(); sexi.lpParameters = args; sexi.nShow = nShow; if(ShellExecuteEx(&sexi)) { DWORD wait = WaitForSingleObject(sexi.hProcess, INFINITE); if(wait == WAIT_OBJECT_0) GetExitCodeProcess(sexi.hProcess, &returnCode); } ``` Without it, the above code will crash on runtime.
What's happening here is called **aggregate** initialization. Here is the (abbreviated) definition of an aggregate from section 8.5.1 of the ISO spec: > > An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions. > > > Now, using `{0}` to initialize an aggregate like this is basically a trick to `0` the entire thing. This is because when using aggregate initialization **you don't have to specify all the members** and the spec requires that all unspecified members be default initialized, which means set to `0` for simple types. Here is the relevant quote from the spec: > > If there are fewer initializers in the list than there are members in the > aggregate, then each member not > explicitly initialized shall be > default-initialized. > Example: > > > > ``` > struct S { int a; char* b; int c; }; > S ss = { 1, "asdf" }; > > ``` > > initializes `ss.a` with `1`, `ss.b` with > `"asdf"`, and `ss.c` with the value of an > expression of the form `int()`, that is, > `0`. > > > You can find the complete spec on this topic [here](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf#page=207)
88,991
<p>I do not mean the compile errors because I made a syntax mistake or whatever. In C++ we can create compile time errors based on conditions as in the following example:</p> <pre><code>template&lt;int&gt; struct CompileTimeError; template&lt;&gt; struct CompileTimeError&lt;true&gt; {}; #define STATIC_CHECK(expr, msg) { CompileTimeError&lt;((expr) != 0)&gt; ERROR_##msg; (void)ERROR_##msg; } int main(int argc, char* argv[]) { STATIC_CHECK(false, Compile_Time_Failure); return 0; } </code></pre> <p>In VS 2005 this will output:</p> <pre><code>------ Build started: Project: Test, Configuration: Debug Win32 ------ Compiling... Test.cpp f:\temp\test\test\test.cpp(17) : error C2079: 'ERROR_Compile_Time_Failure' uses undefined struct 'CompileTimeError&lt;__formal&gt;' with [ __formal=0 ] Build log was saved at "file://f:\temp\Test\Test\Debug\BuildLog.htm" Test - 1 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== </code></pre> <p>Is there any way to achieve this in Java?</p>
[ { "answer_id": 89017, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "<p>There is no way to produce any actions based on compile-time logic in Java without the use of a separate tool. Technically, it is <em>possible</em> to use the C pre-processor on Java, but you would have to be careful of its built-in assumptions about the underlying language. If I were you, I would find a better way to accomplish whatever it is you're trying to do with this compile-time error. If necessary, you could even write your own pre-processor (possibly using <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/apt/GettingStarted.html\" rel=\"nofollow noreferrer\">APT</a>) if it is really so unavoidable.</p>\n" }, { "answer_id": 90563, "author": "Matt Quail", "author_id": 15790, "author_profile": "https://Stackoverflow.com/users/15790", "pm_score": 3, "selected": true, "text": "<p>There is no way to do this in Java, not in the same way it works for you in C++.</p>\n\n<p>You could perhaps use annotations, and run <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/apt/GettingStarted.html\" rel=\"nofollow noreferrer\">apt</a> before or after compilation to check your annotations.</p>\n\n<p>For example:</p>\n\n<pre><code>@MyStaticCheck(false, \"Compile Time Error, kind-of\")\npublic static void main(String[] args) {\n return;\n}\n</code></pre>\n\n<p>And then write your own AnnotationProcessorFactory that looked for @MyStaticCheck annotations, and does something with the arguments.</p>\n\n<p>Note: I haven't played too much with apt, but the documentation makes it looks like this is very do-able.</p>\n" }, { "answer_id": 91041, "author": "Confusion", "author_id": 16784, "author_profile": "https://Stackoverflow.com/users/16784", "pm_score": 0, "selected": false, "text": "<p>As Matt Quail answered above, annotations, together with <a href=\"http://xdoclet.sourceforge.net/xdoclet/index.html\" rel=\"nofollow noreferrer\">XDoclet</a>, are suited to address your needs. That combinations allows for a quite a bit of preprocessing, code generation, etc.</p>\n" }, { "answer_id": 11138683, "author": "Stan", "author_id": 1102014, "author_profile": "https://Stackoverflow.com/users/1102014", "pm_score": 0, "selected": false, "text": "<p>Though the question was asked some time ago, I decided to post my answer, because I solved (to a certain degree) a slightly similar problem.</p>\n\n<p>The specific of my task requires two applications with different function set to be built from a single core library (and unused stuff to be not linked in). The selection of function set is made by <code>public static final boolean</code> flags. The problem is that I want to ensure in each of the applications, that it is built with a proper flag set in the core library. And in the case of improper functions are enabled, the application should not compile giving a compile time error.</p>\n\n<p>The only solution I have found so far is to declare in the library final variables along with the flags: <code>public static final int functionSet1 = 0;</code>, etc.</p>\n\n<p>In the application package I added a dummy class with the checkup</p>\n\n<pre><code>ConditionalBuild.functionSet1 = 1;\n</code></pre>\n\n<p>From all the functionSetX variables only one made non-final at a specific build. So only one application can pass the build process without the error. Is there a better way to achieve this? Please let me know in comments.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/88991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508/" ]
I do not mean the compile errors because I made a syntax mistake or whatever. In C++ we can create compile time errors based on conditions as in the following example: ``` template<int> struct CompileTimeError; template<> struct CompileTimeError<true> {}; #define STATIC_CHECK(expr, msg) { CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; } int main(int argc, char* argv[]) { STATIC_CHECK(false, Compile_Time_Failure); return 0; } ``` In VS 2005 this will output: ``` ------ Build started: Project: Test, Configuration: Debug Win32 ------ Compiling... Test.cpp f:\temp\test\test\test.cpp(17) : error C2079: 'ERROR_Compile_Time_Failure' uses undefined struct 'CompileTimeError<__formal>' with [ __formal=0 ] Build log was saved at "file://f:\temp\Test\Test\Debug\BuildLog.htm" Test - 1 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ``` Is there any way to achieve this in Java?
There is no way to do this in Java, not in the same way it works for you in C++. You could perhaps use annotations, and run [apt](http://java.sun.com/j2se/1.5.0/docs/guide/apt/GettingStarted.html) before or after compilation to check your annotations. For example: ``` @MyStaticCheck(false, "Compile Time Error, kind-of") public static void main(String[] args) { return; } ``` And then write your own AnnotationProcessorFactory that looked for @MyStaticCheck annotations, and does something with the arguments. Note: I haven't played too much with apt, but the documentation makes it looks like this is very do-able.
89,051
<p>What I'd like to know is if there is a nice way to queue jQuery functions to execute after a set amount of time. This wouldn't pause the execution of other functions, just the ones following in the chain. Perhaps an example of what I'd envisage it would look like would illustrate:</p> <pre><code>$('#alert') .show() .wait(5000) // &lt;-- this bit .hide() ; </code></pre> <p>I know that it's possible by using timeouts, but it seems like that's a messy way to do it, especially compared to the above example (if it were real).</p> <p>So, is something like this already built-in to jQuery, and if not, what is the best way to emulate it?</p>
[ { "answer_id": 89076, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 4, "selected": true, "text": "<p>You can't do that, and you probably don't want to. While it certainly looks pretty, there is no mechanism in Javascript that will allow you do to that without just looping in \"wait\" until the time has passed. You could certainly do that but you risk seriously degrading the browser performance and if your timeout is longer than a handful of seconds browsers will show a warning to the user that your javascript seems to be stuck.</p>\n\n<p>The correct way to do this is with timeouts:</p>\n\n<pre><code>var el = $('#alert');\nel.show()\nsetTimeout(function() { el.hide() }, 5000);\n</code></pre>\n\n<p>Your other option would be to extend jquery to essentially add an effect for actions you want to delay:</p>\n\n<pre><code>jQuery.fn.extend({\n delayedHide: function(time) {\n var self = this;\n setTimeout(function() { self.hide(); }, time);\n }\n});\n\n$('#alert')\n .show()\n .delayedHide(5000)\n;\n</code></pre>\n\n<p>You could also extend jquery with a method similar to setTimeout:</p>\n\n<pre><code>jQuery.fn.extend({\n delayThis: function(fn, time, args) {\n var self = this;\n setTimeout(function() { jQuery.fn[fn].apply(self, args); }, time);\n }\n});\n\n$('#alert')\n .show()\n .delayThis('hide', 5000)\n;\n</code></pre>\n\n<p>or to call with args pass arguments in an array:</p>\n\n<pre><code>$('#alert')\n .show()\n .delayThis('css', 5000, [ 'display', 'none' ])\n;\n</code></pre>\n" }, { "answer_id": 89792, "author": "dansays", "author_id": 1923, "author_profile": "https://Stackoverflow.com/users/1923", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://web.archive.org/web/20111025005225/http://plugins.jquery.com:80/project/fxqueues\" rel=\"nofollow noreferrer\">jQuery FxQueues plug-in</a> does just what you need:</p>\n\n<pre><code>$('#element').fadeOut({\n speed: 'fast',\n preDelay: 5000\n});\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
What I'd like to know is if there is a nice way to queue jQuery functions to execute after a set amount of time. This wouldn't pause the execution of other functions, just the ones following in the chain. Perhaps an example of what I'd envisage it would look like would illustrate: ``` $('#alert') .show() .wait(5000) // <-- this bit .hide() ; ``` I know that it's possible by using timeouts, but it seems like that's a messy way to do it, especially compared to the above example (if it were real). So, is something like this already built-in to jQuery, and if not, what is the best way to emulate it?
You can't do that, and you probably don't want to. While it certainly looks pretty, there is no mechanism in Javascript that will allow you do to that without just looping in "wait" until the time has passed. You could certainly do that but you risk seriously degrading the browser performance and if your timeout is longer than a handful of seconds browsers will show a warning to the user that your javascript seems to be stuck. The correct way to do this is with timeouts: ``` var el = $('#alert'); el.show() setTimeout(function() { el.hide() }, 5000); ``` Your other option would be to extend jquery to essentially add an effect for actions you want to delay: ``` jQuery.fn.extend({ delayedHide: function(time) { var self = this; setTimeout(function() { self.hide(); }, time); } }); $('#alert') .show() .delayedHide(5000) ; ``` You could also extend jquery with a method similar to setTimeout: ``` jQuery.fn.extend({ delayThis: function(fn, time, args) { var self = this; setTimeout(function() { jQuery.fn[fn].apply(self, args); }, time); } }); $('#alert') .show() .delayThis('hide', 5000) ; ``` or to call with args pass arguments in an array: ``` $('#alert') .show() .delayThis('css', 5000, [ 'display', 'none' ]) ; ```
89,118
<p>I am getting an 403 access forbidden when attempting to open a page under a vhost where the document root is sitting on a different drive than where apache is sitting. I installed using the apachefriends release. This is my httpd-vhosts.conf file: </p> <p><pre><code> NameVirtualHost 127.0.0.1</p> <p>&lt;VirtualHost 127.0.0.1> ServerName foo.localhost DocumentRoot "C:/xampp/htdocs/foo/public" &lt;/VirtualHost></p> <p>&lt;VirtualHost 127.0.0.1> ServerName bar.localhost DocumentRoot "F:/bar/public" &lt;/VirtualHost> </pre></code></p> <p>When opening bar.localhost in my browser, Apache is giving me 403 Access Forbidden. I tried setting lots of different access rights, even full rights to everyone, but nothing I tried helped.</p> <p>Edit: Thanks! For future reference, add 'Options indexes' within to show directory indexes.</p>
[ { "answer_id": 91885, "author": "Mark Embling", "author_id": 6844, "author_profile": "https://Stackoverflow.com/users/6844", "pm_score": 6, "selected": false, "text": "<p>Somewhere, you need to tell Apache that people are allowed to see contents of this directory.</p>\n\n<pre><code>&lt;Directory \"F:/bar/public\"&gt;\n Order Allow,Deny\n Allow from All\n # Any other directory-specific stuff\n&lt;/Directory&gt;\n</code></pre>\n\n<p><a href=\"http://httpd.apache.org/docs/2.1/mod/core.html#directory\" rel=\"noreferrer\">More info</a></p>\n" }, { "answer_id": 12519708, "author": "cloudwhale", "author_id": 356824, "author_profile": "https://Stackoverflow.com/users/356824", "pm_score": 5, "selected": false, "text": "<p>For <strong>Apache 2.4.2</strong>: I was getting <em>403: Forbidden</em> continuously when I was trying to access WAMP on my Windows 7 desktop from my iPhone on WiFi. On one <a href=\"http://dabase.com/blog/AH01630:_client_denied_by_server_configuration/\" rel=\"noreferrer\">blog</a>, I found the solution - add <strong>Require all granted</strong> after <em>Allow all</em> in the <em>&lt;Directory&gt;</em> section. So this is how my <em>&lt;Directory&gt;</em> section looks like inside &lt;VirtualHost&gt;</p>\n\n<pre><code>&lt;Directory \"C:/wamp/www\"&gt;\n Options Indexes FollowSymLinks MultiViews Includes ExecCGI\n AllowOverride All\n Order Allow,Deny\n Allow from all\n Require all granted\n&lt;/Directory&gt;\n</code></pre>\n" }, { "answer_id": 12545200, "author": "Michael Klink", "author_id": 1691095, "author_profile": "https://Stackoverflow.com/users/1691095", "pm_score": 7, "selected": true, "text": "<p>You did not need</p>\n\n<pre><code>Options Indexes FollowSymLinks MultiViews Includes ExecCGI\nAllowOverride All\nOrder Allow,Deny\nAllow from all\nRequire all granted\n</code></pre>\n\n<p>the only thing what you need is...</p>\n\n<pre><code>Require all granted\n</code></pre>\n\n<p>...inside the directory section.</p>\n\n<p>See Apache 2.4 upgrading side:</p>\n\n<p><a href=\"http://httpd.apache.org/docs/2.4/upgrading.html\" rel=\"noreferrer\">http://httpd.apache.org/docs/2.4/upgrading.html</a></p>\n" }, { "answer_id": 27319355, "author": "mujaffars", "author_id": 2520185, "author_profile": "https://Stackoverflow.com/users/2520185", "pm_score": 0, "selected": false, "text": "<p>I have fixed it with removing below code from </p>\n\n<p><strong>C:\\wamp\\bin\\apache\\apache2.4.9\\conf\\extra\\httpd-vhosts.conf</strong> file</p>\n\n<pre><code>&lt;VirtualHost *:80&gt;\n ServerAdmin [email protected]\n DocumentRoot \"c:/Apache24/docs/dummy-host.example.com\"\n ServerName dummy-host.example.com\n ServerAlias www.dummy-host.example.com\n ErrorLog \"logs/dummy-host.example.com-error.log\"\n CustomLog \"logs/dummy-host.example.com-access.log\" common\n &lt;/VirtualHost&gt;\n\n&lt;VirtualHost *:80&gt;\n ServerAdmin [email protected]\n DocumentRoot \"c:/Apache24/docs/dummy-host2.example.com\"\n ServerName dummy-host2.example.com\n ErrorLog \"logs/dummy-host2.example.com-error.log\"\n CustomLog \"logs/dummy-host2.example.com-access.log\" common\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>And added </p>\n\n<pre><code>&lt;VirtualHost *:80&gt;\n ServerAdmin webmaster@localhost\n DocumentRoot \"c:/wamp/www\"\n ServerName localhost\n ErrorLog \"logs/localhost-error.log\"\n CustomLog \"logs/localhost-access.log\" common\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>And it has worked like charm</p>\n" }, { "answer_id": 59900172, "author": "Dupls", "author_id": 5494550, "author_profile": "https://Stackoverflow.com/users/5494550", "pm_score": 0, "selected": false, "text": "<p>Solved 403: Forbidden when visiting localhost. Using ports 80,443,3308 (the later to handle conflict with MySQL Server installation) \nWindows 10, XAMPP 7.4.1, Apache 2.4.x My web files are in a separate folder.</p>\n\n<p>httpd.conf - look for these lines and set it up where you have your files, mine is web folder.</p>\n\n<pre><code>DocumentRoot \"C:/web\"\n&lt;Directory \"C:/web\"&gt;\n</code></pre>\n\n<p>Changed these 2 lines. </p>\n\n<pre><code>&lt;VirtualHost *:80&gt;\n ServerAdmin [email protected]\n DocumentRoot \"C:/web/project1\"\n ServerName project1.localhost\n &lt;Directory \"C:/web/project1\"&gt;\n Order allow,deny\n allow from all\n &lt;/Directory&gt;\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>&lt;VirtualHost *:80&gt;\n ServerAdmin [email protected]\n DocumentRoot \"C:/web/project1\"\n ServerName project1.localhost\n &lt;Directory \"C:/web/project1\"&gt;\n Require all granted\n &lt;/Directory&gt;\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>Add your details in your hosts file\nC:\\Windows\\System32\\drivers\\etc\\hosts file</p>\n\n<pre><code>127.0.0.1 localhost\n127.0.0.1 project1.localhost\n</code></pre>\n\n<p>Stop start XAMPP, and click Apache admin (or localhost) and the wonderful XAMPP dashboard now displays! And visit your project at project1.localhost</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6752/" ]
I am getting an 403 access forbidden when attempting to open a page under a vhost where the document root is sitting on a different drive than where apache is sitting. I installed using the apachefriends release. This is my httpd-vhosts.conf file: ``` NameVirtualHost 127.0.0.1 ``` <VirtualHost 127.0.0.1> ServerName foo.localhost DocumentRoot "C:/xampp/htdocs/foo/public" </VirtualHost> <VirtualHost 127.0.0.1> ServerName bar.localhost DocumentRoot "F:/bar/public" </VirtualHost> When opening bar.localhost in my browser, Apache is giving me 403 Access Forbidden. I tried setting lots of different access rights, even full rights to everyone, but nothing I tried helped. Edit: Thanks! For future reference, add 'Options indexes' within to show directory indexes.
You did not need ``` Options Indexes FollowSymLinks MultiViews Includes ExecCGI AllowOverride All Order Allow,Deny Allow from all Require all granted ``` the only thing what you need is... ``` Require all granted ``` ...inside the directory section. See Apache 2.4 upgrading side: <http://httpd.apache.org/docs/2.4/upgrading.html>
89,154
<pre><code>boolean a = false, b = true; if ( a &amp;&amp; b ) { ... }; </code></pre> <p>In most languages, <code>b</code> will not get evaluated because <code>a</code> is false so <code>a &amp;&amp; b</code> cannot be true. My question is, wouldn't short circuiting be slower in terms of architecture? In a pipeline, do you just stall while waiting to get the result of a to determine if b should be evaluated or not? Would it be better to do nested ifs instead? Does that even help?</p> <p>Also, does anyone know what short-circuit evaluation is typically called? This question arose after I found out that my programming friend had never heard of short-circuit evaluation and stated that it is not common, nor found in many languages, and is inefficient in pipeline. I am not certain about the last one, so asking you folks!</p> <p>Okay, I think a different example to perhaps explain where my friend might be coming from. He believes that since evaluating a statement like the following in parallel:</p> <pre><code>(a) if ( ( a != null ) &amp;&amp; ( a.equals(b) ) ) { ... } </code></pre> <p>will crash the system, an architecture that doesn't have short-circuiting (and thereby not allowing statements like the above) would be faster in processing statements like these:</p> <pre><code>(b) if ( ( a == 4 ) &amp;&amp; ( b == 5 ) ) </code></pre> <p>since if it couldn't do (a) in parallel, it can't do (b) in parallel. In this case, a language that allows short-circuiting is slower than one that does not.</p> <p>I don't know if that's true or not.</p> <p>Thanks</p>
[ { "answer_id": 89170, "author": "user10392", "author_id": 10392, "author_profile": "https://Stackoverflow.com/users/10392", "pm_score": 1, "selected": false, "text": "<p>How can a nested if not stall? Actually if a and b are both variables and not expressions with side effects, they can be loaded in parallel by a good compiler. There's no benefit to using more ifs except increasing your line count. Really, this would be the worst kind of second guessing a compiler.</p>\n\n<p>It's called short-circuit evaluation.</p>\n" }, { "answer_id": 89173, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 0, "selected": false, "text": "<p>Depending upon the context, it can also be called \"Guarding\".</p>\n\n<p>And I've seen it in just about every language I've worked in - which pushes close to a dozen.</p>\n" }, { "answer_id": 89175, "author": "sirwart", "author_id": 6222, "author_profile": "https://Stackoverflow.com/users/6222", "pm_score": 4, "selected": false, "text": "<p>Short circuit evaluation is translated into branches in assembly language in the same way if statements are (branches are basically a goto), which means it is not going to be any slower than if statements.</p>\n\n<p>Branches don't typically stall the pipeline, but the processor will guess whether the branch is taken or not, and if the processor is wrong it will have to flush everything that has happened since it made the wrong guess from the pipeline.</p>\n\n<p>Short circuit evaluation is also the most common name for it, and is found in most languages in some form or another.</p>\n" }, { "answer_id": 89179, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": false, "text": "<p>I honestly wouldn't worry about it. Testing a boolean is <em>really fast</em>. Short-circuiting only gets interesting / useful when the second expression has side effects:</p>\n\n<pre><code>if ( ConfirmAction() &amp;&amp; DestroyAllData() )\n Reboot();\n</code></pre>\n\n<p>...or depends on the first test:</p>\n\n<pre><code>if ( myDodgyVar != null &amp;&amp; myDodgyVar.IsActive() )\n DoSomethingWith(myDodgyVar);\n</code></pre>\n" }, { "answer_id": 89180, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 1, "selected": false, "text": "<p>A useful short circuit I use is something like this:</p>\n\n<pre><code>if (a != null &amp;&amp; a.equals(somevalue)) {\n ... do something.\n}\n</code></pre>\n\n<p>This is, in my opinion very readable, and functions quite well. Generally, I try too avoid to much nesting because it leads to ugly code.</p>\n\n<p>All my opinion though.</p>\n" }, { "answer_id": 89182, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 1, "selected": false, "text": "<p>Most languages do short-circuit evaluation of boolean expressions. I have always heard it referred to as short-circuit evaluation. </p>\n\n<p>The example in the question is a pretty simplistic example that doesn't really provide much of a performance benefit. The performance benefit comes when the expressions are complex to evaluate. </p>\n\n<p>As an example of when this would be good imagine a game program that has something like:</p>\n\n<pre><code>if (someObject.isActive() &amp;&amp; someOtherObject.isActive() &amp;&amp; CollisionDetection.collides(someObject, someOtherObject) {\n doSomething();\n}\n</code></pre>\n\n<p>In this case the collision detection is far more expensive than the active checks. There would be a significant performance boost if there were lots of inactive objects in the system. </p>\n" }, { "answer_id": 89183, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 0, "selected": false, "text": "<p>I don't know anything about pipelining, but short-circuit evaluation is a common feature of many languages (and that's also the name I know it by). In C, &amp;&amp; and the other operators define a <a href=\"http://en.wikipedia.org/wiki/Sequence_point\" rel=\"nofollow noreferrer\">sequence point</a> just like the ; operator does, so I don't see how short-circuit evaluation is any less efficient than just using multiple statements.</p>\n" }, { "answer_id": 89189, "author": "Redbeard", "author_id": 14977, "author_profile": "https://Stackoverflow.com/users/14977", "pm_score": 2, "selected": false, "text": "<p>First, your friend is wrong. Short-circuit evaluation (aka minimal evaluation) is available in most languages and is better than nested ifs for parallel languages (in which case the first of the conditions that returns will cause execution to continue)</p>\n\n<p>In any case, even in a straightforward non-parallel language I don't see how nested ifs would be faster as execution would block until the first condition is evaluated.</p>\n" }, { "answer_id": 89194, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 0, "selected": false, "text": "<p>i've only heard of it as short circuit. in a pipeline doesnt the next op that goes in depend on the outcome of the if statement? if that is the case this would more optimized so it wouldnt have to test two values every time.</p>\n" }, { "answer_id": 89196, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 1, "selected": false, "text": "<p>Short-circuit, or minimal evaluation is just syntactic sugar for nested ifs.\nTo assume it is inefficient, or causes stalls is a case of premature optimization.\nAt this point, most compilers are intelligent enough to correctly interpret and optimize these statements. Using these statements can greatly reduce nesting, and therefore improve code readability, which should be your number one goal.</p>\n" }, { "answer_id": 89204, "author": "RobbieGee", "author_id": 6752, "author_profile": "https://Stackoverflow.com/users/6752", "pm_score": 0, "selected": false, "text": "<p>A single thread is sequential so if you have two ifs the first will of course be evaluated before the second, so I can't see a difference on that. I use the conditional-AND operator (which is what &amp;&amp; is called afaik) much more than nested ifs. If I want to check something that may take a while to evaluate, I do the simpler test first then the harder one after the conditional and.</p>\n\n<pre><code>a = obj.somethingQuickToTest() && obj.somethingSlowToTest();</code></pre>\n\n<p>doesn't seem to be any different than</p>\n\n<p><pre><code>a = false;\nif(obj.somethingQuickToTest())\n a = obj.somethingSlowToTest();</pre></code></p>\n" }, { "answer_id": 89224, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Regarding whether or not short-circuiting is efficient, pipelining is unlikely to have much of an impact on performance. In situations where it could have an impact, there's nothing to stop the compiler from testing multiple conditions in parallel so long as these tests doesn't have side-effects. Plus, modern CPUs have several mechanisms useful for improving the pipeline performance of branchy code.</p>\n\n<p>Nested ifs will have the same effect as short-circuiting &amp;&amp;.</p>\n\n<p>'Short-circuit evaluation' is the most common name for it, and your friend is wrong about it being uncommon; it's very common.</p>\n" }, { "answer_id": 89234, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<p>VB.Net has a different syntax depending on whether or not you want it to short circuit or not. Because of legacy reasons, the default behaviour is to not short circuit. The syntax is as follows</p>\n\n<p>Non Short Circuit</p>\n\n<pre><code>IF A And B THEN\n ...\nEND IF\n</code></pre>\n\n<p>Short Circuit</p>\n\n<pre><code>IF A AndAlso B THEN\n ...\nEND IF\n</code></pre>\n\n<p>You can use Or / OrElse if you want to short circuit an OR statement. Which is really nice in situations like the following</p>\n\n<pre><code>If MyObj IsNot Nothing AndAlso MyObj.Value &lt; SomeValue Then\n ....\nEnd If\n</code></pre>\n\n<p>Personally while I understand that short circuiting can speed things up, it's definitely not something that's obvious from just looking at the code. I could see an inexperienced developer getting confused by the behaviour. It even seems like something that could happen or not depending on compiler flags for level of optimization. I like how VB is verbose about which behaviour you actually want to accomplish.</p>\n" }, { "answer_id": 89313, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 4, "selected": true, "text": "<p>Short-circuiting boolean expressions are exactly equivalent to some set of nested ifs, so are as efficient as that would be.</p>\n\n<p>If b doesn't have side-effects, it can still be executed in parallel with a (for any value of \"in parallel\", including pipelining).</p>\n\n<p>If b has side effects which the CPU architecture can't cancel when branch prediction fails then yes, this might require delays which wouldn't be there if both sides were always evaluated. So it's something to look at if you do ever find that short-circuiting operators are creating a performance bottleneck in your code, but not worth worrying about otherwise.</p>\n\n<p>But short-circuiting is used for control flow as much as to save unnecessary work. It's common among languages I've used, for example the Perl idiom:</p>\n\n<pre><code>open($filename) or die(\"couldn't open file\");\n</code></pre>\n\n<p>the shell idiom:</p>\n\n<pre><code>do_something || echo \"that failed\"\n</code></pre>\n\n<p>or the C/C++/Java/etc idiom:</p>\n\n<pre><code>if ((obj != 0) &amp;&amp; (obj-&gt;ready)) { do_something; } // not -&gt; in Java of course.\n</code></pre>\n\n<p>In all these cases you need short-circuiting, so that the RHS is only evaluated if the LHS dictates that it should be. In such cases there's no point comparing performance with alternative code that's wrong!</p>\n" }, { "answer_id": 1024534, "author": "AlejandroR", "author_id": 120007, "author_profile": "https://Stackoverflow.com/users/120007", "pm_score": 3, "selected": false, "text": "<p><strong>Languages supporting short-circuiting:</strong></p>\n\n<p>Ada, Eiffel, ALGOL 68, C1, C++, C#, Java, R, Erlang, Standard ML, Javascript, MATLAB, Lisp, Lua, Scheme, OCaml, Haskell, Pascal,Perl, Ruby, PHP, Python, Smalltalk, Visual Basic .NET</p>\n\n<p>Taken from <a href=\"http://en.wikipedia.org/wiki/Short-circuit_evaluation\" rel=\"noreferrer\">Short-circuit evaluation</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12682/" ]
``` boolean a = false, b = true; if ( a && b ) { ... }; ``` In most languages, `b` will not get evaluated because `a` is false so `a && b` cannot be true. My question is, wouldn't short circuiting be slower in terms of architecture? In a pipeline, do you just stall while waiting to get the result of a to determine if b should be evaluated or not? Would it be better to do nested ifs instead? Does that even help? Also, does anyone know what short-circuit evaluation is typically called? This question arose after I found out that my programming friend had never heard of short-circuit evaluation and stated that it is not common, nor found in many languages, and is inefficient in pipeline. I am not certain about the last one, so asking you folks! Okay, I think a different example to perhaps explain where my friend might be coming from. He believes that since evaluating a statement like the following in parallel: ``` (a) if ( ( a != null ) && ( a.equals(b) ) ) { ... } ``` will crash the system, an architecture that doesn't have short-circuiting (and thereby not allowing statements like the above) would be faster in processing statements like these: ``` (b) if ( ( a == 4 ) && ( b == 5 ) ) ``` since if it couldn't do (a) in parallel, it can't do (b) in parallel. In this case, a language that allows short-circuiting is slower than one that does not. I don't know if that's true or not. Thanks
Short-circuiting boolean expressions are exactly equivalent to some set of nested ifs, so are as efficient as that would be. If b doesn't have side-effects, it can still be executed in parallel with a (for any value of "in parallel", including pipelining). If b has side effects which the CPU architecture can't cancel when branch prediction fails then yes, this might require delays which wouldn't be there if both sides were always evaluated. So it's something to look at if you do ever find that short-circuiting operators are creating a performance bottleneck in your code, but not worth worrying about otherwise. But short-circuiting is used for control flow as much as to save unnecessary work. It's common among languages I've used, for example the Perl idiom: ``` open($filename) or die("couldn't open file"); ``` the shell idiom: ``` do_something || echo "that failed" ``` or the C/C++/Java/etc idiom: ``` if ((obj != 0) && (obj->ready)) { do_something; } // not -> in Java of course. ``` In all these cases you need short-circuiting, so that the RHS is only evaluated if the LHS dictates that it should be. In such cases there's no point comparing performance with alternative code that's wrong!
89,178
<p>For example:</p> <pre><code>&gt;&gt;&gt; x = [1, 1, 2, 'a', 'a', 3] &gt;&gt;&gt; unique(x) [1, 2, 'a', 3] </code></pre> <p>Assume list elements are hashable.</p> <p><strong>Clarification:</strong> The result should keep the first duplicate in the list. For example, [1, 2, 3, 2, 3, 1] becomes [1, 2, 3].</p>
[ { "answer_id": 89197, "author": "solinent", "author_id": 13852, "author_profile": "https://Stackoverflow.com/users/13852", "pm_score": 0, "selected": false, "text": "<p>I have no experience with python, but an algorithm would be to sort the list, then remove duplicates (by comparing to previous items in the list), and finally find the position in the new list by comparing with the old list.</p>\n\n<p>Longer answer: <a href=\"http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560\" rel=\"nofollow noreferrer\">http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560</a></p>\n" }, { "answer_id": 89198, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": -1, "selected": false, "text": "<p>I haven't done any tests, but one possible algorithm might be to create a second list, and iterate through the first list. If an item is not in the second list, add it to the second list.</p>\n\n<pre><code>x = [1, 1, 2, 'a', 'a', 3]\ny = []\nfor each in x:\n if each not in y:\n y.append(each)\n</code></pre>\n" }, { "answer_id": 89202, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 3, "selected": false, "text": "<p>Taken from <a href=\"http://www.peterbe.com/plog/uniqifiers-benchmark\" rel=\"noreferrer\">http://www.peterbe.com/plog/uniqifiers-benchmark</a></p>\n\n<pre><code>def f5(seq, idfun=None): \n # order preserving \n if idfun is None: \n def idfun(x): return x \n seen = {} \n result = [] \n for item in seq: \n marker = idfun(item) \n # in old Python versions: \n # if seen.has_key(marker) \n # but in new ones: \n if marker in seen: continue \n seen[marker] = 1 \n result.append(item) \n return result\n</code></pre>\n" }, { "answer_id": 89208, "author": "etchasketch", "author_id": 14640, "author_profile": "https://Stackoverflow.com/users/14640", "pm_score": 0, "selected": false, "text": "<pre><code>&gt;&gt;&gt; def unique(list):\n... y = []\n... for x in list:\n... if x not in y:\n... y.append(x)\n... return y\n</code></pre>\n" }, { "answer_id": 89218, "author": "Allen", "author_id": 6043, "author_profile": "https://Stackoverflow.com/users/6043", "pm_score": 4, "selected": false, "text": "<p>What's going to be fastest depends on what percentage of your list is duplicates. If it's nearly all duplicates, with few unique items, creating a new list will probably be faster. If it's mostly unique items, removing them from the original list (or a copy) will be faster.</p>\n\n<p>Here's one for modifying the list in place:</p>\n\n<pre><code>def unique(items):\n seen = set()\n for i in xrange(len(items)-1, -1, -1):\n it = items[i]\n if it in seen:\n del items[i]\n else:\n seen.add(it)\n</code></pre>\n\n<p>Iterating backwards over the indices ensures that removing items doesn't affect the iteration.</p>\n" }, { "answer_id": 89230, "author": "Wesley Tarle", "author_id": 17057, "author_profile": "https://Stackoverflow.com/users/17057", "pm_score": 1, "selected": false, "text": "<p>O(n) if dict is hash, O(nlogn) if dict is tree, and simple, fixed. Thanks to Matthew for the suggestion. Sorry I don't know the underlying types.</p>\n\n<pre><code>def unique(x): \n output = []\n y = {}\n for item in x:\n y[item] = \"\"\n\n for item in x:\n if item in y:\n output.append(item)\n\n return output\n</code></pre>\n" }, { "answer_id": 89250, "author": "Terhorst", "author_id": 8062, "author_profile": "https://Stackoverflow.com/users/8062", "pm_score": 5, "selected": false, "text": "<pre><code>def unique(items):\n found = set()\n keep = []\n\n for item in items:\n if item not in found:\n found.add(item)\n keep.append(item)\n \n return keep\n\nprint unique([1, 1, 2, 'a', 'a', 3])\n</code></pre>\n" }, { "answer_id": 89260, "author": "Jake", "author_id": 10675, "author_profile": "https://Stackoverflow.com/users/10675", "pm_score": 2, "selected": false, "text": "<p>You can actually do something really cool in Python to solve this. You can create a list comprehension that would reference itself as it is being built. As follows:</p>\n\n<pre><code> # remove duplicates...\n def unique(my_list):\n return [x for x in my_list if x not in locals()['_[1]'].__self__]\n</code></pre>\n\n<p>Edit: <strong>I removed the \"self\", and it works on Mac OS X, Python 2.5.1.</strong></p>\n\n<p>The _[1] is Python's \"secret\" reference to the new list. The above, of course, is a little messy, but you could adapt it fit your needs as necessary. For example, you can actually write a function that returns a reference to the comprehension; it would look more like:</p>\n\n<pre><code>return [x for x in my_list if x not in this_list()]\n</code></pre>\n\n<hr>\n" }, { "answer_id": 89308, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": -1, "selected": false, "text": "<pre><code>&gt;&gt;&gt; x=[1,1,2,'a','a',3]\n&gt;&gt;&gt; y = [ _x for _x in x if not _x in locals()['_[1]'] ]\n&gt;&gt;&gt; y\n[1, 2, 'a', 3]\n</code></pre>\n\n<p><br>\n\"locals()['_[1]']\" is the \"secret name\" of the list being created.</p>\n" }, { "answer_id": 89331, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 3, "selected": false, "text": "<p>One-liner:</p>\n\n<pre><code>new_list = reduce(lambda x,y: x+[y][:1-int(y in x)], my_list, [])\n</code></pre>\n" }, { "answer_id": 89373, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "<p>Do the duplicates necessarily need to be in the list in the first place? There's no overhead as far as looking the elements up, but there is a little bit more overhead in adding elements (though the overhead should be O(1) ).</p>\n\n<pre><code>&gt;&gt;&gt; x = []\n&gt;&gt;&gt; y = set()\n&gt;&gt;&gt; def add_to_x(val):\n... if val not in y:\n... x.append(val)\n... y.add(val)\n... print x\n... print y\n... \n&gt;&gt;&gt; add_to_x(1)\n[1]\nset([1])\n&gt;&gt;&gt; add_to_x(1)\n[1]\nset([1])\n&gt;&gt;&gt; add_to_x(1)\n[1]\nset([1])\n&gt;&gt;&gt; \n</code></pre>\n" }, { "answer_id": 89917, "author": "etchasketch", "author_id": 14640, "author_profile": "https://Stackoverflow.com/users/14640", "pm_score": 1, "selected": false, "text": "<p>has_key in python is O(1). Insertion and retrieval from a hash is also O(1). Loops through n items twice, so O(n).</p>\n\n<pre><code>def unique(list):\n s = {}\n output = []\n for x in list:\n count = 1\n if(s.has_key(x)):\n count = s[x] + 1\n\n s[x] = count\n for x in list:\n count = s[x]\n if(count &gt; 0):\n s[x] = 0\n output.append(x)\n return output\n</code></pre>\n" }, { "answer_id": 90191, "author": "Sergey Stolyarov", "author_id": 15958, "author_profile": "https://Stackoverflow.com/users/15958", "pm_score": -1, "selected": false, "text": "<p>One pass.</p>\n\n<pre><code>a = [1,1,'a','b','c','c']\n\nnew_list = []\nprev = None\n\nwhile 1:\n try:\n i = a.pop(0)\n if i != prev:\n new_list.append(i)\n prev = i\n except IndexError:\n break\n</code></pre>\n" }, { "answer_id": 90225, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 4, "selected": false, "text": "<p>Using:</p>\n\n<pre><code>lst = [8, 8, 9, 9, 7, 15, 15, 2, 20, 13, 2, 24, 6, 11, 7, 12, 4, 10, 18, 13, 23, 11, 3, 11, 12, 10, 4, 5, 4, 22, 6, 3, 19, 14, 21, 11, 1, 5, 14, 8, 0, 1, 16, 5, 10, 13, 17, 1, 16, 17, 12, 6, 10, 0, 3, 9, 9, 3, 7, 7, 6, 6, 7, 5, 14, 18, 12, 19, 2, 8, 9, 0, 8, 4, 5]\n</code></pre>\n\n<p>And using the timeit module:</p>\n\n<pre><code>$ python -m timeit -s 'import uniquetest' 'uniquetest.etchasketch(uniquetest.lst)'\n</code></pre>\n\n<p>And so on for the various other functions (which I named after their posters), I have the following results (on my first generation Intel MacBook Pro):</p>\n\n<pre><code>Allen: 14.6 µs per loop [1]\nTerhorst: 26.6 µs per loop\nTarle: 44.7 µs per loop\nctcherry: 44.8 µs per loop\nEtchasketch 1 (short): 64.6 µs per loop\nSchinckel: 65.0 µs per loop\nEtchasketch 2: 71.6 µs per loop\nLittle: 89.4 µs per loop\nTyler: 179.0 µs per loop\n</code></pre>\n\n<p>[1] Note that Allen modifies the list in place – I believe this has skewed the time, in that the <code>timeit</code> module runs the code 100000 times and 99999 of them are with the dupe-less list.</p>\n\n<hr>\n\n<p><strong>Summary</strong>: Straight-forward implementation with sets wins over confusing one-liners :-)</p>\n" }, { "answer_id": 91028, "author": "Franck Mesirard", "author_id": 16070, "author_profile": "https://Stackoverflow.com/users/16070", "pm_score": -1, "selected": false, "text": "<p>I don't know if this one is fast or not, but at least it is simple.</p>\n\n<p>Simply, convert it first to a set and then again to a list</p>\n\n<pre><code>def unique(container):\n return list(set(container))\n</code></pre>\n" }, { "answer_id": 91430, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 3, "selected": false, "text": "<p>This is the fastest in-place method I've found (assuming a large proportion of duplicates):</p>\n\n<pre><code>def unique(l):\n s = set(); n = 0\n for x in l:\n if x not in s: s.add(x); l[n] = x; n += 1\n del l[n:]\n</code></pre>\n\n<p>This is 10% faster than Allen's implementation, on which it is based (timed with timeit.repeat, JIT compiled by psyco). It keeps the first instance of any duplicate.</p>\n\n<p>repton-infinity: I'd be interested if you could confirm my timings.</p>\n" }, { "answer_id": 92486, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 1, "selected": false, "text": "<p>There are some great, efficient solutions here. However, for anyone not concerned with the absolute most efficient <code>O(n)</code> solution, I'd go with the simple one-liner <code>O(n^2*log(n))</code> solution:</p>\n\n<pre><code>def unique(xs):\n return sorted(set(xs), key=lambda x: xs.index(x))\n</code></pre>\n\n<p>or the more efficient two-liner <code>O(n*log(n))</code> solution:</p>\n\n<pre><code>def unique(xs):\n positions = dict((e,pos) for pos,e in reversed(list(enumerate(xs))))\n return sorted(set(xs), key=lambda x: positions[x])\n</code></pre>\n" }, { "answer_id": 100784, "author": "user18695", "author_id": 18695, "author_profile": "https://Stackoverflow.com/users/18695", "pm_score": 0, "selected": false, "text": "<p>If you take out the empty list from the call to set() in Terhost's answer, you get a little speed boost.</p>\n\n<p>Change:\n found = set([])<br>\nto:\n found = set()</p>\n\n<p>However, you don't need the set at all.</p>\n\n<pre><code>def unique(items):\n keep = []\n\n for item in items:\n if item not in keep:\n keep.append(item)\n\n return keep\n</code></pre>\n\n<p>Using timeit I got these results:</p>\n\n<p>with set([]) -- 4.97210427363<br>\nwith set() -- 4.65712377445<br>\nwith no set -- 3.44865284975</p>\n" }, { "answer_id": 143883, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 3, "selected": false, "text": "<p>Obligatory generator-based variation:</p>\n\n<pre><code>def unique(seq):\n seen = set()\n for x in seq:\n if x not in seen:\n seen.add(x)\n yield x\n</code></pre>\n" }, { "answer_id": 279674, "author": "aboSamoor", "author_id": 35062, "author_profile": "https://Stackoverflow.com/users/35062", "pm_score": -1, "selected": false, "text": "<pre><code>a=[1,2,3,4,5,7,7,8,8,9,9,3,45]\n\ndef unique(l):\n\n ids={}\n for item in l:\n if not ids.has_key(item):\n ids[item]=item\n return ids.keys()\nprint a\n\nprint unique(a)\n</code></pre>\n<p>Inserting elements will take theta(n)\nretrieving if element is exiting or not will take constant time\ntesting all the items will take also theta(n)\nso we can see that this solution will take theta(n).\nBear in mind that dictionary in python implemented by hash table.</p>\n" }, { "answer_id": 282589, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "<p><strong>Update</strong>: <a href=\"https://stackoverflow.com/a/39835527/4279\">on Python3.7+</a>:</p>\n<pre><code>&gt;&gt;&gt; list(dict.fromkeys('abracadabra'))\n['a', 'b', 'r', 'c', 'd']\n</code></pre>\n<hr />\n<p><sup>old answer:</sup></p>\n<p>Here is the fastest solution so far (for the following input):</p>\n<pre><code>def del_dups(seq):\n seen = {}\n pos = 0\n for item in seq:\n if item not in seen:\n seen[item] = True\n seq[pos] = item\n pos += 1\n del seq[pos:]\n\nlst = [8, 8, 9, 9, 7, 15, 15, 2, 20, 13, 2, 24, 6, 11, 7, 12, 4, 10, 18, \n 13, 23, 11, 3, 11, 12, 10, 4, 5, 4, 22, 6, 3, 19, 14, 21, 11, 1, \n 5, 14, 8, 0, 1, 16, 5, 10, 13, 17, 1, 16, 17, 12, 6, 10, 0, 3, 9, \n 9, 3, 7, 7, 6, 6, 7, 5, 14, 18, 12, 19, 2, 8, 9, 0, 8, 4, 5]\ndel_dups(lst)\nprint(lst)\n# -&gt; [8, 9, 7, 15, 2, 20, 13, 24, 6, 11, 12, 4, 10, 18, 23, 3, 5, 22, 19, 14, \n# 21, 1, 0, 16, 17]\n</code></pre>\n<p>Dictionary lookup is slightly faster then the set's one in Python 3.</p>\n" }, { "answer_id": 2607669, "author": "Mario Ruggier", "author_id": 2185854, "author_profile": "https://Stackoverflow.com/users/2185854", "pm_score": 2, "selected": false, "text": "<p>An in-place one-liner for this:</p>\n\n<pre><code>&gt;&gt;&gt; x = [1, 1, 2, 'a', 'a', 3]\n&gt;&gt;&gt; [ item for pos,item in enumerate(x) if x.index(item)==pos ]\n[1, 2, 'a', 3]\n</code></pre>\n" }, { "answer_id": 4556143, "author": "Scot", "author_id": 557383, "author_profile": "https://Stackoverflow.com/users/557383", "pm_score": 2, "selected": false, "text": "<p>Remove duplicates and preserve order:</p>\n\n<p>This is a fast 2-liner that leverages built-in functionality of list comprehensions and dicts.</p>\n\n<pre><code>x = [1, 1, 2, 'a', 'a', 3]\n\ntmpUniq = {} # temp variable used below \nresults = [tmpUniq.setdefault(i,i) for i in x if i not in tmpUniq]\n\nprint results\n[1, 2, 'a', 3]\n</code></pre>\n\n<p>The dict.setdefaults() function returns the value as well as adding it to the temp dict directly in the list comprehension. Using the built-in functions and the hashes of the dict will work to maximize efficiency for the process.</p>\n" }, { "answer_id": 7843997, "author": "Raymond Hettinger", "author_id": 424499, "author_profile": "https://Stackoverflow.com/users/424499", "pm_score": 1, "selected": false, "text": "<p>Here are two recipes from the <em>itertools</em> documentation:</p>\n\n<pre><code>def unique_everseen(iterable, key=None):\n \"List unique elements, preserving order. Remember all elements ever seen.\"\n # unique_everseen('AAAABBBCCDAABBB') --&gt; A B C D\n # unique_everseen('ABBCcAD', str.lower) --&gt; A B C D\n seen = set()\n seen_add = seen.add\n if key is None:\n for element in ifilterfalse(seen.__contains__, iterable):\n seen_add(element)\n yield element\n else:\n for element in iterable:\n k = key(element)\n if k not in seen:\n seen_add(k)\n yield element\n\ndef unique_justseen(iterable, key=None):\n \"List unique elements, preserving order. Remember only the element just seen.\"\n # unique_justseen('AAAABBBCCDAABBB') --&gt; A B C D A B\n # unique_justseen('ABBCcAD', str.lower) --&gt; A B C A D\n return imap(next, imap(itemgetter(1), groupby(iterable, key)))\n</code></pre>\n" }, { "answer_id": 7844011, "author": "Raymond Hettinger", "author_id": 424499, "author_profile": "https://Stackoverflow.com/users/424499", "pm_score": 3, "selected": false, "text": "<p>This may be the simplest way:</p>\n\n<pre><code>list(OrderedDict.fromkeys(iterable))\n</code></pre>\n\n<p>As of Python 3.5, OrderedDict is now implemented in C, so this was is now the shortest, cleanest, and fastest.</p>\n" }, { "answer_id": 20787336, "author": "Michael", "author_id": 715042, "author_profile": "https://Stackoverflow.com/users/715042", "pm_score": 2, "selected": false, "text": "<p>This is the fastest one, comparing all the stuff from this <a href=\"http://www.peterbe.com/plog/uniqifiers-benchmark\" rel=\"nofollow\">lengthy discussion</a> and the other answers given here, refering to this <a href=\"http://www.peterbe.com/plog/uniqifiers-benchmark/uniqifiers_benchmark.py\" rel=\"nofollow\">benchmark</a>. It's another 25% faster than the fastest function from the discussion, <code>f8</code>. Thanks to David Kirby for the idea.</p>\n\n<pre><code>def uniquify(seq):\n seen = set()\n seen_add = seen.add\n return [x for x in seq if x not in seen and not seen_add(x)]\n</code></pre>\n\n<p>Some time comparison:</p>\n\n<pre><code>$ python uniqifiers_benchmark.py \n* f8_original 3.76\n* uniquify 3.0\n* terhorst 5.44\n* terhorst_localref 4.08\n* del_dups 4.76\n</code></pre>\n" }, { "answer_id": 25958705, "author": "BigDataGuy", "author_id": 4063267, "author_profile": "https://Stackoverflow.com/users/4063267", "pm_score": 0, "selected": false, "text": "<pre><code>x = [] # Your list of items that includes Duplicates\n\n# Assuming that your list contains items of only immutable data types\n\ndict_x = {} \n\ndict_x = {item : item for i, item in enumerate(x) if item not in dict_x.keys()}\n# Average t.c. = O(n)* O(1) ; furthermore the dict comphrehension and generator like behaviour of enumerate adds a certain efficiency and pythonic feel to it.\n\nx = dict_x.keys() # if you want your output in list format \n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16976/" ]
For example: ``` >>> x = [1, 1, 2, 'a', 'a', 3] >>> unique(x) [1, 2, 'a', 3] ``` Assume list elements are hashable. **Clarification:** The result should keep the first duplicate in the list. For example, [1, 2, 3, 2, 3, 1] becomes [1, 2, 3].
``` def unique(items): found = set() keep = [] for item in items: if item not in found: found.add(item) keep.append(item) return keep print unique([1, 1, 2, 'a', 'a', 3]) ```
89,188
<p>Is it possible to get the x,y coordinates of a Flex app within an HTML page? I know you can use ExternalInterface.ObjecID to get the "id attribute of the object tag in Internet Explorer, or the name attribute of the embed tag in Netscape" but I can't seem to get past that step. It seems like it should be possible to get a handle on that embed object. Any suggestions? </p> <p>Thanks.</p>
[ { "answer_id": 89286, "author": "Robert", "author_id": 4959, "author_profile": "https://Stackoverflow.com/users/4959", "pm_score": 0, "selected": false, "text": "<p>If you are trying just to measure where it's at within a page as the external user the only thing that pops into my mind is a Firefox extension called MeasureIt I've used it occasionally for various measuring on web pages.</p>\n\n<p>Are you trying to do this programmatically from within the embedded page itself and if so which langauge?</p>\n" }, { "answer_id": 91732, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": true, "text": "<p>I think the easiest thing to do is to include some kind of JavaScript library on the HTML page, say jQuery, and use it's functions for determining the position and size of DOM nodes. I would do it more or less like this:</p>\n\n<pre><code>var jsCode : String = \"function( id ) { return $('#' + id).offset(); }\";\n\nvar offset : Object = ExternalInterface.call(jsCode, ExternalObject.objectID);\n\ntrace(offset.left, offset.top);\n</code></pre>\n\n<p>Notice that this is ActionScript code, but it runs JavaScript code through <code>ExternalInterface</code>. It uses jQuery and in particular its <code>offset</code> method that returns the left and top offset of a DOM node.</p>\n\n<p>You could do without jQuery if you looked at how the <code>offset</code> method is implemented and included that code in place of the call to jQuery. That way you wouldn't need to load jQuery in the HTML and the Flex app would be self-contained. The reason I suggest to use a library like jQuery is that browsers do these things differently. I'm not sure if calculating offsets is very different from browser to browser, but it doesn't hurt to be insulated from browser differences.</p>\n\n<p>The JavaScript in my example is an anonymous function so that the ID of the embed/object tag can be passed in to it as a parameter to <code>ExternalInterface.call</code>, but you could just use string concatenation if you want:</p>\n\n<pre><code>var jsCode : String = \"$('#' +\" + ExternalInterface.objectID + \").offset()\";\n\nvar offset : Object = ExternalInterface.call(jsCode);\n</code></pre>\n\n<p>That would work too, I just think the first version is more elegant.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15899/" ]
Is it possible to get the x,y coordinates of a Flex app within an HTML page? I know you can use ExternalInterface.ObjecID to get the "id attribute of the object tag in Internet Explorer, or the name attribute of the embed tag in Netscape" but I can't seem to get past that step. It seems like it should be possible to get a handle on that embed object. Any suggestions? Thanks.
I think the easiest thing to do is to include some kind of JavaScript library on the HTML page, say jQuery, and use it's functions for determining the position and size of DOM nodes. I would do it more or less like this: ``` var jsCode : String = "function( id ) { return $('#' + id).offset(); }"; var offset : Object = ExternalInterface.call(jsCode, ExternalObject.objectID); trace(offset.left, offset.top); ``` Notice that this is ActionScript code, but it runs JavaScript code through `ExternalInterface`. It uses jQuery and in particular its `offset` method that returns the left and top offset of a DOM node. You could do without jQuery if you looked at how the `offset` method is implemented and included that code in place of the call to jQuery. That way you wouldn't need to load jQuery in the HTML and the Flex app would be self-contained. The reason I suggest to use a library like jQuery is that browsers do these things differently. I'm not sure if calculating offsets is very different from browser to browser, but it doesn't hurt to be insulated from browser differences. The JavaScript in my example is an anonymous function so that the ID of the embed/object tag can be passed in to it as a parameter to `ExternalInterface.call`, but you could just use string concatenation if you want: ``` var jsCode : String = "$('#' +" + ExternalInterface.objectID + ").offset()"; var offset : Object = ExternalInterface.call(jsCode); ``` That would work too, I just think the first version is more elegant.
89,193
<p>Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following:</p> <pre><code>var people = from p in Person where p.age &lt; 18 select p var otherPeople = from p in people where p.firstName equals "Daniel" select p </code></pre> <p>Assuming that <code>Person</code> is an ADO entity which defines the <code>age</code> and <code>firstName</code> fields, what would this do from a database standpoint? Specifically, would the <code>people</code> query be run to produce an in-memory structure, which would then be queried by the <code>otherPeople</code> query? Or would the construction of <code>otherPeople</code> merely pull the data regarding the query from <code>people</code> and then produce a new database-peered query? So, if I iterated over both of these queries, how many SQL statements would be executed?</p>
[ { "answer_id": 89211, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 1, "selected": false, "text": "<p><code>people</code> and <code>otherPeople</code> contain objects of type <code>IQueryable&lt;Person></code>.</p>\n\n<p>If you iterate over both, separatly, it will run two queries.\nIf you only iterate over <code>otherPeople</code>, it will run the expected query, with two where clauses.</p>\n\n<p>If you do <code>.ToList()</code> on <code>people</code> and use the returned <code>List&lt;Person></code> in the second query instead of people, it becomes LINQ-to-Objects and no SQL is executed.</p>\n\n<p>This behavior is referred to as deferred execution. Meaning no query is done until it is needed. Before execution they are just expression trees that get manipulated to formulate the final query.</p>\n" }, { "answer_id": 89220, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 0, "selected": false, "text": "<p>Both these queries will be executes when you'll try to access final results. You can try to view original SQL generated from DataContext object properties.</p>\n" }, { "answer_id": 89223, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 5, "selected": true, "text": "<p>They are composable. This is possible because LINQ queries are actually expressions (code as data), which LINQ providers like LINQ-to-SQL can evaluate and generate corresponding SQL.</p>\n\n<p>Because LINQ queries are lazily evaluated (e.g. won't get executed until you iterate over the elements), the code you showed won't actually touch the database. Not until you iterate over otherPeople or people will SQL get generated and executed.</p>\n" }, { "answer_id": 89227, "author": "Michael L Perry", "author_id": 7668, "author_profile": "https://Stackoverflow.com/users/7668", "pm_score": 2, "selected": false, "text": "<p>Yes, the resulting query is composed. It includes the full where clause. Turn on SQL profiling and try it to see for yourself.</p>\n\n<p>Linq does this through expression trees. The first linq statement produces an expression tree; it doesn't execute the query. The second linq statement builds on the expression tree created by the first. The statement is only executed when you enumerate the resulting collection.</p>\n" }, { "answer_id": 89982, "author": "Ant", "author_id": 3709, "author_profile": "https://Stackoverflow.com/users/3709", "pm_score": 2, "selected": false, "text": "<pre><code>var people = from p in Person\n where p.age &lt; 18\n select p\n</code></pre>\n\n<p>Translates to:</p>\n\n<pre><code>SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]\nFROM [dbo].[Person] AS [t0]\nWHERE [t0].[Age] &lt; @p0\n</code></pre>\n\n<p>where @p0 gets sent through as 18</p>\n\n<pre><code>var otherPeople = from p in people\n where p.firstName equals \"Daniel\"\n select p\n</code></pre>\n\n<p>Translates to:</p>\n\n<pre><code>SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]\nFROM [dbo].[Person] AS [t0]\nWHERE [t0].[FirstName] = @p0\n</code></pre>\n\n<p>where @p0 gets sent through as \"Daniel\"</p>\n\n<pre><code>var morePeople = from p1 in people\n from p2 in otherPeople\n where p1.PersonId == p2.PersonId\n select p1;\n</code></pre>\n\n<p>Translates to:</p>\n\n<pre><code>SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]\nFROM [dbo].[Person] AS [t0], [dbo].[Person] AS [t1]\nWHERE ([t0].[PersonId] = [t1].[PersonId]) AND ([t0].[Age] &lt; @p0) AND ([t1].[FirstName] = @p1)\n</code></pre>\n\n<p>where @p0 is 18, @p1 is \"Daniel\"</p>\n\n<p>When in doubt, call the ToString() on your IQueryable or give a TextWriter to the DataContext's Log property.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9815/" ]
Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following: ``` var people = from p in Person where p.age < 18 select p var otherPeople = from p in people where p.firstName equals "Daniel" select p ``` Assuming that `Person` is an ADO entity which defines the `age` and `firstName` fields, what would this do from a database standpoint? Specifically, would the `people` query be run to produce an in-memory structure, which would then be queried by the `otherPeople` query? Or would the construction of `otherPeople` merely pull the data regarding the query from `people` and then produce a new database-peered query? So, if I iterated over both of these queries, how many SQL statements would be executed?
They are composable. This is possible because LINQ queries are actually expressions (code as data), which LINQ providers like LINQ-to-SQL can evaluate and generate corresponding SQL. Because LINQ queries are lazily evaluated (e.g. won't get executed until you iterate over the elements), the code you showed won't actually touch the database. Not until you iterate over otherPeople or people will SQL get generated and executed.
89,228
<p>How do I call an external command within Python as if I'd typed it in a shell or command prompt?</p>
[ { "answer_id": 89237, "author": "nimish", "author_id": 3926, "author_profile": "https://Stackoverflow.com/users/3926", "pm_score": 8, "selected": false, "text": "<pre><code>import os\nos.system(\"your command\")\n</code></pre>\n\n<p>Note that this is dangerous, since the command isn't cleaned. I leave it up to you to google for the relevant documentation on the 'os' and 'sys' modules. There are a bunch of functions (exec* and spawn*) that will do similar things.</p>\n" }, { "answer_id": 89238, "author": "Alexandra Franks", "author_id": 16203, "author_profile": "https://Stackoverflow.com/users/16203", "pm_score": 7, "selected": false, "text": "<pre><code>import os\ncmd = 'ls -al'\nos.system(cmd)\n</code></pre>\n\n<p>If you want to return the results of the command, you can use <a href=\"https://docs.python.org/2/library/os.html#os.popen\" rel=\"noreferrer\"><code>os.popen</code></a>. However, this is deprecated since version 2.6 in favor of the <a href=\"https://docs.python.org/2/library/subprocess.html#module-subprocess\" rel=\"noreferrer\">subprocess module</a>, which other answers have covered well.</p>\n" }, { "answer_id": 89243, "author": "David Cournapeau", "author_id": 11465, "author_profile": "https://Stackoverflow.com/users/11465", "pm_score": 13, "selected": true, "text": "<p>Use the <a href=\"https://docs.python.org/library/subprocess.html\" rel=\"noreferrer\"><code>subprocess</code></a> module in the standard library:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import subprocess\nsubprocess.run([&quot;ls&quot;, &quot;-l&quot;])\n</code></pre>\n<p>The advantage of <a href=\"https://docs.python.org/library/subprocess.html#subprocess.run\" rel=\"noreferrer\"><code>subprocess.run</code></a> over <a href=\"https://docs.python.org/library/os.html#os.system\" rel=\"noreferrer\"><code>os.system</code></a> is that it is more flexible (you can get the <a href=\"https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout\" rel=\"noreferrer\"><code>stdout</code></a>, <a href=\"https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr\" rel=\"noreferrer\"><code>stderr</code></a>, the <a href=\"https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode\" rel=\"noreferrer\">&quot;real&quot; status code</a>, better <a href=\"https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError\" rel=\"noreferrer\">error handling</a>, etc...).</p>\n<p>Even <a href=\"https://docs.python.org/library/os.html#os.system\" rel=\"noreferrer\">the documentation for <code>os.system</code></a> recommends using <code>subprocess</code> instead:</p>\n<blockquote>\n<p>The <code>subprocess</code> module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the <a href=\"https://docs.python.org/library/subprocess.html#subprocess-replacements\" rel=\"noreferrer\">Replacing Older Functions with the subprocess Module</a> section in the <a href=\"https://docs.python.org/library/subprocess.html\" rel=\"noreferrer\"><code>subprocess</code></a> documentation for some helpful recipes.</p>\n</blockquote>\n<p>On Python 3.4 and earlier, use <code>subprocess.call</code> instead of <code>.run</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>subprocess.call([&quot;ls&quot;, &quot;-l&quot;])\n</code></pre>\n" }, { "answer_id": 89255, "author": "sirwart", "author_id": 6222, "author_profile": "https://Stackoverflow.com/users/6222", "pm_score": 7, "selected": false, "text": "<p>I'd recommend using the <a href=\"http://docs.python.org/library/subprocess.html\" rel=\"noreferrer\">subprocess</a> module instead of os.system because it does shell escaping for you and is therefore much safer.</p>\n\n<pre><code>subprocess.call(['ping', 'localhost'])\n</code></pre>\n" }, { "answer_id": 89262, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 6, "selected": false, "text": "<p>Use <em><a href=\"https://docs.python.org/2/library/subprocess.html\" rel=\"noreferrer\">subprocess</a></em>.</p>\n\n<p>...or for a very simple command:</p>\n\n<pre><code>import os\nos.system('cat testfile')\n</code></pre>\n" }, { "answer_id": 89304, "author": "Martin W", "author_id": 14199, "author_profile": "https://Stackoverflow.com/users/14199", "pm_score": 5, "selected": false, "text": "<p><code>os.system</code> is OK, but kind of dated. It's also not very secure. Instead, try <code>subprocess</code>. <code>subprocess</code> does not call sh directly and is therefore more secure than <code>os.system</code>.</p>\n\n<p>Get more information <a href=\"https://docs.python.org/library/subprocess.html\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 92395, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 12, "selected": false, "text": "<p>Summary of ways to call external programs, including their advantages and disadvantages:</p>\n<ol>\n<li><p><a href=\"https://docs.python.org/3/library/os.html#os.system\" rel=\"noreferrer\"><code>os.system</code></a> passes the command and arguments to your system's shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>os.system(&quot;some_command &lt; input_file | another_command &gt; output_file&quot;) \n</code></pre>\n<p>However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, et cetera. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs.</p>\n</li>\n<li><p><a href=\"https://docs.python.org/3/library/os.html#os.popen\" rel=\"noreferrer\"><code>os.popen</code></a> will do the same thing as <code>os.system</code> except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don't need to worry about escaping anything. Example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(os.popen(&quot;ls -l&quot;).read())\n</code></pre>\n</li>\n<li><p><a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.Popen\" rel=\"noreferrer\"><code>subprocess.Popen</code></a>. This is intended as a replacement for <code>os.popen</code>, but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you'd say:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print subprocess.Popen(&quot;echo Hello World&quot;, shell=True, stdout=subprocess.PIPE).stdout.read()\n</code></pre>\n<p>instead of</p>\n<pre class=\"lang-py prettyprint-override\"><code>print os.popen(&quot;echo Hello World&quot;).read()\n</code></pre>\n<p>but it is nice to have all of the options there in one unified class instead of 4 different popen functions. See <a href=\"https://docs.python.org/3/library/subprocess.html#popen-constructor\" rel=\"noreferrer\">the documentation</a>.</p>\n</li>\n<li><p><a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.call\" rel=\"noreferrer\"><code>subprocess.call</code></a>. This is basically just like the <code>Popen</code> class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>return_code = subprocess.call(&quot;echo Hello World&quot;, shell=True)\n</code></pre>\n</li>\n<li><p><a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.run\" rel=\"noreferrer\"><code>subprocess.run</code></a>. Python 3.5+ only. Similar to the above but even more flexible and returns a <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess\" rel=\"noreferrer\"><code>CompletedProcess</code></a> object when the command finishes executing.</p>\n</li>\n<li><p><code>os.fork</code>, <code>os.exec</code>, <code>os.spawn</code> are similar to their C language counterparts, but I don't recommend using them directly.</p>\n</li>\n</ol>\n<p>The <code>subprocess</code> module should probably be what you use.</p>\n<p>Finally, please be aware that for all methods where you pass the final command to be executed by the shell as a string and you are responsible for escaping it. <strong>There are serious security implications</strong> if any part of the string that you pass can not be fully trusted. For example, if a user is entering some/any part of the string. If you are unsure, only use these methods with constants. To give you a hint of the implications consider this code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print subprocess.Popen(&quot;echo %s &quot; % user_input, stdout=PIPE).stdout.read()\n</code></pre>\n<p>and imagine that the user enters something &quot;<code>my mama didnt love me &amp;&amp; rm -rf /</code>&quot; which could erase the whole filesystem.</p>\n" }, { "answer_id": 95246, "author": "EmmEff", "author_id": 9188, "author_profile": "https://Stackoverflow.com/users/9188", "pm_score": 9, "selected": false, "text": "<p>Typical implementation:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import subprocess\n\np = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\nfor line in p.stdout.readlines():\n print line,\nretval = p.wait()\n</code></pre>\n<p>You are free to do what you want with the <code>stdout</code> data in the pipe. In fact, you can simply omit those parameters (<code>stdout=</code> and <code>stderr=</code>) and it'll behave like <code>os.system()</code>.</p>\n" }, { "answer_id": 2030768, "author": "Atinc Delican", "author_id": 246735, "author_profile": "https://Stackoverflow.com/users/246735", "pm_score": 5, "selected": false, "text": "<p>There is another difference here which is not mentioned previously.</p>\n\n<p><code>subprocess.Popen</code> executes the &lt;command> as a subprocess. In my case, I need to execute file &lt;a> which needs to communicate with another program, &lt;b>. </p>\n\n<p>I tried subprocess, and execution was successful. However &lt;b> could not communicate with &lt;a>.\nEverything is normal when I run both from the terminal.</p>\n\n<p>One more: \n(NOTE: kwrite behaves different from other applications. If you try the below with Firefox, the results will not be the same.)</p>\n\n<p>If you try <code>os.system(\"kwrite\")</code>, program flow freezes until the user closes kwrite. To overcome that I tried instead <code>os.system(konsole -e kwrite)</code>. This time program continued to flow, but kwrite became the subprocess of the console.</p>\n\n<p>Anyone runs the kwrite not being a subprocess (i.e. in the system monitor it must appear at the leftmost edge of the tree).</p>\n" }, { "answer_id": 2251026, "author": "newtover", "author_id": 68998, "author_profile": "https://Stackoverflow.com/users/68998", "pm_score": 8, "selected": false, "text": "<p>Some hints on detaching the child process from the calling one (starting the child process in background).</p>\n\n<p>Suppose you want to start a long task from a CGI script. That is, the child process should live longer than the CGI script execution process.</p>\n\n<p>The classical example from the subprocess module documentation is:</p>\n\n<pre><code>import subprocess\nimport sys\n\n# Some code here\n\npid = subprocess.Popen([sys.executable, \"longtask.py\"]) # Call subprocess\n\n# Some more code here\n</code></pre>\n\n<p>The idea here is that you do not want to wait in the line 'call subprocess' until the longtask.py is finished. But it is not clear what happens after the line 'some more code here' from the example.</p>\n\n<p>My target platform was FreeBSD, but the development was on Windows, so I faced the problem on Windows first.</p>\n\n<p>On Windows (Windows&nbsp;XP), the parent process will not finish until the longtask.py has finished its work. It is not what you want in a CGI script. The problem is not specific to Python; in the PHP community the problems are the same.</p>\n\n<p>The solution is to pass DETACHED_PROCESS <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx\" rel=\"noreferrer\">Process Creation Flag</a> to the underlying CreateProcess function in Windows API.\nIf you happen to have installed pywin32, you can import the flag from the win32process module, otherwise you should define it yourself:</p>\n\n<pre><code>DETACHED_PROCESS = 0x00000008\n\npid = subprocess.Popen([sys.executable, \"longtask.py\"],\n creationflags=DETACHED_PROCESS).pid\n</code></pre>\n\n<p>/* <em>UPD 2015.10.27</em> @eryksun in a comment below notes, that the semantically correct flag is CREATE_NEW_CONSOLE (0x00000010) */</p>\n\n<p>On FreeBSD we have another problem: when the parent process is finished, it finishes the child processes as well. And that is not what you want in a CGI script either. Some experiments showed that the problem seemed to be in sharing sys.stdout. And the working solution was the following:</p>\n\n<pre><code>pid = subprocess.Popen([sys.executable, \"longtask.py\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n</code></pre>\n\n<p>I have not checked the code on other platforms and do not know the reasons of the behaviour on FreeBSD. If anyone knows, please share your ideas. Googling on starting background processes in Python does not shed any light yet.</p>\n" }, { "answer_id": 3879406, "author": "athanassis", "author_id": 463023, "author_profile": "https://Stackoverflow.com/users/463023", "pm_score": 6, "selected": false, "text": "<p>Check the \"pexpect\" Python library, too.</p>\n\n<p>It allows for interactive controlling of external programs/commands, even ssh, ftp, telnet, etc. You can just type something like:</p>\n\n<pre><code>child = pexpect.spawn('ftp 192.168.0.24')\n\nchild.expect('(?i)name .*: ')\n\nchild.sendline('anonymous')\n\nchild.expect('(?i)password')\n</code></pre>\n" }, { "answer_id": 4728086, "author": "cdunn2001", "author_id": 263998, "author_profile": "https://Stackoverflow.com/users/263998", "pm_score": 5, "selected": false, "text": "<p><code>subprocess.check_call</code> is convenient if you don't want to test return values. It throws an exception on any error.</p>\n" }, { "answer_id": 5824565, "author": "Facundo Casco", "author_id": 181337, "author_profile": "https://Stackoverflow.com/users/181337", "pm_score": 6, "selected": false, "text": "<p>If you need the output from the command you are calling,\nthen you can use <a href=\"https://docs.python.org/3.6/library/subprocess.html#subprocess.check_output\" rel=\"noreferrer\">subprocess.check_output</a> (Python 2.7+).</p>\n\n<pre><code>&gt;&gt;&gt; subprocess.check_output([\"ls\", \"-l\", \"/dev/null\"])\n'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\\n'\n</code></pre>\n\n<p>Also note the <a href=\"https://docs.python.org/3.6/library/subprocess.html#frequently-used-arguments\" rel=\"noreferrer\">shell</a> parameter.</p>\n\n<blockquote>\n <p>If shell is <code>True</code>, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, <code>glob</code>, <code>fnmatch</code>, <code>os.walk()</code>, <code>os.path.expandvars()</code>, <code>os.path.expanduser()</code>, and <code>shutil</code>).</p>\n</blockquote>\n" }, { "answer_id": 9676642, "author": "Jorge E. Cardona", "author_id": 361023, "author_profile": "https://Stackoverflow.com/users/361023", "pm_score": 6, "selected": false, "text": "<p>I always use <code>fabric</code> for this things like:</p>\n\n<pre><code>from fabric.operations import local\nresult = local('ls', capture=True)\nprint \"Content:/n%s\" % (result, )\n</code></pre>\n\n<p>But this seem to be a good tool: <a href=\"https://github.com/amoffat/sh\" rel=\"noreferrer\"><code>sh</code> (Python subprocess interface)</a>.</p>\n\n<p>Look at an example:</p>\n\n<pre><code>from sh import vgdisplay\nprint vgdisplay()\nprint vgdisplay('-v')\nprint vgdisplay(v=True)\n</code></pre>\n" }, { "answer_id": 10988365, "author": "Saurabh Bangad", "author_id": 1449929, "author_profile": "https://Stackoverflow.com/users/1449929", "pm_score": 5, "selected": false, "text": "<p><code>os.system</code> does not allow you to store results, so if you want to store results in some list or something, a <code>subprocess.call</code> works.</p>\n" }, { "answer_id": 11507283, "author": "kanghyojmun", "author_id": 1417123, "author_profile": "https://Stackoverflow.com/users/1417123", "pm_score": 4, "selected": false, "text": "<p>You can use Popen, and then you can check the procedure's status:</p>\n\n<pre><code>from subprocess import Popen\n\nproc = Popen(['ls', '-l'])\nif proc.poll() is None:\n proc.kill()\n</code></pre>\n\n<p>Check out <a href=\"http://docs.python.org/library/subprocess.html#popen-objects\" rel=\"noreferrer\">subprocess.Popen</a>.</p>\n" }, { "answer_id": 11644161, "author": "Garfield", "author_id": 789213, "author_profile": "https://Stackoverflow.com/users/789213", "pm_score": 4, "selected": false, "text": "<p>Very simplest way to run any command and get the result back:</p>\n\n<pre><code>from commands import getstatusoutput\n\ntry:\n return getstatusoutput(\"ls -ltr\")\nexcept Exception, e:\n return None\n</code></pre>\n" }, { "answer_id": 13106558, "author": "Usman Khan", "author_id": 1755213, "author_profile": "https://Stackoverflow.com/users/1755213", "pm_score": 6, "selected": false, "text": "<p>This is how I run my commands. This code has everything you need pretty much</p>\n\n<pre><code>from subprocess import Popen, PIPE\ncmd = \"ls -l ~/\"\np = Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)\nout, err = p.communicate()\nprint \"Return code: \", p.returncode\nprint out.rstrip(), err.rstrip()\n</code></pre>\n" }, { "answer_id": 13402722, "author": "Joe", "author_id": 233098, "author_profile": "https://Stackoverflow.com/users/233098", "pm_score": 6, "selected": false, "text": "<h1>Update:</h1>\n\n<p><code>subprocess.run</code> is the recommended approach <a href=\"https://docs.python.org/3.6/whatsnew/3.5.html#whatsnew-subprocess\" rel=\"noreferrer\">as of Python 3.5</a> if your code does not need to maintain compatibility with earlier Python versions. It's more consistent and offers similar ease-of-use as Envoy. (Piping isn't as straightforward though. See <a href=\"https://stackoverflow.com/questions/7389662/link-several-popen-commands-with-pipes\">this question for how</a>.)</p>\n\n<p>Here's some examples from <a href=\"https://docs.python.org/3.6/library/subprocess.html#subprocess.run\" rel=\"noreferrer\">the documentation</a>.</p>\n\n<p>Run a process:</p>\n\n<pre><code>&gt;&gt;&gt; subprocess.run([\"ls\", \"-l\"]) # Doesn't capture output\nCompletedProcess(args=['ls', '-l'], returncode=0)\n</code></pre>\n\n<p>Raise on failed run:</p>\n\n<pre><code>&gt;&gt;&gt; subprocess.run(\"exit 1\", shell=True, check=True)\nTraceback (most recent call last):\n ...\nsubprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1\n</code></pre>\n\n<p>Capture output:</p>\n\n<pre><code>&gt;&gt;&gt; subprocess.run([\"ls\", \"-l\", \"/dev/null\"], stdout=subprocess.PIPE)\nCompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,\nstdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\\n')\n</code></pre>\n\n<h1>Original answer:</h1>\n\n<p>I recommend trying <a href=\"https://github.com/kennethreitz/envoy\" rel=\"noreferrer\">Envoy</a>. It's a wrapper for subprocess, which in turn <a href=\"http://docs.python.org/2/library/subprocess.html\" rel=\"noreferrer\">aims to replace</a> the older modules and functions. Envoy is subprocess for humans.</p>\n\n<p>Example usage from <a href=\"https://github.com/kennethreitz/envoy#readme\" rel=\"noreferrer\">the README</a>:</p>\n\n<pre><code>&gt;&gt;&gt; r = envoy.run('git config', data='data to pipe in', timeout=2)\n\n&gt;&gt;&gt; r.status_code\n129\n&gt;&gt;&gt; r.std_out\n'usage: git config [options]'\n&gt;&gt;&gt; r.std_err\n''\n</code></pre>\n\n<p>Pipe stuff around too:</p>\n\n<pre><code>&gt;&gt;&gt; r = envoy.run('uptime | pbcopy')\n\n&gt;&gt;&gt; r.command\n'pbcopy'\n&gt;&gt;&gt; r.status_code\n0\n\n&gt;&gt;&gt; r.history\n[&lt;Response 'uptime'&gt;]\n</code></pre>\n" }, { "answer_id": 15954964, "author": "Honza Javorek", "author_id": 325365, "author_profile": "https://Stackoverflow.com/users/325365", "pm_score": 6, "selected": false, "text": "<h3>With the standard library</h3>\n\n<p>Use the <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.run\" rel=\"noreferrer\">subprocess module</a> (Python 3):</p>\n\n<pre><code>import subprocess\nsubprocess.run(['ls', '-l'])\n</code></pre>\n\n<p>It is the recommended standard way. However, more complicated tasks (pipes, output, input, etc.) can be tedious to construct and write.</p>\n\n<p><em>Note on Python version: If you are still using Python 2, <a href=\"https://docs.python.org/2/library/subprocess.html#subprocess.call\" rel=\"noreferrer\">subprocess.call</a> works in a similar way.</em></p>\n\n<p><em>ProTip: <a href=\"https://docs.python.org/2/library/shlex.html#shlex.split\" rel=\"noreferrer\">shlex.split</a> can help you to parse the command for <code>run</code>, <code>call</code>, and other <code>subprocess</code> functions in case you don't want (or you can't!) provide them in form of lists:</em></p>\n\n<pre><code>import shlex\nimport subprocess\nsubprocess.run(shlex.split('ls -l'))\n</code></pre>\n\n<h3>With external dependencies</h3>\n\n<p>If you do not mind external dependencies, use <a href=\"https://pypi.python.org/pypi/plumbum\" rel=\"noreferrer\">plumbum</a>:</p>\n\n<pre><code>from plumbum.cmd import ifconfig\nprint(ifconfig['wlan0']())\n</code></pre>\n\n<p>It is the best <code>subprocess</code> wrapper. It's cross-platform, i.e. it works on both Windows and Unix-like systems. Install by <code>pip install plumbum</code>.</p>\n\n<p>Another popular library is <a href=\"https://pypi.python.org/pypi/sh\" rel=\"noreferrer\">sh</a>:</p>\n\n<pre><code>from sh import ifconfig\nprint(ifconfig('wlan0'))\n</code></pre>\n\n<p>However, <code>sh</code> dropped Windows support, so it's not as awesome as it used to be. Install by <code>pip install sh</code>.</p>\n" }, { "answer_id": 16062355, "author": "Jens Timmerman", "author_id": 869482, "author_profile": "https://Stackoverflow.com/users/869482", "pm_score": 3, "selected": false, "text": "<p>There are a lot of different ways to run external commands in Python,\nand all of them have their own plus sides and drawbacks.</p>\n<p>My colleagues and me have been writing Python system administration tools, so we need to run a lot of external commands, and sometimes you want them to block or run asynchronously, time-out, update every second, etc.</p>\n<p>There are also different ways of handling the return code and errors,\nand you might want to parse the output, and provide new input (in an <a href=\"http://en.wikipedia.org/wiki/Expect\" rel=\"nofollow noreferrer\">expect</a> kind of style). Or you will need to redirect <a href=\"https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)\" rel=\"nofollow noreferrer\">standard input</a>, <a href=\"https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29\" rel=\"nofollow noreferrer\">standard output</a>, and <a href=\"https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)\" rel=\"nofollow noreferrer\">standard error</a> to run in a different tty (e.g., when using <a href=\"https://en.wikipedia.org/wiki/GNU_Screen\" rel=\"nofollow noreferrer\">GNU Screen</a>).</p>\n<p>So you will probably have to write a lot of wrappers around the external command. So here is a Python module which we have written which can handle\nalmost anything you would want, and if not, it's very flexible so you can easily extend it:</p>\n<p><a href=\"https://github.com/hpcugent/vsc-base/blob/master/lib/vsc/utils/run.py\" rel=\"nofollow noreferrer\">https://github.com/hpcugent/vsc-base/blob/master/lib/vsc/utils/run.py</a></p>\n<p>It doesn't work stand-alone and requires some of our other tools, and got a lot of specialised functionality over the years, so it might not be a drop-in replacement for you, but it can give you a lot of information on how the internals of Python for running commands work and ideas on how to handle certain situations.</p>\n" }, { "answer_id": 16089689, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 3, "selected": false, "text": "<p>Update 2015: Python 3.5 added <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.run\" rel=\"nofollow noreferrer\">subprocess.run</a> which is much easier to use than subprocess.Popen. I recommend that.</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; subprocess.run([&quot;ls&quot;, &quot;-l&quot;]) # doesn't capture output\nCompletedProcess(args=['ls', '-l'], returncode=0)\n\n&gt;&gt;&gt; subprocess.run(&quot;exit 1&quot;, shell=True, check=True)\nTraceback (most recent call last):\n ...\nsubprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1\n\n&gt;&gt;&gt; subprocess.run([&quot;ls&quot;, &quot;-l&quot;, &quot;/dev/null&quot;], capture_output=True)\nCompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,\nstdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\\n', stderr=b'')\n</code></pre>\n" }, { "answer_id": 17202916, "author": "imagineerThat", "author_id": 1119779, "author_profile": "https://Stackoverflow.com/users/1119779", "pm_score": 4, "selected": false, "text": "<p>Just to add to the discussion, if you include using a Python console, you can call external commands from <a href=\"http://en.wikipedia.org/wiki/IPython\" rel=\"noreferrer\">IPython</a>. While in the IPython prompt, you can call shell commands by prefixing '!'. You can also combine Python code with the shell, and assign the output of shell scripts to Python variables.</p>\n\n<p>For instance:</p>\n\n<pre><code>In [9]: mylist = !ls\n\nIn [10]: mylist\nOut[10]:\n['file1',\n 'file2',\n 'file3',]\n</code></pre>\n" }, { "answer_id": 22395328, "author": "Jake W", "author_id": 746837, "author_profile": "https://Stackoverflow.com/users/746837", "pm_score": 3, "selected": false, "text": "<p>After some research, I have the following code which works very well for me. It basically prints both standard output and standard error in real time.</p>\n<pre><code>stdout_result = 1\nstderr_result = 1\n\n\ndef stdout_thread(pipe):\n global stdout_result\n while True:\n out = pipe.stdout.read(1)\n stdout_result = pipe.poll()\n if out == '' and stdout_result is not None:\n break\n\n if out != '':\n sys.stdout.write(out)\n sys.stdout.flush()\n\n\ndef stderr_thread(pipe):\n global stderr_result\n while True:\n err = pipe.stderr.read(1)\n stderr_result = pipe.poll()\n if err == '' and stderr_result is not None:\n break\n\n if err != '':\n sys.stdout.write(err)\n sys.stdout.flush()\n\n\ndef exec_command(command, cwd=None):\n if cwd is not None:\n print '[' + ' '.join(command) + '] in ' + cwd\n else:\n print '[' + ' '.join(command) + ']'\n\n p = subprocess.Popen(\n command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd\n )\n\n out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))\n err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))\n\n err_thread.start()\n out_thread.start()\n\n out_thread.join()\n err_thread.join()\n\n return stdout_result + stderr_result\n</code></pre>\n" }, { "answer_id": 23030076, "author": "andruso", "author_id": 950708, "author_profile": "https://Stackoverflow.com/users/950708", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"https://docs.python.org/2/library/subprocess.html\" rel=\"noreferrer\">subprocess.call</a>:</p>\n\n\n\n<pre class=\"lang-python prettyprint-override\"><code>from subprocess import call\n\n# Using list\ncall([\"echo\", \"Hello\", \"world\"])\n\n# Single string argument varies across platforms so better split it\ncall(\"echo Hello world\".split(\" \"))\n</code></pre>\n" }, { "answer_id": 23391049, "author": "Emil Stenström", "author_id": 117268, "author_profile": "https://Stackoverflow.com/users/117268", "pm_score": 5, "selected": false, "text": "<p>I tend to use <a href=\"https://docs.python.org/2/library/subprocess.html\" rel=\"noreferrer\">subprocess</a> together with <a href=\"https://docs.python.org/2/library/shlex.html\" rel=\"noreferrer\">shlex</a> (to handle escaping of quoted strings):</p>\n\n<pre><code>&gt;&gt;&gt; import subprocess, shlex\n&gt;&gt;&gt; command = 'ls -l \"/your/path/with spaces/\"'\n&gt;&gt;&gt; call_params = shlex.split(command)\n&gt;&gt;&gt; print call_params\n[\"ls\", \"-l\", \"/your/path/with spaces/\"]\n&gt;&gt;&gt; subprocess.call(call_params)\n</code></pre>\n" }, { "answer_id": 23416345, "author": "houqp", "author_id": 929095, "author_profile": "https://Stackoverflow.com/users/929095", "pm_score": 4, "selected": false, "text": "<p>I wrote a library for this, <em><a href=\"https://github.com/houqp/shell.py\" rel=\"nofollow noreferrer\">shell.py</a></em>.</p>\n<p>It's basically a wrapper for popen and shlex for now. It also supports piping commands, so you can chain commands easier in Python. So you can do things like:</p>\n<pre><code>ex('echo hello shell.py') | &quot;awk '{print $2}'&quot;\n</code></pre>\n" }, { "answer_id": 25476624, "author": "amehta", "author_id": 658247, "author_profile": "https://Stackoverflow.com/users/658247", "pm_score": 4, "selected": false, "text": "<p>A simple way is to use the <a href=\"https://docs.python.org/2/library/os.html\" rel=\"noreferrer\">os module</a>:</p>\n\n<pre><code>import os\nos.system('ls')\n</code></pre>\n\n<p>Alternatively, you can also use the subprocess module:</p>\n\n<pre><code>import subprocess\nsubprocess.check_call('ls')\n</code></pre>\n\n<p>If you want the result to be stored in a variable try:</p>\n\n<pre><code>import subprocess\nr = subprocess.check_output('ls')\n</code></pre>\n" }, { "answer_id": 26305089, "author": "stuckintheshuck", "author_id": 394370, "author_profile": "https://Stackoverflow.com/users/394370", "pm_score": 5, "selected": false, "text": "<p>There is also <a href=\"http://plumbum.readthedocs.org/en/latest/\">Plumbum</a></p>\n\n<pre><code>&gt;&gt;&gt; from plumbum import local\n&gt;&gt;&gt; ls = local[\"ls\"]\n&gt;&gt;&gt; ls\nLocalCommand(&lt;LocalPath /bin/ls&gt;)\n&gt;&gt;&gt; ls()\nu'build.py\\ndist\\ndocs\\nLICENSE\\nplumbum\\nREADME.rst\\nsetup.py\\ntests\\ntodo.txt\\n'\n&gt;&gt;&gt; notepad = local[\"c:\\\\windows\\\\notepad.exe\"]\n&gt;&gt;&gt; notepad() # Notepad window pops up\nu'' # Notepad window is closed by user, command returns\n</code></pre>\n" }, { "answer_id": 31114625, "author": "Priyankara", "author_id": 2781812, "author_profile": "https://Stackoverflow.com/users/2781812", "pm_score": 5, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>import os\n\ncmd = 'ls -al'\n\nos.system(cmd)\n</code></pre>\n\n<p><strong>os - This module provides a portable way of using operating system-dependent functionality.</strong></p>\n\n<p>For the more <code>os</code> functions, <a href=\"https://docs.python.org/2/library/os.html\" rel=\"noreferrer\">here</a> is the documentation.</p>\n" }, { "answer_id": 31618111, "author": "Asif Hasnain", "author_id": 4527213, "author_profile": "https://Stackoverflow.com/users/4527213", "pm_score": 2, "selected": false, "text": "<p>Using the <code>Popen</code> function of the <code>subprocess</code> Python module is the simplest way of running Linux commands. In that, the <code>Popen.communicate()</code> function will give your commands output. For example</p>\n\n<pre><code>import subprocess\n\n..\nprocess = subprocess.Popen(..) # Pass command and arguments to the function\nstdout, stderr = process.communicate() # Get command output and error\n..\n</code></pre>\n" }, { "answer_id": 33118899, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Here are my two cents: In my view, this is the best practice when dealing with external commands...</p>\n\n<p>These are the return values from the execute method...</p>\n\n<pre><code>pass, stdout, stderr = execute([\"ls\",\"-la\"],\"/home/user/desktop\")\n</code></pre>\n\n<p>This is the execute method...</p>\n\n<pre><code>def execute(cmdArray,workingDir):\n\n stdout = ''\n stderr = ''\n\n try:\n try:\n process = subprocess.Popen(cmdArray,cwd=workingDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)\n except OSError:\n return [False, '', 'ERROR : command(' + ' '.join(cmdArray) + ') could not get executed!']\n\n for line in iter(process.stdout.readline, b''):\n\n try:\n echoLine = line.decode(\"utf-8\")\n except:\n echoLine = str(line)\n\n stdout += echoLine\n\n for line in iter(process.stderr.readline, b''):\n\n try:\n echoLine = line.decode(\"utf-8\")\n except:\n echoLine = str(line)\n\n stderr += echoLine\n\n except (KeyboardInterrupt,SystemExit) as err:\n return [False,'',str(err)]\n\n process.stdout.close()\n\n returnCode = process.wait()\n if returnCode != 0 or stderr != '':\n return [False, stdout, stderr]\n else:\n return [True, stdout, stderr]\n</code></pre>\n" }, { "answer_id": 36058314, "author": "chtenb", "author_id": 1546844, "author_profile": "https://Stackoverflow.com/users/1546844", "pm_score": 3, "selected": false, "text": "<p>For Python 3.5+ it is recommended that you use the <a href=\"https://docs.python.org/3.5/library/subprocess.html#subprocess.run\" rel=\"nofollow noreferrer\">run function from the subprocess module</a>. This returns a <code>CompletedProcess</code> object, from which you can easily obtain the output as well as return code.</p>\n\n<pre><code>from subprocess import PIPE, run\n\ncommand = ['echo', 'hello']\nresult = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)\nprint(result.returncode, result.stdout, result.stderr)\n</code></pre>\n" }, { "answer_id": 36913076, "author": "Viswesn", "author_id": 527813, "author_profile": "https://Stackoverflow.com/users/527813", "pm_score": 2, "selected": false, "text": "<p>I would recommend the following method 'run' and it will help us in getting <a href=\"https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29\" rel=\"nofollow noreferrer\">standard output</a>, <a href=\"https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)\" rel=\"nofollow noreferrer\">standard error</a> and exit status as a dictionary; the caller of this can read the dictionary return by 'run' method to know the actual state of the process.</p>\n<pre><code> def run (cmd):\n print &quot;+ DEBUG exec({0})&quot;.format(cmd)\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)\n (out, err) = p.communicate()\n ret = p.wait()\n out = filter(None, out.split('\\n'))\n err = filter(None, err.split('\\n'))\n ret = True if ret == 0 else False\n return dict({'output': out, 'error': err, 'status': ret})\n #end\n</code></pre>\n" }, { "answer_id": 37877635, "author": "Swadhikar", "author_id": 5397845, "author_profile": "https://Stackoverflow.com/users/5397845", "pm_score": 4, "selected": false, "text": "<p>In Windows you can just import the <code>subprocess</code> module and run external commands by calling <code>subprocess.Popen()</code>, <code>subprocess.Popen().communicate()</code> and <code>subprocess.Popen().wait()</code> as below:</p>\n\n<pre><code># Python script to run a command line\nimport subprocess\n\ndef execute(cmd):\n \"\"\"\n Purpose : To execute a command and return exit status\n Argument : cmd - command to execute\n Return : exit_code\n \"\"\"\n process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n (result, error) = process.communicate()\n\n rc = process.wait()\n\n if rc != 0:\n print \"Error: failed to execute command:\", cmd\n print error\n return result\n# def\n\ncommand = \"tasklist | grep python\"\nprint \"This process detail: \\n\", execute(command)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>This process detail:\npython.exe 604 RDP-Tcp#0 4 5,660 K\n</code></pre>\n" }, { "answer_id": 38012358, "author": "David Okwii", "author_id": 547050, "author_profile": "https://Stackoverflow.com/users/547050", "pm_score": 3, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>import subprocess\n\np = subprocess.Popen(\"df -h\", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]\nprint p.split(\"\\n\")\n</code></pre>\n\n<p>It gives nice output which is easier to work with:</p>\n\n<pre><code>['Filesystem Size Used Avail Use% Mounted on',\n '/dev/sda6 32G 21G 11G 67% /',\n 'none 4.0K 0 4.0K 0% /sys/fs/cgroup',\n 'udev 1.9G 4.0K 1.9G 1% /dev',\n 'tmpfs 387M 1.4M 386M 1% /run',\n 'none 5.0M 0 5.0M 0% /run/lock',\n 'none 1.9G 58M 1.9G 3% /run/shm',\n 'none 100M 32K 100M 1% /run/user',\n '/dev/sda5 340G 222G 100G 69% /home',\n '']\n</code></pre>\n" }, { "answer_id": 38477871, "author": "IRSHAD", "author_id": 3089950, "author_profile": "https://Stackoverflow.com/users/3089950", "pm_score": 4, "selected": false, "text": "<p>To fetch the network id from the <a href=\"https://en.wikipedia.org/wiki/OpenStack\" rel=\"noreferrer\">OpenStack</a> <a href=\"https://en.wikipedia.org/wiki/OpenStack#Networking_(Neutron)\" rel=\"noreferrer\">Neutron</a>:</p>\n\n<pre><code>#!/usr/bin/python\nimport os\nnetid = \"nova net-list | awk '/ External / { print $2 }'\"\ntemp = os.popen(netid).read() /* Here temp also contains new line (\\n) */\nnetworkId = temp.rstrip()\nprint(networkId)\n</code></pre>\n\n<p>Output of <strong>nova net-list</strong></p>\n\n<pre><code>+--------------------------------------+------------+------+\n| ID | Label | CIDR |\n+--------------------------------------+------------+------+\n| 431c9014-5b5d-4b51-a357-66020ffbb123 | test1 | None |\n| 27a74fcd-37c0-4789-9414-9531b7e3f126 | External | None |\n| 5a2712e9-70dc-4b0e-9281-17e02f4684c9 | management | None |\n| 7aa697f5-0e60-4c15-b4cc-9cb659698512 | Internal | None |\n+--------------------------------------+------------+------+\n</code></pre>\n\n<p>Output of <strong>print(networkId)</strong></p>\n\n<pre><code>27a74fcd-37c0-4789-9414-9531b7e3f126\n</code></pre>\n" }, { "answer_id": 39447501, "author": "liuyip", "author_id": 5771451, "author_profile": "https://Stackoverflow.com/users/5771451", "pm_score": 2, "selected": false, "text": "<p>There are many ways to call a command.</p>\n\n<ul>\n<li>For example:</li>\n</ul>\n\n<p>if <code>and.exe</code> needs two parameters. In cmd we can call <code>sample.exe</code> use this:\n <code>and.exe 2 3</code> and it show <code>5</code> on screen.</p>\n\n<p>If we use a Python script to call <code>and.exe</code>, we should do like..</p>\n\n<ol>\n<li><p><code>os.system(cmd,...)</code></p>\n\n<ul>\n<li><code>os.system((\"and.exe\" + \" \" + \"2\" + \" \" + \"3\"))</code></li>\n</ul></li>\n<li><p><code>os.popen(cmd,...)</code></p>\n\n<ul>\n<li><code>os.popen((\"and.exe\" + \" \" + \"2\" + \" \" + \"3\"))</code></li>\n</ul></li>\n<li><code>subprocess.Popen(cmd,...)</code>\n\n<ul>\n<li><code>subprocess.Popen((\"and.exe\" + \" \" + \"2\" + \" \" + \"3\"))</code></li>\n</ul></li>\n</ol>\n\n<p>It's too hard, so we can join cmd with a space:</p>\n\n<pre><code>import os\ncmd = \" \".join(exename,parameters)\nos.popen(cmd)\n</code></pre>\n" }, { "answer_id": 39969619, "author": "Rajiv Sharma", "author_id": 2679465, "author_profile": "https://Stackoverflow.com/users/2679465", "pm_score": 3, "selected": false, "text": "<p>Here is calling an external command and return or print the command's output:</p>\n\n<p>Python <a href=\"https://docs.python.org/2/library/subprocess.html\" rel=\"nofollow noreferrer\">Subprocess</a> check_output is good for</p>\n\n<blockquote>\n <p>Run command with arguments and return its output as a byte string.</p>\n</blockquote>\n\n<pre><code>import subprocess\nproc = subprocess.check_output('ipconfig /all')\nprint proc\n</code></pre>\n" }, { "answer_id": 40319875, "author": "Tom Fuller", "author_id": 5177604, "author_profile": "https://Stackoverflow.com/users/5177604", "pm_score": 7, "selected": false, "text": "<p>There are lots of different libraries which allow you to call external commands with Python. For each library I've given a description and shown an example of calling an external command. The command I used as the example is <code>ls -l</code> (list all files). If you want to find out more about any of the libraries I've listed and linked the documentation for each of them.</p>\n<h3>Sources</h3>\n<ul>\n<li>subprocess: <a href=\"https://docs.python.org/3.5/library/subprocess.html\" rel=\"noreferrer\">https://docs.python.org/3.5/library/subprocess.html</a></li>\n<li>shlex: <a href=\"https://docs.python.org/3/library/shlex.html\" rel=\"noreferrer\">https://docs.python.org/3/library/shlex.html</a></li>\n<li>os: <a href=\"https://docs.python.org/3.5/library/os.html\" rel=\"noreferrer\">https://docs.python.org/3.5/library/os.html</a></li>\n<li>sh: <a href=\"https://amoffat.github.io/sh/\" rel=\"noreferrer\">https://amoffat.github.io/sh/</a></li>\n<li>plumbum: <a href=\"https://plumbum.readthedocs.io/en/latest/\" rel=\"noreferrer\">https://plumbum.readthedocs.io/en/latest/</a></li>\n<li>pexpect: <a href=\"https://pexpect.readthedocs.io/en/stable/\" rel=\"noreferrer\">https://pexpect.readthedocs.io/en/stable/</a></li>\n<li>fabric: <a href=\"http://www.fabfile.org/\" rel=\"noreferrer\">http://www.fabfile.org/</a></li>\n<li>envoy: <a href=\"https://github.com/kennethreitz/envoy\" rel=\"noreferrer\">https://github.com/kennethreitz/envoy</a></li>\n<li>commands: <a href=\"https://docs.python.org/2/library/commands.html\" rel=\"noreferrer\">https://docs.python.org/2/library/commands.html</a></li>\n</ul>\n<h3>These are all the libraries</h3>\n<p>Hopefully this will help you make a decision on which library to use :)</p>\n<h3><em>subprocess</em></h3>\n<p>Subprocess allows you to call external commands and connect them to their input/output/error pipes (stdin, stdout, and stderr). Subprocess is the default choice for running commands, but sometimes other modules are better.</p>\n<pre><code>subprocess.run([&quot;ls&quot;, &quot;-l&quot;]) # Run command\nsubprocess.run([&quot;ls&quot;, &quot;-l&quot;], stdout=subprocess.PIPE) # This will run the command and return any output\nsubprocess.run(shlex.split(&quot;ls -l&quot;)) # You can also use the shlex library to split the command\n</code></pre>\n<h3><em>os</em></h3>\n<p>os is used for &quot;operating system dependent functionality&quot;. It can also be used to call external commands with <code>os.system</code> and <code>os.popen</code> (Note: There is also a subprocess.popen). os will always run the shell and is a simple alternative for people who don't need to, or don't know how to use <code>subprocess.run</code>.</p>\n<pre class=\"lang-python prettyprint-override\"><code>os.system(&quot;ls -l&quot;) # Run command\nos.popen(&quot;ls -l&quot;).read() # This will run the command and return any output\n</code></pre>\n<h3><em>sh</em></h3>\n<p>sh is a subprocess interface which lets you call programs as if they were functions. This is useful if you want to run a command multiple times.</p>\n<pre><code>sh.ls(&quot;-l&quot;) # Run command normally\nls_cmd = sh.Command(&quot;ls&quot;) # Save command as a variable\nls_cmd() # Run command as if it were a function\n</code></pre>\n<h3><em>plumbum</em></h3>\n<p>plumbum is a library for &quot;script-like&quot; Python programs. You can call programs like functions as in <code>sh</code>. Plumbum is useful if you want to run a pipeline without the shell.</p>\n<pre><code>ls_cmd = plumbum.local(&quot;ls -l&quot;) # Get command\nls_cmd() # Run command\n</code></pre>\n<h3><em>pexpect</em></h3>\n<p>pexpect lets you spawn child applications, control them and find patterns in their output. This is a better alternative to subprocess for commands that expect a tty on Unix.</p>\n<pre><code>pexpect.run(&quot;ls -l&quot;) # Run command as normal\nchild = pexpect.spawn('scp foo [email protected]:.') # Spawns child application\nchild.expect('Password:') # When this is the output\nchild.sendline('mypassword')\n</code></pre>\n<h3><em>fabric</em></h3>\n<p>fabric is a Python 2.5 and 2.7 library. It allows you to execute local and remote shell commands. Fabric is simple alternative for running commands in a secure shell (SSH)</p>\n<pre><code>fabric.operations.local('ls -l') # Run command as normal\nfabric.operations.local('ls -l', capture = True) # Run command and receive output\n</code></pre>\n<h3><em>envoy</em></h3>\n<p>envoy is known as &quot;subprocess for humans&quot;. It is used as a convenience wrapper around the <code>subprocess</code> module.</p>\n<pre><code>r = envoy.run(&quot;ls -l&quot;) # Run command\nr.std_out # Get output\n</code></pre>\n<h3><em>commands</em></h3>\n<p><code>commands</code> contains wrapper functions for <code>os.popen</code>, but it has been removed from Python 3 since <code>subprocess</code> is a better alternative.</p>\n" }, { "answer_id": 40824514, "author": "Yuval Atzmon", "author_id": 2476373, "author_profile": "https://Stackoverflow.com/users/2476373", "pm_score": 4, "selected": false, "text": "<p>Under Linux, in case you would like to call an external command that will execute independently (will keep running after the Python script terminates), you can use a simple queue as <a href=\"http://vicerveza.homeunix.net/%7Eviric/soft/ts/\" rel=\"nofollow noreferrer\">task spooler</a> or the <a href=\"https://linux.die.net/man/1/at\" rel=\"nofollow noreferrer\">at</a> command.</p>\n<p>An example with task spooler:</p>\n<pre><code>import os\nos.system('ts &lt;your-command&gt;')\n</code></pre>\n<p>Notes about task spooler (<code>ts</code>):</p>\n<ol>\n<li><p>You could set the number of concurrent processes to be run (&quot;slots&quot;) with:</p>\n<p><code>ts -S &lt;number-of-slots&gt;</code></p>\n</li>\n<li><p>Installing <code>ts</code> doesn't requires admin privileges. You can download and compile it from source with a simple <code>make</code>, add it to your path and you're done.</p>\n</li>\n</ol>\n" }, { "answer_id": 46815111, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 6, "selected": false, "text": "<blockquote>\n<h2>How to execute a program or call a system command from Python</h2>\n</blockquote>\n<p>Simple, use <code>subprocess.run</code>, which returns a <code>CompletedProcess</code> object:</p>\n<pre><code>&gt;&gt;&gt; from subprocess import run\n&gt;&gt;&gt; from shlex import split\n&gt;&gt;&gt; completed_process = run(split('python --version'))\nPython 3.8.8\n&gt;&gt;&gt; completed_process\nCompletedProcess(args=['python', '--version'], returncode=0)\n</code></pre>\n<p>(<code>run</code> wants a list of lexically parsed shell arguments - this is what you'd type in a shell, separated by spaces, but not where the spaces are quoted, so use a specialized function, <code>split</code>, to split up what you would literally type into your shell)</p>\n<h3>Why?</h3>\n<p>As of Python 3.5, the documentation recommends <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.run\" rel=\"noreferrer\">subprocess.run</a>:</p>\n<blockquote>\n<p>The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.</p>\n</blockquote>\n<p>Here's an example of the simplest possible usage - and it does exactly as asked:</p>\n<pre><code>&gt;&gt;&gt; from subprocess import run\n&gt;&gt;&gt; from shlex import split\n&gt;&gt;&gt; completed_process = run(split('python --version'))\nPython 3.8.8\n&gt;&gt;&gt; completed_process\nCompletedProcess(args=['python', '--version'], returncode=0)\n</code></pre>\n<p><code>run</code> waits for the command to successfully finish, then returns a <code>CompletedProcess</code> object. It may instead raise <code>TimeoutExpired</code> (if you give it a <code>timeout=</code> argument) or <code>CalledProcessError</code> (if it fails and you pass <code>check=True</code>).</p>\n<p>As you might infer from the above example, stdout and stderr both get piped to your own stdout and stderr by default.</p>\n<p>We can inspect the returned object and see the command that was given and the returncode:</p>\n<pre><code>&gt;&gt;&gt; completed_process.args\n['python', '--version']\n&gt;&gt;&gt; completed_process.returncode\n0\n</code></pre>\n<h3>Capturing output</h3>\n<p>If you want to capture the output, you can pass <code>subprocess.PIPE</code> to the appropriate <code>stderr</code> or <code>stdout</code>:</p>\n<pre><code>&gt;&gt;&gt; from subprocess import PIPE\n&gt;&gt;&gt; completed_process = run(shlex.split('python --version'), stdout=PIPE, stderr=PIPE)\n&gt;&gt;&gt; completed_process.stdout\nb'Python 3.8.8\\n'\n&gt;&gt;&gt; completed_process.stderr\nb''\n</code></pre>\n<p>And those respective attributes return bytes.</p>\n<h2>Pass a command list</h2>\n<p>One might easily move from manually providing a command string (like the question suggests) to providing a string built programmatically. <strong>Don't build strings programmatically.</strong> This is a potential security issue. It's better to assume you don't trust the input.</p>\n<pre><code>&gt;&gt;&gt; import textwrap\n&gt;&gt;&gt; args = ['python', textwrap.__file__]\n&gt;&gt;&gt; cp = run(args, stdout=subprocess.PIPE)\n&gt;&gt;&gt; cp.stdout\nb'Hello there.\\n This is indented.\\n'\n</code></pre>\n<p>Note, only <code>args</code> should be passed positionally.</p>\n<h2>Full Signature</h2>\n<p>Here's the actual signature in the source and as shown by <code>help(run)</code>:</p>\n<blockquote>\n<pre><code>def run(*popenargs, input=None, timeout=None, check=False, **kwargs):\n</code></pre>\n</blockquote>\n<p>The <code>popenargs</code> and <code>kwargs</code> are given to the <code>Popen</code> constructor. <code>input</code> can be a string of bytes (or unicode, if specify encoding or <code>universal_newlines=True</code>) that will be piped to the subprocess's stdin.</p>\n<p>The documentation describes <code>timeout=</code> and <code>check=True</code> better than I could:</p>\n<blockquote>\n<p>The timeout argument is passed to Popen.communicate(). If the timeout\nexpires, the child process will be killed and waited for. The\nTimeoutExpired exception will be re-raised after the child process has\nterminated.</p>\n<p>If check is true, and the process exits with a non-zero exit code, a\nCalledProcessError exception will be raised. Attributes of that\nexception hold the arguments, the exit code, and stdout and stderr if\nthey were captured.</p>\n</blockquote>\n<p>and this example for <code>check=True</code> is better than one I could come up with:</p>\n<blockquote>\n<pre><code>&gt;&gt;&gt; subprocess.run(&quot;exit 1&quot;, shell=True, check=True)\nTraceback (most recent call last):\n ...\nsubprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1\n</code></pre>\n</blockquote>\n<h3>Expanded Signature</h3>\n<p>Here's an expanded signature, as given in the documentation:</p>\n<blockquote>\n<pre><code>subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, \nshell=False, cwd=None, timeout=None, check=False, encoding=None, \nerrors=None)\n</code></pre>\n</blockquote>\n<p>Note that this indicates that only the args list should be passed positionally. So pass the remaining arguments as keyword arguments.</p>\n<h3>Popen</h3>\n<p>When use <code>Popen</code> instead? I would struggle to find use-case based on the arguments alone. Direct usage of <code>Popen</code> would, however, give you access to its methods, including <code>poll</code>, 'send_signal', 'terminate', and 'wait'.</p>\n<p>Here's the <code>Popen</code> signature as given in <a href=\"https://github.com/python/cpython/blob/master/Lib/subprocess.py#L752\" rel=\"noreferrer\">the source</a>. I think this is the most precise encapsulation of the information (as opposed to <code>help(Popen)</code>):</p>\n<pre><code>\ndef __init__(self, args, bufsize=-1, executable=None,\n stdin=None, stdout=None, stderr=None,\n preexec_fn=None, close_fds=True,\n shell=False, cwd=None, env=None, universal_newlines=None,\n startupinfo=None, creationflags=0,\n restore_signals=True, start_new_session=False,\n pass_fds=(), *, user=None, group=None, extra_groups=None,\n encoding=None, errors=None, text=None, umask=-1, pipesize=-1):\n\n</code></pre>\n<p>But more informative is <a href=\"https://docs.python.org/3/library/subprocess.html#popen-constructor\" rel=\"noreferrer\">the <code>Popen</code> documentation</a>:</p>\n<blockquote>\n<pre><code>subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, \nstderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None,\nenv=None, universal_newlines=None, startupinfo=None, creationflags=0, \nrestore_signals=True, start_new_session=False, pass_fds=(), *, group=None, \nextra_groups=None, user=None, umask=-1, encoding=None, errors=None, \ntext=None)\n</code></pre>\n<p>Execute a child program in a new process. On POSIX, the class uses\nos.execvp()-like behavior to execute the child program. On Windows,\nthe class uses the Windows CreateProcess() function. The arguments to\nPopen are as follows.</p>\n</blockquote>\n<p>Understanding the remaining documentation on <code>Popen</code> will be left as an exercise for the reader.</p>\n" }, { "answer_id": 46921537, "author": "Asav Patel", "author_id": 2260553, "author_profile": "https://Stackoverflow.com/users/2260553", "pm_score": 2, "selected": false, "text": "<p>I have written a wrapper to handle errors and redirecting output and other stuff.</p>\n\n<pre><code>import shlex\nimport psutil\nimport subprocess\n\ndef call_cmd(cmd, stdout=sys.stdout, quiet=False, shell=False, raise_exceptions=True, use_shlex=True, timeout=None):\n \"\"\"Exec command by command line like 'ln -ls \"/var/log\"'\n \"\"\"\n if not quiet:\n print(\"Run %s\", str(cmd))\n if use_shlex and isinstance(cmd, (str, unicode)):\n cmd = shlex.split(cmd)\n if timeout is None:\n process = subprocess.Popen(cmd, stdout=stdout, stderr=sys.stderr, shell=shell)\n retcode = process.wait()\n else:\n process = subprocess.Popen(cmd, stdout=stdout, stderr=sys.stderr, shell=shell)\n p = psutil.Process(process.pid)\n finish, alive = psutil.wait_procs([p], timeout)\n if len(alive) &gt; 0:\n ps = p.children()\n ps.insert(0, p)\n print('waiting for timeout again due to child process check')\n finish, alive = psutil.wait_procs(ps, 0)\n if len(alive) &gt; 0:\n print('process {} will be killed'.format([p.pid for p in alive]))\n for p in alive:\n p.kill()\n if raise_exceptions:\n print('External program timeout at {} {}'.format(timeout, cmd))\n raise CalledProcessTimeout(1, cmd)\n retcode = process.wait()\n if retcode and raise_exceptions:\n print(\"External program failed %s\", str(cmd))\n raise subprocess.CalledProcessError(retcode, cmd)\n</code></pre>\n\n<p>You can call it like this:</p>\n\n<pre><code>cmd = 'ln -ls \"/var/log\"'\nstdout = 'out.txt'\ncall_cmd(cmd, stdout)\n</code></pre>\n" }, { "answer_id": 48548332, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>As an example (in Linux):</p>\n\n<pre><code>import subprocess\nsubprocess.run('mkdir test.dir', shell=True)\n</code></pre>\n\n<p>This creates test.dir in the current directory.\nNote that this also works:</p>\n\n<pre><code>import subprocess\nsubprocess.call('mkdir test.dir', shell=True)\n</code></pre>\n\n<p>The equivalent code using os.system is:</p>\n\n<pre><code>import os\nos.system('mkdir test.dir')\n</code></pre>\n\n<p>Best practice would be to use subprocess instead of os, with .run favored over .call. \nAll you need to know about subprocess is <a href=\"https://docs.python.org/3.5/library/subprocess.html\" rel=\"noreferrer\">here</a>.\nAlso, note that all Python documentation is available for download from <a href=\"https://docs.python.org/3/download.html\" rel=\"noreferrer\">here</a>. I downloaded the PDF packed as .zip. I mention this because there's a nice overview of the os module in tutorial.pdf (page 81). Besides, it's an authoritative resource for Python coders.</p>\n" }, { "answer_id": 49441486, "author": "am5", "author_id": 4521562, "author_profile": "https://Stackoverflow.com/users/4521562", "pm_score": 4, "selected": false, "text": "<p>Often, I use the following function for external commands, and this is especially handy for <strong>long running processes</strong>. The below method <strong>tails process output</strong> <em>while</em> it is running and returns the output, <strong>raises an exception</strong> if process fails.</p>\n\n<p>It comes out if the process is done using the <strong>poll() method on the process</strong>.</p>\n\n<pre><code>import subprocess,sys\n\ndef exec_long_running_proc(command, args):\n cmd = \"{} {}\".format(command, \" \".join(str(arg) if ' ' not in arg else arg.replace(' ','\\ ') for arg in args))\n print(cmd)\n process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n # Poll process for new output until finished\n while True:\n nextline = process.stdout.readline().decode('UTF-8')\n if nextline == '' and process.poll() is not None:\n break\n sys.stdout.write(nextline)\n sys.stdout.flush()\n\n output = process.communicate()[0]\n exitCode = process.returncode\n\n if (exitCode == 0):\n return output\n else:\n raise Exception(command, exitCode, output)\n</code></pre>\n\n<p><strong>You can invoke it like this:</strong></p>\n\n<pre><code>exec_long_running_proc(command = \"hive\", args=[\"-f\", hql_path])\n</code></pre>\n" }, { "answer_id": 49644672, "author": "rashok", "author_id": 596370, "author_profile": "https://Stackoverflow.com/users/596370", "pm_score": 3, "selected": false, "text": "<p><strong>Calling an external command in Python</strong></p>\n\n<p>A simple way to call an external command is using <code>os.system(...)</code>. And this function returns the exit value of the command. But the drawback is we won't get stdout and stderr.</p>\n\n<pre><code>ret = os.system('some_cmd.sh')\nif ret != 0 :\n print 'some_cmd.sh execution returned failure'\n</code></pre>\n\n<p><strong>Calling an external command in Python in background</strong></p>\n\n<p><code>subprocess.Popen</code> provides more flexibility for running an external command rather than using <code>os.system</code>. We can start a command in the background and wait for it to finish. And after that we can get the stdout and stderr.</p>\n\n<pre><code>proc = subprocess.Popen([\"./some_cmd.sh\"], stdout=subprocess.PIPE)\nprint 'waiting for ' + str(proc.pid)\nproc.wait()\nprint 'some_cmd.sh execution finished'\n(out, err) = proc.communicate()\nprint 'some_cmd.sh output : ' + out\n</code></pre>\n\n<p><strong>Calling a long running external command in Python in the background and stop after some time</strong></p>\n\n<p>We can even start a long running process in the background using <code>subprocess.Popen</code> and kill it after sometime once its task is done.</p>\n\n<pre><code>proc = subprocess.Popen([\"./some_long_run_cmd.sh\"], stdout=subprocess.PIPE)\n# Do something else\n# Now some_long_run_cmd.sh exeuction is no longer needed, so kill it\nos.system('kill -15 ' + str(proc.pid))\nprint 'Output : ' proc.communicate()[0]\n</code></pre>\n" }, { "answer_id": 50101887, "author": "Samadi Salahedine", "author_id": 6634322, "author_profile": "https://Stackoverflow.com/users/6634322", "pm_score": 5, "selected": false, "text": "<p>It can be this simple:</p>\n\n<pre><code>import os\ncmd = \"your command\"\nos.system(cmd)\n</code></pre>\n" }, { "answer_id": 50242060, "author": "dportman", "author_id": 7812314, "author_profile": "https://Stackoverflow.com/users/7812314", "pm_score": 3, "selected": false, "text": "<p>If you need to call a shell command from a Python notebook (like <a href=\"https://en.wikipedia.org/wiki/IPython#Project_Jupyter\" rel=\"noreferrer\">Jupyter</a>, Zeppelin, Databricks, or Google Cloud Datalab) you can just use the <code>!</code> prefix.</p>\n\n<p>For example,</p>\n\n<pre><code>!ls -ilF\n</code></pre>\n" }, { "answer_id": 52339862, "author": "Valery Ramusik", "author_id": 5992385, "author_profile": "https://Stackoverflow.com/users/5992385", "pm_score": 4, "selected": false, "text": "<p><strong><a href=\"http://www.pyinvoke.org/\" rel=\"nofollow noreferrer\">Invoke</a></strong> is a Python (2.7 and 3.4+) task execution tool and library. It provides a clean, high-level API for running shell commands:</p>\n<pre><code>&gt;&gt;&gt; from invoke import run\n&gt;&gt;&gt; cmd = &quot;pip install -r requirements.txt&quot;\n&gt;&gt;&gt; result = run(cmd, hide=True, warn=True)\n&gt;&gt;&gt; print(result.ok)\nTrue\n&gt;&gt;&gt; print(result.stdout.splitlines()[-1])\nSuccessfully installed invocations-0.13.0 pep8-1.5.7 spec-1.3.1\n</code></pre>\n" }, { "answer_id": 53063521, "author": "Cédric", "author_id": 4045907, "author_profile": "https://Stackoverflow.com/users/4045907", "pm_score": 4, "selected": false, "text": "<p>I wrote a small library to help with this use case:</p>\n<p><a href=\"https://pypi.org/project/citizenshell/\" rel=\"nofollow noreferrer\">https://pypi.org/project/citizenshell/</a></p>\n<p>It can be installed using</p>\n<pre><code>pip install citizenshell\n</code></pre>\n<p>And then used as follows:</p>\n<pre><code>from citizenshell import sh\nassert sh(&quot;echo Hello World&quot;) == &quot;Hello World&quot;\n</code></pre>\n<p>You can separate standard output from standard error and extract the exit code as follows:</p>\n<pre><code>result = sh(&quot;&gt;&amp;2 echo error &amp;&amp; echo output &amp;&amp; exit 13&quot;)\nassert result.stdout() == [&quot;output&quot;]\nassert result.stderr() == [&quot;error&quot;]\nassert result.exit_code() == 13\n</code></pre>\n<p>And the cool thing is that you don't have to wait for the underlying shell to exit before starting processing the output:</p>\n<pre><code>for line in sh(&quot;for i in 1 2 3 4; do echo -n 'It is '; date +%H:%M:%S; sleep 1; done&quot;, wait=False)\n print &quot;&gt;&gt;&gt;&quot;, line + &quot;!&quot;\n</code></pre>\n<p>will print the lines as they are available thanks to the wait=False</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; It is 14:24:52!\n&gt;&gt;&gt; It is 14:24:53!\n&gt;&gt;&gt; It is 14:24:54!\n&gt;&gt;&gt; It is 14:24:55!\n</code></pre>\n<p>More examples can be found at <a href=\"https://github.com/meuter/citizenshell\" rel=\"nofollow noreferrer\">https://github.com/meuter/citizenshell</a></p>\n" }, { "answer_id": 54414217, "author": "Farzad Vertigo", "author_id": 3939318, "author_profile": "https://Stackoverflow.com/users/3939318", "pm_score": 3, "selected": false, "text": "<p>For using <code>subprocess</code> in Python 3.5+, the following did the trick for me on Linux:</p>\n<pre><code>import subprocess\n\n# subprocess.run() returns a completed process object that can be inspected\nc = subprocess.run([&quot;ls&quot;, &quot;-ltrh&quot;], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nprint(c.stdout.decode('utf-8'))\n</code></pre>\n<p>As mentioned in <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess\" rel=\"nofollow noreferrer\">the documentation</a>, <code>PIPE</code> values are byte sequences and for properly showing them decoding should be considered. For later versions of Python, <code>text=True</code> and <code>encoding='utf-8'</code> are added to kwargs of <a href=\"https://docs.python.org/3.6/library/subprocess.html#subprocess.run\" rel=\"nofollow noreferrer\"><code>subprocess.run()</code></a>.</p>\n<p>The output of the abovementioned code is:</p>\n<pre><code>total 113M\n-rwxr-xr-x 1 farzad farzad 307 Jan 15 2018 vpnscript\n-rwxrwxr-x 1 farzad farzad 204 Jan 15 2018 ex\ndrwxrwxr-x 4 farzad farzad 4.0K Jan 22 2018 scripts\n.... # Some other lines\n</code></pre>\n" }, { "answer_id": 55440842, "author": "geckos", "author_id": 652528, "author_profile": "https://Stackoverflow.com/users/652528", "pm_score": 3, "selected": false, "text": "<p>If you are <strong>not</strong> using user input in the commands, you can use this:</p>\n<pre><code>from os import getcwd\nfrom subprocess import check_output\nfrom shlex import quote\n\ndef sh(command):\n return check_output(quote(command), shell=True, cwd=getcwd(), universal_newlines=True).strip()\n</code></pre>\n<p>And use it as</p>\n<pre><code>branch = sh('git rev-parse --abbrev-ref HEAD')\n</code></pre>\n<p><code>shell=True</code> will spawn a shell, so you can use pipe and such shell things <code>sh('ps aux | grep python')</code>. This is very very handy for running hardcoded commands and processing its output. The <code>universal_lines=True</code> make sure the output is returned in a string instead of binary.</p>\n<p><code>cwd=getcwd()</code> will make sure that the command is run with the same working directory as the interpreter. This is handy for Git commands to work like the Git branch name example above.</p>\n<p>Some recipes</p>\n<ul>\n<li>free memory in megabytes: <code>sh('free -m').split('\\n')[1].split()[1]</code></li>\n<li>free space on / in percent <code>sh('df -m /').split('\\n')[1].split()[4][0:-1]</code></li>\n<li>CPU load <code>sum(map(float, sh('ps -ef -o pcpu').split('\\n')[1:])</code></li>\n</ul>\n<p>But this isn't safe for user input, from the documentation:</p>\n<blockquote>\n<p>Security Considerations</p>\n<p>Unlike some other popen functions, this implementation will never\nimplicitly call a system shell. This means that all characters,\nincluding shell metacharacters, can safely be passed to child\nprocesses. If the shell is invoked explicitly, via shell=True, it is\nthe application’s responsibility to ensure that all whitespace and\nmetacharacters are quoted appropriately to avoid shell injection\nvulnerabilities.</p>\n<p>When using shell=True, the shlex.quote() function can be used to\nproperly escape whitespace and shell metacharacters in strings that\nare going to be used to construct shell commands.</p>\n</blockquote>\n<p>Even using the <code>shlex.quote()</code>, it is good to keep a little paranoid when using user inputs on shell commands. One option is using a hardcoded command to take some generic output and filtering by user input. Anyway using <code>shell=False</code> will make sure that only the exactly process that you want to execute will be executed or you get a <code>No such file or directory</code> error.</p>\n<p>Also there is some performance impact on <code>shell=True</code>, from my tests it seems about 20% slower than <code>shell=False</code> (the default).</p>\n<pre class=\"lang-none prettyprint-override\"><code>In [50]: timeit(&quot;check_output('ls -l'.split(), universal_newlines=True)&quot;, number=1000, globals=globals())\nOut[50]: 2.6801227919995654\n\nIn [51]: timeit(&quot;check_output('ls -l', universal_newlines=True, shell=True)&quot;, number=1000, globals=globals())\nOut[51]: 3.243950183999914\n</code></pre>\n" }, { "answer_id": 56842257, "author": "Zach Valenta", "author_id": 6813490, "author_profile": "https://Stackoverflow.com/users/6813490", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://github.com/aeroxis/sultan\" rel=\"nofollow noreferrer\">Sultan</a> is a recent-ish package meant for this purpose. It provides some niceties around managing user privileges and adding helpful error messages.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from sultan.api import Sultan\n\nwith Sultan.load(sudo=True, hostname=&quot;myserver.com&quot;) as sultan:\n sultan.yum(&quot;install -y tree&quot;).run()\n</code></pre>\n" }, { "answer_id": 57696996, "author": "noɥʇʎԀʎzɐɹƆ", "author_id": 1459669, "author_profile": "https://Stackoverflow.com/users/1459669", "pm_score": 3, "selected": false, "text": "<p>If you're writing a Python shell script and have <a href=\"http://en.wikipedia.org/wiki/IPython\" rel=\"nofollow noreferrer\">IPython</a> installed on your system, you can use the bang prefix to run a shell command inside IPython:</p>\n\n<pre><code>!ls\nfilelist = !ls\n</code></pre>\n" }, { "answer_id": 58212263, "author": "Vishal", "author_id": 197473, "author_profile": "https://Stackoverflow.com/users/197473", "pm_score": 2, "selected": false, "text": "<p>Python 3.5+</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import subprocess\n\np = subprocess.run([\"ls\", \"-ltr\"], capture_output=True)\nprint(p.stdout.decode(), p.stderr.decode())\n</code></pre>\n\n<p><a href=\"https://code.labstack.com/GIzH7jnS\" rel=\"nofollow noreferrer\"><strong>Try online</strong></a></p>\n" }, { "answer_id": 58297652, "author": "Vishal", "author_id": 197473, "author_profile": "https://Stackoverflow.com/users/197473", "pm_score": 3, "selected": false, "text": "<pre class=\"lang-py prettyprint-override\"><code>import subprocess\n\np = subprocess.run([\"ls\", \"-ltr\"], capture_output=True)\nprint(p.stdout.decode(), p.stderr.decode())\n</code></pre>\n\n<p><strong><a href=\"https://code.labstack.com/GIzH7jnS\" rel=\"noreferrer\">Try online</a></strong></p>\n" }, { "answer_id": 59050139, "author": "Trect", "author_id": 9789097, "author_profile": "https://Stackoverflow.com/users/9789097", "pm_score": 2, "selected": false, "text": "<p><code>os.popen()</code> is the easiest and the most safest way to execute a command. You can execute any command that you run on the command line. In addition you will also be able to capture the output of the command using <code>os.popen().read()</code></p>\n\n<p>You can do it like this:</p>\n\n<pre><code>import os\noutput = os.popen('Your Command Here').read()\nprint (output)\n</code></pre>\n\n<p>An example where you list all the files in the current directory:</p>\n\n<pre><code>import os\noutput = os.popen('ls').read()\nprint (output)\n# Outputs list of files in the directory\n</code></pre>\n" }, { "answer_id": 59090212, "author": "N.Nonkovic", "author_id": 7221283, "author_profile": "https://Stackoverflow.com/users/7221283", "pm_score": 4, "selected": false, "text": "<p><em><strong>MOST OF THE CASES:</strong></em></p>\n<p><strong>For the most of cases, a short snippet of code like this is all you are going to need</strong>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import subprocess\nimport shlex\n\nsource = &quot;test.txt&quot;\ndestination = &quot;test_copy.txt&quot;\n\nbase = &quot;cp {source} {destination}'&quot;\ncmd = base.format(source=source, destination=destination)\nsubprocess.check_call(shlex.split(cmd))\n</code></pre>\n<p><strong>It is clean and simple</strong>.</p>\n<blockquote>\n<p><code>subprocess.check_call</code> run command with arguments and wait for\ncommand to complete.</p>\n<p><code>shlex.split</code> split the string cmd using shell-like syntax</p>\n</blockquote>\n<p><em><strong>REST OF THE CASES:</strong></em></p>\n<p>If this do not work for some specific command, most probably you have a problem with <a href=\"https://en.wikipedia.org/wiki/List_of_command-line_interpreters\" rel=\"nofollow noreferrer\"> <strong>command-line interpreters</strong></a>. The operating system chose the default one which is not suitable for your type of program or could not found an adequate one on the system executable path.</p>\n<p><strong>Example:</strong></p>\n<p>Using the redirection operator on a Unix system</p>\n<pre class=\"lang-py prettyprint-override\"><code>input_1 = &quot;input_1.txt&quot;\ninput_2 = &quot;input_2.txt&quot;\noutput = &quot;merged.txt&quot;\nbase_command = &quot;/bin/bash -c 'cat {input} &gt;&gt; {output}'&quot;\n\nbase_command.format(input_1, output=output)\nsubprocess.check_call(shlex.split(base_command))\n\nbase_command.format(input_2, output=output)\nsubprocess.check_call(shlex.split(base_command))\n</code></pre>\n<blockquote>\n<p>As it is stated in <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">The Zen of Python</a>: <strong>Explicit is better than\nimplicit</strong></p>\n</blockquote>\n<p>So if using a Python &gt;=3.6 function, it would look something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import subprocess\nimport shlex\n\ndef run_command(cmd_interpreter: str, command: str) -&gt; None:\n base_command = f&quot;{cmd_interpreter} -c '{command}'&quot;\n subprocess.check_call(shlex.split(base_command)\n\n</code></pre>\n" }, { "answer_id": 60427071, "author": "Kashif Iftikhar", "author_id": 12598819, "author_profile": "https://Stackoverflow.com/users/12598819", "pm_score": 2, "selected": false, "text": "<p>There are a number of ways of <em>calling</em> an external <em>command</em> from Python. There are some functions and modules with the good helper functions that can make it really easy. But the recommended thing among all is the <code>subprocess</code> module.</p>\n<pre><code>import subprocess as s\ns.call([&quot;command.exe&quot;, &quot;...&quot;])\n</code></pre>\n<p>The call function will start the external process, pass some command line arguments and wait for it to finish. When it finishes you continue executing. Arguments in <em>call</em> function are passed through the list. The first argument in the list is the command typically in the form of an executable file and subsequent arguments in the list whatever you want to pass.</p>\n<p>If you have called processes from the command line in the windows before, you'll be aware that you often need to quote arguments. You need to put quotations mark around it. If there's a space then there's a backslash and there are some complicated rules, but you can avoid a whole lot of that in Python by using <code>subprocess</code> module because it is a list and each item is known to be a distinct and python can get quoting correctly for you.</p>\n<p>In the end, after the list, there are a number of optional parameters one of these is a shell and if you set shell equals to true then your command is going to be run as if you have typed in at the command prompt.</p>\n<pre><code>s.call([&quot;command.exe&quot;, &quot;...&quot;], shell=True)\n</code></pre>\n<p>This gives you access to functionality like piping, you can redirect to files, you can call multiple commands in one thing.</p>\n<p>One more thing, if your script relies on the process succeeding then you want to check the result and the result can be checked with the check call helper function.</p>\n<pre><code>s.check_call(...)\n</code></pre>\n<p>It is exactly the same as a call function, it takes the same arguments, takes the same list, you can pass in any of the extra arguments but it going to wait for the functions to complete. And if the exit code of the function is anything other then zero, it will through an exception in the python script.</p>\n<p>Finally, if you want tighter control <code>Popen</code> constructor which is also from the <code>subprocess</code> module. It also takes the same arguments as incall &amp; check_call function but it returns an object representing the running process.</p>\n<pre><code>p=s.Popen(&quot;...&quot;)\n</code></pre>\n<p>It does not wait for the running process to finish also it's not going to throw any exception immediately but it gives you an object that will let you do things like wait for it to finish, let you communicate to it, you can redirect standard input, standard output if you want to display output somewhere else and a lot more.</p>\n" }, { "answer_id": 61307412, "author": "ivanmara", "author_id": 6195439, "author_profile": "https://Stackoverflow.com/users/6195439", "pm_score": -1, "selected": false, "text": "<p>I use this for Python 3.6+:</p>\n<pre><code>import subprocess\ndef execute(cmd):\n &quot;&quot;&quot;\n Purpose : To execute a command and return exit status\n Argument : cmd - command to execute\n Return : result, exit_code\n &quot;&quot;&quot;\n process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n (result, error) = process.communicate()\n rc = process.wait()\n if rc != 0:\n print (&quot;Error: failed to execute command: &quot;, cmd)\n print (error.rstrip().decode(&quot;utf-8&quot;))\n return result.rstrip().decode(&quot;utf-8&quot;), serror.rstrip().decode(&quot;utf-8&quot;)\n# def\n</code></pre>\n" }, { "answer_id": 64341833, "author": "fameman", "author_id": 6685358, "author_profile": "https://Stackoverflow.com/users/6685358", "pm_score": 5, "selected": false, "text": "<p><em>As of <strong>Python 3.7.0 released on June 27th 2018 (<a href=\"https://docs.python.org/3/whatsnew/3.7.html\" rel=\"noreferrer\">https://docs.python.org/3/whatsnew/3.7.html</a>)</strong>, you can achieve your desired result in the most powerful while equally simple way. This answer intends to show you the essential summary of various options in a short manner. For in-depth answers, please see the other ones.</em></p>\n<hr />\n<h1>TL;DR in 2021</h1>\n<p>The big advantage of <code>os.system(...)</code> was its simplicity. <code>subprocess</code> is better and still easy to use, especially as of <strong>Python 3.5</strong>.</p>\n<pre><code>import subprocess\nsubprocess.run(&quot;ls -a&quot;, shell=True)\n</code></pre>\n<p><em><strong>Note:</strong></em> This is the exact answer to your question - running a command</p>\n<blockquote>\n<p>like in a shell</p>\n</blockquote>\n<hr />\n<h3>Preferred Way</h3>\n<p>If possible, remove the shell overhead and run the command directly (requires a list).</p>\n<pre><code>import subprocess\nsubprocess.run([&quot;help&quot;])\nsubprocess.run([&quot;ls&quot;, &quot;-a&quot;])\n</code></pre>\n<p>Pass program arguments in a list. <strong>Don't include <code>\\&quot;</code>-escaping for arguments containing spaces.</strong></p>\n<hr />\n<h1>Advanced Use Cases</h1>\n<h2>Checking The Output</h2>\n<p>The following code speaks for itself:</p>\n<pre><code>import subprocess\nresult = subprocess.run([&quot;ls&quot;, &quot;-a&quot;], capture_output=True, text=True)\nif &quot;stackoverflow-logo.png&quot; in result.stdout:\n print(&quot;You're a fan!&quot;)\nelse:\n print(&quot;You're not a fan?&quot;)\n</code></pre>\n<p><code>result.stdout</code> is all normal program output <strong>excluding errors</strong>. Read <code>result.stderr</code> to get them.</p>\n<p><code>capture_output=True</code> - turns capturing on. Otherwise <code>result.stderr</code> and <code>result.stdout</code> would be <code>None</code>. Available from <em>Python 3.7</em>.</p>\n<p><code>text=True</code> - a convenience argument added in <em>Python 3.7</em> which converts the received binary data to Python strings you can easily work with.</p>\n<h2>Checking the returncode</h2>\n<p>Do</p>\n<pre><code>if result.returncode == 127: print(&quot;The program failed for some weird reason&quot;)\nelif result.returncode == 0: print(&quot;The program succeeded&quot;)\nelse: print(&quot;The program failed unexpectedly&quot;)\n</code></pre>\n<p>If you just want to check if the program succeeded (returncode == 0) and otherwise throw an Exception, there is a more convenient function:</p>\n<pre><code>result.check_returncode()\n</code></pre>\n<p>But it's Python, so there's an even more convenient argument <code>check</code> which does the same thing automatically for you:</p>\n<pre><code>result = subprocess.run(..., check=True)\n</code></pre>\n<h2>stderr should be inside stdout</h2>\n<p>You might want to have all program output inside stdout, even errors. To accomplish this, run</p>\n<pre><code>result = subprocess.run(..., stderr=subprocess.STDOUT)\n</code></pre>\n<p><code>result.stderr</code> will then be <code>None</code> and <code>result.stdout</code> will contain everything.</p>\n<h2>Using shell=False with an argument string</h2>\n<p><code>shell=False</code> expects a <strong>list</strong> of arguments. You might however, split an argument string on your own using shlex.</p>\n<pre><code>import subprocess\nimport shlex\nsubprocess.run(shlex.split(&quot;ls -a&quot;))\n</code></pre>\n<p>That's it.</p>\n<h1>Common Problems</h1>\n<p>Chances are high you just started using Python when you come across this question. Let's look at some common problems.</p>\n<blockquote>\n<p>FileNotFoundError: [Errno 2] No such file or directory: 'ls -a': 'ls -a'</p>\n</blockquote>\n<p><em>You're running a subprocess without <code>shell=True</code> . Either use a list (<code>[&quot;ls&quot;, &quot;-a&quot;]</code>) or set <code>shell=True</code>.</em></p>\n<blockquote>\n<p>TypeError: [...] NoneType [...]</p>\n</blockquote>\n<p><em>Check that you've set <code>capture_output=True</code>.</em></p>\n<blockquote>\n<p>TypeError: a bytes-like object is required, not [...]</p>\n</blockquote>\n<p><em>You always receive byte results from your program. If you want to work with it like a normal string, set <code>text=True</code>.</em></p>\n<blockquote>\n<p>subprocess.CalledProcessError: Command '[...]' returned non-zero exit status 1.</p>\n</blockquote>\n<p><em>Your command didn't run successfully. You could disable returncode checking or check your actual program's validity.</em></p>\n<blockquote>\n<p>TypeError: <strong>init</strong>() got an unexpected keyword argument [...]</p>\n</blockquote>\n<p><em>You're likely using a version of Python older than 3.7.0; update it to the most recent one available. Otherwise there are other answers in this Stack Overflow post showing you older alternative solutions.</em></p>\n" }, { "answer_id": 69012133, "author": "Bilal Ahmed Yaseen", "author_id": 1846656, "author_profile": "https://Stackoverflow.com/users/1846656", "pm_score": 2, "selected": false, "text": "<p>You can run any command using <em><strong>Popen</strong></em> from the <em><strong>subprocess</strong></em> module.</p>\n<pre><code>from subprocess import Popen\n</code></pre>\n<p>First of all, a command object is created with all arguments which you want to run. For example, in the snippet below, the <em>gunicorm</em> command object has been formed with all the arguments:</p>\n<pre><code>cmd = (\n &quot;gunicorn &quot;\n &quot;-c gunicorn_conf.py &quot;\n &quot;-w {workers} &quot;\n &quot;--timeout {timeout} &quot;\n &quot;-b {address}:{port} &quot;\n &quot;--limit-request-line 0 &quot;\n &quot;--limit-request-field_size 0 &quot;\n &quot;--log-level debug &quot;\n &quot;--max-requests {max_requests} &quot;\n &quot;manage:app&quot;).format(**locals())\n</code></pre>\n<p>Then this command object is used with <em><strong>Popen</strong></em> to instantiate a process:</p>\n<pre><code>process = Popen(cmd, shell=True)\n</code></pre>\n<p>This process can be terminated as well based upon any signal, using the code line below:</p>\n<pre><code>Popen.terminate(process)\n</code></pre>\n<p>And you can wait till the completion of above command's execution:</p>\n<pre><code>process.wait()\n</code></pre>\n" }, { "answer_id": 70789418, "author": "Badr Elmers", "author_id": 3020379, "author_profile": "https://Stackoverflow.com/users/3020379", "pm_score": 2, "selected": false, "text": "<p>Here there are a lot of answers, but none fulfilled all my needs.</p>\n<ul>\n<li>I need to run the command and capture the <strong>output</strong> and <strong>exit code</strong>.</li>\n<li>I need to <strong>timeout</strong> the executed program and <strong>force</strong> it to exit if timeout is reached, and <strong>kill all its child processes</strong>.</li>\n<li>and I need that it works in <a href=\"https://en.wikipedia.org/wiki/Windows_XP\" rel=\"nofollow noreferrer\">Windows XP</a> and later, <a href=\"https://en.wikipedia.org/wiki/Cygwin\" rel=\"nofollow noreferrer\">Cygwin</a> and Linux. In Python 2 and 3.</li>\n</ul>\n<p>So I created this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _run(command, timeout_s=False, shell=False):\n ### run a process, capture the output and wait for it to finish. if timeout is specified then Kill the subprocess and its children when the timeout is reached (if parent did not detach)\n ## usage: _run(arg1, arg2, arg3)\n # arg1: command + arguments. Always pass a string; the function will split it when needed\n # arg2: (optional) timeout in seconds before force killing\n # arg3: (optional) shell usage. default shell=False\n ## return: a list containing: exit code, output, and if timeout was reached or not\n\n # - Tested on Python 2 and 3 on Windows XP, Windows 7, Cygwin and Linux.\n # - preexec_fn=os.setsid (py2) is equivalent to start_new_session (py3) (works on Linux only), in Windows and Cygwin we use TASKKILL\n # - we use stderr=subprocess.STDOUT to merge standard error and standard output\n import sys, subprocess, os, signal, shlex, time\n\n def _runPY3(command, timeout_s=None, shell=False):\n # py3.3+ because: timeout was added to communicate() in py3.3.\n new_session=False\n if sys.platform.startswith('linux'): new_session=True\n p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=new_session, shell=shell)\n\n try:\n out = p.communicate(timeout=timeout_s)[0].decode('utf-8')\n is_timeout_reached = False\n except subprocess.TimeoutExpired:\n print('Timeout reached: Killing the whole process group...')\n killAll(p.pid)\n out = p.communicate()[0].decode('utf-8')\n is_timeout_reached = True\n return p.returncode, out, is_timeout_reached\n\n def _runPY2(command, timeout_s=0, shell=False):\n preexec=None\n if sys.platform.startswith('linux'): preexec=os.setsid\n p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=preexec, shell=shell)\n\n start_time = time.time()\n is_timeout_reached = False\n while timeout_s and p.poll() == None:\n if time.time()-start_time &gt;= timeout_s:\n print('Timeout reached: Killing the whole process group...')\n killAll(p.pid)\n is_timeout_reached = True\n break\n time.sleep(1)\n out = p.communicate()[0].decode('utf-8')\n return p.returncode, out, is_timeout_reached\n\n def killAll(ParentPid):\n if sys.platform.startswith('linux'):\n os.killpg(os.getpgid(ParentPid), signal.SIGTERM)\n elif sys.platform.startswith('cygwin'):\n # subprocess.Popen(shlex.split('bash -c &quot;TASKKILL /F /PID $(&lt;/proc/{pid}/winpid) /T&quot;'.format(pid=ParentPid)))\n winpid=int(open(&quot;/proc/{pid}/winpid&quot;.format(pid=ParentPid)).read())\n subprocess.Popen(['TASKKILL', '/F', '/PID', str(winpid), '/T'])\n elif sys.platform.startswith('win32'):\n subprocess.Popen(['TASKKILL', '/F', '/PID', str(ParentPid), '/T'])\n\n # - In Windows, we never need to split the command, but in Cygwin and Linux we need to split if shell=False (default), shlex will split the command for us\n if shell==False and (sys.platform.startswith('cygwin') or sys.platform.startswith('linux')):\n command=shlex.split(command)\n\n if sys.version_info &gt;= (3, 3): # py3.3+\n if timeout_s==False:\n returnCode, output, is_timeout_reached = _runPY3(command, timeout_s=None, shell=shell)\n else:\n returnCode, output, is_timeout_reached = _runPY3(command, timeout_s=timeout_s, shell=shell)\n else: # Python 2 and up to 3.2\n if timeout_s==False:\n returnCode, output, is_timeout_reached = _runPY2(command, timeout_s=0, shell=shell)\n else:\n returnCode, output, is_timeout_reached = _runPY2(command, timeout_s=timeout_s, shell=shell)\n\n return returnCode, output, is_timeout_reached\n</code></pre>\n<p>Then use it like this:</p>\n<p>Always pass the command as one string (it is easier). You do not need to split it; the function will split it when needed.</p>\n<p>If your command works in your shell, it will work with this function, so test your command in your shell first cmd/Bash.</p>\n<p>So we can use it like this with a timeout:</p>\n<pre class=\"lang-py prettyprint-override\"><code>a=_run('cmd /c echo 11111 &amp; echo 22222 &amp; calc',3)\nfor i in a[1].splitlines(): print(i)\n</code></pre>\n<p>Or without a timeout:</p>\n<pre class=\"lang-py prettyprint-override\"><code>b=_run('cmd /c echo 11111 &amp; echo 22222 &amp; calc')\n</code></pre>\n<p>More examples:</p>\n<pre class=\"lang-py prettyprint-override\"><code>b=_run('''wmic nic where 'NetConnectionID=&quot;Local Area Connection&quot;' get NetConnectionStatus /value''')\nprint(b)\n\nc=_run('cmd /C netsh interface ip show address &quot;Local Area Connection&quot;')\nprint(c)\n\nd=_run('printf &quot;&lt;%s&gt;\\n&quot; &quot;{foo}&quot;')\nprint(d)\n</code></pre>\n<p>You can also specify shell=True, but it is useless in most cases with this function. I prefer to choose myself the shell I want, but here it is if you need it too:</p>\n<pre class=\"lang-py prettyprint-override\"><code># windows\ne=_run('echo 11111 &amp; echo 22222 &amp; calc',3, shell=True)\nprint(e)\n# Cygwin/Linux:\nf=_run('printf &quot;&lt;%s&gt;\\n&quot; &quot;{foo}&quot;', shell=True)\nprint(f)\n</code></pre>\n<hr />\n<p><strong>Why did I not use the simpler new method <code>subprocess.run()</code>?</strong></p>\n<ul>\n<li>because it is supported in Python <em>3.7+</em>, but the last supported Python version in Windows XP is <em>3.4</em>.</li>\n<li>and because the timeout argument of this function is useless in Windows, it does not kill the child processes of the executed command.</li>\n<li>if you use the <code>capture_output</code> + <code>timeout</code> argument, it will hang if there is a child process still running. And it is still broken in Windows, for which the <a href=\"https://bugs.python.org/issue31447\" rel=\"nofollow noreferrer\">issue 31447</a> is <a href=\"https://bugs.python.org/issue32795\" rel=\"nofollow noreferrer\">still open</a>.</li>\n</ul>\n" }, { "answer_id": 72216447, "author": "Mr. Day", "author_id": 18147761, "author_profile": "https://Stackoverflow.com/users/18147761", "pm_score": 3, "selected": false, "text": "<p>You can try using <code>os.system()</code> for running external commands.</p>\n<p>Example:</p>\n<pre><code>import os\n\ntry:\n os.system('ls')\n pass\nexcept:\n print(&quot;Error running command&quot;)\n pass\n</code></pre>\n<p>In the example, the script imports <code>os</code> and tries to run the command listed in <code>os.system()</code>. If the command was to fail then it would print &quot;Error running command&quot; without the script stopping due to the error.</p>\n<p>And yes, it’s just that simple!</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17085/" ]
How do I call an external command within Python as if I'd typed it in a shell or command prompt?
Use the [`subprocess`](https://docs.python.org/library/subprocess.html) module in the standard library: ```py import subprocess subprocess.run(["ls", "-l"]) ``` The advantage of [`subprocess.run`](https://docs.python.org/library/subprocess.html#subprocess.run) over [`os.system`](https://docs.python.org/library/os.html#os.system) is that it is more flexible (you can get the [`stdout`](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout), [`stderr`](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr), the ["real" status code](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode), better [error handling](https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError), etc...). Even [the documentation for `os.system`](https://docs.python.org/library/os.html#os.system) recommends using `subprocess` instead: > > The `subprocess` module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the [Replacing Older Functions with the subprocess Module](https://docs.python.org/library/subprocess.html#subprocess-replacements) section in the [`subprocess`](https://docs.python.org/library/subprocess.html) documentation for some helpful recipes. > > > On Python 3.4 and earlier, use `subprocess.call` instead of `.run`: ```py subprocess.call(["ls", "-l"]) ```
89,245
<p>Suppose a large composite application built on several foundation components packaged in their own assemblies: (database reading, protocol handlers, etc.). For some deployments, this can include over 20 assemblies. Each of these assemblies has settings or configuration information. Our team tends to like the VS settings editor (and the easy-to-use code it generates!), and the application vs. user distinction meets most of our needs.</p> <p>BUT....</p> <p>It is very tedious to copy &amp; paste the many configuration sections into our application's .xml. Furthermore, for shared components that tend to have similar configurations across applications, this means we need to maintain duplicate settings in multiple .config files.</p> <p>Microsoft's EntLib solves this problem with an external tool to generate the monster .config file, but this feels klunky as well.</p> <p>What techniques do you use to manage large .NET .config files with sections from multiple shared assemblies? Some kind of include mechanism? Custom configuration readers?</p> <p>FOLLOWUP:</p> <p>Will's <a href="https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618">answer</a> was exactly what I was getting at, and looks elegant for flat key/value pair sections. Is there a way to combine this approach with <a href="https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618">custom configuration sections</a> ? </p> <p>Thanks also for the suggestions about managing different .configs for different build targets. That's also quite useful.</p> <p>Dave </p>
[ { "answer_id": 89261, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>You use one master config file that points to other config files. <a href=\"http://blog.andreloker.de/post/2008/06/Keep-your-config-clean-with-external-config-files.aspx\" rel=\"noreferrer\">Here's an example of how to do this.</a></p>\n\n<hr>\n\n<p>In case the link rots, what you do is specify the <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx\" rel=\"noreferrer\">configSource</a> for a particular configuration section. This allows you to define that particular section within a separate file.</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;pages configSource=\"pages.config\"/&gt;\n</code></pre>\n\n<p>which implies that there is a file called \"pages.config\" within the same directory that contains the entire <code>&lt;pages /&gt;</code> node tree.</p>\n" }, { "answer_id": 89519, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 1, "selected": false, "text": "<p>We created an AssemblySettingsConfig class that acts like ConfigurationManager, but loads a .config for each individual assembly. So the application has a .config, and any DLLs it references have their own .config files. Has worked out well so far.</p>\n" }, { "answer_id": 89618, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<p>A great way to manage large sets of configuration is to create custom configuration sections. Phil Haack discusses this very nicely in this article <a href=\"http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-steps.aspx\" rel=\"nofollow noreferrer\">Custom configuration sections in 3 easy steps</a></p>\n" }, { "answer_id": 90118, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 3, "selected": false, "text": "<p>My preferred method is to use MSBuild, if you right click on a project and click 'unload' a new menu option will pop up that says 'edit '. Select that and it'll open up the project file so you can edit it, scroll down until you find a commented out section that is called \"AfterBuild\".</p>\n\n<p>You can then add something like:</p>\n\n<pre><code>&lt;Target Name=\"AfterBuild\"&gt;\n &lt;Delete Files=\"$(TargetDir)$(TargetFileName).config\" /&gt;\n &lt;Copy SourceFiles=\"$(ProjectDir)$(Configuration).config\" DestinationFiles=\"$(TargetDir)$(TargetFileName).config\" /&gt;\n&lt;/Target&gt;\n</code></pre>\n\n<p>This will replace the application config with one named [Release|Debug]app.exe.config. So you can maintain separate configurations depending on how the project is built.</p>\n\n<p>But a quick and dirty option (if you don't want to play with msbuild) is to just maintain separate config files and then define which one you want to include, like this:</p>\n\n<pre><code>&lt;appSettings configSource=\"Config\\appSettingsDebug.config\"/&gt;\n&lt;roleManager configSource=\"Config\\roleManagerDebug.config\"/&gt;\n</code></pre>\n\n<p>And if you are doing an asp.net application, microsoft provides a great utility called \"Web Deployment Projects\" that will allow you to manage all of this easily, <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&amp;displaylang=en\" rel=\"noreferrer\">click here</a></p>\n" }, { "answer_id": 90686, "author": "Geir-Tore Lindsve", "author_id": 4582, "author_profile": "https://Stackoverflow.com/users/4582", "pm_score": 2, "selected": false, "text": "<p>Set up build configurations for each of your deployment/testing environment and use separate config files based on each build configuration.</p>\n\n<p>ScottGu has <a href=\"http://weblogs.asp.net/scottgu/archive/2007/09/21/tip-trick-automating-dev-qa-staging-and-production-web-config-settings-with-vs-2005.aspx\" rel=\"nofollow noreferrer\">a nice post</a> about this and it works great. The only quirk we have is that we need to make sure that the config files (web.config) are checked out for edit from TFS before each build so that it can be copied over.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6996/" ]
Suppose a large composite application built on several foundation components packaged in their own assemblies: (database reading, protocol handlers, etc.). For some deployments, this can include over 20 assemblies. Each of these assemblies has settings or configuration information. Our team tends to like the VS settings editor (and the easy-to-use code it generates!), and the application vs. user distinction meets most of our needs. BUT.... It is very tedious to copy & paste the many configuration sections into our application's .xml. Furthermore, for shared components that tend to have similar configurations across applications, this means we need to maintain duplicate settings in multiple .config files. Microsoft's EntLib solves this problem with an external tool to generate the monster .config file, but this feels klunky as well. What techniques do you use to manage large .NET .config files with sections from multiple shared assemblies? Some kind of include mechanism? Custom configuration readers? FOLLOWUP: Will's [answer](https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618) was exactly what I was getting at, and looks elegant for flat key/value pair sections. Is there a way to combine this approach with [custom configuration sections](https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618) ? Thanks also for the suggestions about managing different .configs for different build targets. That's also quite useful. Dave
You use one master config file that points to other config files. [Here's an example of how to do this.](http://blog.andreloker.de/post/2008/06/Keep-your-config-clean-with-external-config-files.aspx) --- In case the link rots, what you do is specify the [configSource](http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx) for a particular configuration section. This allows you to define that particular section within a separate file. ```xml <pages configSource="pages.config"/> ``` which implies that there is a file called "pages.config" within the same directory that contains the entire `<pages />` node tree.
89,246
<p>I’m trying to run this SQL using get external.</p> <p>It works, but when I try to rename the sub-queries or anything for that matter it remove it.</p> <p>I tried <code>as</code>, <code>as</code> and the name in <code>''</code>, <code>as</code> then the name in <code>""</code>, and the same with space. What is the right way to do that? </p> <p>Relevant SQL:</p> <pre><code>SELECT list_name, app_name, (SELECT fname + ' ' + lname FROM dbo.d_agent_define map WHERE map.agent_id = tac.agent_id) as agent_login, input, CONVERT(varchar,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970')) FROM dbo.maps_report_list list JOIN dbo.report_tac_agent tac ON (tac.list_id = list.list_id) WHERE input = 'SYS_ERR' AND app_name = 'CHARLOTT' AND convert(VARCHAR,DATEADD(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008' AND list_name LIKE 'NRBAD%' ORDER BY agent_login,CONVERT(VARCHAR,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970')) </code></pre>
[ { "answer_id": 89314, "author": "jttraino", "author_id": 3203, "author_profile": "https://Stackoverflow.com/users/3203", "pm_score": 1, "selected": false, "text": "<p>You could get rid of your <code>dbo.d_agent_define</code> subquery and just add in a join to the agent define table.</p>\n\n<p>Would this code work?</p>\n\n<pre><code>select list_name, app_name, \nmap.fname + ' ' + map.lname as agent_login, \ninput, \nconvert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970')) as tac_seconds\nfrom dbo.maps_report_list list \njoin dbo.report_tac_agent tac \non (tac.list_id = list.list_id) \njoin dbo.d_agent_define map\non (map.agent_id = tac.agent_id)\nwhere input = 'SYS_ERR' \nand app_name = 'CHARLOTT' \nand convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008' \nand list_name LIKE 'NRBAD%' \norder by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))\n</code></pre>\n\n<p>Note that I named your dateadd column because it did not have a name. I also tried to keep your convention of how you do a join. There are a few things that I would do different with this query to make it more readable, but I only focused on getting rid of the subquery problem.</p>\n\n<p>I did not do this, but I would recommend that you qualify all of your columns with the table from which you are getting them.</p>\n" }, { "answer_id": 89450, "author": "Brettski", "author_id": 5836, "author_profile": "https://Stackoverflow.com/users/5836", "pm_score": 0, "selected": false, "text": "<p>To remove the sub query in the SELECT statement I suggest the following:</p>\n\n<pre><code>SELECT list_name, app_name, map.fname + ' ' + map.lname as agent_login, input, convert(varchar,dateadd(ss, TAC_BEG_tstamp, '01/01/1970))\nFROM dbo.maps_report_list inner join\n (dbo.report_tac_agent as tac inner join dbo.d_agent_define as map ON (tac.agent_id=map.agent_id)) ON list.list_id = tac.list_id\nWHERE input = 'SYS_ERR' and app_name = 'CHARLOTT' and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008' \n and list_name LIKE 'NRBAD%' order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))\n</code></pre>\n\n<p>I used parentheses to create the inner join between dbo.report_tac_agent and dbo.d_agent_define first. This is now a set of join data.\nThe combination of those tables are then joined to your list table, which I am assuming is the driving table here. If I am understand what you are trying to do with your sub select, this should work for you. </p>\n\n<p>As stated by the other poster you should use table names on your columns (e.g. map.fname), it just makes things easy to understand. I didn't in my example because I am note 100% sure which columns go with which tables. Please let me know if this doesn't do it for you and how the data it returns is wrong. That will make it easier to solve in needed.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13122/" ]
I’m trying to run this SQL using get external. It works, but when I try to rename the sub-queries or anything for that matter it remove it. I tried `as`, `as` and the name in `''`, `as` then the name in `""`, and the same with space. What is the right way to do that? Relevant SQL: ``` SELECT list_name, app_name, (SELECT fname + ' ' + lname FROM dbo.d_agent_define map WHERE map.agent_id = tac.agent_id) as agent_login, input, CONVERT(varchar,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970')) FROM dbo.maps_report_list list JOIN dbo.report_tac_agent tac ON (tac.list_id = list.list_id) WHERE input = 'SYS_ERR' AND app_name = 'CHARLOTT' AND convert(VARCHAR,DATEADD(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008' AND list_name LIKE 'NRBAD%' ORDER BY agent_login,CONVERT(VARCHAR,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970')) ```
You could get rid of your `dbo.d_agent_define` subquery and just add in a join to the agent define table. Would this code work? ``` select list_name, app_name, map.fname + ' ' + map.lname as agent_login, input, convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970')) as tac_seconds from dbo.maps_report_list list join dbo.report_tac_agent tac on (tac.list_id = list.list_id) join dbo.d_agent_define map on (map.agent_id = tac.agent_id) where input = 'SYS_ERR' and app_name = 'CHARLOTT' and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008' and list_name LIKE 'NRBAD%' order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970')) ``` Note that I named your dateadd column because it did not have a name. I also tried to keep your convention of how you do a join. There are a few things that I would do different with this query to make it more readable, but I only focused on getting rid of the subquery problem. I did not do this, but I would recommend that you qualify all of your columns with the table from which you are getting them.
89,257
<p>I've run into what appears to be a variable scope issue I haven't encountered before. I'm using Perl's CGI module and a call to DBI's do() method. Here's the code structure, simplified a bit:</p> <pre><code>use DBI; use CGI qw(:cgi-lib); &amp;ReadParse; my $dbh = DBI-&gt;connect(...............); my $test = $in{test}; $dbh-&gt;do(qq{INSERT INTO events VALUES (?,?,?)},undef,$in{test},"$in{test}",$test); </code></pre> <p>The #1 placeholder variable evaluates as if it is uninitialized. The other two placeholder variables work.</p> <p><strong>The question: Why is the %in hash not available within the context of do(), unless I wrap it in double quotes (#2 placeholder) or reassign the value to a new variable (#3 placeholder)?</strong></p> <p>I think it's something to do with how the CGI module's ReadParse() function assigns scope to the %in hash, but I don't know Perl scoping well enough to understand why %in is available at the top level but not from within my do() statement.</p> <p>If someone does understand the scoping issue, is there a better way to handle it? Wrapping all the %in references in double quotes seems a little messy. Creating new variables for each query parameter isn't realistic.</p> <p>Just to be clear, my question is about the variable scoping issue. I realize that ReadParse() isn't the recommended method to grab query params with CGI.</p> <p>I'm using Perl 5.8.8, CGI 3.20, and DBI 1.52. Thank you in advance to anyone reading this.</p> <p>@Pi &amp; @Bob, thanks for the suggestions. Pre-declaring the scope for %in has no effect (and I always use strict). The result is the same as before: in the db, col1 is null while cols 2 &amp; 3 are set to the expected value.</p> <p>For reference, here's the ReadParse function (see below). It's a standard function that's part of CGI.pm. The way I understand it, I'm not meant to initialize the %in hash (other than satisfying strict) for purposes of setting scope, since the function appears to me to handle that:</p> <pre><code>sub ReadParse { local(*in); if (@_) { *in = $_[0]; } else { my $pkg = caller(); *in=*{"${pkg}::in"}; } tie(%in,CGI); return scalar(keys %in); } </code></pre> <p>I guess my question is what is the best way to get the %in hash within the context of do()? Thanks again! I hope this is the right way to provide additional info to my original question.</p> <p>@Dan: I hear ya regarding the &amp;ReadParse syntax. I'd normally use CGI::ReadParse() but in this case I thought it was best to stick to how <a href="http://search.cpan.org/src/LDS/CGI.pm-3.42/cgi-lib_porting.html" rel="nofollow noreferrer">the CGI.pm documentation has it</a> exactly.</p>
[ { "answer_id": 89282, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 2, "selected": false, "text": "<p><code>use strict;</code>. Always.</p>\n\n<p>Try declaring</p>\n\n<pre><code>our %in;\n</code></pre>\n\n<p>and seeing if that helps. Failing that, <code>strict</code> may produce a more useful error.</p>\n" }, { "answer_id": 89309, "author": "Bob_Gneu", "author_id": 16703, "author_profile": "https://Stackoverflow.com/users/16703", "pm_score": 2, "selected": false, "text": "<p>Firstly, that is not in the context/scope of do. It is still in the context of main or global. You dont leave context until you enter {} in some way relating to subroutines or different 'classes' in perl. Within () parens you are not leaving scope.</p>\n\n<p>The sample you gave us is of an uninitialized hash and as Pi has suggested, using strict will certainly keep those from occuring. </p>\n\n<p>Can you give us a more representative example of your code? Where are you setting %IN and how?</p>\n" }, { "answer_id": 89378, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>Something's very broken there. Perl's scoping is relatively simple, and you're unlikely to stumble upon anything odd like that unless you're doing something daft. As has been suggested, switch on the strict pragma (and warnings, too. In fact you should be using both anyway). </p>\n\n<p>It's pretty hard to tell what's going on without being able to see how %in is defined (is it something to do with that nasty-looking ReadParse call? why are you calling it with the leading &amp;, btw? that syntax has been considered dead and gone for a long time). I suggest posting a bit more code, so we can see what's going on..</p>\n" }, { "answer_id": 89430, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>It doesn't actually look like you're using it as described in the docs:\n<a href=\"https://metacpan.org/pod/CGI#COMPATIBILITY-WITH-CGI-LIB.PL\" rel=\"nofollow noreferrer\">https://metacpan.org/pod/CGI#COMPATIBILITY-WITH-CGI-LIB.PL</a></p>\n\n<p>If you must use it, then CGI::ReadParse(); seems more sensible and less crufty syntax. Although I can't see it making much difference in this situation, but then it is a tied variable, so who the hell knows what it's doing ;)</p>\n\n<p>Is there a particular reason you can't use the more-common $cgi->param('foo') syntax? It's a little bit cleaner, and filths up your namespace in a considerably more predictable manner..</p>\n" }, { "answer_id": 89445, "author": "Bob_Gneu", "author_id": 16703, "author_profile": "https://Stackoverflow.com/users/16703", "pm_score": -1, "selected": false, "text": "<p>Try this</p>\n\n<p>%in = ReadParse();</p>\n\n<p>but i doubt that. Are you trying to get query parameters or something?</p>\n" }, { "answer_id": 89573, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "<p>Okay, try this:</p>\n\n<pre>\nuse CGI;\nmy %in;\nCGI::ReadParse(\\%in);\n</pre>\n\n<p>That might help as it's actually using a variable that you've declared, and therefore can control the scope of (plus it'll let you <code>use strict</code> without other nastiness that could be muddying the waters)</p>\n" }, { "answer_id": 89598, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 2, "selected": false, "text": "<p>I don't know what's wrong, but I can tell you some things that aren't:</p>\n\n<ul>\n<li>It's not a scoping issue. If it were then none of the instances of <code>$in{test}</code> would work.</li>\n<li>It's not the archaic <code>&amp;</code> calling syntax. (It's not \"right\" but it's harmless in this case.)</li>\n</ul>\n\n<p><code>ReadParse</code> is a nasty bit of code. It munges the symbol table to create the global variable %in in the calling package. What's worse is that it's a tied variable, so accessing it could (theoretically) do anything. Looking at the source code for CGI.pm, the <code>FETCH</code> method just invokes the <code>params()</code> method to get the data. I have no idea why the fetch in the <code>$dbh-&gt;do()</code> isn't working.</p>\n" }, { "answer_id": 89703, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 2, "selected": false, "text": "<p>What version of DBI are you using? From looking at the <a href=\"http://search.cpan.org/~timb/DBI-1.607/Changes\" rel=\"nofollow noreferrer\">DBI changelog</a> it appears that versions prior to 1.00 didn't support the attribute argument. I suspect that the \"uninitialized\" <code>$in{test}</code> is actually the <code>undef</code> that you're passing to <code>$dbh-&gt;do()</code>.</p>\n" }, { "answer_id": 89883, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 0, "selected": false, "text": "<p>As this is starting to look like a <code>tie()</code> problem, try the following experiment. Save this as a foo.pl and run it as <code>perl foo.pl \"x=1\"</code></p>\n\n<pre><code>use CGI;\n\nCGI::ReadParse();\np($in{x}, \"$in{x}\");\n\nsub p { my @a = @_; print \"@a\\n\" }\n</code></pre>\n\n<p>It should print <code>1 1</code>. If it doesn't, we've found the culprit.</p>\n" }, { "answer_id": 91229, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": false, "text": "<p>From the example you gave, this is <em>not</em> a scoping issue, or none of the parameters would work.</p>\n\n<p>Looks like DBI (or a DBD, not sure where bind parameters are used) isn't honoring tie magic.\nThe workaround would be to stringize or copy what you pass to it, like your second and third parameters do.</p>\n\n<p>A simple test using SQLite and DBI 1.53 shows it working ok:</p>\n\n<pre><code>$ perl -MDBI -we'sub TIEHASH { bless {} } sub FETCH { \"42\" } tie %x, \"main\" or die; my $dbh = DBI-&gt;connect(\"dbi:SQLite:dbname=dbfile\",\"\",\"\"); $dbh-&gt;do(\"create table foo (bar char(80))\"); $dbh-&gt;do(\"insert into foo values (?)\", undef, $x{foo}); print \"got: \" . $dbh-&gt;selectrow_array(\"select bar from foo\") . \"\\n\"; $dbh-&gt;do(\"drop table foo\")'\ngot: 42\n</code></pre>\n\n<p>Care to share what database you are using?</p>\n" }, { "answer_id": 132107, "author": "Peter Stuifzand", "author_id": 1633, "author_profile": "https://Stackoverflow.com/users/1633", "pm_score": 0, "selected": false, "text": "<p>I just tried your test codce from <a href=\"http://www.carcomplaints.com/test/test.pl.txt\" rel=\"nofollow noreferrer\">http://www.carcomplaints.com/test/test.pl.txt</a>, and it works right away on my computer, no problems. I get three values as expected. I didn't run it as CGI, but using:</p>\n\n<pre><code>...\nuse CGI qw/-debug/;\n...\n</code></pre>\n\n<p>I write a variable on the console (<code>test=test</code>) and your scripts inserts without a problem.</p>\n\n<p>If however your leave this out, tt will insert an empty string and two NULLs. This is a because you interpolate a value into a string. This will makes a string with value of <code>$in{test}</code> which is <code>undef</code> at the moment. <code>undef</code> stringifies to an empty string, which is what is inserted into database.</p>\n" }, { "answer_id": 314987, "author": "masto", "author_id": 11974, "author_profile": "https://Stackoverflow.com/users/11974", "pm_score": 2, "selected": true, "text": "<p>Per the DBI documentation: Binding a tied variable doesn't work, currently.</p>\n\n<p>DBI is pretty complicated under the hood, and unfortunately goes through some gyrations to be efficient that are causing your problem. I agree with everyone else who says to get rid of the ugly old cgi-lib style code. It's unpleasant enough to do CGI without a nice framework (go Catalyst), let alone something that's been obsolete for a decade.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17092/" ]
I've run into what appears to be a variable scope issue I haven't encountered before. I'm using Perl's CGI module and a call to DBI's do() method. Here's the code structure, simplified a bit: ``` use DBI; use CGI qw(:cgi-lib); &ReadParse; my $dbh = DBI->connect(...............); my $test = $in{test}; $dbh->do(qq{INSERT INTO events VALUES (?,?,?)},undef,$in{test},"$in{test}",$test); ``` The #1 placeholder variable evaluates as if it is uninitialized. The other two placeholder variables work. **The question: Why is the %in hash not available within the context of do(), unless I wrap it in double quotes (#2 placeholder) or reassign the value to a new variable (#3 placeholder)?** I think it's something to do with how the CGI module's ReadParse() function assigns scope to the %in hash, but I don't know Perl scoping well enough to understand why %in is available at the top level but not from within my do() statement. If someone does understand the scoping issue, is there a better way to handle it? Wrapping all the %in references in double quotes seems a little messy. Creating new variables for each query parameter isn't realistic. Just to be clear, my question is about the variable scoping issue. I realize that ReadParse() isn't the recommended method to grab query params with CGI. I'm using Perl 5.8.8, CGI 3.20, and DBI 1.52. Thank you in advance to anyone reading this. @Pi & @Bob, thanks for the suggestions. Pre-declaring the scope for %in has no effect (and I always use strict). The result is the same as before: in the db, col1 is null while cols 2 & 3 are set to the expected value. For reference, here's the ReadParse function (see below). It's a standard function that's part of CGI.pm. The way I understand it, I'm not meant to initialize the %in hash (other than satisfying strict) for purposes of setting scope, since the function appears to me to handle that: ``` sub ReadParse { local(*in); if (@_) { *in = $_[0]; } else { my $pkg = caller(); *in=*{"${pkg}::in"}; } tie(%in,CGI); return scalar(keys %in); } ``` I guess my question is what is the best way to get the %in hash within the context of do()? Thanks again! I hope this is the right way to provide additional info to my original question. @Dan: I hear ya regarding the &ReadParse syntax. I'd normally use CGI::ReadParse() but in this case I thought it was best to stick to how [the CGI.pm documentation has it](http://search.cpan.org/src/LDS/CGI.pm-3.42/cgi-lib_porting.html) exactly.
Per the DBI documentation: Binding a tied variable doesn't work, currently. DBI is pretty complicated under the hood, and unfortunately goes through some gyrations to be efficient that are causing your problem. I agree with everyone else who says to get rid of the ugly old cgi-lib style code. It's unpleasant enough to do CGI without a nice framework (go Catalyst), let alone something that's been obsolete for a decade.
89,285
<p>I've been trimming the UI of our website by doing the following in the onload event of that control:</p> <pre><code>btnDelete.isVisible = user.IsInRole("can delete"); </code></pre> <p>This has become very tedious because there are so many controls to check again and again. As soon as I get it all working, designers request to change the UI and then it starts all over.</p> <p>Any suggestions?</p>
[ { "answer_id": 89295, "author": "Christian Hagelid", "author_id": 202, "author_profile": "https://Stackoverflow.com/users/202", "pm_score": 2, "selected": false, "text": "<p>One simple suggestion would be to group controls into panels based on access rights</p>\n" }, { "answer_id": 89307, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>Something I have done before has been to create a custom page class (Actually, I do this part on every project) that each ASP.NET Page inherits.</p>\n\n<p>This page class contains an IsAdmin property.</p>\n\n<p>I then subclass the commonly used controls that may or may not be visible between modes into custom controls, and add code to check the Pages IsAdmin property.</p>\n\n<p>All this is maybe an hour of work, but if you build pages using these controls, they manage their mode automatically.</p>\n\n<p>Another fun timesaving tip is if you need to flip the page in and out of readonly mode. I added a property to the main base class, and then added a custom control that renders a textbox in one mode, and a label in the other.</p>\n\n<p>Again, a little bit of time on the components, but then you can create a readonly version of the page in 2 lines of code...Very worth it.</p>\n" }, { "answer_id": 89340, "author": "Chris Westbrook", "author_id": 16891, "author_profile": "https://Stackoverflow.com/users/16891", "pm_score": 2, "selected": false, "text": "<p>You may be thinking of the situation in the wrong way. Instead of thinking of individual controls, think of it in terms of business roles and what they have the ability to do. This goes along with grouping controls into panels for access rights. For example, maybe only managers have the ability to delete and do other things, and you have a role for managers that you check. This way if there are changes, you can just move users into different roles. Business rules should not change drastically. There will always be tweaking as new positions gain more responsibility, but thinking of it in this way should minimize the number of changes to be made.</p>\n" }, { "answer_id": 89345, "author": "seanb", "author_id": 3354, "author_profile": "https://Stackoverflow.com/users/3354", "pm_score": 1, "selected": false, "text": "<p>A quick and dirty option is using the asp:loginview controls, which can be wired up to user roles.</p>\n\n<p>Not as elegant as the custom page class option suggested by Jonathan, and can be a bit of a performance hit if they are all over the page.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14396/" ]
I've been trimming the UI of our website by doing the following in the onload event of that control: ``` btnDelete.isVisible = user.IsInRole("can delete"); ``` This has become very tedious because there are so many controls to check again and again. As soon as I get it all working, designers request to change the UI and then it starts all over. Any suggestions?
One simple suggestion would be to group controls into panels based on access rights
89,332
<p>I frequently use <code>git stash</code> and <code>git stash pop</code> to save and restore changes in my working tree. Yesterday, I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but <code>git stash pop</code> appears to remove all references to the associated commit.</p> <p>I know that if I use <code>git stash</code> then <em>.git/refs/stash contains</em> the reference of the commit used to create the stash. And <em>.git/logs/refs/stash contains</em> the whole stash. But those references are gone after <code>git stash pop</code>. I know that the commit is still in my repository somewhere, but I don't know what it was.</p> <p>Is there an easy way to recover yesterday's stash commit reference?</p>
[ { "answer_id": 89388, "author": "Nathan Jones", "author_id": 5848, "author_profile": "https://Stackoverflow.com/users/5848", "pm_score": 6, "selected": false, "text": "<p><code>git fsck --unreachable | grep commit</code> should show the sha1, although the list it returns might be quite large. <code>git show &lt;sha1&gt;</code> will show if it is the commit you want.</p>\n\n<p><code>git cherry-pick -m 1 &lt;sha1&gt;</code> will merge the commit onto the current branch.</p>\n" }, { "answer_id": 89394, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": false, "text": "<p>I just constructed a command that helped me find my lost stash commit:</p>\n\n<pre><code>for ref in `find .git/objects | sed -e 's#.git/objects/##' | grep / | tr -d /`; do if [ `git cat-file -t $ref` = \"commit\" ]; then git show --summary $ref; fi; done | less\n</code></pre>\n\n<p>This lists all the objects in the .git/objects tree, locates the ones that are of type commit, then shows a summary of each one. From this point it was just a matter of looking through the commits to find an appropriate \"WIP on work: 6a9bb2\" (\"work\" is my branch, 619bb2 is a recent commit).</p>\n\n<p>I note that if I use \"git stash apply\" instead of \"git stash pop\" I wouldn't have this problem, and if I use \"git stash save <em>message</em>\" then the commit might have been easier to find.</p>\n\n<p>Update: With Nathan's idea, this becomes shorter:</p>\n\n<pre><code>for ref in `git fsck --unreachable | grep commit | cut -d' ' -f3`; do git show --summary $ref; done | less\n</code></pre>\n" }, { "answer_id": 91795, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 13, "selected": true, "text": "<p>Once you know the hash of the stash commit you dropped, you can apply it as a stash:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>git stash apply $stash_hash\n</code></pre>\n<p>Or, you can create a separate branch for it with</p>\n<pre class=\"lang-bash prettyprint-override\"><code>git branch recovered $stash_hash\n</code></pre>\n<p>After that, you can do whatever you want with all the normal tools. When you’re done, just blow the branch away.</p>\n<h1>Finding the hash</h1>\n<p>If you have only just popped it and the terminal is still open, you will <a href=\"https://stackoverflow.com/questions/89332/recover-dropped-stash-in-git/7844566#7844566\">still have the hash value printed by <code>git stash pop</code> on screen</a> (thanks, Dolda).</p>\n<p>Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>git fsck --no-reflog | awk '/dangling commit/ {print $3}'\n</code></pre>\n<p>...or using PowerShell for Windows:</p>\n<pre><code>git fsck --no-reflog | select-string 'dangling commit' | foreach { $_.ToString().Split(&quot; &quot;)[2] }\n</code></pre>\n<p>This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph.</p>\n<p>The easiest way to find the stash commit you want is probably to pass that list to <code>gitk</code>:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )\n</code></pre>\n<p>...or see <a href=\"https://stackoverflow.com/questions/89332#34666995\">the answer from emragins</a> if using PowerShell for Windows.</p>\n<p>This will launch a repository browser showing you <em>every single commit in the repository ever</em>, regardless of whether it is reachable or not.</p>\n<p>You can replace <code>gitk</code> there with something like <code>git log --graph --oneline --decorate</code> if you prefer a nice graph on the console over a separate GUI app.</p>\n<p>To spot stash commits, look for commit messages of this form:</p>\n<p>        WIP on <i>somebranch</i>: <i>commithash Some old commit message</i></p>\n<p><em>Note</em>: The commit message will only be in this form (starting with &quot;WIP on&quot;) if you did not supply a message when you did <code>git stash</code>.</p>\n" }, { "answer_id": 608033, "author": "Wade", "author_id": 1871, "author_profile": "https://Stackoverflow.com/users/1871", "pm_score": 8, "selected": false, "text": "<p>Just wanted to mention this addition to the accepted solution. It wasn't immediately obvious to me the first time I tried this method (maybe it should have been), but to apply the stash from the hash value, just use \"git stash apply \":</p>\n\n<pre><code>$ git stash apply ad38abbf76e26c803b27a6079348192d32f52219\n</code></pre>\n\n<p>When I was new to git, this wasn't clear to me, and I was trying different combinations of \"git show\", \"git apply\", \"patch\", etc.</p>\n" }, { "answer_id": 5879550, "author": "Senthil A Kumar", "author_id": 289715, "author_profile": "https://Stackoverflow.com/users/289715", "pm_score": 8, "selected": false, "text": "<p>To get the list of stashes that are still in your repository, but not reachable any more:</p>\n<pre><code>git fsck --unreachable | grep commit | cut -d&quot; &quot; -f3 | xargs git log --merges --no-walk --grep=WIP\n</code></pre>\n<hr />\n<p>If you gave a title to your stash, replace &quot;WIP&quot; in <code>-grep=WIP</code> at the end of the command with a part of your message, e.g. <code>-grep=Tesselation</code>.</p>\n<p>The command is grepping for &quot;WIP&quot; because the default commit message for a stash is in the form <code>WIP on mybranch: [previous-commit-hash] Message of the previous commit.</code></p>\n<p>When you have found the commit, apply it with <code>git stash apply &lt;commit_hash&gt;</code></p>\n" }, { "answer_id": 6455586, "author": "Colin Hebert", "author_id": 422597, "author_profile": "https://Stackoverflow.com/users/422597", "pm_score": 6, "selected": false, "text": "<p>If you want to restash a lost stash, you need to find the hash of your lost stash first.</p>\n\n<p>As Aristotle Pagaltzis suggested a <code>git fsck</code> should help you.</p>\n\n<p>Personally I use my <code>log-all</code> alias which show me every commit (recoverable commits) to have a better view of the situation :</p>\n\n<pre><code>git log --graph --decorate --pretty=oneline --abbrev-commit --all $(git fsck --no-reflogs | grep commit | cut -d' ' -f3)\n</code></pre>\n\n<p>You can do an even faster search if you're looking only for \"WIP on\" messages.</p>\n\n<p>Once you know your sha1, you simply change your stash reflog to add the old stash :</p>\n\n<pre><code>git update-ref refs/stash ed6721d\n</code></pre>\n\n<p>You'll probably prefer to have an associated message so a <code>-m</code></p>\n\n<pre><code>git update-ref -m \"$(git log -1 --pretty=format:'%s' ed6721d)\" refs/stash ed6721d\n</code></pre>\n\n<p>And you'll even want to use this as an alias :</p>\n\n<pre><code>restash = !git update-ref -m $(git log -1 --pretty=format:'%s' $1) refs/stash $1\n</code></pre>\n" }, { "answer_id": 7844566, "author": "Dolda2000", "author_id": 134252, "author_profile": "https://Stackoverflow.com/users/134252", "pm_score": 10, "selected": false, "text": "<p>If you didn't close the terminal, just look at the output from <code>git stash pop</code> and you'll have the object ID of the dropped stash. It normally looks like this:</p>\n\n<pre><code>$ git stash pop\n[...]\nDropped refs/stash@{0} (2ca03e22256be97f9e40f08e6d6773c7d41dbfd1)\n</code></pre>\n\n<p>(Note that <code>git stash drop</code> also produces the same line.)</p>\n\n<p>To get that stash back, just run <code>git branch tmp 2cae03e</code>, and you'll get it as a branch. To convert this to a stash, run:</p>\n\n<pre><code>git stash apply tmp\ngit stash\n</code></pre>\n\n<p>Having it as a branch also allows you to manipulate it freely; for example, to cherry-pick it or merge it.</p>\n" }, { "answer_id": 14157278, "author": "Phil", "author_id": 1129712, "author_profile": "https://Stackoverflow.com/users/1129712", "pm_score": 4, "selected": false, "text": "<p>I want to add to the accepted solution another good way to go through all the changes, when you either don't have gitk available or no X for output.</p>\n\n<pre><code>git fsck --no-reflog | awk '/dangling commit/ {print $3}' &gt; tmp_commits\n\nfor h in `cat tmp_commits`; do git show $h | less; done\n</code></pre>\n\n<p>Then you get all the diffs for those hashes displayed one after another. Press 'q' to get to the next diff.</p>\n" }, { "answer_id": 14203376, "author": "Shaheen Ghiassy", "author_id": 1179897, "author_profile": "https://Stackoverflow.com/users/1179897", "pm_score": 5, "selected": false, "text": "<p>I liked Aristotle's approach, but didn't like using GITK... as I'm used to using GIT from the command line. </p>\n\n<p>Instead, I took the dangling commits and output the code to a DIFF file for review in my code editor.</p>\n\n<pre><code>git show $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' ) &gt; ~/stash_recovery.diff\n</code></pre>\n\n<p>Now you can load up the resulting diff/txt file (its in your home folder) into your txt editor and see the actual code and resulting SHA.</p>\n\n<p>Then just use </p>\n\n<pre><code>git stash apply ad38abbf76e26c803b27a6079348192d32f52219\n</code></pre>\n" }, { "answer_id": 19839165, "author": "Ben", "author_id": 874660, "author_profile": "https://Stackoverflow.com/users/874660", "pm_score": 2, "selected": false, "text": "<p>What I came here looking for is how to actually get the stash back, regardless of what I have checked out. In particular, I had stashed something, then checked out an older version, then poped it, but the stash was a no-op at that earlier time point, so the stash disappeared; I couldn't just do <code>git stash</code> to push it back on the stack. This worked for me:</p>\n\n<pre><code>$ git checkout somethingOld\n$ git stash pop\n...\nnothing added to commit but untracked files present (use \"git add\" to track)\nDropped refs/stash@{0} (27f6bd8ba3c4a34f134e12fe69bf69c192f71179)\n$ git checkout 27f6bd8ba3c\n$ git reset HEAD^ # Make the working tree differ from the parent.\n$ git stash # Put the stash back in the stack.\nSaved working directory and index state WIP on (no branch): c2be516 Some message.\nHEAD is now at c2be516 Some message.\n$ git checkout somethingOld # Now we are back where we were.\n</code></pre>\n\n<p>In retrospect, I should have been using <code>git stash apply</code> not <code>git stash pop</code>. I was doing a <code>bisect</code> and had a little patch that I wanted to apply at every <code>bisect</code> step. Now I'm doing this:</p>\n\n<pre><code>$ git reset --hard; git bisect good; git stash apply\n$ # Run tests\n$ git reset --hard; git bisect bad; git stash apply\netc.\n</code></pre>\n" }, { "answer_id": 32216966, "author": "Abhijeet", "author_id": 452708, "author_profile": "https://Stackoverflow.com/users/452708", "pm_score": 3, "selected": false, "text": "<p>Recovered it by using following steps:</p>\n\n<ol>\n<li><p>Identify the deleted stash hash code: </p>\n\n<p>gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )</p></li>\n<li><p>Cherry Pick the Stash:</p>\n\n<p>git cherry-pick -m 1 $stash_hash_code</p></li>\n<li><p>Resolve Conflicts if any using: </p>\n\n<p>git mergetool</p></li>\n</ol>\n\n<p>Additionally you might be having issues with commit message if you are using gerrit. Please Stash your changes before following next alternatives:</p>\n\n<ol>\n<li>Use hard reset to previous commit and then recommit this change. </li>\n<li>You may also stash the change, rebase and recommit.</li>\n</ol>\n" }, { "answer_id": 34666995, "author": "emragins", "author_id": 219072, "author_profile": "https://Stackoverflow.com/users/219072", "pm_score": 6, "selected": false, "text": "<p>Windows PowerShell equivalent using gitk:</p>\n\n<p><code>gitk --all $(git fsck --no-reflog | Select-String \"(dangling commit )(.*)\" | %{ $_.Line.Split(' ')[2] })</code></p>\n\n<p>There is probably a more efficient way to do this in one pipe, but this does the job.</p>\n" }, { "answer_id": 37267192, "author": "Brad Feehan", "author_id": 1077375, "author_profile": "https://Stackoverflow.com/users/1077375", "pm_score": 4, "selected": false, "text": "<p>The accepted answer by Aristotle will show all reachable commits, including non-stash-like commits. To filter out the noise:</p>\n\n<pre><code>git fsck --no-reflog | \\\nawk '/dangling commit/ {print $3}' | \\\nxargs git log --no-walk --format=\"%H\" \\\n --grep=\"WIP on\" --min-parents=3 --max-parents=3\n</code></pre>\n\n<p>This will only include commits which have exactly 3 parent commits (which a stash will have), and whose message includes \"WIP on\".</p>\n\n<p>Keep in mind, that if you saved your stash with a message (e.g. <code>git stash save \"My newly created stash\"</code>), this will override the default \"WIP on...\" message.</p>\n\n<p>You can display more information about each commit, e.g. display the commit message, or pass it to <code>git stash show</code>:</p>\n\n<pre><code>git fsck --no-reflog | \\\nawk '/dangling commit/ {print $3}' | \\\nxargs git log --no-walk --format=\"%H\" \\\n --grep=\"WIP on\" --min-parents=3 --max-parents=3 | \\\nxargs -n1 -I '{}' bash -c \"\\\n git log -1 --format=medium --color=always '{}'; echo; \\\n git stash show --color=always '{}'; echo; echo\" | \\\nless -R\n</code></pre>\n" }, { "answer_id": 37458408, "author": "RobbyD", "author_id": 1193349, "author_profile": "https://Stackoverflow.com/users/1193349", "pm_score": 4, "selected": false, "text": "<p>Why do people ask this question? Because they don't yet know about or understand the reflog.</p>\n\n<p>Most answers to this question give long commands with options almost nobody will remember. So people come into this question and copy paste whatever they think they need and forget it almost immediately after.</p>\n\n<p>I would advise everyone with this question to just check the reflog (git reflog), not much more than that. Once you see that list of all commits there are a hundred ways to find out what commit you're looking for and to cherry-pick it or create a branch from it. In the process you'll have learned about the reflog and useful options to various basic git commands.</p>\n" }, { "answer_id": 37727162, "author": "Can Tecim", "author_id": 3294680, "author_profile": "https://Stackoverflow.com/users/3294680", "pm_score": 4, "selected": false, "text": "<p>In OSX with git v2.6.4, I just run git stash drop accidentally, then I found it by going trough below steps</p>\n\n<p>If you know name of the stash then use: </p>\n\n<p><code>$ git fsck --unreachable | grep commit | cut -c 20- | xargs git show | grep -B 6 -A 2 &lt;name of the stash&gt;</code></p>\n\n<p>otherwise you will find ID from the result by manually with:</p>\n\n<p><code>$ git fsck --unreachable | grep commit | cut -c 20- | xargs git show</code></p>\n\n<p>Then when you find the commit-id just hit the git stash apply {commit-id}</p>\n\n<p>Hope this helps someone quickly</p>\n" }, { "answer_id": 42386983, "author": "Koen", "author_id": 1581660, "author_profile": "https://Stackoverflow.com/users/1581660", "pm_score": 4, "selected": false, "text": "<p>I couldn't get any of the answers to work on Windows in a simple command window (Windows 7 in my case). <code>awk</code>, <code>grep</code> and <code>Select-string</code> weren't recognized as commands. So I tried a different approach:</p>\n\n<ul>\n<li>first run: <code>git fsck --unreachable | findstr \"commit\"</code></li>\n<li>copy the output to notepad</li>\n<li>find replace \"unreachable commit\" with <code>start cmd /k git show</code></li>\n</ul>\n\n<p>will look something like this:</p>\n\n<p><code>start cmd /k git show 8506d235f935b92df65d58e7d75e9441220537a4\nstart cmd /k git show 44078733e1b36962571019126243782421fcd8ae\nstart cmd /k git show ec09069ec893db4ec1901f94eefc8dc606b1dbf1\nstart cmd /k git show d00aab9198e8b81d052d90720165e48b287c302e</code></p>\n\n<ul>\n<li>save as a .bat file and run it</li>\n<li>the script will open a bunch of command windows, showing each commit</li>\n<li>if you found the one you're looking for, run: <code>git stash apply (your hash)</code> </li>\n</ul>\n\n<p>may not be the best solution, but worked for me</p>\n" }, { "answer_id": 49150866, "author": "Vivek Kumar", "author_id": 5163085, "author_profile": "https://Stackoverflow.com/users/5163085", "pm_score": 5, "selected": false, "text": "<p>You can list all unreachable commits by writing this command in terminal - </p>\n\n<pre><code>git fsck --unreachable\n</code></pre>\n\n<p>Check unreachable commit hash - </p>\n\n<pre><code>git show hash\n</code></pre>\n\n<p>Finally apply if you find the stashed item - </p>\n\n<pre><code>git stash apply hash\n</code></pre>\n" }, { "answer_id": 57654136, "author": "Adrian W", "author_id": 2311167, "author_profile": "https://Stackoverflow.com/users/2311167", "pm_score": 5, "selected": false, "text": "<p>My favorite is this one-liner:</p>\n\n<pre><code>git log --oneline $( git fsck --no-reflogs | awk '/dangling commit/ {print $3}' )\n</code></pre>\n\n<p>This is basically the same idea as <a href=\"https://stackoverflow.com/a/6455586/2311167\">this answer</a> but much shorter. Of course, you can still add <code>--graph</code> to get a tree-like display.</p>\n\n<p>When you have found the commit in the list, apply with</p>\n\n<pre><code>git stash apply THE_COMMIT_HASH_FOUND\n</code></pre>\n\n<p>For me, using <code>--no-reflogs</code> did reveal the lost stash entry, but <code>--unreachable</code> (as found in many other answers) did not.</p>\n\n<p>Run it on git bash when you are under Windows.</p>\n\n<p>Credits: The details of the above commands are taken from <a href=\"https://gist.github.com/joseluisq/7f0f1402f05c45bac10814a9e38f81bf\" rel=\"noreferrer\">https://gist.github.com/joseluisq/7f0f1402f05c45bac10814a9e38f81bf</a> </p>\n" }, { "answer_id": 66249225, "author": "Treviño", "author_id": 210151, "author_profile": "https://Stackoverflow.com/users/210151", "pm_score": 3, "selected": false, "text": "<p>To see the commits in terminal, only filtering the ones we care about we can use:</p>\n<pre><code>git log --oneline --all --grep=&quot;^WIP on .*: [a-f0-9]\\+&quot; --grep=&quot;^On [^ ]*:&quot; --grep=&quot;^index on [^ ]*:&quot; $( env LANG=C git fsck --no-reflog | awk '/dangling commit/ {print $3}' )\n</code></pre>\n<p>This is based on Aristotle Pagaltzis answer.</p>\n" }, { "answer_id": 69117761, "author": "Lovekush Vishwakarma", "author_id": 3306437, "author_profile": "https://Stackoverflow.com/users/3306437", "pm_score": 0, "selected": false, "text": "<p>You can follow the below process step by step:</p>\n<p>1- use below to list all unreachable commits\ngit fsck --unreachable</p>\n<p>2- to show unreachable commit hash by\ngit show hash</p>\n<p>3- copy all log, you can see log like, unreachable blob, commit, tree.</p>\n<p>4- apply git stash with log having commit hash\ngit stash apply [replace hash]</p>\n" }, { "answer_id": 70871838, "author": "minTwin", "author_id": 8046535, "author_profile": "https://Stackoverflow.com/users/8046535", "pm_score": 3, "selected": false, "text": "<p>This worked for me (in 2022) with recovering my accidently deleted stash in git from a windows environment.</p>\n<p>These steps outline how to recover any deleted git stashes or branches (assuming it has not been permanently delete by garbage collection).</p>\n<ol>\n<li><p>Navigate to the directory where your project located.</p>\n</li>\n<li><p>Enter the command: <code>git fsck --no-reflogs | find &quot;dangling commit&quot;</code>\n<a href=\"https://i.stack.imgur.com/2IuLf.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/2IuLf.jpg\" alt=\"enter image description here\" /></a></p>\n</li>\n<li><p>A list of hashes for dangling commits will appear. These will consist of branches and stashes that were deleted. Start with copy and pasting the hashes near the end of the list to find your stash or branch. For example, use the command: <code>git log -1 [hash]</code></p>\n</li>\n<li><p>If the corresponding hash matches what you are trying to recover, use the following command to restore it&quot;\n<code>git stash apply [hash]</code></p>\n</li>\n</ol>\n" }, { "answer_id": 71327982, "author": "anapsix", "author_id": 1633804, "author_profile": "https://Stackoverflow.com/users/1633804", "pm_score": 1, "selected": false, "text": "<p>Knowing the approximate file name and it's location, and was able to find dropped stash files grepping dangling commits for path</p>\n<pre><code>for i in $(git fsck --no-reflogs | awk '/dangling commit/ {print $3}'); do\n if git log -5 --name-only -u $i | grep -q &quot;&lt;path-to-files&gt;/.*&lt;partial-file-name&gt;.*&quot;; then\n echo &quot;found something in commit $i&quot;;\n fi;\ndone\n</code></pre>\n" }, { "answer_id": 73544681, "author": "Changdae Park", "author_id": 10694438, "author_profile": "https://Stackoverflow.com/users/10694438", "pm_score": 1, "selected": false, "text": "<h3>To see only stash commits, where they attached, and what their contents are</h3>\n<p>result sample</p>\n<pre><code>Checking object directories: 100% (256/256), done.\n2022-08-31 10:20:46 +0900 8d02f61 WIP on master: 243b594 add css\nA favicon.ico\n</code></pre>\n<p>command</p>\n<pre><code>git fsck --dangling | awk '/dangling commit/ {print $3}' | xargs -L 1 git --no-pager show -s --format=&quot;%ct %h&quot; | sort | awk '{print $2}' | { while read hash; do status=$(git stash show $hash --name-status 2&gt;/dev/null); if (( $? == 0 )); then git show $hash -s --format=&quot;%C(green)%ci %C(yellow)%h %C(blue)%B&quot;; echo &quot;$status&quot;; fi; done; }\n</code></pre>\n<ul>\n<li>To see full hash, change <code>%h</code> to <code>%H</code></li>\n<li>To reduce time, tail fsck like <code>git fsck --dangling | tail -100 | awk ...</code></li>\n</ul>\n<p>recover sample\n<a href=\"https://i.stack.imgur.com/bueIH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bueIH.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 74139296, "author": "askepott", "author_id": 9288939, "author_profile": "https://Stackoverflow.com/users/9288939", "pm_score": 0, "selected": false, "text": "<p>Not exactly an answer to get a stash but if the goal is to get uncommited changes that were first stashed and then popped in another branch but meant for both and done in the following way:</p>\n<ol>\n<li>Make changes in <code>branch_a</code></li>\n<li><code>git stash</code></li>\n<li>Make branch_b from <code>branch_a</code></li>\n<li><code>git stash apply</code></li>\n</ol>\n<p>Then to restore the uncommited changes to <code>branch_a</code>:</p>\n<ol>\n<li><code>git checkout branch_a</code></li>\n<li><code>git merge branch_b</code></li>\n<li><code>git reset HEAD~1</code></li>\n</ol>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893/" ]
I frequently use `git stash` and `git stash pop` to save and restore changes in my working tree. Yesterday, I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but `git stash pop` appears to remove all references to the associated commit. I know that if I use `git stash` then *.git/refs/stash contains* the reference of the commit used to create the stash. And *.git/logs/refs/stash contains* the whole stash. But those references are gone after `git stash pop`. I know that the commit is still in my repository somewhere, but I don't know what it was. Is there an easy way to recover yesterday's stash commit reference?
Once you know the hash of the stash commit you dropped, you can apply it as a stash: ```bash git stash apply $stash_hash ``` Or, you can create a separate branch for it with ```bash git branch recovered $stash_hash ``` After that, you can do whatever you want with all the normal tools. When you’re done, just blow the branch away. Finding the hash ================ If you have only just popped it and the terminal is still open, you will [still have the hash value printed by `git stash pop` on screen](https://stackoverflow.com/questions/89332/recover-dropped-stash-in-git/7844566#7844566) (thanks, Dolda). Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows: ```bash git fsck --no-reflog | awk '/dangling commit/ {print $3}' ``` ...or using PowerShell for Windows: ``` git fsck --no-reflog | select-string 'dangling commit' | foreach { $_.ToString().Split(" ")[2] } ``` This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph. The easiest way to find the stash commit you want is probably to pass that list to `gitk`: ```bash gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' ) ``` ...or see [the answer from emragins](https://stackoverflow.com/questions/89332#34666995) if using PowerShell for Windows. This will launch a repository browser showing you *every single commit in the repository ever*, regardless of whether it is reachable or not. You can replace `gitk` there with something like `git log --graph --oneline --decorate` if you prefer a nice graph on the console over a separate GUI app. To spot stash commits, look for commit messages of this form:         WIP on *somebranch*: *commithash Some old commit message* *Note*: The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did `git stash`.
89,418
<p>Assume I have an "images" folder directory under the root of my application. How can I, from within a .css file, reference an image in this directory using an ASP.NET app relative path. </p> <p>Example:</p> <p>When in development, the path of <strong>~/Images/Test.gif</strong> might resolve to <strong>/MyApp/Images/Test.gif</strong> while, in production, it might resolve to <strong>/Images/Test.gif</strong> (depending on the virtual directory for the application). I, obviously, want to avoid having to modify the .css file between environments.</p> <p>I know you can use Page.ResolveClientUrl to inject a url into a control's Style collection dynamically at render time. I would like to avoid doing this.</p>
[ { "answer_id": 89431, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 3, "selected": false, "text": "<p>In case you didn't know you could do this...</p>\n\n<p>If you give a relative path to a resource in a CSS it's relative to the CSS file, not file including the CSS.</p>\n\n<pre><code>background-image: url(../images/test.gif);\n</code></pre>\n\n<p>So this might work for you.</p>\n" }, { "answer_id": 89433, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": -1, "selected": false, "text": "<p>Inside of the .css file you can use relative paths; so in your example, say you put your css file in ~/Styles/mystyles.css. You can use url(../Images/Test.gif) as an example.</p>\n" }, { "answer_id": 442383, "author": "Marcel Popescu", "author_id": 31793, "author_profile": "https://Stackoverflow.com/users/31793", "pm_score": 4, "selected": false, "text": "<p>Unfortunately Firefox has a stupid bug here... the paths are relative to the path of the page, instead of being relative to the position of the CSS file. Which means if you have pages in different positions in the tree (like having Default.aspx in the root and Information.aspx in the View folder) there's no way to have working relative paths. (IE will correctly solve the paths relative to the location of the CSS file.)</p>\n\n<p>The only thing I could find is this comment on <a href=\"http://www.west-wind.com/weblog/posts/269.aspx\" rel=\"noreferrer\">http://www.west-wind.com/weblog/posts/269.aspx</a> but, to be honest, I haven't managed to make it work yet. If I do I'll edit this comment:</p>\n\n<blockquote>\n <p>re: Making sense of ASP.Net Paths by\n Russ Brooks February 25, 2006 @ 8:43\n am</p>\n \n <p>No one fully answered Brant's question\n about the image paths inside the CSS\n file itself. I've got the answer. The\n question was, \"How do we use\n application-relative image paths\n INSIDE the CSS file?\" I have long been\n frustrated by this very problem too,\n so I just spent the last 3 hours\n working out a solution.</p>\n \n <p>The solution is to run your CSS files\n through the ASPX page handler, then\n use a small bit of server-side code in\n each of the paths to output the root\n application path. Ready?</p>\n \n <ol>\n <li>Add to web.config:</li>\n </ol>\n</blockquote>\n\n<pre><code> &lt;compilation debug=\"true\"&gt;\n &lt;!-- Run CSS files through the ASPX handler so we can write code in them. --&gt;\n &lt;buildProviders&gt;\n &lt;add extension=\".css\" type=\"System.Web.Compilation.PageBuildProvider\" /&gt;\n &lt;/buildProviders&gt;\n &lt;/compilation&gt;\n\n &lt;httpHandlers&gt;\n &lt;add path=\"*.css\" verb=\"GET\" type=\"System.Web.UI.PageHandlerFactory\" validate=\"true\" /&gt;\n &lt;/httpHandlers&gt;\n</code></pre>\n\n<blockquote>\n <ol start=\"2\">\n <li><p>Inside your CSS, use the Request.ApplicationPath property\n wherever a path exists, like this:</p>\n \n <p>#content {\n background: url(&lt;%= Request.ApplicationPath\n %>/images/bg_content.gif) repeat-y;\n }</p></li>\n <li><p>.NET serves up ASPX pages with a MIME type of \"text/html\" by default,\n consequently, your new server-side CSS\n pages are served up with this MIME\n type which causes non-IE browsers to\n not read the CSS file correctly. We\n need to override this to be\n \"text/css\". Simply add this line as\n the first line of your CSS file:</p>\n\n<pre><code>&lt;%@ ContentType=\"text/css\" %&gt;\n</code></pre></li>\n </ol>\n</blockquote>\n" }, { "answer_id": 2824055, "author": "Viv Jones", "author_id": 339890, "author_profile": "https://Stackoverflow.com/users/339890", "pm_score": -1, "selected": false, "text": "<p>I was having difficulty in getting background images to display for content containers and have tried many solutions similar to other posted here. I had set the relative path in the CSS file, set it as a style on the aspx page I wanted the background to display - nothing worked. I tried Marcel Popescu's solution and it still didn't work. </p>\n\n<p>I did end up getting it to work following a combination of Marcel's solution and trial and error. I inserted the code into the web.config, inserted the text/css line into my CSS file but I removed the background property in the CSS file altogether and set it as a style on the content container in the aspx page I wanted the background to display.</p>\n\n<p>It does mean that for each or any other pages that I want to display the background I will need to set the style background property but it works beautifully.</p>\n" }, { "answer_id": 3094751, "author": "Snarf", "author_id": 307712, "author_profile": "https://Stackoverflow.com/users/307712", "pm_score": 2, "selected": false, "text": "<p>Marcel Popescu's solution is using Request.ApplicationPath in the css file.</p>\n\n<p>Never use Request.ApplicationPath - it is evil! Returns different results depending on the path!</p>\n\n<p>Use the following instead.</p>\n\n<pre><code>background-image: url(&lt;%= Page.ResolveUrl(\"~/images/bg_content.gif\") %&gt;);\n</code></pre>\n" }, { "answer_id": 4002277, "author": "TchiYuan", "author_id": 483638, "author_profile": "https://Stackoverflow.com/users/483638", "pm_score": 1, "selected": false, "text": "<p>On Windows 7, IIS 7.5:</p>\n\n<p>Not only do you have to do the steps mentionned by Marcel Popescu.</p>\n\n<p>You also need to add a handler mapping in IIS 7.5 handler mappings. So that IIS knows that *.css must be used with the System.Web.UI.PageHandlerFactory</p>\n\n<p>It's not enough to just set the stuff in the web.config file.</p>\n" }, { "answer_id": 4319947, "author": "JohnB", "author_id": 287311, "author_profile": "https://Stackoverflow.com/users/287311", "pm_score": 3, "selected": false, "text": "<p>Make you life easy, just put images used in your CSS in the <code>/css/</code> folder alongside <code>/css/style.css</code>. Then when you reference your images, use relative paths (e.g. <code>url(images/image.jpg)</code>).</p>\n\n<p>I still keep images that are displayed with a <code>&lt;img&gt;</code> in an <code>/images/</code> folder. Photos for example are content, they are not part of the website's skin/theme. Thus, they do not belong in the <code>/css/</code> folder.</p>\n" }, { "answer_id": 9004534, "author": "Andrew Weitzen", "author_id": 1169429, "author_profile": "https://Stackoverflow.com/users/1169429", "pm_score": 2, "selected": false, "text": "<p>Put your dynamic CSS in a user control in an .ascx file and then you do not need to run all your css files through the asp.net page processer.</p>\n\n<pre><code>&lt;%@ Control %&gt;\n&lt;style type=\"text/css&gt;\ndiv.content\n{\nbackground-image:(url(&lt;%= Page.ResolveUrl(\"~/images/image.png\") %&gt;);\n}\n&lt;/style&gt;\n</code></pre>\n\n<p>But the easiest way to solve the <code>~</code> problem is to not use a <code>~</code> at all. In Visual Studio, in Solution Explorer, right click your application, select Properties Window and change the Virtual Path to <code>/</code>.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10834/" ]
Assume I have an "images" folder directory under the root of my application. How can I, from within a .css file, reference an image in this directory using an ASP.NET app relative path. Example: When in development, the path of **~/Images/Test.gif** might resolve to **/MyApp/Images/Test.gif** while, in production, it might resolve to **/Images/Test.gif** (depending on the virtual directory for the application). I, obviously, want to avoid having to modify the .css file between environments. I know you can use Page.ResolveClientUrl to inject a url into a control's Style collection dynamically at render time. I would like to avoid doing this.
Unfortunately Firefox has a stupid bug here... the paths are relative to the path of the page, instead of being relative to the position of the CSS file. Which means if you have pages in different positions in the tree (like having Default.aspx in the root and Information.aspx in the View folder) there's no way to have working relative paths. (IE will correctly solve the paths relative to the location of the CSS file.) The only thing I could find is this comment on <http://www.west-wind.com/weblog/posts/269.aspx> but, to be honest, I haven't managed to make it work yet. If I do I'll edit this comment: > > re: Making sense of ASP.Net Paths by > Russ Brooks February 25, 2006 @ 8:43 > am > > > No one fully answered Brant's question > about the image paths inside the CSS > file itself. I've got the answer. The > question was, "How do we use > application-relative image paths > INSIDE the CSS file?" I have long been > frustrated by this very problem too, > so I just spent the last 3 hours > working out a solution. > > > The solution is to run your CSS files > through the ASPX page handler, then > use a small bit of server-side code in > each of the paths to output the root > application path. Ready? > > > 1. Add to web.config: > > > ``` <compilation debug="true"> <!-- Run CSS files through the ASPX handler so we can write code in them. --> <buildProviders> <add extension=".css" type="System.Web.Compilation.PageBuildProvider" /> </buildProviders> </compilation> <httpHandlers> <add path="*.css" verb="GET" type="System.Web.UI.PageHandlerFactory" validate="true" /> </httpHandlers> ``` > > 2. Inside your CSS, use the Request.ApplicationPath property > wherever a path exists, like this: > > > #content { > background: url(<%= Request.ApplicationPath > %>/images/bg\_content.gif) repeat-y; > } > 3. .NET serves up ASPX pages with a MIME type of "text/html" by default, > consequently, your new server-side CSS > pages are served up with this MIME > type which causes non-IE browsers to > not read the CSS file correctly. We > need to override this to be > "text/css". Simply add this line as > the first line of your CSS file: > > > > ``` > <%@ ContentType="text/css" %> > > ``` > > >
89,441
<p>I have Visual Studio web test attached nicely to a data source, but I need to be able to iterate over each entry in the data source. How should I do this?</p>
[ { "answer_id": 89492, "author": "Ola Karlsson", "author_id": 10696, "author_profile": "https://Stackoverflow.com/users/10696", "pm_score": 2, "selected": true, "text": "<p>This <a href=\"http://www.codeguru.com/csharp/.net/net_general/visualstudionetadd-ins/article.php/c12645__2/\" rel=\"nofollow noreferrer\">article</a> seems to Discuss something quite like what you're talking about.\nGood luck.\nOla</p>\n\n<p><strong>EDIT:</strong> From the linked article, your DataSource is exposed to your test via an attribute.</p>\n\n<pre><code>[DataSource(\"System.Data.SqlClient\",\n \"Data Source=VSTS;Initial Catalog=ContactManagerWebTest;\n Integrated Security=True\", \"ValidContactInfo\",\n DataAccessMethod.Sequential), TestMethod()]\n</code></pre>\n\n<p>There are several other DataSources you can link to, for example CSV, or even Parameters of a Test Case in TFS. Be sure to include the <code>DataAccessMethod.Sequential</code>. If there are multiple rows in the table indicated by the <code>DataSourceAttribute</code>, then each test run will have <code>TestContext.DataRow</code> pointing to the current row/iteration for the test.</p>\n" }, { "answer_id": 89565, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": false, "text": "<p>The trick is to select \"Run test(pause before starting)\"</p>\n\n<p>Then when the test opens up, click the little link that says \"Edit run settings\"</p>\n\n<p>A dialog boxes opens allowing you to choose \"One run per datasource row\"</p>\n" }, { "answer_id": 37029734, "author": "Bharat C", "author_id": 2794406, "author_profile": "https://Stackoverflow.com/users/2794406", "pm_score": 1, "selected": false, "text": "<p>Open Local.testsettings file from solution explorer and go to Web Test -> Select \"One run per data source now\" option. That's it.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13813/" ]
I have Visual Studio web test attached nicely to a data source, but I need to be able to iterate over each entry in the data source. How should I do this?
This [article](http://www.codeguru.com/csharp/.net/net_general/visualstudionetadd-ins/article.php/c12645__2/) seems to Discuss something quite like what you're talking about. Good luck. Ola **EDIT:** From the linked article, your DataSource is exposed to your test via an attribute. ``` [DataSource("System.Data.SqlClient", "Data Source=VSTS;Initial Catalog=ContactManagerWebTest; Integrated Security=True", "ValidContactInfo", DataAccessMethod.Sequential), TestMethod()] ``` There are several other DataSources you can link to, for example CSV, or even Parameters of a Test Case in TFS. Be sure to include the `DataAccessMethod.Sequential`. If there are multiple rows in the table indicated by the `DataSourceAttribute`, then each test run will have `TestContext.DataRow` pointing to the current row/iteration for the test.
89,465
<p>Currently, WScript pops up message box when there is a script error. These scripts are called by other processes, and are ran on a server, so there is nobody to dismiss the error box. </p> <p>What I'd like is for the error message to be dumped to STDOUT, and execution to return the calling process. Popping as a MSGBox just hangs the entire thing.</p> <p>Ideas?</p>
[ { "answer_id": 89511, "author": "X-Cubed", "author_id": 10808, "author_profile": "https://Stackoverflow.com/users/10808", "pm_score": 0, "selected": false, "text": "<p>You haven't stated what language you're using. If you're using VBScript, you can write an error handler using the <a href=\"http://publib.boulder.ibm.com/infocenter/cqhelp/v7r0m0/index.jsp?topic=/com.ibm.rational.clearquest.apiref.doc/c_vbscript_err_hndlng.htm\" rel=\"nofollow noreferrer\">On Error...</a> statement. If you're using JScript, you can use a <a href=\"http://www.w3schools.com/js/js_try_catch.asp\" rel=\"nofollow noreferrer\">try {} catch (x) {}</a> block.</p>\n" }, { "answer_id": 89715, "author": "Jeremy", "author_id": 8557, "author_profile": "https://Stackoverflow.com/users/8557", "pm_score": 0, "selected": false, "text": "<p>don't do this:</p>\n<blockquote>\n<p>vbscript:\nOn error resume next</p>\n<p>english:\n&quot;when you have an error, ignore it &amp; just keep going&quot;.</p>\n</blockquote>\n" }, { "answer_id": 89804, "author": "Jay Michaud", "author_id": 8613, "author_profile": "https://Stackoverflow.com/users/8613", "pm_score": 2, "selected": false, "text": "<p>Don't use WScript; use CScript. At the Windows command prompt, type the following to display help.\n<pre><code>cscript //?</code></pre>\nI suggest the following:\n<pre><code>cscript //H:CScript</code></pre>\nThis will make CScript your default scripting interpreter. CScript prints messages to the console (i.e., stdout) as you desire. (It does not use dialog windows.)\nYou may also want to try the //B switch, but I can't tell if that has to be run per-script or not. If it is a persistent, one-time switch like the //H switch is, then this may work for you; if not, you may need to modify all of your remote programs to include it. From the information you provided, I think just changing the default interpreter (//H) will do what you want.</p>\n\n<p>You will also need to add some sort of error handling to keep the script from terminating on an error. In Visual Basic Scripting Edition, the easiest thing to do if you just want to ignore errors is to add the following to the top of your script.\n<pre><code>On Error Resume Next</code></pre>\nSee <a href=\"http://msdn.microsoft.com/en-us/library/53f3k80h(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/53f3k80h(VS.85).aspx</a> for more information.</p>\n" }, { "answer_id": 96124, "author": "aphoria", "author_id": 2441, "author_profile": "https://Stackoverflow.com/users/2441", "pm_score": 1, "selected": false, "text": "<p>Use <code>WScript.Echo</code> instead of <code>MsgBox</code>. And also run the script using <code>Cscript</code> instead of <code>Wscript</code>.</p>\n" }, { "answer_id": 207756, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>This is how you should be running Script batch jobs:</p>\n\n<pre><code>cscript //b scriptname.vbs\n</code></pre>\n" }, { "answer_id": 7267143, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>I suggest you put your script code in a Sub - e.g. <code>DoWork</code> - and code your script something like:</p>\n\n<pre><code>On Error Resume Next\n\nDoWork\n\nIf Err.Number &lt;&gt; 0 Then\n\n If \"CSCRIPT.EXE\" = UCase( Right( WScript.Fullname, 11 ) ) Then\n WScript.StdErr.Write Err.Number &amp; \": \" &amp; Err.Description\n Else\n WScript.Echo Err.Number &amp; \": \" &amp; Err.Description\n End If\n WScript.Quit 1\nEnd If\n\nPrivate Sub DoWork\n\n ... your code ...\n\nEnd Sub\n</code></pre>\n\n<p>In this way, when you run your script using <code>cscript //b</code>, and it fails, you'll get an error message output to stderr and the caller will receive a non-zero errorlevel.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
Currently, WScript pops up message box when there is a script error. These scripts are called by other processes, and are ran on a server, so there is nobody to dismiss the error box. What I'd like is for the error message to be dumped to STDOUT, and execution to return the calling process. Popping as a MSGBox just hangs the entire thing. Ideas?
This is how you should be running Script batch jobs: ``` cscript //b scriptname.vbs ```
89,480
<p>For reasons I won't go into, I wish to ban an entire company from accessing my web site. Checking the remote hostname in php using gethostbyaddr() works, but this slows down the page load too much. Large organizations (eg. hp.com or microsoft.com) often have blocks of IP addresses. Is there anyway I get the full list, or am I stuck with the slow reverse-DNS lookup? If so, can I speed it up?</p> <p>Edit: Okay, now I know I can use the .htaccess file to ban a range. Now, how can I figure out what that range should be for a given organization?</p>
[ { "answer_id": 89494, "author": "fabiopedrosa", "author_id": 2731698, "author_profile": "https://Stackoverflow.com/users/2731698", "pm_score": 1, "selected": false, "text": "<p>Take a look at .htaccess if you're using apache: <a href=\"http://httpd.apache.org/docs/1.3/howto/htaccess.html\" rel=\"nofollow noreferrer\">.htaccess tutorial</a></p>\n" }, { "answer_id": 89495, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 5, "selected": true, "text": "<p>How about an .htaccess:</p>\n\n<pre><code>Deny from x.x.x.x\n</code></pre>\n\n<p>if you need to deny a range say: 192.168.0.x then you would use</p>\n\n<pre><code>Deny from 192.168.0\n</code></pre>\n\n<p>and the same applies for hostnames:</p>\n\n<pre><code>Deny from sub.domain.tld\n</code></pre>\n\n<p>or if you want a PHP solution</p>\n\n<pre><code>$ips = array('1.1.1.1', '2.2.2.2', '3.3.3.3');\nif(in_array($_SERVER['REMOTE_ADDR'])){die();}\n</code></pre>\n\n<p>For more info on the htaccess method see <a href=\"http://httpd.apache.org/docs/1.3/mod/mod_access.html\" rel=\"nofollow noreferrer\">this</a> page.</p>\n\n<p>Now to determine the range is going to be hard, most companies (unless they are big corperate) are going to have a dynamic IP just like you and me.<br />\nThis is a problem I have had to deal with before and the best thing is either to ban the hostname, or the entire range, for example if they are on 192.168.0.123 then ban 192.168.0.123, unfortunatly you are going to get a few innocent people with either method.</p>\n" }, { "answer_id": 89499, "author": "iros", "author_id": 2108922, "author_profile": "https://Stackoverflow.com/users/2108922", "pm_score": 0, "selected": false, "text": "<p>Do you have access to the actual server config? If so depending on the server you could do it in the configuration.</p>\n\n<p>See <a href=\"http://www.webmasterworld.com/forum92/3546.htm\" rel=\"nofollow noreferrer\">this</a> thread for some information that may be helpful.</p>\n" }, { "answer_id": 89522, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>Continue to use <code>gethostbyaddr()</code>, but behind a cache. You should only have to resolve it once per IP address, and then it would not be a significant performance issue. If you want, prime the cache from your server logs so returning users won't even hit the one-time slowdown.</p>\n" }, { "answer_id": 89524, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p>If you're practicing safe webhosting, then you have a firewall. Use it.</p>\n\n<p>Large companies have blocks of IP addresses, but even smaller companies rarely change their IP. So there's an easy way to do this without reducing your performance:</p>\n\n<p>Every month do a reverse lookup on all the IPs in your log and then put all the IPs used by that company in your firewall as deny.</p>\n\n<p>After awhile yo'll begin to see whether they have dynamic addresses or not. If they do, then you may have to do reverse lookups for each connection attempt, but unless they are a small company you shouldn't have to worry about it.</p>\n" }, { "answer_id": 89527, "author": "jtimberman", "author_id": 7672, "author_profile": "https://Stackoverflow.com/users/7672", "pm_score": 1, "selected": false, "text": "<p>First search for the company on <a href=\"http://www.whois.net\" rel=\"nofollow noreferrer\">whois.net</a>. If you know they are just one domain, do a whois lookup. Otherwise, search for domains they own by keyword.</p>\n\n<p>You can find out the main IP ranges assigned to the company through whois queries, and then build your deny rule(s) accordingly. </p>\n" }, { "answer_id": 89549, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Rwhois\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Rwhois</a>\ntelnet rwhois.arin.net 4321</p>\n\n<p>This used to work.</p>\n" }, { "answer_id": 89644, "author": "Matt Blaine", "author_id": 16272, "author_profile": "https://Stackoverflow.com/users/16272", "pm_score": 1, "selected": false, "text": "<p>I know <a href=\"http://wikiscanner.virgil.gr/\" rel=\"nofollow noreferrer\">WikiScanner</a> lets you search for a company or other organization, and then lists the IP address ranges belonging to them. Just as an example, here's all the <a href=\"http://wikiscanner.virgil.gr/name2ip.php?orgname=Google\" rel=\"nofollow noreferrer\">IP addresses belonging to Google</a>, at least according to WikiScanner.</p>\n\n<p>According to <a href=\"http://computer.howstuffworks.com/wikipedia-scanner1.htm\" rel=\"nofollow noreferrer\">HowStuffWorks</a>, they use something called \"IP2Location\".</p>\n" }, { "answer_id": 89646, "author": "Jason Morrison", "author_id": 15098, "author_profile": "https://Stackoverflow.com/users/15098", "pm_score": 2, "selected": false, "text": "<p>If your goal in doing this is to make it slightly inconvenient for people from a company to access your site, follow the advice above. But you won't be able to completely ensure you're blocking every access because they could always be going through a proxy. And if it's accessible to the rest of the public, you'll have to worry about archive.org, search engine caches, etc.</p>\n\n<p>Probably not the answer you're looking for, but it's accurate.</p>\n" }, { "answer_id": 89849, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The load shouldn't be put on the webserver, you should put it on the firewall. </p>\n" }, { "answer_id": 90347, "author": "jan.vdbergh", "author_id": 9540, "author_profile": "https://Stackoverflow.com/users/9540", "pm_score": 0, "selected": false, "text": "<p>Note that using the techniques above it will never be possible to completely ban the specific company from accessing your website. It will still be possible for them to use proxy servers or look at your site from home.</p>\n\n<p>If you absolutely want to control who has access, you should only allow authenticated and authorized users to access your site. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15947/" ]
For reasons I won't go into, I wish to ban an entire company from accessing my web site. Checking the remote hostname in php using gethostbyaddr() works, but this slows down the page load too much. Large organizations (eg. hp.com or microsoft.com) often have blocks of IP addresses. Is there anyway I get the full list, or am I stuck with the slow reverse-DNS lookup? If so, can I speed it up? Edit: Okay, now I know I can use the .htaccess file to ban a range. Now, how can I figure out what that range should be for a given organization?
How about an .htaccess: ``` Deny from x.x.x.x ``` if you need to deny a range say: 192.168.0.x then you would use ``` Deny from 192.168.0 ``` and the same applies for hostnames: ``` Deny from sub.domain.tld ``` or if you want a PHP solution ``` $ips = array('1.1.1.1', '2.2.2.2', '3.3.3.3'); if(in_array($_SERVER['REMOTE_ADDR'])){die();} ``` For more info on the htaccess method see [this](http://httpd.apache.org/docs/1.3/mod/mod_access.html) page. Now to determine the range is going to be hard, most companies (unless they are big corperate) are going to have a dynamic IP just like you and me. This is a problem I have had to deal with before and the best thing is either to ban the hostname, or the entire range, for example if they are on 192.168.0.123 then ban 192.168.0.123, unfortunatly you are going to get a few innocent people with either method.
89,488
<p>I've been trying to implement a C#-like event system in C++ with the tr1 function templates used to store a function that handles the event. </p> <p>I created a vector so that multiple listeners can be attached to this event, i.e.:</p> <pre><code>vector&lt; function&lt;void (int)&gt; &gt; listenerList; </code></pre> <p>I'd like to be able to remove a handler from the list to stop a listener receiving events.</p> <p>So, how can I find the entry in this list that corresponds to a given listener? Can I test if a 'function' object in the list refers to a particular function?</p> <p>Thanks!</p> <p>EDIT: Having looked into the boost::signal approach, it seems it's probably implemented using a token system as some of you have suggested. <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/signals/tutorial.html" rel="nofollow noreferrer">Here's some info on this</a>. An observer retains a "Connection" object when they attach to an event, and this connection object is used to disconnect if needed. So it looks like whether you use Boost or roll your own with tr1, the basic principle's the same. i.e. it will be a bit clumsy :) </p>
[ { "answer_id": 89542, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/function/faq.html\" rel=\"nofollow noreferrer\">FAQ #1</a> in the boost function documentation seems to address your question - and the easy answer is \"no\".</p>\n" }, { "answer_id": 89563, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2002/n1402.html\" rel=\"nofollow noreferrer\">proposal</a> (section IIIb.) states they will not be comparable in any way. If you attach some extra information to them, you can easily identify each callback. For instance, if you simply define a struct wrapping the function pointer, you can remove them (assuming you have the same struct you inserted). You can also add some fields to the struct (like an automatically generated guid the client can hold on to) and compare against that.</p>\n" }, { "answer_id": 89595, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "<p>If you are storing function pointers only (and not other functors that match the signature required), this is easy (see code below). But in general, the answer, like other posters have said, is no. In that case, you probably want to store your functors in a hash, as values, with keys being something the user supplies on adding and removing.</p>\n\n<p>The code below demonstrates how to get the functor/pointer object that is to be called. To use it, you must know the exact type of the object to extract (i.e., the <code>typeid</code> of the type you specify must match the <code>typeid</code> of the contained functor/pointer).</p>\n\n<pre><code>#include &lt;cstdio&gt;\n#include &lt;functional&gt;\n\nusing std::printf;\nusing std::tr1::function;\n\nint main(int, char**);\nstatic function&lt;int (int, char**)&gt; main_func(&amp;main);\n\nint\nmain(int argc, char** argv)\n{\n printf(\"%p == %p\\n\", *main_func.target&lt;int (*)(int, char**)&gt;(), &amp;main);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 89693, "author": "Flame", "author_id": 5387, "author_profile": "https://Stackoverflow.com/users/5387", "pm_score": 0, "selected": false, "text": "<p>What about </p>\n\n<pre><code>map&lt;key-type, function&lt;void (int)&gt; &gt; listeners;\n</code></pre>\n" }, { "answer_id": 90115, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 2, "selected": false, "text": "<p>Okay, you got me working. The hard part is trying to match the exact usage pattern of C# events. If you skip that, there are MUCH easier ways to do what you're asking. (My co-worker Jason uses a Notifier object all over the place.) Anyway, here's the incredibly boring code which does what you want. Unfortunately, it doesn't allow you to pass parameters from the Subject to the Observer. To do that, you'd need to add even more smarts.</p>\n\n<pre><code>#include \"stdafx.h\"\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;list&gt;\n#include &lt;algorithm&gt;\n#include &lt;boost/tr1/functional.hpp&gt;\n#include &lt;boost/tr1/memory.hpp&gt;\n\nusing namespace std;\nusing namespace std::tr1;\n\ntemplate &lt;typename T&gt;\nclass ObserverHandle\n{\npublic:\n typedef boost::function&lt;void (T*)&gt; const UnderlyingFunction;\n\n ObserverHandle(UnderlyingFunction underlying)\n : _underlying(new UnderlyingFunction(underlying))\n {\n }\n\n void operator()(T* data) const\n {\n (*_underlying)(data);\n }\n\n bool operator==(ObserverHandle&lt;T&gt; const&amp; other) const\n {\n return (other._underlying == _underlying);\n }\n\nprivate:\n shared_ptr&lt;UnderlyingFunction&gt; const _underlying;\n};\n\nclass BaseDelegate\n{\npublic:\n virtual bool operator==(BaseDelegate const&amp; other)\n {\n return false;\n }\n\n virtual void operator() () const = 0;\n};\n\ntemplate &lt;typename T&gt;\nclass Delegate : public BaseDelegate\n{\npublic:\n Delegate(T* observer, ObserverHandle&lt;T&gt; handle)\n : _observer(observer),\n _handle(handle)\n {\n }\n\n virtual bool operator==(BaseDelegate const&amp; other)\n {\n BaseDelegate const * otherPtr = &amp;other;\n Delegate&lt;T&gt; const * otherDT = dynamic_cast&lt;Delegate&lt;T&gt; const *&gt;(otherPtr);\n return ((otherDT) &amp;&amp;\n (otherDT-&gt;_observer == _observer) &amp;&amp;\n (otherDT-&gt;_handle == _handle));\n }\n\n virtual void operator() () const\n {\n _handle(_observer);\n }\n\nprivate:\n T* _observer;\n ObserverHandle&lt;T&gt; _handle;\n};\n\nclass Event\n{\npublic:\n template &lt;typename T&gt;\n void add(T* observer, ObserverHandle&lt;T&gt; handle)\n {\n _observers.push_back(shared_ptr&lt;BaseDelegate&gt;(new Delegate&lt;T&gt;(observer, handle)));\n }\n\n template &lt;typename T&gt;\n void remove(T* observer, ObserverHandle&lt;T&gt; handle)\n {\n // I should be able to come up with a bind2nd(equals(dereference(_1))) kind of thing, but I can't figure it out now\n Observers::iterator it = find_if(_observers.begin(), _observers.end(), Compare(Delegate&lt;T&gt;(observer, handle)));\n if (it != _observers.end())\n {\n _observers.erase(it);\n }\n }\n\n void operator()() const\n {\n for (Observers::const_iterator it = _observers.begin();\n it != _observers.end();\n ++it)\n {\n (*(*it))();\n }\n }\n\nprivate:\n typedef list&lt;shared_ptr&lt;BaseDelegate&gt;&gt; Observers;\n Observers _observers;\n\n class Compare\n {\n public:\n Compare(BaseDelegate const&amp; other)\n : _other(other)\n {\n }\n\n bool operator() (shared_ptr&lt;BaseDelegate&gt; const&amp; other) const\n {\n return (*other) == _other;\n }\n\n private:\n BaseDelegate const&amp; _other;\n };\n};\n\n// Example usage:\n\nclass SubjectA\n{\npublic:\n Event event;\n\n void do_event()\n {\n cout &lt;&lt; \"doing event\" &lt;&lt; endl;\n event();\n cout &lt;&lt; \"done\" &lt;&lt; endl;\n }\n};\n\nclass ObserverA\n{\npublic:\n void test(SubjectA&amp; subject)\n {\n subject.do_event();\n cout &lt;&lt; endl;\n\n subject.event.add(this, _observe);\n subject.do_event();\n subject.event.remove(this, _observe);\n cout &lt;&lt; endl;\n\n subject.do_event();\n cout &lt;&lt; endl;\n\n subject.event.add(this, _observe);\n subject.event.add(this, _observe);\n subject.do_event();\n subject.event.remove(this, _observe);\n subject.do_event();\n subject.event.remove(this, _observe);\n cout &lt;&lt; endl;\n\n }\n\n void observe()\n {\n cout &lt;&lt; \"..observed!\" &lt;&lt; endl;\n }\n\nprivate:\n static ObserverHandle&lt;ObserverA&gt; _observe;\n};\n\n// Here's the trick: make a static object for each method you might want to turn into a Delegate\nObserverHandle&lt;ObserverA&gt; ObserverA::_observe(boost::bind(&amp;ObserverA::observe, _1));\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n SubjectA sa;\n ObserverA oa;\n oa.test(sa);\n\n return 0;\n}\n</code></pre>\n\n<p>And here's the output:</p>\n\n<blockquote>\n <p>doing event<br>\n done </p>\n \n <p>doing event<br>\n ..observed!<br>\n done </p>\n \n <p>doing event<br>\n done </p>\n \n <p>doing event<br>\n ..observed!<br>\n ..observed!<br>\n done<br>\n doing event<br>\n ..observed!<br>\n done </p>\n</blockquote>\n" }, { "answer_id": 90495, "author": "Nick Bastin", "author_id": 1502059, "author_profile": "https://Stackoverflow.com/users/1502059", "pm_score": 3, "selected": false, "text": "<p>I don't know if you're locked into std C++ and tr1, but if you aren't, it seems like your problem could be completely avoided if you just used something like boost::signal and boost::bind to solve your original problem - creating an event system - instead of trying to roll your own.</p>\n" }, { "answer_id": 6890563, "author": "Paul Manta", "author_id": 627005, "author_profile": "https://Stackoverflow.com/users/627005", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem and found a solution to it. I used some C++0x features, but only for convenience, they are not an essential part. Take a look here:<br>\n> <a href=\"https://stackoverflow.com/questions/6884041/messaging-system-callbacks-can-be-anything/6890543#6890543\">Messaging system: Callbacks can be anything</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17136/" ]
I've been trying to implement a C#-like event system in C++ with the tr1 function templates used to store a function that handles the event. I created a vector so that multiple listeners can be attached to this event, i.e.: ``` vector< function<void (int)> > listenerList; ``` I'd like to be able to remove a handler from the list to stop a listener receiving events. So, how can I find the entry in this list that corresponds to a given listener? Can I test if a 'function' object in the list refers to a particular function? Thanks! EDIT: Having looked into the boost::signal approach, it seems it's probably implemented using a token system as some of you have suggested. [Here's some info on this](http://www.boost.org/doc/libs/1_36_0/doc/html/signals/tutorial.html). An observer retains a "Connection" object when they attach to an event, and this connection object is used to disconnect if needed. So it looks like whether you use Boost or roll your own with tr1, the basic principle's the same. i.e. it will be a bit clumsy :)
I don't know if you're locked into std C++ and tr1, but if you aren't, it seems like your problem could be completely avoided if you just used something like boost::signal and boost::bind to solve your original problem - creating an event system - instead of trying to roll your own.
89,504
<p>I've got a standard Rails app with Nginx and Mongrel running at <a href="http://mydomain" rel="noreferrer">http://mydomain</a>. I need to run a Wordpress blog at <a href="http://mydomain.com/blog" rel="noreferrer">http://mydomain.com/blog</a>. My preference would be to host the blog in Apache running on either the same server or a separate box but I don't want the user to see a different server in the URL. Is that possible and if not, what would you recommend to accomplish the goal?</p>
[ { "answer_id": 89512, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 0, "selected": false, "text": "<p>Seems to me that something like a rewrite manipulator would do what you want. Sorry I don't have anymore details -- just thinking aloud :)</p>\n" }, { "answer_id": 89530, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 3, "selected": false, "text": "<p>Actually, since you're using Nginx, you're already in great shape and don't need Apache.</p>\n\n<p>You can run PHP through fastcgi (there are examples of how to do this <a href=\"http://wiki.codemongers.com/NginxFcgiExample\" rel=\"noreferrer\">in the Nginx wiki</a>), and use a URL-matching pattern in your Nginx configuration to direct some URLs to Rails and others to PHP.</p>\n\n<p>Here's an example Nginx configuration for running a WordPress blog through PHP fastcgi (note I've also put in the Nginx equivalent of the WordPress .htaccess, so you will also have fancy URLs already working with this config):</p>\n\n<pre><code>server {\n listen example.com:80;\n server_name example.com;\n charset utf-8;\n error_log /www/example.com/log/error.log;\n access_log /www/example.com/log/access.log main;\n root /www/example.com/htdocs;\n\n include /www/etc/nginx/fastcgi.conf;\n fastcgi_index index.php;\n\n # Send *.php to PHP FastCGI on :9001\n location ~ \\.php$ {\n fastcgi_pass 127.0.0.1:9001;\n }\n\n # You could put another \"location\" section here to match some URLs and send\n # them to Rails. Or do it the opposite way and have \"/blog/*\" go to PHP\n # first and then everything else go to Rails. Whatever regexes you feel like\n # putting into \"location\" sections!\n\n location / {\n index index.html index.php;\n # URLs that don't exist go to WordPress /index.php PHP FastCGI\n if (!-e $request_filename) {\n rewrite ^.* /index.php break;\n fastcgi_pass 127.0.0.1:9001;\n }\n\n }\n}\n</code></pre>\n\n<p>Here's the fastcgi.conf file I'm including in the above config (I put it in a separate file so all of my virtual host config files can include it in the right place, but you don't have to do this):</p>\n\n<pre><code># joelhardi fastcgi.conf, see http://wiki.codemongers.com/NginxFcgiExample for source\nfastcgi_param GATEWAY_INTERFACE CGI/1.1;\nfastcgi_param SERVER_SOFTWARE nginx;\n\nfastcgi_param QUERY_STRING $query_string;\nfastcgi_param REQUEST_METHOD $request_method;\nfastcgi_param CONTENT_TYPE $content_type;\nfastcgi_param CONTENT_LENGTH $content_length;\n\nfastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\nfastcgi_param SCRIPT_NAME $fastcgi_script_name;\nfastcgi_param REQUEST_URI $request_uri;\nfastcgi_param DOCUMENT_URI $document_uri;\nfastcgi_param DOCUMENT_ROOT $document_root;\nfastcgi_param SERVER_PROTOCOL $server_protocol;\n\nfastcgi_param REMOTE_ADDR $remote_addr;\nfastcgi_param REMOTE_PORT $remote_port;\nfastcgi_param SERVER_ADDR $server_addr;\nfastcgi_param SERVER_PORT $server_port;\nfastcgi_param SERVER_NAME $server_name;\n\n# PHP only, required if PHP was built with --enable-force-cgi-redirect\n#fastcgi_param REDIRECT_STATUS 200;\n</code></pre>\n\n<p>I also happen to do what the Nginx wiki suggests, and use spawn-fcgi from Lighttpd as my CGI-spawner (Lighttpd is a pretty fast compile w/o weird dependencies, so a quick and easy thing to install), but you can also use a short shell/Perl script for that.</p>\n" }, { "answer_id": 90896, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 4, "selected": true, "text": "<p>I think joelhardi's solution is superior to the following. However, in my own application, I like to keep the blog on a separate VPS than the Rails site (separation of memory issues). To make the user see the same URL, you use the same proxy trick that you normally use for proxying to a mongrel cluster, except you proxy to port 80 (or whatever) on another box. Easy peasy. To the user it is as transparent as you proxying to mongrel -- they only \"see\" the NGINX responding on port 80 at your domain.</p>\n\n<pre><code>upstream myBlogVPS {\n server 127.0.0.2:80; #fix me to point to your blog VPS\n}\n\n server {\n listen 80;\n\n\n #You'll have plenty of things for Rails compatibility here\n\n #Make sure you don't accidentally step on this with the Rails config!\n\n location /blog {\n proxy_pass http://myBlogVPS;\n proxy_redirect off;\n\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n }\n</code></pre>\n\n<p>You can use this trick to have Rails play along with ANY server technology you want, incidentally. Proxy directly to the appropriate server/port, and NGINX will hide it from the outside world. Additionally, since the URLs will all refer to the same domain, you can seemlessly integrate a PHP-based blog, Python based tracking system, and Rails app -- as long as you write your URLs correctly.</p>\n" }, { "answer_id": 729638, "author": "Jauder Ho", "author_id": 26366, "author_profile": "https://Stackoverflow.com/users/26366", "pm_score": 2, "selected": false, "text": "<p>The answers above pretty addresses your question.</p>\n\n<p>An alternative FCGI would be to use php-fpm. Docs are a tad sparse but it works well. </p>\n" }, { "answer_id": 12233407, "author": "New Alexandria", "author_id": 263858, "author_profile": "https://Stackoverflow.com/users/263858", "pm_score": 1, "selected": false, "text": "<p>Nginx now <a href=\"http://nginx.org/en/docs/howto_setup_development_environment_on_ec2.html\" rel=\"nofollow\">provides a script for doing this</a> if you're in the EC2 / AWS environment. </p>\n\n<p>It may be easily adaptable to your situation. It's pretty handy.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14619/" ]
I've got a standard Rails app with Nginx and Mongrel running at <http://mydomain>. I need to run a Wordpress blog at <http://mydomain.com/blog>. My preference would be to host the blog in Apache running on either the same server or a separate box but I don't want the user to see a different server in the URL. Is that possible and if not, what would you recommend to accomplish the goal?
I think joelhardi's solution is superior to the following. However, in my own application, I like to keep the blog on a separate VPS than the Rails site (separation of memory issues). To make the user see the same URL, you use the same proxy trick that you normally use for proxying to a mongrel cluster, except you proxy to port 80 (or whatever) on another box. Easy peasy. To the user it is as transparent as you proxying to mongrel -- they only "see" the NGINX responding on port 80 at your domain. ``` upstream myBlogVPS { server 127.0.0.2:80; #fix me to point to your blog VPS } server { listen 80; #You'll have plenty of things for Rails compatibility here #Make sure you don't accidentally step on this with the Rails config! location /blog { proxy_pass http://myBlogVPS; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } ``` You can use this trick to have Rails play along with ANY server technology you want, incidentally. Proxy directly to the appropriate server/port, and NGINX will hide it from the outside world. Additionally, since the URLs will all refer to the same domain, you can seemlessly integrate a PHP-based blog, Python based tracking system, and Rails app -- as long as you write your URLs correctly.
89,543
<p>I want to set something up so that if an Account within my app is disabled, I want all requests to be redirected to a "disabled" message.</p> <p>I've set this up in my ApplicationController:</p> <pre><code>class ApplicationController &lt; ActionController::Base before_filter :check_account def check_account redirect_to :controller =&gt; "main", :action =&gt; "disabled" and return if !$account.active? end end </code></pre> <p>Of course, this doesn't quite work as it goes into an infinite loop if the Account is not active. I was hoping to use something like:</p> <pre><code>redirect_to :controller =&gt; "main", :action =&gt; "disabled" and return if !$account.active? &amp;&amp; @controller.controller_name != "main" &amp;&amp; @controller.action_name != "disabled" </code></pre> <p>but I noticed that in Rails v2.1 (what I'm using), @controller is now controller and this doesn't seem to work in ApplicationController.</p> <p>What would be the best way to implement something like this?</p>
[ { "answer_id": 89637, "author": "flukus", "author_id": 407256, "author_profile": "https://Stackoverflow.com/users/407256", "pm_score": 0, "selected": false, "text": "<p>If theres not too many overrides then just put the if in the redirect filter</p>\n\n<p>if action != disabled\n redirect()\nend</p>\n" }, { "answer_id": 89647, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 3, "selected": false, "text": "<p>You have several options.</p>\n\n<p>If your action method \"disabled\" is uniquely named in the scope of the application, you can add an exception to the before_filter call, like this:</p>\n\n<pre><code>before_filter :check_account, :except =&gt; :disabled\n</code></pre>\n\n<p>If you want to check specifically for the controller and action in the filter, you should note that this code is already part of the controller object. You can refer to it as \"self,\" like so:</p>\n\n<pre><code> def check_account\n return if self.controller_name == \"main\" &amp;&amp; self.action_name == \"disabled\"\n\n redirect_to :controller =&gt; \"main\", :action =&gt; \"disabled\" and return if !$account.active?\n end\n</code></pre>\n\n<p>Finally, if you like, you can overwrite the filter method from within MainController.rb:</p>\n\n<pre><code> def check_account\n return if action_name == \"disabled\"\n super\n end\n</code></pre>\n" }, { "answer_id": 90149, "author": "Tony Pitale", "author_id": 1167846, "author_profile": "https://Stackoverflow.com/users/1167846", "pm_score": 3, "selected": true, "text": "<p>You could also use a <code>skip_before_filter</code> for the one controller/method you don't want to have the filter apply to.</p>\n" }, { "answer_id": 95814, "author": "Eric Allam", "author_id": 7434, "author_profile": "https://Stackoverflow.com/users/7434", "pm_score": 1, "selected": false, "text": "<p>How about first getting rid of that global variable $account. You are basically setting yourself up for some serious bugs by using a global. Just use an instance variable instead @ or better yet create a method on ApplicationController called current_account which access the @current_account instance variable. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14530/" ]
I want to set something up so that if an Account within my app is disabled, I want all requests to be redirected to a "disabled" message. I've set this up in my ApplicationController: ``` class ApplicationController < ActionController::Base before_filter :check_account def check_account redirect_to :controller => "main", :action => "disabled" and return if !$account.active? end end ``` Of course, this doesn't quite work as it goes into an infinite loop if the Account is not active. I was hoping to use something like: ``` redirect_to :controller => "main", :action => "disabled" and return if !$account.active? && @controller.controller_name != "main" && @controller.action_name != "disabled" ``` but I noticed that in Rails v2.1 (what I'm using), @controller is now controller and this doesn't seem to work in ApplicationController. What would be the best way to implement something like this?
You could also use a `skip_before_filter` for the one controller/method you don't want to have the filter apply to.
89,588
<p>You do <code>AssignProcessToJobObject</code> and it fails with "access denied" but only when you are running in the debugger. Why is this?</p>
[ { "answer_id": 89589, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 6, "selected": true, "text": "<p>This one puzzled me for for about 30 minutes.</p>\n\n<p>First off, you probably need a UAC manifest embedded in your app (<a href=\"https://stackoverflow.com/questions/53208/how-do-i-automatically-destroy-child-processes-in-windows#53214\">as suggested here</a>). Something like this:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?&gt;\n &lt;assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\"&gt;\n &lt;!-- Identify the application security requirements. --&gt;\n &lt;trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\"&gt;\n &lt;security&gt;\n &lt;requestedPrivileges&gt;\n &lt;requestedExecutionLevel\n level=\"asInvoker\"\n uiAccess=\"false\"/&gt;\n &lt;/requestedPrivileges&gt;\n &lt;/security&gt;\n &lt;/trustInfo&gt;\n &lt;/assembly&gt;\n</code></pre>\n\n<p>Secondly (and this is the bit I got stuck on), when you are running your app under the debugger, it creates your process in a job object. Which your child process needs to be able to breakaway from before you can assign it to your job. So (duh), you need to specify <code>CREATE_BREAKAWAY_FROM_JOB</code> in the flags for <code>CreateProcess</code>).</p>\n\n<p>If you weren't running under the debugger, or your parent process were in the job, this wouldn't have happened.</p>\n" }, { "answer_id": 9200935, "author": "Cameron", "author_id": 86375, "author_profile": "https://Stackoverflow.com/users/86375", "pm_score": 3, "selected": false, "text": "<p>This seems to bite me quite often, and while good, 1800INFORMATION's post doesn't seem to include a number of reasons and fixes that seem helpful, so it seem worthwhile to post a summary of why I've seen this happen.</p>\n\n<ol>\n<li>When trying to solve this for yourself, note than this problem\ncan occur for different reasons when running from CMD.EXE, Explorer,\nand Visual Studio. Trying to run the failing executable from the\nrespective places can help identify the cause of the problem. You\napp may just work find from CMD.EXE in spite of failing from V.S.\nand Explorer.exe</li>\n<li>In my case, under Win7, I seemed to need to un-comment the \"supportedOS\"\nelement indicating Win7 compatibility from the app.manifest\nfile. This seems to fix the problem when running from Explorer. To\nadd a manifest, right click on the project, hit Add, and find\n'Application Manifest File'.</li>\n<li>To get Visual Studio 2010 working, I seemed to need to stop it from using the Program Compatibility Assistant, Tom Minka shares two ways to do this here: <a href=\"https://stackoverflow.com/a/4232259/86375\">https://stackoverflow.com/a/4232259/86375</a>, note, I had to restart VS2010 to take his suggested changes.</li>\n</ol>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
You do `AssignProcessToJobObject` and it fails with "access denied" but only when you are running in the debugger. Why is this?
This one puzzled me for for about 30 minutes. First off, you probably need a UAC manifest embedded in your app ([as suggested here](https://stackoverflow.com/questions/53208/how-do-i-automatically-destroy-child-processes-in-windows#53214)). Something like this: ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <!-- Identify the application security requirements. --> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> ``` Secondly (and this is the bit I got stuck on), when you are running your app under the debugger, it creates your process in a job object. Which your child process needs to be able to breakaway from before you can assign it to your job. So (duh), you need to specify `CREATE_BREAKAWAY_FROM_JOB` in the flags for `CreateProcess`). If you weren't running under the debugger, or your parent process were in the job, this wouldn't have happened.
89,607
<p>I have added some code which compiles cleanly and have just received this Windows error:</p> <pre><code>--------------------------- (MonTel Administrator) 2.12.7: MtAdmin.exe - Application Error --------------------------- The exception Privileged instruction. (0xc0000096) occurred in the application at location 0x00486752. </code></pre> <p>I am about to go on a bug hunt, and I am expecting it to be something silly that I have done which just happens to produce this message. The code compiles cleanly with no errors or warnings. The size of the EXE file has grown to 1,454,132 bytes and includes links to <code>ODCS.lib</code>, but it is otherwise pure C to the Win32 API, with DEBUG on (running on a P4 on Windows&nbsp;2000).</p>
[ { "answer_id": 89643, "author": "Tim Williscroft", "author_id": 2789, "author_profile": "https://Stackoverflow.com/users/2789", "pm_score": 2, "selected": false, "text": "<p>I saw this with Visual c++ 6.0 in the year 2000.</p>\n\n<p>The debug C++ library had calls to physical I/O instructions in it, in an exception handler.\nIf I remember correctly, it was dumping status to an I/O port that used to be for DMA base registers, which I assume someone at Microsoft was using for a debugger card.</p>\n\n<p>Look for some error condition that might be latent causing diagnostics code to run.</p>\n\n<p>I was debugging, backtracked and read the dissassembly. It was an exception while processing <code>std::string</code>, maybe indexing off the end.</p>\n" }, { "answer_id": 89653, "author": "Daniel", "author_id": 6852, "author_profile": "https://Stackoverflow.com/users/6852", "pm_score": 3, "selected": false, "text": "<p>This sort of thing usually happens when using function pointers that point to invalid data.\nIt can also happen if you have code that trashes your return stack. It can sometimes be quite tricky to track these sort of bugs down because they usually are hard to reproduce.</p>\n" }, { "answer_id": 89654, "author": "artificialidiot", "author_id": 7988, "author_profile": "https://Stackoverflow.com/users/7988", "pm_score": 2, "selected": false, "text": "<p>First probability that I can think of is, you may be using a local array and it is near the top of the function declaration. Your bounds checking gone insane and overwrite the return address and it points to some instruction that only kernel is allowed to execute.</p>\n" }, { "answer_id": 89655, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 3, "selected": false, "text": "<p>A privileged instruction is an IA-32 instruction that is only allowed to be executed in Ring-0 (i.e. kernel mode). If you're hitting this in userspace, you've either got a really old EXE, or a corrupted binary.</p>\n" }, { "answer_id": 89674, "author": "Jeremy", "author_id": 3657, "author_profile": "https://Stackoverflow.com/users/3657", "pm_score": 2, "selected": false, "text": "<p>The error location 0x00486752 seems really small to me, before where executable code usually lives. I agree with Daniel, it looks like a wild pointer to me.</p>\n" }, { "answer_id": 89716, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 6, "selected": true, "text": "<p>To answer the question, a privileged instruction is a processor op-code (assembler instruction) which can only be executed in \"supervisor\" (or Ring-0) mode.\nThese types of instructions tend to be used to access I/O devices and protected data structures from the windows kernel.</p>\n\n<p>Regular programs execute in \"user mode\" (Ring-3) which disallows direct access to I/O devices, etc...</p>\n\n<p>As others mentioned, the cause is probably a corrupted stack or a messed up function pointer call.</p>\n" }, { "answer_id": 89856, "author": "David L Morris", "author_id": 3137, "author_profile": "https://Stackoverflow.com/users/3137", "pm_score": 3, "selected": false, "text": "<p>As I suspected, it was something silly that I did. I think I solved this twice as fast because of some of the clues in comments in the messages above. Thanks to those, especially those who pointed to something early in the app overwriting the stack. I actually found several answers here more useful than the post I have marked as answering the question as they clued and queued me as to where to look, though I think it best sums up the answer.</p>\n<p>As it turned out, I had just added a button that went over the maximum size of an array holding some toolbar button information (which was on the stack). I had forgotten that</p>\n<pre>\n#define MAX_NUM_TOOBAR_BUTTONS (24)\n</pre>\n<p>even existed!</p>\n" }, { "answer_id": 1661038, "author": "Maliha Atteeq", "author_id": 200926, "author_profile": "https://Stackoverflow.com/users/200926", "pm_score": 2, "selected": false, "text": "<p>The CPU of most processors manufactured in the last 15 years have some special instructions which are very powerful. These privileged instructions are kept for operating system kernel applications and are not able to be used by user written programs.</p>\n\n<p>This restricts the damage that a user-written program can inflict upon the system and cuts down the number of times that the system actually crashes. </p>\n" }, { "answer_id": 4423487, "author": "Bushara", "author_id": 539780, "author_profile": "https://Stackoverflow.com/users/539780", "pm_score": 2, "selected": false, "text": "<p>When executing in kernel mode, the operating system has unrestricted access to both the kernel and the user program's memory.</p>\n\n<p>The load instructions for the base and limit registers are privileged instructions.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3137/" ]
I have added some code which compiles cleanly and have just received this Windows error: ``` --------------------------- (MonTel Administrator) 2.12.7: MtAdmin.exe - Application Error --------------------------- The exception Privileged instruction. (0xc0000096) occurred in the application at location 0x00486752. ``` I am about to go on a bug hunt, and I am expecting it to be something silly that I have done which just happens to produce this message. The code compiles cleanly with no errors or warnings. The size of the EXE file has grown to 1,454,132 bytes and includes links to `ODCS.lib`, but it is otherwise pure C to the Win32 API, with DEBUG on (running on a P4 on Windows 2000).
To answer the question, a privileged instruction is a processor op-code (assembler instruction) which can only be executed in "supervisor" (or Ring-0) mode. These types of instructions tend to be used to access I/O devices and protected data structures from the windows kernel. Regular programs execute in "user mode" (Ring-3) which disallows direct access to I/O devices, etc... As others mentioned, the cause is probably a corrupted stack or a messed up function pointer call.
89,609
<p>I'm looking for the best way to take a simple input:</p> <pre><code>echo -n "Enter a string here: " read -e STRING </code></pre> <p>and clean it up by removing non-alphanumeric characters, lower(case), and replacing spaces with underscores.</p> <p>Does order matter? Is <code>tr</code> the best / only way to go about this?</p>
[ { "answer_id": 89642, "author": "Devin Reams", "author_id": 16248, "author_profile": "https://Stackoverflow.com/users/16248", "pm_score": 0, "selected": false, "text": "<p>After a bit of looking around it seems <code>tr</code> is indeed the simplest way:</p>\n\n<pre><code>export CLEANSTRING=\"`echo -n \"${STRING}\" | tr -cd '[:alnum:] [:space:]' | tr '[:space:]' '-' | tr '[:upper:]' '[:lower:]'`\"\n</code></pre>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Occam&#39;s_Razor\" rel=\"nofollow noreferrer\">Occam's razor</a>, I suppose.</p>\n" }, { "answer_id": 89780, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 0, "selected": false, "text": "<p>You could run it through perl.</p>\n\n<pre><code>export CLEANSTRING=$(perl -e 'print join( q//, map { s/\\\\s+/_/g; lc } split /[^\\\\s\\\\w]+/, \\$ENV{STRING} )')\n</code></pre>\n\n<p>I'm using ksh-style subshell here, I'm not totally sure that it works in bash.</p>\n\n<p>That's the nice thing about shell, is that you can use perl, awk, sed, grep....</p>\n" }, { "answer_id": 89970, "author": "dj_segfault", "author_id": 14924, "author_profile": "https://Stackoverflow.com/users/14924", "pm_score": 5, "selected": false, "text": "<p>Bash can do this all on it's own, thank you very much. If you look at the section of the man page on <strong>Parameter Expansion</strong>, you'll see that that bash has built-in substitutions, substring, trim, rtrim, etc. </p>\n\n<p>To eliminate all non-alphanumeric characters, do </p>\n\n<pre><code>CLEANSTRING=${STRING//[^a-zA-Z0-9]/}\n</code></pre>\n\n<p><strong>That's</strong> Occam's razor. No need to launch another process.</p>\n" }, { "answer_id": 94500, "author": "Thomee", "author_id": 12825, "author_profile": "https://Stackoverflow.com/users/12825", "pm_score": 7, "selected": true, "text": "<p>As dj_segfault points out, the shell can do most of this for you. Looks like you'll have to fall back on something external for lower-casing the string, though. For this you have many options, like the perl one-liners above, etc., but I think tr is probably the simplest.</p>\n\n<pre><code># first, strip underscores\nCLEAN=${STRING//_/}\n# next, replace spaces with underscores\nCLEAN=${CLEAN// /_}\n# now, clean out anything that's not alphanumeric or an underscore\nCLEAN=${CLEAN//[^a-zA-Z0-9_]/}\n# finally, lowercase with TR\nCLEAN=`echo -n $CLEAN | tr A-Z a-z`\n</code></pre>\n\n<p>The order here is somewhat important. We want to get rid of underscores, plus replace spaces with underscores, so we have to be sure to strip underscores first. By waiting to pass things to tr until the end, we know we have only alphanumeric and underscores, and we can be sure we have no spaces, so we don't have to worry about special characters being interpreted by the shell.</p>\n" }, { "answer_id": 59919397, "author": "anon_stackoverflock", "author_id": 5800081, "author_profile": "https://Stackoverflow.com/users/5800081", "pm_score": 2, "selected": false, "text": "<p>For <strong>Bash >= 4.0</strong>:</p>\n\n<pre><code>CLEAN=\"${STRING//_/}\" &amp;&amp; \\\nCLEAN=\"${CLEAN// /_}\" &amp;&amp; \\\nCLEAN=\"${CLEAN//[^a-zA-Z0-9]/}\" &amp;&amp; \\\nCLEAN=\"${CLEAN,,}\"\n</code></pre>\n\n<p>This is especially useful for creating container names programmatically using docker/podman. However, in this case you'll also want to remove the underscores:</p>\n\n<pre><code># Sanitize $STRING for a container name\nCLEAN=\"${STRING//[^a-zA-Z0-9]/}\" &amp;&amp; \\\nCLEAN=\"${CLEAN,,}\"\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16248/" ]
I'm looking for the best way to take a simple input: ``` echo -n "Enter a string here: " read -e STRING ``` and clean it up by removing non-alphanumeric characters, lower(case), and replacing spaces with underscores. Does order matter? Is `tr` the best / only way to go about this?
As dj\_segfault points out, the shell can do most of this for you. Looks like you'll have to fall back on something external for lower-casing the string, though. For this you have many options, like the perl one-liners above, etc., but I think tr is probably the simplest. ``` # first, strip underscores CLEAN=${STRING//_/} # next, replace spaces with underscores CLEAN=${CLEAN// /_} # now, clean out anything that's not alphanumeric or an underscore CLEAN=${CLEAN//[^a-zA-Z0-9_]/} # finally, lowercase with TR CLEAN=`echo -n $CLEAN | tr A-Z a-z` ``` The order here is somewhat important. We want to get rid of underscores, plus replace spaces with underscores, so we have to be sure to strip underscores first. By waiting to pass things to tr until the end, we know we have only alphanumeric and underscores, and we can be sure we have no spaces, so we don't have to worry about special characters being interpreted by the shell.
89,650
<p>I would like to pass an argument(s) to a method being defined using define_method, how would I do that?</p>
[ { "answer_id": 89661, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 9, "selected": true, "text": "<p>The block that you pass to define_method can include some parameters. That's how your defined method accepts arguments. When you define a method you're really just nicknaming the block and keeping a reference to it in the class. The parameters come with the block. So:</p>\n\n<pre><code>define_method(:say_hi) { |other| puts \"Hi, \" + other }\n</code></pre>\n" }, { "answer_id": 109379, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 6, "selected": false, "text": "<p>In addition to Kevin Conner's answer: block arguments do not support the same semantics as method arguments. You cannot define default arguments or block arguments.</p>\n\n<p>This is only fixed in Ruby 1.9 with the new alternative \"stabby lambda\" syntax which supports full method argument semantics.</p>\n\n<p>Example:</p>\n\n<pre><code># Works\ndef meth(default = :foo, *splat, &amp;block) puts 'Bar'; end\n\n# Doesn't work\ndefine_method :meth { |default = :foo, *splat, &amp;block| puts 'Bar' }\n\n# This works in Ruby 1.9 (modulo typos, I don't actually have it installed)\ndefine_method :meth, -&gt;(default = :foo, *splat, &amp;block) { puts 'Bar' }\n</code></pre>\n" }, { "answer_id": 11098487, "author": "equivalent8", "author_id": 473040, "author_profile": "https://Stackoverflow.com/users/473040", "pm_score": 7, "selected": false, "text": "<p>... and if you want optional parameters</p>\n\n<pre><code> class Bar\n define_method(:foo) do |arg=nil| \n arg \n end \n end\n\n a = Bar.new\n a.foo\n #=&gt; nil\n a.foo 1\n # =&gt; 1\n</code></pre>\n\n<p>... as many arguments as you want</p>\n\n<pre><code> class Bar\n define_method(:foo) do |*arg| \n arg \n end \n end\n\n a = Bar.new\n a.foo\n #=&gt; []\n a.foo 1\n # =&gt; [1]\n a.foo 1, 2 , 'AAA'\n # =&gt; [1, 2, 'AAA']\n</code></pre>\n\n<p>...combination of </p>\n\n<pre><code> class Bar\n define_method(:foo) do |bubla,*arg|\n p bubla \n p arg \n end \n end\n\n a = Bar.new\n a.foo\n #=&gt; wrong number of arguments (0 for 1)\n a.foo 1\n # 1\n # []\n\n a.foo 1, 2 ,3 ,4\n # 1\n # [2,3,4]\n</code></pre>\n\n<p>... all of them</p>\n\n<pre><code> class Bar\n define_method(:foo) do |variable1, variable2,*arg, &amp;block| \n p variable1 \n p variable2\n p arg\n p block.inspect \n end \n end\n a = Bar.new \n a.foo :one, 'two', :three, 4, 5 do\n 'six'\n end\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<p>Ruby 2.0 introduced double splat <code>**</code> (two stars) which (<a href=\"https://stackoverflow.com/questions/18289152/what-does-a-double-splat-operator-do\">I quote</a>) does: </p>\n\n<blockquote>\n <p>Ruby 2.0 introduced keyword arguments, and ** acts like *, but for keyword arguments. It returns a Hash with key / value pairs.</p>\n</blockquote>\n\n<p>...and of course you can use it in define method too :) </p>\n\n<pre><code> class Bar \n define_method(:foo) do |variable1, variable2,*arg,**options, &amp;block|\n p variable1\n p variable2\n p arg\n p options\n p block.inspect\n end \n end \n a = Bar.new\n a.foo :one, 'two', :three, 4, 5, ruby: 'is awesome', foo: :bar do\n 'six'\n end\n# :one\n# \"two\"\n# [:three, 4, 5]\n# {:ruby=&gt;\"is awesome\", :foo=&gt;:bar}\n</code></pre>\n\n<p>Named attributes example:</p>\n\n<pre><code> class Bar\n define_method(:foo) do |variable1, color: 'blue', **other_options, &amp;block|\n p variable1\n p color\n p other_options\n p block.inspect\n end\n end\n a = Bar.new\n a.foo :one, color: 'red', ruby: 'is awesome', foo: :bar do\n 'six'\n end\n# :one\n# \"red\"\n# {:ruby=&gt;\"is awesome\", :foo=&gt;:bar}\n</code></pre>\n\n<p>I was trying to create example with keyword argument, splat and double splat all in one:</p>\n\n<pre><code> define_method(:foo) do |variable1, variable2,*arg, i_will_not: 'work', **options, &amp;block|\n # ...\n</code></pre>\n\n<p>or </p>\n\n<pre><code> define_method(:foo) do |variable1, variable2, i_will_not: 'work', *arg, **options, &amp;block|\n # ...\n</code></pre>\n\n<p>... but this will not work, it looks like there is a limitation. When you think about it makes sense as splat operator is \"capturing all remaining arguments\" and double splat is \"capturing all remaining keyword arguments\" therefore mixing them would break expected logic. (I don't have any reference to prove this point doh! )</p>\n\n<p><strong>update 2018 August:</strong></p>\n\n<p>Summary article: <a href=\"https://blog.eq8.eu/til/metaprogramming-ruby-examples.html\" rel=\"noreferrer\">https://blog.eq8.eu/til/metaprogramming-ruby-examples.html</a></p>\n" }, { "answer_id": 37006132, "author": "akostadinov", "author_id": 520567, "author_profile": "https://Stackoverflow.com/users/520567", "pm_score": 3, "selected": false, "text": "<p>With 2.2 you can now use keyword arguments:\n<a href=\"https://robots.thoughtbot.com/ruby-2-keyword-arguments\" rel=\"noreferrer\">https://robots.thoughtbot.com/ruby-2-keyword-arguments</a></p>\n\n<pre><code>define_method(:method) do |refresh: false|\n ..........\nend\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ]
I would like to pass an argument(s) to a method being defined using define\_method, how would I do that?
The block that you pass to define\_method can include some parameters. That's how your defined method accepts arguments. When you define a method you're really just nicknaming the block and keeping a reference to it in the class. The parameters come with the block. So: ``` define_method(:say_hi) { |other| puts "Hi, " + other } ```
89,705
<p>I'm going through the problems on projecteuler.net to learn how to program in Erlang, and I am having the hardest time creating a prime generator that can create all of the primes below 2 million, in less than a minute. Using the sequential style, I have already written three types of generators, including the Sieve of Eratosthenes, and none of them perform well enough.</p> <p>I figured a concurrent Sieve would work great, but I'm getting bad_arity messages, and I'm not sure why. Any suggestions on why I have the problem, or how to code it properly? </p> <p>Here's my code, the commented out sections are where I tried to make things concurrent:</p> <pre> -module(primeserver). -compile(export_all). start() -> register(primes, spawn(fun() -> loop() end)). is_prime(N) -> rpc({is_prime,N}). rpc(Request) -> primes ! {self(), Request}, receive {primes, Response} -> Response end. loop() -> receive {From, {is_prime, N}} -> if N From ! {primes, false}; N =:= 2 -> From ! {primes, true}; N rem 2 =:= 0 -> From ! {primes, false}; true -> Values = is_not_prime(N), Val = not(lists:member(true, Values)), From ! {primes, Val} end, loop() end. for(N,N,_,F) -> [F(N)]; for(I,N,S,F) when I + S [F(I)|for(I+S, N, S, F)]; for(I,N,S,F) when I + S =:= N -> [F(I)|for(I+S, N, S, F)]; for(I,N,S,F) when I + S > N -> [F(I)]. get_list(I, Limit) -> if I [I*A || A [] end. is_not_prime(N) -> for(3, N, 2, fun(I) -> List = get_list(I,trunc(N/I)), lists:member(N,lists:flatten(List)) end ). %%L = for(1,N, fun() -> spawn(fun(I) -> wait(I,N) end) end), %%SeedList = [A || A %% lists:foreach(fun(X) -> %% Pid ! {in_list, X} %% end, SeedList) %% end, L). %%wait(I,N) -> %% List = [I*A || A lists:member(X,List) %% end. </pre>
[ { "answer_id": 89726, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": -1, "selected": false, "text": "<p>I love Project Euler.</p>\n\n<p>On the subject of prime generators, I am a big fan of the Sieve of Eratosthenes.</p>\n\n<p>For the purposes of the numbers under 2,000,000 you might try a simple isPrime check implementation. I don't know how you'd do it in erlang, but the logic is simple.</p>\n\n<pre><code>For Each NUMBER in LIST_OF_PRIMES\n If TEST_VALUE % NUMBER == 0\n Then FALSE\nEND\nTRUE\n\nif isPrime == TRUE add TEST_VALUE to your LIST_OF_PRIMES\n\niterate starting at 14 or so with a preset list of your beginning primes. \n</code></pre>\n\n<p>c# ran a list like this for 2,000,000 in well under the 1 minute mark</p>\n\n<p><strong>Edit:</strong> <em>On a side note, the sieve of Eratosthenes can be implemented easily and runs quickly, but gets unwieldy when you start getting into huge lists. The simplest implementation, using a boolean array and int values runs extremely quickly. The trouble is that you begin running into limits for the size of your value as well as the length of your array. -- Switching to a string or bitarray implementation helps, but you still have the challenge of iterating through your list at large values.</em> </p>\n" }, { "answer_id": 89727, "author": "Jason Punyon", "author_id": 6212, "author_profile": "https://Stackoverflow.com/users/6212", "pm_score": -1, "selected": false, "text": "<p>Project Euler problems (I'd say most of the first 50 if not more) are mostly about brute force with a splash of ingenuity in choosing your bounds.</p>\n\n<p>Remember to test any if N is prime (by brute force), you only need to see if its divisible by any prime up to floor(sqrt(N)) + 1, not N/2.</p>\n\n<p>Good luck</p>\n" }, { "answer_id": 90036, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 0, "selected": false, "text": "<p>The Sieve of Eratosthenes is fairly easy to implement but -- as you have discovered -- not the most efficient. Have you tried the Sieve of Atkin?</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Sieve_of_Atkin\" rel=\"nofollow noreferrer\">Sieve of Atkin @ Wikipedia</a></p>\n" }, { "answer_id": 90770, "author": "Roskoto", "author_id": 13635, "author_profile": "https://Stackoverflow.com/users/13635", "pm_score": 1, "selected": false, "text": "<p>Primes parallel algorithm : <a href=\"http://www.cs.cmu.edu/~scandal/cacm/node8.html\" rel=\"nofollow noreferrer\">http://www.cs.cmu.edu/~scandal/cacm/node8.html</a></p>\n" }, { "answer_id": 94249, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Another alternative to consider is to use probabalistic prime generation. There is an example of this in Joe's book (the \"prime server\") which uses Miller-Rabin I think...</p>\n" }, { "answer_id": 113878, "author": "uwiger", "author_id": 6834, "author_profile": "https://Stackoverflow.com/users/6834", "pm_score": 3, "selected": true, "text": "<p>The 'badarity' error means that you're trying to call a 'fun' with the wrong number of arguments. In this case...</p>\n\n<p>%%L = for(1,N, fun() -> spawn(fun(I) -> wait(I,N) end) end),</p>\n\n<p>The for/3 function expects a fun of arity 1, and the spawn/1 function expects a fun of arity 0. Try this instead:</p>\n\n<pre><code>L = for(1, N, fun(I) -&gt; spawn(fun() -&gt; wait(I, N) end) end),\n</code></pre>\n\n<p>The fun passed to spawn inherits needed parts of its environment (namely I), so there's no need to pass it explicitly.</p>\n\n<p>While calculating primes is always good fun, please keep in mind that this is not the kind of problem Erlang was designed to solve. Erlang was designed for massive actor-style concurrency. It will most likely perform rather badly on all examples of data-parallel computation. In many cases, <a href=\"http://home.mindspring.com/~eric_rollins/erlangAnt.html\" rel=\"nofollow noreferrer\">a sequential solution in, say, ML</a> will be so fast that any number of cores will not suffice for Erlang to catch up, and e.g. <a href=\"http://undirectedgrad.blogspot.com/2007/12/f-and-task-parallel-library.html\" rel=\"nofollow noreferrer\">F# and the .NET Task Parallel Library</a> would certainly be a much better vehicle for these kinds of operations.</p>\n" }, { "answer_id": 479965, "author": "Bruno Rijsman", "author_id": 21435, "author_profile": "https://Stackoverflow.com/users/21435", "pm_score": 1, "selected": false, "text": "<p>You can find four different Erlang implementations for finding prime numbers (two of which are based on the Sieve of Eratosthenes) <a href=\"http://caylespandon.blogspot.com/2009/01/in-euler-problem-10-we-are-asked-to.html\" rel=\"nofollow noreferrer\">here</a>. This link also contains graphs comparing the performance of the 4 solutions.</p>\n" }, { "answer_id": 634799, "author": "dbasnett", "author_id": 66532, "author_profile": "https://Stackoverflow.com/users/66532", "pm_score": -1, "selected": false, "text": "<p>here is a vb version </p>\n\n<pre><code> 'Sieve of Eratosthenes \n'http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes \n'1. Create a contiguous list of numbers from two to some highest number n. \n'2. Strike out from the list all multiples of two (4, 6, 8 etc.). \n'3. The list's next number that has not been struck out is a prime number. \n'4. Strike out from the list all multiples of the number you identified in the previous step. \n'5. Repeat steps 3 and 4 until you reach a number that is greater than the square root of n (the highest number in the list). \n'6. All the remaining numbers in the list are prime. \nPrivate Function Sieve_of_Eratosthenes(ByVal MaxNum As Integer) As List(Of Integer)\n 'tested to MaxNum = 10,000,000 - on 1.8Ghz Laptop it took 1.4 seconds\n Dim thePrimes As New List(Of Integer)\n Dim toNum As Integer = MaxNum, stpw As New Stopwatch\n If toNum &gt; 1 Then 'the first prime is 2\n stpw.Start()\n thePrimes.Capacity = toNum 'size the list\n Dim idx As Integer\n Dim stopAT As Integer = CInt(Math.Sqrt(toNum) + 1)\n '1. Create a contiguous list of numbers from two to some highest number n.\n '2. Strike out from the list all multiples of 2, 3, 5. \n For idx = 0 To toNum\n If idx &gt; 5 Then\n If idx Mod 2 &lt;&gt; 0 _\n AndAlso idx Mod 3 &lt;&gt; 0 _\n AndAlso idx Mod 5 &lt;&gt; 0 Then thePrimes.Add(idx) Else thePrimes.Add(-1)\n Else\n thePrimes.Add(idx)\n End If\n Next\n 'mark 0,1 and 4 as non-prime\n thePrimes(0) = -1\n thePrimes(1) = -1\n thePrimes(4) = -1\n Dim aPrime, startAT As Integer\n idx = 7 'starting at 7 check for primes and multiples \n Do\n '3. The list's next number that has not been struck out is a prime number. \n '4. Strike out from the list all multiples of the number you identified in the previous step. \n '5. Repeat steps 3 and 4 until you reach a number that is greater than the square root of n (the highest number in the list). \n If thePrimes(idx) &lt;&gt; -1 Then ' if equal to -1 the number is not a prime\n 'not equal to -1 the number is a prime\n aPrime = thePrimes(idx)\n 'get rid of multiples \n startAT = aPrime * aPrime\n For mltpl As Integer = startAT To thePrimes.Count - 1 Step aPrime\n If thePrimes(mltpl) &lt;&gt; -1 Then thePrimes(mltpl) = -1\n Next\n End If\n idx += 2 'increment index \n Loop While idx &lt; stopAT\n '6. All the remaining numbers in the list are prime. \n thePrimes = thePrimes.FindAll(Function(i As Integer) i &lt;&gt; -1)\n stpw.Stop()\n Debug.WriteLine(stpw.ElapsedMilliseconds)\n End If\n Return thePrimes\nEnd Function\n</code></pre>\n" }, { "answer_id": 1343326, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Two quick single-process erlang prime generators; sprimes generates all primes under 2m in ~2.7 seconds, fprimes ~3 seconds on my computer (Macbook with a 2.4 GHz Core 2 Duo). Both are based on the Sieve of Eratosthenes, but since Erlang works best with lists, rather than arrays, both keep a list of non-eliminated primes, checking for divisibility by the current head and keeping an accumulator of verified primes. Both also implement a prime wheel to do initial reduction of the list.</p>\n\n<pre><code>-module(primes).\n-export([sprimes/1, wheel/3, fprimes/1, filter/2]). \n\nsieve([H|T], M) when H=&lt; M -&gt; [H|sieve([X || X&lt;- T, X rem H /= 0], M)];\nsieve(L, _) -&gt; L.\nsprimes(N) -&gt; [2,3,5,7|sieve(wheel(11, [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10], N), math:sqrt(N))].\n\nwheel([X|Xs], _Js, M) when X &gt; M -&gt;\n lists:reverse(Xs);\nwheel([X|Xs], [J|Js], M) -&gt;\n wheel([X+J,X|Xs], lazy:next(Js), M);\nwheel(S, Js, M) -&gt;\n wheel([S], lazy:lazy(Js), M).\n\nfprimes(N) -&gt;\n fprimes(wheel(11, [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10], N), [7,5,3,2], N).\nfprimes([H|T], A, Max) when H*H =&lt; Max -&gt;\n fprimes(filter(H, T), [H|A], Max);\nfprimes(L, A, _Max) -&gt; lists:append(lists:reverse(A), L).\n\nfilter(N, L) -&gt;\n filter(N, N*N, L, []).\nfilter(N, N2, [X|Xs], A) when X &lt; N2 -&gt;\n filter(N, N2, Xs, [X|A]);\nfilter(N, _N2, L, A) -&gt;\n filter(N, L, A).\nfilter(N, [X|Xs], A) when X rem N /= 0 -&gt;\n filter(N, Xs, [X|A]);\nfilter(N, [_X|Xs], A) -&gt;\n filter(N, Xs, A);\nfilter(_N, [], A) -&gt;\n lists:reverse(A).\n</code></pre>\n\n<p>lazy:lazy/1 and lazy:next/1 refer to a simple implementation of pseudo-lazy infinite lists:</p>\n\n<pre><code>lazy(L) -&gt;\n repeat(L).\n\nrepeat(L) -&gt; L++[fun() -&gt; L end].\n\nnext([F]) -&gt; F()++[F];\nnext(L) -&gt; L.\n</code></pre>\n\n<p>Prime generation by sieves is not a great place for concurrency (but it could use parallelism in checking for divisibility, although the operation is not sufficiently complex to justify the additional overhead of all parallel filters I have written thus far).</p>\n\n<p>`</p>\n" }, { "answer_id": 2391751, "author": "Hai-Anh Trinh", "author_id": 191069, "author_profile": "https://Stackoverflow.com/users/191069", "pm_score": 3, "selected": false, "text": "<p>I wrote an Eratosthenesque concurrent prime sieve using the Go and channels.</p>\n\n<p>Here is the code: <a href=\"http://github.com/aht/gosieve\" rel=\"noreferrer\">http://github.com/aht/gosieve</a></p>\n\n<p>I blogged about it here: <a href=\"http://blog.onideas.ws/eratosthenes.go\" rel=\"noreferrer\">http://blog.onideas.ws/eratosthenes.go</a></p>\n\n<p>The program can sieve out the first million primes (all primes upto 15,485,863) in about 10 seconds. The sieve is concurrent, but the algorithm is mainly synchronous: there are far too many synchronization points required between goroutines (\"actors\" -- if you like) and thus they can not roam freely in parallel.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8040/" ]
I'm going through the problems on projecteuler.net to learn how to program in Erlang, and I am having the hardest time creating a prime generator that can create all of the primes below 2 million, in less than a minute. Using the sequential style, I have already written three types of generators, including the Sieve of Eratosthenes, and none of them perform well enough. I figured a concurrent Sieve would work great, but I'm getting bad\_arity messages, and I'm not sure why. Any suggestions on why I have the problem, or how to code it properly? Here's my code, the commented out sections are where I tried to make things concurrent: ``` -module(primeserver). -compile(export_all). start() -> register(primes, spawn(fun() -> loop() end)). is_prime(N) -> rpc({is_prime,N}). rpc(Request) -> primes ! {self(), Request}, receive {primes, Response} -> Response end. loop() -> receive {From, {is_prime, N}} -> if N From ! {primes, false}; N =:= 2 -> From ! {primes, true}; N rem 2 =:= 0 -> From ! {primes, false}; true -> Values = is_not_prime(N), Val = not(lists:member(true, Values)), From ! {primes, Val} end, loop() end. for(N,N,_,F) -> [F(N)]; for(I,N,S,F) when I + S [F(I)|for(I+S, N, S, F)]; for(I,N,S,F) when I + S =:= N -> [F(I)|for(I+S, N, S, F)]; for(I,N,S,F) when I + S > N -> [F(I)]. get_list(I, Limit) -> if I [I*A || A [] end. is_not_prime(N) -> for(3, N, 2, fun(I) -> List = get_list(I,trunc(N/I)), lists:member(N,lists:flatten(List)) end ). %%L = for(1,N, fun() -> spawn(fun(I) -> wait(I,N) end) end), %%SeedList = [A || A %% lists:foreach(fun(X) -> %% Pid ! {in_list, X} %% end, SeedList) %% end, L). %%wait(I,N) -> %% List = [I*A || A lists:member(X,List) %% end. ```
The 'badarity' error means that you're trying to call a 'fun' with the wrong number of arguments. In this case... %%L = for(1,N, fun() -> spawn(fun(I) -> wait(I,N) end) end), The for/3 function expects a fun of arity 1, and the spawn/1 function expects a fun of arity 0. Try this instead: ``` L = for(1, N, fun(I) -> spawn(fun() -> wait(I, N) end) end), ``` The fun passed to spawn inherits needed parts of its environment (namely I), so there's no need to pass it explicitly. While calculating primes is always good fun, please keep in mind that this is not the kind of problem Erlang was designed to solve. Erlang was designed for massive actor-style concurrency. It will most likely perform rather badly on all examples of data-parallel computation. In many cases, [a sequential solution in, say, ML](http://home.mindspring.com/~eric_rollins/erlangAnt.html) will be so fast that any number of cores will not suffice for Erlang to catch up, and e.g. [F# and the .NET Task Parallel Library](http://undirectedgrad.blogspot.com/2007/12/f-and-task-parallel-library.html) would certainly be a much better vehicle for these kinds of operations.
89,708
<p>I am trying to extract a gif image embedded as a resource within my ISAPI dll using WebBroker technology. The resource has been added to the DLL using the following RC code:</p> <pre><code>LOGO_GIF RCDATA logo.gif </code></pre> <p>Using resource explorer I verified it is in the DLL properly.</p> <p>using the following code always throws an exception, "resource not found" (using Delphi 2009)</p> <pre><code>var rc : tResourceStream; begin rc := tResourceStream.Create(hInstance,'LOGO_GIF','RCDATA'); end; </code></pre>
[ { "answer_id": 90236, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 1, "selected": false, "text": "<p>If I remember correctly you are actually dealing with an instance of the web server, not the dll. I don't remember the work around though, but that is the explanation for why that doesn't work. Hopefully someone else can build off of this.</p>\n" }, { "answer_id": 90496, "author": "Tim Knipe", "author_id": 10493, "author_profile": "https://Stackoverflow.com/users/10493", "pm_score": 3, "selected": true, "text": "<p>RCDATA is a <a href=\"http://msdn.microsoft.com/en-us/library/aa381039(VS.85).aspx\" rel=\"nofollow noreferrer\">pre-defined</a> resource type with an integer ID of RT_RCDATA (declared in Types unit).</p>\n\n<p>Try accessing it this way:</p>\n\n<pre><code>rc := tResourceStream.Create(hInstance,'LOGO_GIF', MakeIntResource(RT_RCDATA));\n</code></pre>\n" }, { "answer_id": 90742, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 1, "selected": false, "text": "<p>Either use your own arbitrary resource type like GIF: </p>\n\n<pre><code>LOGO_GIF GIF logo.gif\n</code></pre>\n\n<p>then use </p>\n\n<pre><code>rc := tResourceStream.Create(hInstance,'LOGO_GIF','GIF'); \n</code></pre>\n\n<p>or simply use </p>\n\n<pre><code>rc := tResourceStream.Create(hInstance,'LOGO_GIF', RT_RCDATA); \n</code></pre>\n" }, { "answer_id": 1164249, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>or simply use </p>\n \n <p>rc := tResourceStream.Create(hInstance,'LOGO_GIF', <strong>RT__RCDATA</strong>);</p>\n</blockquote>\n\n<p>This. Works like a charm. </p>\n\n<p>D2009 here, too, had the same issue, but was trying to get TStringsList out of the DLL.</p>\n\n<p>Thanks.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9217/" ]
I am trying to extract a gif image embedded as a resource within my ISAPI dll using WebBroker technology. The resource has been added to the DLL using the following RC code: ``` LOGO_GIF RCDATA logo.gif ``` Using resource explorer I verified it is in the DLL properly. using the following code always throws an exception, "resource not found" (using Delphi 2009) ``` var rc : tResourceStream; begin rc := tResourceStream.Create(hInstance,'LOGO_GIF','RCDATA'); end; ```
RCDATA is a [pre-defined](http://msdn.microsoft.com/en-us/library/aa381039(VS.85).aspx) resource type with an integer ID of RT\_RCDATA (declared in Types unit). Try accessing it this way: ``` rc := tResourceStream.Create(hInstance,'LOGO_GIF', MakeIntResource(RT_RCDATA)); ```
89,745
<p>I am trying to find the virtual file that contains the current users id. I was told that I could find it in the proc directory, but not quite sure which file.</p>
[ { "answer_id": 89763, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "<p>I'm not sure that can be found in <code>/proc</code>. You could try using the <code>getuid()</code> function or the <code>$USER</code> environment variable.</p>\n" }, { "answer_id": 89765, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 3, "selected": false, "text": "<p>Why not just use \"<code>id -u</code>\"?</p>\n" }, { "answer_id": 89778, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 1, "selected": false, "text": "<p>Most likely, you either want to check the <code>$USER</code> environment variable. Other options include <code>getuid</code> and <code>id -u</code>, but searching <code>/proc</code> is certainly not the best method of action.</p>\n" }, { "answer_id": 89788, "author": "jfs", "author_id": 6223, "author_profile": "https://Stackoverflow.com/users/6223", "pm_score": 2, "selected": false, "text": "<p>As far as I know, <code>/proc</code> is specific to Linux, it's not in UNIX in general. If you really just want the current UID, use the <code>getuid()</code> or <code>geteuid()</code> function.</p>\n\n<p>If you know you'll be on Linux only, you can explore the hierarchy under <code>/proc/self/*</code>, it contains various information about the current process. Remember that <code>/proc</code> is \"magical\", it's a virtual filesystem the kernel serves and the contents is dynamically generated at the point you request it. Therefore it can return information specific for the current process.</p>\n\n<p>For example, try this command: <code>cat /proc/self/status</code></p>\n" }, { "answer_id": 89797, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 1, "selected": false, "text": "<p>In <code>/proc/<em>process_id</em>/status</code> (at least on Linux) you'll find a line like this:</p>\n\n<pre>Uid: 1000 1000 1000 1000</pre>\n\n<p>This tells you the uid of the user under whose account the process is running.</p>\n\n<p>However, to find out the process id of the current process you would need a system call, and then you might as well call <code>getuid</code> to get the uid directly.</p>\n\n<p>Edit: ah, <code>/proc/self/status</code>... learning something new every day!</p>\n" }, { "answer_id": 89802, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": true, "text": "<p>You actually want <code>/proc/self/status</code>, which will give you information about the currently executed process.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>$ cat /proc/self/status\nName: cat\nState: R (running)\nTgid: 17618\nPid: 17618\nPPid: 3083\nTracerPid: 0\nUid: 500 500 500 500\nGid: 500 500 500 500\nFDSize: 32\nGroups: 10 488 500 \nVmPeak: 4792 kB\nVmSize: 4792 kB\nVmLck: 0 kB\nVmHWM: 432 kB\nVmRSS: 432 kB\nVmData: 156 kB\nVmStk: 84 kB\nVmExe: 32 kB\nVmLib: 1532 kB\nVmPTE: 24 kB\nThreads: 1\nSigQ: 0/32268\nSigPnd: 0000000000000000\nShdPnd: 0000000000000000\nSigBlk: 0000000000000000\nSigIgn: 0000000000000000\nSigCgt: 0000000000000000\nCapInh: 0000000000000000\nCapPrm: 0000000000000000\nCapEff: 0000000000000000\nCpus_allowed: 00000003\nMems_allowed: 1\nvoluntary_ctxt_switches: 0\nnonvoluntary_ctxt_switches: 3\n</code></pre>\n\n<p>You probably want to look at the first numbers on the Uid and Gid lines. You can look up which uid numbers map to what username by looking at <code>/etc/passwd</code>, or calling the relevant functions for mapping uid to username in whatever language you're using.</p>\n\n<p>Ideally, you would just call the system call <code>getuid()</code> to look up this information, doing it by looking at <code>/proc/</code> is counterproductive.</p>\n" }, { "answer_id": 93156, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The things you are looking for may be in environment variables. You need to be careful about what shell you are using when you check environment variables. bash uses \"UID\" while tcsh uses \"uid\" and in <code>*nix</code> case matters. I've also found that tcsh sets \"gid\" but I wasn't able to find a matching variable in bash.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17162/" ]
I am trying to find the virtual file that contains the current users id. I was told that I could find it in the proc directory, but not quite sure which file.
You actually want `/proc/self/status`, which will give you information about the currently executed process. Here is an example: ``` $ cat /proc/self/status Name: cat State: R (running) Tgid: 17618 Pid: 17618 PPid: 3083 TracerPid: 0 Uid: 500 500 500 500 Gid: 500 500 500 500 FDSize: 32 Groups: 10 488 500 VmPeak: 4792 kB VmSize: 4792 kB VmLck: 0 kB VmHWM: 432 kB VmRSS: 432 kB VmData: 156 kB VmStk: 84 kB VmExe: 32 kB VmLib: 1532 kB VmPTE: 24 kB Threads: 1 SigQ: 0/32268 SigPnd: 0000000000000000 ShdPnd: 0000000000000000 SigBlk: 0000000000000000 SigIgn: 0000000000000000 SigCgt: 0000000000000000 CapInh: 0000000000000000 CapPrm: 0000000000000000 CapEff: 0000000000000000 Cpus_allowed: 00000003 Mems_allowed: 1 voluntary_ctxt_switches: 0 nonvoluntary_ctxt_switches: 3 ``` You probably want to look at the first numbers on the Uid and Gid lines. You can look up which uid numbers map to what username by looking at `/etc/passwd`, or calling the relevant functions for mapping uid to username in whatever language you're using. Ideally, you would just call the system call `getuid()` to look up this information, doing it by looking at `/proc/` is counterproductive.
89,752
<p>How can I get <strong>hierarchy recordset</strong> in ms access through <strong>select</strong> statement?</p>
[ { "answer_id": 89763, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "<p>I'm not sure that can be found in <code>/proc</code>. You could try using the <code>getuid()</code> function or the <code>$USER</code> environment variable.</p>\n" }, { "answer_id": 89765, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 3, "selected": false, "text": "<p>Why not just use \"<code>id -u</code>\"?</p>\n" }, { "answer_id": 89778, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 1, "selected": false, "text": "<p>Most likely, you either want to check the <code>$USER</code> environment variable. Other options include <code>getuid</code> and <code>id -u</code>, but searching <code>/proc</code> is certainly not the best method of action.</p>\n" }, { "answer_id": 89788, "author": "jfs", "author_id": 6223, "author_profile": "https://Stackoverflow.com/users/6223", "pm_score": 2, "selected": false, "text": "<p>As far as I know, <code>/proc</code> is specific to Linux, it's not in UNIX in general. If you really just want the current UID, use the <code>getuid()</code> or <code>geteuid()</code> function.</p>\n\n<p>If you know you'll be on Linux only, you can explore the hierarchy under <code>/proc/self/*</code>, it contains various information about the current process. Remember that <code>/proc</code> is \"magical\", it's a virtual filesystem the kernel serves and the contents is dynamically generated at the point you request it. Therefore it can return information specific for the current process.</p>\n\n<p>For example, try this command: <code>cat /proc/self/status</code></p>\n" }, { "answer_id": 89797, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 1, "selected": false, "text": "<p>In <code>/proc/<em>process_id</em>/status</code> (at least on Linux) you'll find a line like this:</p>\n\n<pre>Uid: 1000 1000 1000 1000</pre>\n\n<p>This tells you the uid of the user under whose account the process is running.</p>\n\n<p>However, to find out the process id of the current process you would need a system call, and then you might as well call <code>getuid</code> to get the uid directly.</p>\n\n<p>Edit: ah, <code>/proc/self/status</code>... learning something new every day!</p>\n" }, { "answer_id": 89802, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": true, "text": "<p>You actually want <code>/proc/self/status</code>, which will give you information about the currently executed process.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>$ cat /proc/self/status\nName: cat\nState: R (running)\nTgid: 17618\nPid: 17618\nPPid: 3083\nTracerPid: 0\nUid: 500 500 500 500\nGid: 500 500 500 500\nFDSize: 32\nGroups: 10 488 500 \nVmPeak: 4792 kB\nVmSize: 4792 kB\nVmLck: 0 kB\nVmHWM: 432 kB\nVmRSS: 432 kB\nVmData: 156 kB\nVmStk: 84 kB\nVmExe: 32 kB\nVmLib: 1532 kB\nVmPTE: 24 kB\nThreads: 1\nSigQ: 0/32268\nSigPnd: 0000000000000000\nShdPnd: 0000000000000000\nSigBlk: 0000000000000000\nSigIgn: 0000000000000000\nSigCgt: 0000000000000000\nCapInh: 0000000000000000\nCapPrm: 0000000000000000\nCapEff: 0000000000000000\nCpus_allowed: 00000003\nMems_allowed: 1\nvoluntary_ctxt_switches: 0\nnonvoluntary_ctxt_switches: 3\n</code></pre>\n\n<p>You probably want to look at the first numbers on the Uid and Gid lines. You can look up which uid numbers map to what username by looking at <code>/etc/passwd</code>, or calling the relevant functions for mapping uid to username in whatever language you're using.</p>\n\n<p>Ideally, you would just call the system call <code>getuid()</code> to look up this information, doing it by looking at <code>/proc/</code> is counterproductive.</p>\n" }, { "answer_id": 93156, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The things you are looking for may be in environment variables. You need to be careful about what shell you are using when you check environment variables. bash uses \"UID\" while tcsh uses \"uid\" and in <code>*nix</code> case matters. I've also found that tcsh sets \"gid\" but I wasn't able to find a matching variable in bash.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I get **hierarchy recordset** in ms access through **select** statement?
You actually want `/proc/self/status`, which will give you information about the currently executed process. Here is an example: ``` $ cat /proc/self/status Name: cat State: R (running) Tgid: 17618 Pid: 17618 PPid: 3083 TracerPid: 0 Uid: 500 500 500 500 Gid: 500 500 500 500 FDSize: 32 Groups: 10 488 500 VmPeak: 4792 kB VmSize: 4792 kB VmLck: 0 kB VmHWM: 432 kB VmRSS: 432 kB VmData: 156 kB VmStk: 84 kB VmExe: 32 kB VmLib: 1532 kB VmPTE: 24 kB Threads: 1 SigQ: 0/32268 SigPnd: 0000000000000000 ShdPnd: 0000000000000000 SigBlk: 0000000000000000 SigIgn: 0000000000000000 SigCgt: 0000000000000000 CapInh: 0000000000000000 CapPrm: 0000000000000000 CapEff: 0000000000000000 Cpus_allowed: 00000003 Mems_allowed: 1 voluntary_ctxt_switches: 0 nonvoluntary_ctxt_switches: 3 ``` You probably want to look at the first numbers on the Uid and Gid lines. You can look up which uid numbers map to what username by looking at `/etc/passwd`, or calling the relevant functions for mapping uid to username in whatever language you're using. Ideally, you would just call the system call `getuid()` to look up this information, doing it by looking at `/proc/` is counterproductive.
89,791
<p>When I start my process from Visual Studio, it is always created inside a job object. I would like to know how to turn this behaviour off. Any ideas?</p> <p>I expect that it is created in a job object to be debugged. I want to place my program in a different job object.</p> <p>It's not the hosting process. I'm talking about a <a href="http://msdn.microsoft.com/en-us/library/ms684161(VS.85).aspx" rel="noreferrer">Job Object</a>. This is an unmanaged C++ application.</p>
[ { "answer_id": 93065, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 1, "selected": false, "text": "<p>I'm not aware of any ways to control this aspect of processes spawned for debugging by VS.NET. But there's a workaround, which is applicable to any situation in which VS.NET can't or doesn't start your process in the exact way you want:</p>\n\n<p>Start your process (possibly using a wrapper EXE that runs as part of the post-build event), then attach to the newly started process using Tools/Attach to Process. If you break into the debugger as part of your startup code, this won't even be required (and you can also debug startup issues...).</p>\n" }, { "answer_id": 93266, "author": "Peter Ritchie", "author_id": 5620, "author_profile": "https://Stackoverflow.com/users/5620", "pm_score": 1, "selected": false, "text": "<p>I can't reproduce what you're seeing. I've created an unmanaged C++ application in both VS 2005 and VS 2008 and I have no problems associating that process to a new job object when starting the process in VS.</p>\n\n<p>Are you sure the debugger is doing this?</p>\n" }, { "answer_id": 4232259, "author": "Tom Minka", "author_id": 513835, "author_profile": "https://Stackoverflow.com/users/513835", "pm_score": 5, "selected": false, "text": "<p>This happens when <code>devenv.exe</code> or <code>VSLauncher.exe</code> run in compatibility mode. The <a href=\"http://msdn.microsoft.com/en-us/library/bb756937.aspx\" rel=\"noreferrer\">Program Compatibility Assistant</a> (PCA) attaches a job object to the Visual Studio process, and every child process inherits it. Check if the job name (as reported by Process Explorer) starts with <strong>PCA</strong>. If so, PCA can be disabled as described in the link. </p>\n\n<p>You can globally disable PCA using <code>Run</code> -> <code>gpedit.msc</code> -> <code>Administrative Templates\\Windows Components\\Application Compatibility</code> -> <code>Turn off Program Compatibility Assistant</code> -> <code>Enable</code>.</p>\n\n<p>You can disable PCA for specific executables by adding a registry entry. For Windows 7, the appropriate registry key is <code>HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Compatibility Assistant</code>. In regedit, right-click that key, select <code>New</code> -> <code>Multi-String Value</code>, name it <code>ExecutablesToExclude</code>. Set the value to the full path of <code>denenv.exe</code> and <code>VSLauncher.exe</code>, on separate lines and without quotes. For me, these were:</p>\n\n<pre><code>C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE\\devenv.exe\nC:\\Program Files (x86)\\Common Files\\microsoft shared\\MSEnv\\VSLauncher.exe\n</code></pre>\n\n<p>A related issue, on Windows 7, is that executables you build in Visual Studio and run from Explorer (not Visual Studio or the command line) may run in compatibility mode, and again get job objects wrapped around them. To prevent this, your executable needs a manifest that declares compatibility with Windows 7, using the new <a href=\"http://msdn.microsoft.com/en-us/library/dd371711(VS.85).aspx\" rel=\"noreferrer\">Application Manifest Compability section</a>. The link gives an example of a Windows 7 compatible manifest. The default manifest provided by Visual Studio 2010 does not include this Compatibility section.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
When I start my process from Visual Studio, it is always created inside a job object. I would like to know how to turn this behaviour off. Any ideas? I expect that it is created in a job object to be debugged. I want to place my program in a different job object. It's not the hosting process. I'm talking about a [Job Object](http://msdn.microsoft.com/en-us/library/ms684161(VS.85).aspx). This is an unmanaged C++ application.
This happens when `devenv.exe` or `VSLauncher.exe` run in compatibility mode. The [Program Compatibility Assistant](http://msdn.microsoft.com/en-us/library/bb756937.aspx) (PCA) attaches a job object to the Visual Studio process, and every child process inherits it. Check if the job name (as reported by Process Explorer) starts with **PCA**. If so, PCA can be disabled as described in the link. You can globally disable PCA using `Run` -> `gpedit.msc` -> `Administrative Templates\Windows Components\Application Compatibility` -> `Turn off Program Compatibility Assistant` -> `Enable`. You can disable PCA for specific executables by adding a registry entry. For Windows 7, the appropriate registry key is `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant`. In regedit, right-click that key, select `New` -> `Multi-String Value`, name it `ExecutablesToExclude`. Set the value to the full path of `denenv.exe` and `VSLauncher.exe`, on separate lines and without quotes. For me, these were: ``` C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe C:\Program Files (x86)\Common Files\microsoft shared\MSEnv\VSLauncher.exe ``` A related issue, on Windows 7, is that executables you build in Visual Studio and run from Explorer (not Visual Studio or the command line) may run in compatibility mode, and again get job objects wrapped around them. To prevent this, your executable needs a manifest that declares compatibility with Windows 7, using the new [Application Manifest Compability section](http://msdn.microsoft.com/en-us/library/dd371711(VS.85).aspx). The link gives an example of a Windows 7 compatible manifest. The default manifest provided by Visual Studio 2010 does not include this Compatibility section.
89,820
<p>I am using mssql and am having trouble using a subquery. The real query is quite complicated, but it has the same structure as this:</p> <pre><code>select customerName, customerId, ( select count(*) from Purchases where Purchases.customerId=customerData.customerId ) as numberTransactions from customerData </code></pre> <p>And what I want to do is order the table by the number of transactions, but when I use</p> <pre><code>order by numberTransactions </code></pre> <p>It tells me there is no such field. Is it possible to do this? Should I be using some sort of special keyword, such as <code>this</code>, or <code>self</code>?</p>
[ { "answer_id": 89831, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 4, "selected": true, "text": "<p>use the field number, in this case:</p>\n\n<pre><code>order by 3\n</code></pre>\n" }, { "answer_id": 89834, "author": "Jason Punyon", "author_id": 6212, "author_profile": "https://Stackoverflow.com/users/6212", "pm_score": 2, "selected": false, "text": "<p>Do an inner join. It's much easier and more readable.</p>\n\n<p><pre><code>select \ncustomerName,\ncustomerID,\ncount(*) as numberTransactions\nfrom\n customerdata c inner join purchases p on c.customerID = p.customerID\ngroup by customerName,customerID\norder by numberTransactions</p>\n\n<p></code></pre>EDIT: Hey Nathan,</p>\n\n<p>You realize you can inner join this whole table as a sub right?</p>\n\n<pre><code>Select T.*, T2.*\nFrom T inner join \n(select \ncustomerName,\ncustomerID,\ncount(*) as numberTransactions\nfrom\n customerdata c inner join purchases p on c.customerID = p.customerID\ngroup by customerName,customerID\n) T2 on T.CustomerID = T2.CustomerID\norder by T2.numberTransactions\n</code></pre>\n\n<p>Or if that's no good you can construct your queries using temporary tables (#T1 etc)</p>\n" }, { "answer_id": 89835, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": -1, "selected": false, "text": "<p>You need to duplicate your logic. SQL Server isn't very smart at columns that you've named but aren't part of the dataset in your FROM statement.</p>\n\n<p>So use</p>\n\n<pre><code>select \n customerName, \n customerId,\n (\n select count(*) \n from Purchases p\n where p.customerId = c.customerId\n ) as numberTransactions\nfrom customerData c\norder by (select count(*) from purchases p where p.customerID = c.customerid)\n</code></pre>\n\n<p>Also, use aliases, they make your code easier to read and maintain. ;)</p>\n" }, { "answer_id": 89836, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 0, "selected": false, "text": "<p>The same thing could be achieved by using <code>GROUP BY</code> and a <code>JOIN</code>, and you'll be rid of the subquery. This might be faster too.</p>\n" }, { "answer_id": 89838, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 0, "selected": false, "text": "<p>I think you can do this in SQL2005, but not SQL2000. </p>\n" }, { "answer_id": 89842, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "<p>Sometimes you have to wrestle with SQL's syntax (expected scope of clauses)</p>\n\n<pre><code>SELECT *\nFROM\n(\nselect\n customerName,\n customerId,\n (\n select count(*)\n from Purchases\n where Purchases.customerId=customerData.customerId\n ) as numberTransactions\nfrom customerData\n) as sub\norder by sub.numberTransactions\n</code></pre>\n\n<p>Also, a solution using JOIN is correct. Look at the query plan, SQL Server should give identical plans for both solutions.</p>\n" }, { "answer_id": 90139, "author": "MotoWilliams", "author_id": 2730, "author_profile": "https://Stackoverflow.com/users/2730", "pm_score": 2, "selected": false, "text": "<p><strong><em>There are better ways to get your result but just from your example query this will work on SQL2000 or better.</em></strong></p>\n\n<p>If you wrap your alias in single ticks <strong>'numberTransactions'</strong> and then call <strong>ORDER BY 'numberTransactions'</strong></p>\n\n<pre><code>select\n customerName, \n customerId,\n (\n select count(*) \n from Purchases \n where Purchases.customerId=customerData.customerId\n ) as 'numberTransactions'\nfrom customerData\nORDER BY 'numberTransactions'\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6062/" ]
I am using mssql and am having trouble using a subquery. The real query is quite complicated, but it has the same structure as this: ``` select customerName, customerId, ( select count(*) from Purchases where Purchases.customerId=customerData.customerId ) as numberTransactions from customerData ``` And what I want to do is order the table by the number of transactions, but when I use ``` order by numberTransactions ``` It tells me there is no such field. Is it possible to do this? Should I be using some sort of special keyword, such as `this`, or `self`?
use the field number, in this case: ``` order by 3 ```
89,866
<p>We are creating a Real-Time Process in VxWorks 6.x, and we would like to limit the amount of memory which can be allocated to the heap. How do we do this?</p>
[ { "answer_id": 89911, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 3, "selected": true, "text": "<p>When creating a RTP via rtpSpawn(), you can specify an environment variable which controls how the heap behaves.<br>\nThere are 3 environment variables:</p>\n\n<pre>\nHEAP_INITIAL_SIZE - How much heap to allocate initially (defaults to 64K) \nHEAP_MAX_SIZE - Maximum heap to allocate (defaults to no limit)\nHEAP_INCR_SIZE - memory increment when adding to RTP heap (defaults to 1 virtual page)\n\nThe following code shows how to use the environment variables:\n<code>\n char * envp[] = {\"HEAP_INITIAL_SIZE=0x20000\", \"HEAP_MAX_SIZE=0x100000\", NULL);\n rtpSpawn (\"myrtp.vxe\", NULL, envp, 100, 0x10000, 0, 0);\n</code>\n</pre>\n" }, { "answer_id": 89931, "author": "unwieldy", "author_id": 14963, "author_profile": "https://Stackoverflow.com/users/14963", "pm_score": 0, "selected": false, "text": "<p>This can be done through the use of the HEAP_MAX_SIZE environment variable. If it is set, it limits the ability of the heap to grow beyond that size. It does not, however, limit the initial heap size.</p>\n\n<p><a href=\"http://www.slac.stanford.edu/grp/cd/soft/vxworks/doc/6.6/vxworks_application_api_reference_6.6.pdf\" rel=\"nofollow noreferrer\">See page 31</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
We are creating a Real-Time Process in VxWorks 6.x, and we would like to limit the amount of memory which can be allocated to the heap. How do we do this?
When creating a RTP via rtpSpawn(), you can specify an environment variable which controls how the heap behaves. There are 3 environment variables: ``` HEAP_INITIAL_SIZE - How much heap to allocate initially (defaults to 64K) HEAP_MAX_SIZE - Maximum heap to allocate (defaults to no limit) HEAP_INCR_SIZE - memory increment when adding to RTP heap (defaults to 1 virtual page) The following code shows how to use the environment variables: char * envp[] = {"HEAP_INITIAL_SIZE=0x20000", "HEAP_MAX_SIZE=0x100000", NULL); rtpSpawn ("myrtp.vxe", NULL, envp, 100, 0x10000, 0, 0); ```
89,873
<p>Is it possible to manipulate the components, such as <code>year</code>, <code>month</code>, <code>day</code> of a <code>date</code> in VBA? I would like a function that, given a day, a month, and a year, returns the corresponding date.</p>
[ { "answer_id": 89892, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 2, "selected": false, "text": "<p>There are several date functions in VBA - check this <a href=\"http://www.classanytime.com/mis333k/sjdatetime.html\" rel=\"nofollow noreferrer\">site</a></p>\n<p>DateSerial(YEAR, MONTH, DAY)</p>\n" }, { "answer_id": 89899, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 4, "selected": true, "text": "<pre><code>DateSerial(YEAR, MONTH, DAY)\n</code></pre>\n\n<p>would be what you are looking for.</p>\n\n<p><code>DateSerial(2008, 8, 19)</code> returns <code>8/19/2008</code></p>\n" }, { "answer_id": 89903, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 2, "selected": false, "text": "<p>You want <a href=\"http://msdn.microsoft.com/en-us/library/bbx05d0c(VS.80).aspx\" rel=\"nofollow noreferrer\">DateSerial</a>:</p>\n\n<pre><code>Dim someDate As Date = DateSerial(year, month, day)\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10439/" ]
Is it possible to manipulate the components, such as `year`, `month`, `day` of a `date` in VBA? I would like a function that, given a day, a month, and a year, returns the corresponding date.
``` DateSerial(YEAR, MONTH, DAY) ``` would be what you are looking for. `DateSerial(2008, 8, 19)` returns `8/19/2008`
89,897
<p>Maybe the need to do this is a 'design smell' but thinking about another question, I was wondering what the cleanest way to implement the <strong>inverse</strong> of this:</p> <pre><code>foreach(ISomethingable somethingableClass in collectionOfRelatedObjects) { somethingableClass.DoSomething(); } </code></pre> <p>i.e. How to get/iterate through all the objects that <em>don't</em> implement a particular interface?</p> <p>Presumably you'd need to start by upcasting to the highest level:</p> <pre><code>foreach(ParentType parentType in collectionOfRelatedObjects) { // TODO: iterate through everything which *doesn't* implement ISomethingable } </code></pre> <p>Answer by solving the TODO: in the cleanest/simplest and/or most efficient way</p>
[ { "answer_id": 89933, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 3, "selected": false, "text": "<p>Something like this?</p>\n\n<pre><code>foreach (ParentType parentType in collectionOfRelatedObjects) {\n if (!(parentType is ISomethingable)) {\n }\n}\n</code></pre>\n" }, { "answer_id": 89985, "author": "Tim Erickson", "author_id": 8787, "author_profile": "https://Stackoverflow.com/users/8787", "pm_score": 2, "selected": false, "text": "<p>Probably best to go all the way and improve the variable names:</p>\n\n<pre><code>foreach (object obj in collectionOfRelatedObjects)\n{\n if (obj is ISomethingable) continue;\n\n //do something to/with the not-ISomethingable\n}\n</code></pre>\n" }, { "answer_id": 89993, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 0, "selected": false, "text": "<p>J D OConal's is the best way to do this but as a side note, you can use the as keyword to cast an object, and it'll return null if its not of that type.</p>\n\n<p>So something like:</p>\n\n<pre><code>foreach (ParentType parentType in collectionOfRelatedObjects) {\n var obj = (parentType as ISomethingable);\n if (obj == null) {\n }\n}\n</code></pre>\n" }, { "answer_id": 90466, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": true, "text": "<p>this should do the trick:</p>\n\n<pre><code>collectionOfRelatedObjects.Where(o =&gt; !(o is ISomethingable))\n</code></pre>\n" }, { "answer_id": 943865, "author": "Max Galkin", "author_id": 2351099, "author_profile": "https://Stackoverflow.com/users/2351099", "pm_score": 0, "selected": false, "text": "<p>With some help from the LINQ extension method OfType&lt;>(), you can write:</p>\n\n<pre><code>using System.Linq;\n\n...\n\nforeach(ISomethingable s in collection.OfType&lt;ISomethingable&gt;())\n{\n s.DoSomething();\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12726/" ]
Maybe the need to do this is a 'design smell' but thinking about another question, I was wondering what the cleanest way to implement the **inverse** of this: ``` foreach(ISomethingable somethingableClass in collectionOfRelatedObjects) { somethingableClass.DoSomething(); } ``` i.e. How to get/iterate through all the objects that *don't* implement a particular interface? Presumably you'd need to start by upcasting to the highest level: ``` foreach(ParentType parentType in collectionOfRelatedObjects) { // TODO: iterate through everything which *doesn't* implement ISomethingable } ``` Answer by solving the TODO: in the cleanest/simplest and/or most efficient way
this should do the trick: ``` collectionOfRelatedObjects.Where(o => !(o is ISomethingable)) ```
89,908
<p>I have three models:</p> <pre><code>class ReleaseItem &lt; ActiveRecord::Base has_many :pack_release_items has_one :pack, :through =&gt; :pack_release_items end class Pack &lt; ActiveRecord::Base has_many :pack_release_items has_many :release_items, :through=&gt;:pack_release_items end class PackReleaseItem &lt; ActiveRecord::Base belongs_to :pack belongs_to :release_item end </code></pre> <p>The problem is that, during execution, if I add a pack to a release_item it is not aware that the pack is a pack. For instance:</p> <pre><code>Loading development environment (Rails 2.1.0) &gt;&gt; item = ReleaseItem.new(:filename=&gt;'MAESTRO.TXT') =&gt; #&lt;ReleaseItem id: nil, filename: "MAESTRO.TXT", created_by: nil, title: nil, sauce_author: nil, sauce_group: nil, sauce_comment: nil, filedate: nil, filesize: nil, created_at: nil, updated_at: nil, content: nil&gt; &gt;&gt; pack = Pack.new(:filename=&gt;'legion01.zip', :year=&gt;1998) =&gt; #&lt;Pack id: nil, filename: "legion01.zip", created_by: nil, filesize: nil, items: nil, year: 1998, month: nil, filedate: nil, created_at: nil, updated_at: nil&gt; &gt;&gt; item.pack = pack =&gt; #&lt;Pack id: nil, filename: "legion01.zip", created_by: nil, filesize: nil, items: nil, year: 1998, month: nil, filedate: nil, created_at: nil, updated_at: nil&gt; &gt;&gt; item.pack.filename NoMethodError: undefined method `filename' for #&lt;Class:0x2196318&gt; from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1667:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.3/lib/will_paginate/finder.rb:164:in `method_missing' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:285:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:285:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1852:in `with_scope' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_proxy.rb:168:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_proxy.rb:168:in `with_scope' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:281:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.3/lib/will_paginate/finder.rb:164:in `method_missing' from (irb):5 &gt;&gt; </code></pre> <p>It seems that I should have access to item.pack, but it is unaware that the pack is a Pack item.</p>
[ { "answer_id": 90003, "author": "Misplaced", "author_id": 13710, "author_profile": "https://Stackoverflow.com/users/13710", "pm_score": 4, "selected": true, "text": "<p>It appears that your usage of has_one :through is correct. The problem you're seeing has to do with saving objects. For an association to work, the object that is being referenced needs to have an id to populate the <code>model_id</code> field for the object. In this case, <code>PackReleaseItems</code> have a <code>pack_id</code> and a <code>release_item_id</code> field that need to be filled for the association to work correctly. Try saving before accessing objects through an association.</p>\n" }, { "answer_id": 90055, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 2, "selected": false, "text": "<p>Your problem is in how you're associating the <code>ReleaseItem</code> and the <code>Pack</code>.</p>\n\n<p><code>has_many :through</code> and <code>has_one :through</code> both work through an object that also acts as a join table, in this case <code>PackReleaseItem</code>. Since this is not just a join table (if it were, you should just use <code>has_many</code> without <code>:through</code>), properly creating the association requires creating the join object, like so:</p>\n\n<pre><code>&gt;&gt; item.pack_release_items.create :pack =&gt; pack\n</code></pre>\n\n<p>What you're doing with your <code>item.pack = pack</code> call is simply associating the objects in memory. When you go to look it up again, it looks \"<code>through</code>\" the <code>pack_release_items</code>, which is empty.</p>\n" }, { "answer_id": 90144, "author": "Tony Pitale", "author_id": 1167846, "author_profile": "https://Stackoverflow.com/users/1167846", "pm_score": 1, "selected": false, "text": "<p>You want to save or create (instead of new) the item and pack. Otherwise, the database has not assigned id's for the association.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13179/" ]
I have three models: ``` class ReleaseItem < ActiveRecord::Base has_many :pack_release_items has_one :pack, :through => :pack_release_items end class Pack < ActiveRecord::Base has_many :pack_release_items has_many :release_items, :through=>:pack_release_items end class PackReleaseItem < ActiveRecord::Base belongs_to :pack belongs_to :release_item end ``` The problem is that, during execution, if I add a pack to a release\_item it is not aware that the pack is a pack. For instance: ``` Loading development environment (Rails 2.1.0) >> item = ReleaseItem.new(:filename=>'MAESTRO.TXT') => #<ReleaseItem id: nil, filename: "MAESTRO.TXT", created_by: nil, title: nil, sauce_author: nil, sauce_group: nil, sauce_comment: nil, filedate: nil, filesize: nil, created_at: nil, updated_at: nil, content: nil> >> pack = Pack.new(:filename=>'legion01.zip', :year=>1998) => #<Pack id: nil, filename: "legion01.zip", created_by: nil, filesize: nil, items: nil, year: 1998, month: nil, filedate: nil, created_at: nil, updated_at: nil> >> item.pack = pack => #<Pack id: nil, filename: "legion01.zip", created_by: nil, filesize: nil, items: nil, year: 1998, month: nil, filedate: nil, created_at: nil, updated_at: nil> >> item.pack.filename NoMethodError: undefined method `filename' for #<Class:0x2196318> from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1667:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.3/lib/will_paginate/finder.rb:164:in `method_missing' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:285:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:285:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1852:in `with_scope' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_proxy.rb:168:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_proxy.rb:168:in `with_scope' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:281:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.3/lib/will_paginate/finder.rb:164:in `method_missing' from (irb):5 >> ``` It seems that I should have access to item.pack, but it is unaware that the pack is a Pack item.
It appears that your usage of has\_one :through is correct. The problem you're seeing has to do with saving objects. For an association to work, the object that is being referenced needs to have an id to populate the `model_id` field for the object. In this case, `PackReleaseItems` have a `pack_id` and a `release_item_id` field that need to be filled for the association to work correctly. Try saving before accessing objects through an association.
89,909
<p>I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.</p>
[ { "answer_id": 89915, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": -1, "selected": false, "text": "<p>use a regex and see if it matches!</p>\n\n<pre><code>([a-z][A-Z][0-9]\\_\\-)*\n</code></pre>\n" }, { "answer_id": 89919, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 8, "selected": true, "text": "<p>A regular expression will do the trick with very little code:</p>\n\n<pre><code>import re\n\n...\n\nif re.match(\"^[A-Za-z0-9_-]*$\", my_little_string):\n # do something here\n</code></pre>\n" }, { "answer_id": 89937, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 2, "selected": false, "text": "<pre><code> pat = re.compile ('[^\\w-]')\n\n def onlyallowed(s):\n return not pat.search (s)\n</code></pre>\n" }, { "answer_id": 89940, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": -1, "selected": false, "text": "<p>You could always use a list comprehension and check the results with all, it would be a little less resource intensive than using a regex: <code>all([c in string.letters + string.digits + [\"_\", \"-\"] for c in mystring])</code></p>\n" }, { "answer_id": 89971, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "<p>There are a variety of ways of achieving this goal, some are clearer than others. For each of my examples, 'True' means that the string passed is valid, 'False' means it contains invalid characters.</p>\n\n<p>First of all, there's the naive approach:</p>\n\n<pre><code>import string\nallowed = string.letters + string.digits + '_' + '-'\n\ndef check_naive(mystring):\n return all(c in allowed for c in mystring)\n</code></pre>\n\n<p>Then there's use of a regular expression, you can do this with re.match(). Note that '-' has to be at the end of the [] otherwise it will be used as a 'range' delimiter. Also note the $ which means 'end of string'. Other answers noted in this question use a special character class, '\\w', I always prefer using an explicit character class range using [] because it is easier to understand without having to look up a quick reference guide, and easier to special-case.</p>\n\n<pre><code>import re\nCHECK_RE = re.compile('[a-zA-Z0-9_-]+$')\ndef check_re(mystring):\n return CHECK_RE.match(mystring)\n</code></pre>\n\n<p>Another solution noted that you can do an inverse match with regular expressions, I've included that here now. Note that [^...] inverts the character class because the ^ is used:</p>\n\n<pre><code>CHECK_INV_RE = re.compile('[^a-zA-Z0-9_-]')\ndef check_inv_re(mystring):\n return not CHECK_INV_RE.search(mystring)\n</code></pre>\n\n<p>You can also do something tricky with the 'set' object. Have a look at this example, which removes from the original string all the characters that are allowed, leaving us with a set containing either a) nothing, or b) the offending characters from the string:</p>\n\n<pre><code>def check_set(mystring):\n return not set(mystring) - set(allowed)\n</code></pre>\n" }, { "answer_id": 91564, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 2, "selected": false, "text": "<p>As an alternative to using regex you could do it in Sets:</p>\n\n<pre><code>from sets import Set\n\nallowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')\n\nif Set(my_little_sting).issubset(allowed_chars):\n # your action\n print True\n</code></pre>\n" }, { "answer_id": 91572, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 4, "selected": false, "text": "<p>If it were not for the dashes and underscores, the easiest solution would be</p>\n\n<pre><code>my_little_string.isalnum()\n</code></pre>\n\n<p>(Section <a href=\"https://docs.python.org/3/library/stdtypes.html#str.isalnum\" rel=\"nofollow noreferrer\">3.6.1</a> of the Python Library Reference)</p>\n" }, { "answer_id": 92000, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 5, "selected": false, "text": "<p>[Edit] There's another solution not mentioned yet, and it seems to outperform the others given so far in most cases.</p>\n\n<p>Use string.translate to replace all valid characters in the string, and see if we have any invalid ones left over. This is pretty fast as it uses the underlying C function to do the work, with very little python bytecode involved.</p>\n\n<p>Obviously performance isn't everything - going for the most readable solutions is probably the best approach when not in a performance critical codepath, but just to see how the solutions stack up, here's a performance comparison of all the methods proposed so far. check_trans is the one using the string.translate method.</p>\n\n<p>Test code:</p>\n\n<pre><code>import string, re, timeit\n\npat = re.compile('[\\w-]*$')\npat_inv = re.compile ('[^\\w-]')\nallowed_chars=string.ascii_letters + string.digits + '_-'\nallowed_set = set(allowed_chars)\ntrans_table = string.maketrans('','')\n\ndef check_set_diff(s):\n return not set(s) - allowed_set\n\ndef check_set_all(s):\n return all(x in allowed_set for x in s)\n\ndef check_set_subset(s):\n return set(s).issubset(allowed_set)\n\ndef check_re_match(s):\n return pat.match(s)\n\ndef check_re_inverse(s): # Search for non-matching character.\n return not pat_inv.search(s)\n\ndef check_trans(s):\n return not s.translate(trans_table,allowed_chars)\n\ntest_long_almost_valid='a_very_long_string_that_is_mostly_valid_except_for_last_char'*99 + '!'\ntest_long_valid='a_very_long_string_that_is_completely_valid_' * 99\ntest_short_valid='short_valid_string'\ntest_short_invalid='/$%$%&amp;'\ntest_long_invalid='/$%$%&amp;' * 99\ntest_empty=''\n\ndef main():\n funcs = sorted(f for f in globals() if f.startswith('check_'))\n tests = sorted(f for f in globals() if f.startswith('test_'))\n for test in tests:\n print \"Test %-15s (length = %d):\" % (test, len(globals()[test]))\n for func in funcs:\n print \" %-20s : %.3f\" % (func, \n timeit.Timer('%s(%s)' % (func, test), 'from __main__ import pat,allowed_set,%s' % ','.join(funcs+tests)).timeit(10000))\n print\n\nif __name__=='__main__': main()\n</code></pre>\n\n<p>The results on my system are:</p>\n\n<pre><code>Test test_empty (length = 0):\n check_re_inverse : 0.042\n check_re_match : 0.030\n check_set_all : 0.027\n check_set_diff : 0.029\n check_set_subset : 0.029\n check_trans : 0.014\n\nTest test_long_almost_valid (length = 5941):\n check_re_inverse : 2.690\n check_re_match : 3.037\n check_set_all : 18.860\n check_set_diff : 2.905\n check_set_subset : 2.903\n check_trans : 0.182\n\nTest test_long_invalid (length = 594):\n check_re_inverse : 0.017\n check_re_match : 0.015\n check_set_all : 0.044\n check_set_diff : 0.311\n check_set_subset : 0.308\n check_trans : 0.034\n\nTest test_long_valid (length = 4356):\n check_re_inverse : 1.890\n check_re_match : 1.010\n check_set_all : 14.411\n check_set_diff : 2.101\n check_set_subset : 2.333\n check_trans : 0.140\n\nTest test_short_invalid (length = 6):\n check_re_inverse : 0.017\n check_re_match : 0.019\n check_set_all : 0.044\n check_set_diff : 0.032\n check_set_subset : 0.037\n check_trans : 0.015\n\nTest test_short_valid (length = 18):\n check_re_inverse : 0.125\n check_re_match : 0.066\n check_set_all : 0.104\n check_set_diff : 0.051\n check_set_subset : 0.046\n check_trans : 0.017\n</code></pre>\n\n<p>The translate approach seems best in most cases, dramatically so with long valid strings, but is beaten out by regexes in test_long_invalid (Presumably because the regex can bail out immediately, but translate always has to scan the whole string). The set approaches are usually worst, beating regexes only for the empty string case.</p>\n\n<p>Using all(x in allowed_set for x in s) performs well if it bails out early, but can be bad if it has to iterate through every character. isSubSet and set difference are comparable, and are consistently proportional to the length of the string regardless of the data.</p>\n\n<p>There's a similar difference between the regex methods matching all valid characters and searching for invalid characters. Matching performs a little better when checking for a long, but fully valid string, but worse for invalid characters near the end of the string.</p>\n" }, { "answer_id": 13649498, "author": "MB.", "author_id": 11961, "author_profile": "https://Stackoverflow.com/users/11961", "pm_score": -1, "selected": false, "text": "<p>Here's something based on Jerub's \"naive approach\" (naive being his words, not mine!):</p>\n\n<pre><code>import string\nALLOWED = frozenset(string.ascii_letters + string.digits + '_' + '-')\n\ndef check(mystring):\n return all(c in ALLOWED for c in mystring)\n</code></pre>\n\n<p>If <code>ALLOWED</code> was a string then I think <code>c in ALLOWED</code> would involve iterating over each character in the string until it found a match or reached the end. Which, to quote Joel Spolsky, is something of a <a href=\"http://www.joelonsoftware.com/articles/fog0000000319.html\" rel=\"nofollow\">Shlemiel the Painter algorithm</a>.</p>\n\n<p>But testing for existence in a set should be more efficient, or at least less dependent on the number of allowed characters. Certainly this approach is a little bit faster on my machine. It's clear and I think it performs plenty well enough for most cases (on my slow machine I can validate tens of thousands of short-ish strings in a fraction of a second). I like it.</p>\n\n<p><strong>ACTUALLY</strong> on my machine a regexp works out several times faster, and is just as simple as this (arguably simpler). So that probably is the best way forward.</p>\n" }, { "answer_id": 19970696, "author": "Sravan K Ghantasala", "author_id": 1878063, "author_profile": "https://Stackoverflow.com/users/1878063", "pm_score": 0, "selected": false, "text": "<p>Well you can ask the help of regex, the great in here :)</p>\n\n<p>code:</p>\n\n<pre><code>import re\n\nstring = 'adsfg34wrtwe4r2_()' #your string that needs to be matched.\nregex = r'^[\\w\\d_()]*$' # you can also add a space in regex if u want to allow it in the string \nif re.match(regex,string):\n print 'yes'\nelse: \n print 'false'\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>yes \n</code></pre>\n\n<p>Hope this helps :)</p>\n" }, { "answer_id": 54306902, "author": "Alston", "author_id": 1033591, "author_profile": "https://Stackoverflow.com/users/1033591", "pm_score": 2, "selected": false, "text": "<p>Regular expression can be very flexible. </p>\n\n<pre><code>import re;\nre.fullmatch(\"^[\\w-]+$\", target_string) # fullmatch looks also workable for python 3.4\n</code></pre>\n\n<p><code>\\w</code>: Only <code>[a-zA-Z0-9_]</code></p>\n\n<p>So you need to add <code>-</code> char for justify hyphen char.</p>\n\n<p><code>+</code>: Match one or more repetitions of the preceding char. I guess you don't accept blank input. But if you do, change to <code>*</code> .</p>\n\n<p><code>^</code>: Matches the start of the string.</p>\n\n<p><code>$</code>: Matches the end of the string.</p>\n\n<p>You need these two special characters since you need to avoid the following case. The unwanted chars like <code>&amp;</code> here might appear between the matched pattern.</p>\n\n<p><code>&amp;&amp;&amp;PATTERN&amp;&amp;PATTERN</code></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4527/" ]
I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.
A regular expression will do the trick with very little code: ``` import re ... if re.match("^[A-Za-z0-9_-]*$", my_little_string): # do something here ```
89,987
<p>My DataView is acting funny and it is sorting things alphabetically and I need it to sort things numerically. I have looked all across the web for this one and found many ideas on how to sort it with ICompare, but nothing really solid.</p> <p>So my questions are </p> <ol> <li>How do I implement ICompare on a DataView (Looking for code here).</li> <li>How to correctly decipher from a column full of strings that are actual strings and a column full of numbers(with commas).</li> </ol> <p>I need code to help me out with this one guys. I am more or less lost on the idea of ICompare and how to implement in different scenarios so an over all good explanation would be great.</p> <p>Also, Please don't hand me links. I am looking for solid answers on this one.</p> <p>Some Code that I use.</p> <pre><code> DataView dataView = (DataView)Session["kingdomData"]; dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection); gvAllData.DataSource = dataView; gvAllData.DataBind(); private string ConvertSortDirectionToSql(SortDirection sortDirection) { string newSortDirection = String.Empty; if (Session["SortDirection"] == null) { switch (sortDirection) { case SortDirection.Ascending: newSortDirection = "ASC"; break; case SortDirection.Descending: newSortDirection = "DESC"; break; } } else { newSortDirection = Session["SortDirection"].ToString(); switch (newSortDirection) { case "ASC": newSortDirection = "DESC"; break; case "DESC": newSortDirection = "ASC"; break; } } Session["SortDirection"] = newSortDirection; return newSortDirection; } </code></pre> <hr> <p>For the scenario, I build a datatable dynamically and shove it into a dataview where I put the dataview into a gridview while also remembering to put the dataview into a session object for sorting capabilities.</p> <p>When the user calls on the gridview to sort a column, I recall the dataview in the session object and build the dataview sorting expression like this:</p> <pre><code>dataview.sort = e.sortexpression + " " + e.Sortdirection; </code></pre> <p>Or something along those lines. So what ussually comes out is right for all real strings such as </p> <p>Car; Home; scott; zach etc...</p> <p>But when I do the same for number fields WITH comma seperated values it comes out something like</p> <p>900; 800; 700; 600; 200; 120; 1,200; 12,340; 1,000,000;</p> <p>See what I mean? It just sorts the items as an alpha sort instead of a Natural sort. I want to make my Dataview NATURALLY sort the numeric columns correctly like</p> <p>120; 200; 600; 700; 800; 900; 1,200; 12,340; 1,000,000;</p> <p>Let me know what you can do to help me out.<br> P.S. I have looked through countless articles on how to do this and all of them say to shove into a List/Array and do it that way, but is there a much more efficient way?</p>
[ { "answer_id": 90498, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 2, "selected": false, "text": "<p>For the first issue - IIRC you can't sort a DataView with a comparer. If you just need to sort numerically a field you must be sure that the column type is numeric and not string. Some code would help to elucidate this.</p>\n\n<p>For the second issue also you can't do that directly in the DataView. If you really need to sort the records based on some processing of data in a column then I'd copy the data in an array and use an IComparer on the array:</p>\n\n<pre><code>DataView dv = new DataView(dt);\nArrayList lst = new ArrayList();\nlst.AddRange(dv.Table.Rows);\nlst.Sort(new MyComparer());\nforeach (DataRow dr in lst)\n Debug.WriteLine(dr[0]);\n</code></pre>\n\n<p>The comparer is like this:</p>\n\n<pre><code> class MyComparer : IComparer\n {\n public int Compare(object x, object y)\n {\n DataRow rx = x as DataRow;\n DataRow ry = y as DataRow;\n string datax = (string)rx[colName];\n string datay = (string)ry[colName];\n // Process datax and datay here then compare them (ASC)\n return datax.CompareTo(datay);\n }\n }\n</code></pre>\n\n<p>This will increase the memory consumption, so you need to think if there is maybe a better way to preprocess the data in the table so that you can sort directly the DataView by a column.</p>\n\n<p>P.S. colName is the name of the column you're interested to sort by. Replace the comment with actual code to extract the sorting info from the column. You can also use this method to extract sorting info from more columns. Just use something like this:</p>\n\n<pre><code>int cmp = colAx.CompareTo(colAy);\nif (cmp != 0)\n return cmp;\ncmp = colBy.CompareTo(colBx);\nreturn cmp;\n</code></pre>\n\n<p>This will compare ascending by colA values and then descending by colB values (not that the second compare has <em>y</em> first and then <em>x</em>)</p>\n\n<p><strong>Edit</strong>: OK, I interpreted wrongly the term comma separated values. From your example I think that you actually meant numbers with thousand separators (1,000,000 = one million). If you store numbers like this in the database then it must be that you're using a text field and that should be the reason your sorting order is alphanumeric.</p>\n\n<p>Based on this assumption I would propose to change the type of that column to numeric, keep normal numbers inside and format them (with thousand separators) only when you display them. This way the sort should work directly in the DataView and you don't have to copy the data.</p>\n" }, { "answer_id": 1640846, "author": "srmark", "author_id": 41662, "author_profile": "https://Stackoverflow.com/users/41662", "pm_score": 1, "selected": false, "text": "<p>It's ugly, but: </p>\n\n<pre><code> DataView dv = GetDataViewSomewhere();\n\n //Naturally sort by COLUMN_TO_SORT_ON\n try\n {\n List&lt;string&gt; rowList = new List&lt;string&gt;();\n foreach (DataRowView drv in dv)\n rowList.Add((string)drv[\"COLUMN_TO_SORT_ON\"]);\n rowList.Sort(new NaturalComparer());\n Dictionary&lt;string, int&gt; sortValueHash = new Dictionary&lt;string, int&gt;();\n for (int i = 0; i &lt; rowList.Count; i++)\n sortValueHash.Add(rowList[i], i); \n\n dv.Table.Columns.Add(\"NATURAL_SORT_ORDER\", typeof(int));\n foreach (DataRowView drv in dv)\n drv[\"NATURAL_SORT_ORDER\"] = sortValueHash[(string)drv[\"COLUMN_TO_SORT_ON\"]];\n dv.Sort = \"NATURAL_SORT_ORDER\"; \n }\n catch (Exception)\n { \n DEBUG_TRACE(\"Could not naturally sort\");\n dv.Sort = \"COLUMN_TO_SORT_ON\";\n }\n</code></pre>\n\n<p>Where <code>NaturalComparer</code> is <a href=\"http://www.codeproject.com/KB/string/NaturalSortComparer.aspx\" rel=\"nofollow noreferrer\">this class</a>.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ]
My DataView is acting funny and it is sorting things alphabetically and I need it to sort things numerically. I have looked all across the web for this one and found many ideas on how to sort it with ICompare, but nothing really solid. So my questions are 1. How do I implement ICompare on a DataView (Looking for code here). 2. How to correctly decipher from a column full of strings that are actual strings and a column full of numbers(with commas). I need code to help me out with this one guys. I am more or less lost on the idea of ICompare and how to implement in different scenarios so an over all good explanation would be great. Also, Please don't hand me links. I am looking for solid answers on this one. Some Code that I use. ``` DataView dataView = (DataView)Session["kingdomData"]; dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection); gvAllData.DataSource = dataView; gvAllData.DataBind(); private string ConvertSortDirectionToSql(SortDirection sortDirection) { string newSortDirection = String.Empty; if (Session["SortDirection"] == null) { switch (sortDirection) { case SortDirection.Ascending: newSortDirection = "ASC"; break; case SortDirection.Descending: newSortDirection = "DESC"; break; } } else { newSortDirection = Session["SortDirection"].ToString(); switch (newSortDirection) { case "ASC": newSortDirection = "DESC"; break; case "DESC": newSortDirection = "ASC"; break; } } Session["SortDirection"] = newSortDirection; return newSortDirection; } ``` --- For the scenario, I build a datatable dynamically and shove it into a dataview where I put the dataview into a gridview while also remembering to put the dataview into a session object for sorting capabilities. When the user calls on the gridview to sort a column, I recall the dataview in the session object and build the dataview sorting expression like this: ``` dataview.sort = e.sortexpression + " " + e.Sortdirection; ``` Or something along those lines. So what ussually comes out is right for all real strings such as Car; Home; scott; zach etc... But when I do the same for number fields WITH comma seperated values it comes out something like 900; 800; 700; 600; 200; 120; 1,200; 12,340; 1,000,000; See what I mean? It just sorts the items as an alpha sort instead of a Natural sort. I want to make my Dataview NATURALLY sort the numeric columns correctly like 120; 200; 600; 700; 800; 900; 1,200; 12,340; 1,000,000; Let me know what you can do to help me out. P.S. I have looked through countless articles on how to do this and all of them say to shove into a List/Array and do it that way, but is there a much more efficient way?
For the first issue - IIRC you can't sort a DataView with a comparer. If you just need to sort numerically a field you must be sure that the column type is numeric and not string. Some code would help to elucidate this. For the second issue also you can't do that directly in the DataView. If you really need to sort the records based on some processing of data in a column then I'd copy the data in an array and use an IComparer on the array: ``` DataView dv = new DataView(dt); ArrayList lst = new ArrayList(); lst.AddRange(dv.Table.Rows); lst.Sort(new MyComparer()); foreach (DataRow dr in lst) Debug.WriteLine(dr[0]); ``` The comparer is like this: ``` class MyComparer : IComparer { public int Compare(object x, object y) { DataRow rx = x as DataRow; DataRow ry = y as DataRow; string datax = (string)rx[colName]; string datay = (string)ry[colName]; // Process datax and datay here then compare them (ASC) return datax.CompareTo(datay); } } ``` This will increase the memory consumption, so you need to think if there is maybe a better way to preprocess the data in the table so that you can sort directly the DataView by a column. P.S. colName is the name of the column you're interested to sort by. Replace the comment with actual code to extract the sorting info from the column. You can also use this method to extract sorting info from more columns. Just use something like this: ``` int cmp = colAx.CompareTo(colAy); if (cmp != 0) return cmp; cmp = colBy.CompareTo(colBx); return cmp; ``` This will compare ascending by colA values and then descending by colB values (not that the second compare has *y* first and then *x*) **Edit**: OK, I interpreted wrongly the term comma separated values. From your example I think that you actually meant numbers with thousand separators (1,000,000 = one million). If you store numbers like this in the database then it must be that you're using a text field and that should be the reason your sorting order is alphanumeric. Based on this assumption I would propose to change the type of that column to numeric, keep normal numbers inside and format them (with thousand separators) only when you display them. This way the sort should work directly in the DataView and you don't have to copy the data.
89,989
<p>I want to download a lot of urls in a script but I do not want to save the ones that lead to HTTP errors.</p> <p>As far as I can tell from the man pages, neither <code>curl</code> or <code>wget</code> provide such functionality. Does anyone know about another downloader who does?</p>
[ { "answer_id": 90009, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 5, "selected": false, "text": "<p>I think the <code>-f</code> option to <code>curl</code> does what you want:</p>\n\n<blockquote>\n <p><code>-f</code>, <code>--fail</code></p>\n \n <p>(HTTP) Fail silently (no output at all) on server errors. This is mostly done to better\n enable scripts etc to better deal with failed attempts. In normal cases when an HTTP\n server fails to deliver a document, it returns an HTML document stating so (which often\n also describes why and more). This flag will prevent curl from outputting that and\n return error 22. [...]</p>\n</blockquote>\n\n<p>However, if the response was actually a 301 or 302 redirect, that still gets saved, even if its destination would result in an error:</p>\n\n<pre><code>$ curl -fO http://google.com/aoeu\n$ cat aoeu\n&lt;HTML&gt;&lt;HEAD&gt;&lt;meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"&gt;\n&lt;TITLE&gt;301 Moved&lt;/TITLE&gt;&lt;/HEAD&gt;&lt;BODY&gt;\n&lt;H1&gt;301 Moved&lt;/H1&gt;\nThe document has moved\n&lt;A HREF=\"http://www.google.com/aoeu\"&gt;here&lt;/A&gt;.\n&lt;/BODY&gt;&lt;/HTML&gt;\n</code></pre>\n\n<p>To follow the redirect to its dead end, also give the <code>-L</code> option:</p>\n\n<blockquote>\n <p><code>-L</code>, <code>--location</code></p>\n \n <p>(HTTP/HTTPS) If the server reports that the requested page has moved to a different\n location (indicated with a Location: header and a 3XX response code), this option will\n make curl redo the request on the new place. [...]</p>\n</blockquote>\n" }, { "answer_id": 2327058, "author": "Oct", "author_id": 112514, "author_profile": "https://Stackoverflow.com/users/112514", "pm_score": 5, "selected": true, "text": "<p>One liner I just setup for this very purpose:</p>\n\n<p>(works only with a single file, might be useful for others)</p>\n\n<pre><code>A=$$; ( wget -q \"http://foo.com/pipo.txt\" -O $A.d &amp;&amp; mv $A.d pipo.txt ) || (rm $A.d; echo \"Removing temp file\")\n</code></pre>\n\n<p>This will attempt to download the file from the remote Host. If there is an Error, the file is not kept. In all other cases, it's kept and renamed.</p>\n" }, { "answer_id": 8218688, "author": "Marc Queralt", "author_id": 950065, "author_profile": "https://Stackoverflow.com/users/950065", "pm_score": -1, "selected": false, "text": "<p>You can download the file without saving using <code>\"-O -\"</code> option as </p>\n\n<pre><code>wget -O - http://jagor.srce.hr/\n</code></pre>\n\n<p>You can get mor information at <a href=\"http://www.gnu.org/software/wget/manual/wget.html#Advanced-Usage\" rel=\"nofollow\">http://www.gnu.org/software/wget/manual/wget.html#Advanced-Usage</a></p>\n\n\n" }, { "answer_id": 29350043, "author": "sajal", "author_id": 135625, "author_profile": "https://Stackoverflow.com/users/135625", "pm_score": 2, "selected": false, "text": "<p>Ancient thread.. landed here looking for a solution... ended up writing some shell code to do it.</p>\n\n<pre><code>if [ `curl -s -w \"%{http_code}\" --compress -o /tmp/something \\\n http://example.com/my/url/` = \"200\" ]; then \n echo \"yay\"; cp /tmp/something /path/to/destination/filename\nfi\n</code></pre>\n\n<p>This will download output to a tmp file, and create/overwrite output file only if status was a 200. My usecase is slightly different.. in my case the output takes > 10 seconds to generate... and I did not want the destination file to remain blank for that duration.</p>\n" }, { "answer_id": 36557153, "author": "vmonteco", "author_id": 3156085, "author_profile": "https://Stackoverflow.com/users/3156085", "pm_score": 0, "selected": false, "text": "<p>I have a workaround to propose, it does download the file but it also removes it if its size is 0 (which happens if a 404 occurs).</p>\n\n<pre><code>wget -O &lt;filename&gt; &lt;url/to/file&gt;\nif [[ (du &lt;filename&gt; | cut -f 1) == 0 ]]; then\n rm &lt;filename&gt;;\nfi;\n</code></pre>\n\n<p>It works for zsh but you can adapt it for other shells.</p>\n\n<p>But it only saves it in first place if you provide the <code>-O</code> option</p>\n" }, { "answer_id": 54956116, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><strong>NOTE:</strong> I am aware that this is an older question, but I believe I have found a better solution for those using <code>wget</code> than any of the above answers provide.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>wget -q $URL 2&gt;/dev/null\n</code></pre>\n\n<p>Will save the target file to the local directory if and only if the HTTP status code is within the 200 range (Ok).</p>\n\n<p>Additionally, if you wanted to do something like print out an error whenever the request was met with an error, you could check the <a href=\"https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html\" rel=\"nofollow noreferrer\">wget exit code</a> for non-zero values like so:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>wget -q $URL 2&gt;/dev/null\nif [ $? != 0]; then\n echo \"There was an error!\"\nfi\n</code></pre>\n\n<p>I hope this is helpful to someone out there facing the same issues I was.</p>\n\n<p><strong>Update:</strong>\nI just put this into a more script-able form for my own project, and thought I'd share:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>function dl {\n pushd . &gt; /dev/null\n cd $(dirname $1)\n wget -q $BASE_URL/$1 2&gt; /dev/null\n if [ $? != 0 ]; then\n echo \"&gt;&gt; ERROR could not download file \\\"$1\\\"\" 1&gt;&amp;2\n exit 1\n fi\n popd &gt; /dev/null\n}\n</code></pre>\n" }, { "answer_id": 60302046, "author": "Juan Lago", "author_id": 1641558, "author_profile": "https://Stackoverflow.com/users/1641558", "pm_score": 0, "selected": false, "text": "<p>As alternative you can create a temporal rotational file:</p>\n\n<pre><code>wget http://example.net/myfile.json -O myfile.json.tmp -t 3 -q &amp;&amp; mv list.json.tmp list.json\n</code></pre>\n\n<p>The previous command will always download the file \"myfile.json.tmp\" however only when the wget exit status is equal to 0 the file is rotated as \"myfile.json\".</p>\n\n<p>This solution will prevent to overwrite the final file when a <a href=\"https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html\" rel=\"nofollow noreferrer\">network failure occurs</a>.</p>\n\n<p>The advantage of this method is that in case that something is wrong you can inspect the temporal file and see what error message is returned.</p>\n\n<p>The \"-t\" parameter attempt to download the file several times in case of error.</p>\n\n<p>The \"-q\" is the quiet mode and it's important to use with cron because cron will report any output of wget.</p>\n\n<p>The \"-O\" is the output file path and name. </p>\n\n<p>Remember that for Cron schedules it's very important to provide always the full path for all the files and in this case for the \"wget\" program it self as well.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/89989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65724/" ]
I want to download a lot of urls in a script but I do not want to save the ones that lead to HTTP errors. As far as I can tell from the man pages, neither `curl` or `wget` provide such functionality. Does anyone know about another downloader who does?
One liner I just setup for this very purpose: (works only with a single file, might be useful for others) ``` A=$$; ( wget -q "http://foo.com/pipo.txt" -O $A.d && mv $A.d pipo.txt ) || (rm $A.d; echo "Removing temp file") ``` This will attempt to download the file from the remote Host. If there is an Error, the file is not kept. In all other cases, it's kept and renamed.
90,023
<h2>Update: giving a much more thorough example.</h2> <p>The first two solutions offered were right along the lines of what I was trying to say <em>not</em> to do. I can't know location, it needs to be able to look at the whole document tree. So a solution along these lines, with /Books/ specified as the context will not work:</p> <pre><code>SELECT x.query('.') FROM @xml.nodes('/Books/*[not(@ID) or @ID = 5]') x1(x) </code></pre> <h2>Original question with better example:</h2> <p>Using SQL Server 2005's XQuery implementation I need to select all nodes in an XML document, just once each and keeping their original structure, but only if they are missing a particular attribute, or that attribute has a specific value (passed in by parameter). The query also has to work on the whole XML document (descendant-or-self axis) rather than selecting at a predefined depth.</p> <p>That is to say, each individual node will appear in the resultant document only if it and every one of its ancestors are missing the attribute, or have the attribute with a single specific value.</p> <h2>For example:</h2> <p>If this were the XML:</p> <pre><code> DECLARE @Xml XML SET @Xml = N' &lt;Library&gt; &lt;Novels&gt; &lt;Novel category=&quot;1&quot;&gt;Novel1&lt;/Novel&gt; &lt;Novel category=&quot;2&quot;&gt;Novel2&lt;/Novel&gt; &lt;Novel&gt;Novel3&lt;/Novel&gt; &lt;Novel category=&quot;4&quot;&gt;Novel4&lt;/Novel&gt; &lt;/Novels&gt; &lt;Encyclopedias&gt; &lt;Encyclopedia&gt; &lt;Volume&gt;A-F&lt;/Volume&gt; &lt;Volume category=&quot;2&quot;&gt;G-L&lt;/Volume&gt; &lt;Volume category=&quot;3&quot;&gt;M-S&lt;/Volume&gt; &lt;Volume category=&quot;4&quot;&gt;T-Z&lt;/Volume&gt; &lt;/Encyclopedia&gt; &lt;/Encyclopedias&gt; &lt;Dictionaries category=&quot;1&quot;&gt; &lt;Dictionary&gt;Webster&lt;/Dictionary&gt; &lt;Dictionary&gt;Oxford&lt;/Dictionary&gt; &lt;/Dictionaries&gt; &lt;/Library&gt; ' </code></pre> <p>A parameter of 1 for category would result in this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Library&gt; &lt;Novels&gt; &lt;Novel category=&quot;1&quot;&gt;Novel1&lt;/Novel&gt; &lt;Novel&gt;Novel3&lt;/Novel&gt; &lt;/Novels&gt; &lt;Encyclopedias&gt; &lt;Encyclopedia&gt; &lt;Volume&gt;A-F&lt;/Volume&gt; &lt;/Encyclopedia&gt; &lt;/Encyclopedias&gt; &lt;Dictionaries category=&quot;1&quot;&gt; &lt;Dictionary&gt;Webster&lt;/Dictionary&gt; &lt;Dictionary&gt;Oxford&lt;/Dictionary&gt; &lt;/Dictionaries&gt; &lt;/Library&gt; </code></pre> <p>A parameter of 2 for category would result in this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Library&gt; &lt;Novels&gt; &lt;Novel category=&quot;2&quot;&gt;Novel2&lt;/Novel&gt; &lt;Novel&gt;Novel3&lt;/Novel&gt; &lt;/Novels&gt; &lt;Encyclopedias&gt; &lt;Encyclopedia&gt; &lt;Volume&gt;A-F&lt;/Volume&gt; &lt;Volume category=&quot;2&quot;&gt;G-L&lt;/Volume&gt; &lt;/Encyclopedia&gt; &lt;/Encyclopedias&gt; &lt;/Library&gt; </code></pre> <p>I know XSLT is perfectly suited for this job, but it's not an option. We have to accomplish this entirely in SQL Server 2005. Any implementations not using XQuery are fine too, as long as it can be done entirely in T-SQL.</p>
[ { "answer_id": 90795, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 3, "selected": true, "text": "<p>It's not clear for me from your example what you're actually trying to achieve. Do you want to return a new XML with all the nodes stripped out except those that fulfill the condition? If yes, then this looks like the job for an XSLT transform which I don't think it's built-in in MSSQL 2005 (can be added as a UDF: <a href=\"http://www.topxml.com/rbnews/SQLXML/re-23872_Performing-XSLT-Transforms-on-XML-Data-Stored-in-SQL-Server-2005.aspx\" rel=\"nofollow noreferrer\">http://www.topxml.com/rbnews/SQLXML/re-23872_Performing-XSLT-Transforms-on-XML-Data-Stored-in-SQL-Server-2005.aspx</a>).</p>\n\n<p>If you just need to return the list of nodes then you can use this expression:</p>\n\n<pre><code>//Book[not(@ID) or @ID = 5]\n</code></pre>\n\n<p>but I get the impression that it's not what you need. It would help if you can provide a clearer example.</p>\n\n<p><strong>Edit</strong>: This example is indeed more clear. The best that I could find is this:</p>\n\n<pre><code>SET @Xml.modify('delete(//*[@category!=1])')\nSELECT @Xml\n</code></pre>\n\n<p>The idea is to delete from the XML all the nodes that you don't need, so you remain with the original structure and the needed nodes. I tested with your two examples and it produced the wanted result.</p>\n\n<p>However <em>modify</em> has some restrictions - it seems you can't use it in a select statement, it has to modify data in place. If you need to return such data with a select you could use a temporary table in which to copy the original data and then update that table. Something like this:</p>\n\n<pre><code>INSERT INTO #temp VALUES(@Xml)\nUPDATE #temp SET data.modify('delete(//*[@category!=2])')\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 91138, "author": "Jonas Lincoln", "author_id": 17436, "author_profile": "https://Stackoverflow.com/users/17436", "pm_score": 1, "selected": false, "text": "<p>The question is not really clear, but is this what you're looking for?</p>\n\n<pre><code>DECLARE @Xml AS XML\n SET @Xml =\n N'\n &lt;Books&gt;\n &lt;Book ID=\"1\"&gt;Book1&lt;/Book&gt;\n &lt;Book ID=\"2\"&gt;Book2&lt;/Book&gt;\n &lt;Book ID=\"3\"&gt;Book3&lt;/Book&gt;\n &lt;Book&gt;Book4&lt;/Book&gt;\n &lt;Book ID=\"5\"&gt;Book5&lt;/Book&gt;\n &lt;Book ID=\"6\"&gt;Book6&lt;/Book&gt;\n &lt;Book&gt;Book7&lt;/Book&gt;\n &lt;Book ID=\"8\"&gt;Book8&lt;/Book&gt;\n &lt;/Books&gt;\n '\nDECLARE @BookID AS INT\nSET @BookID = 5\nDECLARE @Result AS XML\n\nSET @result = (SELECT @xml.query('//Book[not(@ID) or @ID = sql:variable(\"@BookID\")]'))\nSELECT @result\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507/" ]
Update: giving a much more thorough example. -------------------------------------------- The first two solutions offered were right along the lines of what I was trying to say *not* to do. I can't know location, it needs to be able to look at the whole document tree. So a solution along these lines, with /Books/ specified as the context will not work: ``` SELECT x.query('.') FROM @xml.nodes('/Books/*[not(@ID) or @ID = 5]') x1(x) ``` Original question with better example: -------------------------------------- Using SQL Server 2005's XQuery implementation I need to select all nodes in an XML document, just once each and keeping their original structure, but only if they are missing a particular attribute, or that attribute has a specific value (passed in by parameter). The query also has to work on the whole XML document (descendant-or-self axis) rather than selecting at a predefined depth. That is to say, each individual node will appear in the resultant document only if it and every one of its ancestors are missing the attribute, or have the attribute with a single specific value. For example: ------------ If this were the XML: ``` DECLARE @Xml XML SET @Xml = N' <Library> <Novels> <Novel category="1">Novel1</Novel> <Novel category="2">Novel2</Novel> <Novel>Novel3</Novel> <Novel category="4">Novel4</Novel> </Novels> <Encyclopedias> <Encyclopedia> <Volume>A-F</Volume> <Volume category="2">G-L</Volume> <Volume category="3">M-S</Volume> <Volume category="4">T-Z</Volume> </Encyclopedia> </Encyclopedias> <Dictionaries category="1"> <Dictionary>Webster</Dictionary> <Dictionary>Oxford</Dictionary> </Dictionaries> </Library> ' ``` A parameter of 1 for category would result in this: ```xml <Library> <Novels> <Novel category="1">Novel1</Novel> <Novel>Novel3</Novel> </Novels> <Encyclopedias> <Encyclopedia> <Volume>A-F</Volume> </Encyclopedia> </Encyclopedias> <Dictionaries category="1"> <Dictionary>Webster</Dictionary> <Dictionary>Oxford</Dictionary> </Dictionaries> </Library> ``` A parameter of 2 for category would result in this: ```xml <Library> <Novels> <Novel category="2">Novel2</Novel> <Novel>Novel3</Novel> </Novels> <Encyclopedias> <Encyclopedia> <Volume>A-F</Volume> <Volume category="2">G-L</Volume> </Encyclopedia> </Encyclopedias> </Library> ``` I know XSLT is perfectly suited for this job, but it's not an option. We have to accomplish this entirely in SQL Server 2005. Any implementations not using XQuery are fine too, as long as it can be done entirely in T-SQL.
It's not clear for me from your example what you're actually trying to achieve. Do you want to return a new XML with all the nodes stripped out except those that fulfill the condition? If yes, then this looks like the job for an XSLT transform which I don't think it's built-in in MSSQL 2005 (can be added as a UDF: <http://www.topxml.com/rbnews/SQLXML/re-23872_Performing-XSLT-Transforms-on-XML-Data-Stored-in-SQL-Server-2005.aspx>). If you just need to return the list of nodes then you can use this expression: ``` //Book[not(@ID) or @ID = 5] ``` but I get the impression that it's not what you need. It would help if you can provide a clearer example. **Edit**: This example is indeed more clear. The best that I could find is this: ``` SET @Xml.modify('delete(//*[@category!=1])') SELECT @Xml ``` The idea is to delete from the XML all the nodes that you don't need, so you remain with the original structure and the needed nodes. I tested with your two examples and it produced the wanted result. However *modify* has some restrictions - it seems you can't use it in a select statement, it has to modify data in place. If you need to return such data with a select you could use a temporary table in which to copy the original data and then update that table. Something like this: ``` INSERT INTO #temp VALUES(@Xml) UPDATE #temp SET data.modify('delete(//*[@category!=2])') ``` Hope that helps.
90,029
<p>I'm trying to create a deployment tool that will install software based on the hardware found on a system. I'd like the tool to be able to determine if the optical drive is a writer (to determine if burning software sould be installed) or can read DVDs (to determine if a player should be installed). I tried uing the following code </p> <pre><code>strComputer = "." Set objWMIService = GetObject("winmgmts:\\" &amp; strComputer &amp; "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_CDROMDrive") For Each objItem in colItems Wscript.Echo "MediaType: " &amp; objItem.MediaType Next </code></pre> <p>but it always respons with CD-ROM</p>
[ { "answer_id": 90072, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 1, "selected": false, "text": "<p>You can use WMI to enumerate what Windows knows about a drive; get the <a href=\"http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx\" rel=\"nofollow noreferrer\"><code>Win32_DiskDrive</code></a> instance from which you should be able to grab the the <a href=\"http://msdn.microsoft.com/en-us/library/aa394346(VS.85).aspx\" rel=\"nofollow noreferrer\"><code>Win32_PhysicalMedia</code></a> information for the physical media the drive uses; the <a href=\"http://msdn.microsoft.com/en-us/library/aa394346(VS.85).aspx\" rel=\"nofollow noreferrer\">MediaType</a> property to get what media it uses (CD, CDRW, DVD, DVDRW, etc, etc).</p>\n" }, { "answer_id": 90207, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 0, "selected": false, "text": "<p>Platform SDK - IDiscMaster::EnumDiscRecorders (XP / 2003)</p>\n\n<p>DirectX and DirectShow has extensive interfaces to work with DVD</p>\n\n<p>Else enumerate disk drives and try firing a DeviceIonControlCode that supports extarcting the type info. </p>\n\n<p>Good luck</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to create a deployment tool that will install software based on the hardware found on a system. I'd like the tool to be able to determine if the optical drive is a writer (to determine if burning software sould be installed) or can read DVDs (to determine if a player should be installed). I tried uing the following code ``` strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_CDROMDrive") For Each objItem in colItems Wscript.Echo "MediaType: " & objItem.MediaType Next ``` but it always respons with CD-ROM
You can use WMI to enumerate what Windows knows about a drive; get the [`Win32_DiskDrive`](http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx) instance from which you should be able to grab the the [`Win32_PhysicalMedia`](http://msdn.microsoft.com/en-us/library/aa394346(VS.85).aspx) information for the physical media the drive uses; the [MediaType](http://msdn.microsoft.com/en-us/library/aa394346(VS.85).aspx) property to get what media it uses (CD, CDRW, DVD, DVDRW, etc, etc).
90,049
<p>I'm using a table to design the layout of my web page. I want the table to fill the page even if it doesn't contain much content. Here's the CSS I'm using:</p> <pre class="lang-css prettyprint-override"><code>html, body { height: 100%; margin: 0; padding: 0; } #container { min-height: 100%; width: 100%; } </code></pre> <p>And I place something like this in the page code:</p> <pre><code>&lt;table id="container"&gt; &lt;tr&gt; &lt;td&gt; ... </code></pre> <p>This works for Opera 9, but not for Firefox 2 or Internet Explorer 7. Is there a simple way to make this solution work for all popular browsers?</p> <p>(Adding <code>id="container"</code> to <code>td</code> doesn't help.)</p>
[ { "answer_id": 90109, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 4, "selected": true, "text": "<p>Just use the <code>height</code> property instead of the <code>min-height</code> property when setting <code>#container</code>. Once the data gets too big, the table will automatically grow.</p>\n" }, { "answer_id": 6577742, "author": "deathlock", "author_id": 651170, "author_profile": "https://Stackoverflow.com/users/651170", "pm_score": 4, "selected": false, "text": "<p>Try using this:</p>\n\n<pre><code>html, body {\n height: 100%;\n}\n</code></pre>\n\n<p>So besides making the table's height to 100%, you also should have to make sure that the html'd and body's height are also 100%, so it will stretch properly.</p>\n" }, { "answer_id": 58386700, "author": "Priyanga", "author_id": 11769090, "author_profile": "https://Stackoverflow.com/users/11769090", "pm_score": 0, "selected": false, "text": "<p>You can handle this in Javascript/JQuery.</p>\n\n<pre><code>window_height = $(window).height();\n$('#container').css('min-height', window_height);\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17216/" ]
I'm using a table to design the layout of my web page. I want the table to fill the page even if it doesn't contain much content. Here's the CSS I'm using: ```css html, body { height: 100%; margin: 0; padding: 0; } #container { min-height: 100%; width: 100%; } ``` And I place something like this in the page code: ``` <table id="container"> <tr> <td> ... ``` This works for Opera 9, but not for Firefox 2 or Internet Explorer 7. Is there a simple way to make this solution work for all popular browsers? (Adding `id="container"` to `td` doesn't help.)
Just use the `height` property instead of the `min-height` property when setting `#container`. Once the data gets too big, the table will automatically grow.
90,052
<p>Ok, so i'm working on a regular expression to search out all the header information in a site.</p> <p>I've compiled the regular expression:</p> <pre><code>regex = re.compile(r''' &lt;h[0-9]&gt;\s? (&lt;a[ ]href="[A-Za-z0-9.]*"&gt;)?\s? [A-Za-z0-9.,:'"=/?;\s]*\s? [A-Za-z0-9.,:'"=/?;\s]? ''', re.X) </code></pre> <p>When i run this in python reg ex. tester, it works out wonderfully.</p> <p>Sample data:</p> <pre><code>&lt;body&gt; &lt;h1&gt;Dog &lt;/h1&gt; &lt;h2&gt;Cat &lt;/h2&gt; &lt;h3&gt;Fancy &lt;/h3&gt; &lt;h1&gt;Tall cup of lemons&lt;/h1&gt; &lt;h1&gt;&lt;a href="dog.com"&gt;Dog thing&lt;/a&gt;&lt;/h1&gt; &lt;/body&gt; </code></pre> <p>Now, in the REDemo, it works wonderfully.</p> <p>When i put it in my python code, however, it only prints <code>&lt;a href="dog.com"&gt;</code></p> <p>Here's my python code, I'm not sure if i'm doing something wrong or if something is lost in translation. I appreciate your help.</p> <pre><code>stories=[] response = urllib2.urlopen('http://apricotclub.org/duh.html') html = response.read().lower() p = re.compile('&lt;h[0-9]&gt;\\s?(&lt;a href=\"[A-Za-z0-9.]*\"&gt;)?\\s?[A-Za-z0-9.,:\'\"=/?;\\s]*\\s?[A-Za-z0-9.,:\'\"=/?;\\s]?') stories=re.findall(p, html) for i in stories: if len(i) &gt;= 5: print i </code></pre> <p>I should also note, that when i take out the <code>(&lt;a href=\"[A-Za-z0-9.]*\"&gt;)?</code> from the regular expression it works fine for non-link <code>&lt;hN&gt;</code> lines.</p>
[ { "answer_id": 90095, "author": "habnabit", "author_id": 10999, "author_profile": "https://Stackoverflow.com/users/10999", "pm_score": 2, "selected": false, "text": "<p>Parsing things with regular expressions works for regular languages. HTML is not a regular language, and the stuff you find on web pages these days is absolute crap. <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup</a> deals with tag-soup HTML with browser-like heuristics so you get parsed HTML that resembles what a browser would display.</p>\n\n<p>The downside is it's not very fast. There's <a href=\"http://codespeak.net/lxml/\" rel=\"nofollow noreferrer\">lxml</a> for parsing well-formed html, but you should really use BeautifulSoup if you're not 100% certain that your input will always be well-formed.</p>\n" }, { "answer_id": 90104, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 2, "selected": false, "text": "<p>Because of the braces around the anchor tag, that part is interpreted as a capture group. This causes only the capture group to be returned, and not the whole regex match.</p>\n\n<p>Put the entire regex in braces and you'll see the right matches showing up as the first element in the returned tuples.</p>\n\n<p>But indeed, you should use a real parser.</p>\n" }, { "answer_id": 90138, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 5, "selected": false, "text": "<p>This question has been asked in several forms over the last few days, so I'm going to say this very clearly.</p>\n\n<h1>Q: How do I parse HTML with Regular Expressions?</h1>\n\n<h1>A: Please Don't.</h1>\n\n<p>Use <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup</a>, <a href=\"http://code.google.com/p/html5lib/\" rel=\"nofollow noreferrer\">html5lib</a> or <a href=\"http://codespeak.net/lxml/lxmlhtml.html\" rel=\"nofollow noreferrer\">lxml.html</a>. Please.</p>\n" }, { "answer_id": 90206, "author": "molasses", "author_id": 11293, "author_profile": "https://Stackoverflow.com/users/11293", "pm_score": 1, "selected": false, "text": "<p>As has been mentioned, you should use a parser instead of a regex.</p>\n\n<p>This is how you could do it with a regex though:</p>\n\n<pre><code>import re\n\nhtml = '''\n&lt;body&gt;\n\n&lt;h1&gt;Dog &lt;/h1&gt;\n&lt;h2&gt;Cat &lt;/h2&gt;\n&lt;h3&gt;Fancy &lt;/h3&gt;\n&lt;h1&gt;Tall cup of lemons&lt;/h1&gt;\n&lt;h1&gt;&lt;a href=\"dog.com\"&gt;Dog thing&lt;/a&gt;&lt;/h1&gt;\n&lt;/body&gt;\n'''\n\np = re.compile(r'''\n &lt;(?P&lt;header&gt;h[0-9])&gt; # store header tag for later use\n \\s* # zero or more whitespace\n (&lt;a\\shref=\"(?P&lt;href&gt;.*?)\"&gt;)? # optional link tag. store href portion\n \\s*\n (?P&lt;title&gt;.*?) # title\n \\s*\n (&lt;/a&gt;)? # optional closing link tag\n \\s*\n &lt;/(?P=header)&gt; # must match opening header tag\n''', re.IGNORECASE + re.VERBOSE)\n\nstories = p.finditer(html)\n\nfor match in stories:\n print '%(title)s [%(href)s]' % match.groupdict()\n</code></pre>\n\n<p>Here are a couple of good regular expression resources:</p>\n\n<ul>\n<li><a href=\"http://docs.python.org/dev/howto/regex.html\" rel=\"nofollow noreferrer\">Python Regular Expression HOWTO</a></li>\n<li><a href=\"http://www.regular-expressions.info/\" rel=\"nofollow noreferrer\">Regular-Expressions.info</a></li>\n</ul>\n" }, { "answer_id": 90894, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 2, "selected": false, "text": "<p>Building on the answers so far:</p>\n\n<p>It's best to use a parsing engine. It can cover a lot of cases and in an elegant way. I've tried <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup</a> and I like it very much. Also easy to use, with a great tutorial.</p>\n\n<p>If sometimes it feels like shooting flies with a cannon you can use a regular expression for quick parsing. If that's what you need here is the modified code that will catch all the headers (even those over multiple lines):</p>\n\n<pre><code>p = re.compile(r'&lt;(h[0-9])&gt;(.+?)&lt;/\\1&gt;', re.IGNORECASE | re.DOTALL)\nstories = re.findall(p, html)\nfor i in stories:\n print i\n</code></pre>\n" }, { "answer_id": 618080, "author": "aatifh", "author_id": 56183, "author_profile": "https://Stackoverflow.com/users/56183", "pm_score": 2, "selected": false, "text": "<p>I have used beautifulsoup to parse your desired HTML. I have the above HTML code in\na file called foo.html and later read as a file object.</p>\n\n<pre><code>from BeautifulSoup import BeautifulSoup\n\n\nH_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']\n\ndef extract_data():\n \"\"\"Extract the data from all headers\n in a HTML page.\"\"\"\n f = open('foo.html', 'r+')\n html = f.read()\n soup = BeautifulSoup(html)\n headers = [soup.findAll(h) for h in H_TAGS if soup.findAll(h)]\n lst = []\n for x in headers:\n for y in x:\n if y.string:\n lst.append(y.string)\n else:\n lst.append(y.contents[0].string)\n return lst\n</code></pre>\n\n<p>The above function returns:</p>\n\n<pre><code>&gt;&gt;&gt; [u'Dog ', u'Tall cup of lemons', u'Dog thing', u'Cat ', u'Fancy ']\n</code></pre>\n\n<p>You can add any number of header tags in h_tags list. I have assumed all the headers.\nIf you can solve things easily using BeautifulSoup then its better to use it. :)</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Ok, so i'm working on a regular expression to search out all the header information in a site. I've compiled the regular expression: ``` regex = re.compile(r''' <h[0-9]>\s? (<a[ ]href="[A-Za-z0-9.]*">)?\s? [A-Za-z0-9.,:'"=/?;\s]*\s? [A-Za-z0-9.,:'"=/?;\s]? ''', re.X) ``` When i run this in python reg ex. tester, it works out wonderfully. Sample data: ``` <body> <h1>Dog </h1> <h2>Cat </h2> <h3>Fancy </h3> <h1>Tall cup of lemons</h1> <h1><a href="dog.com">Dog thing</a></h1> </body> ``` Now, in the REDemo, it works wonderfully. When i put it in my python code, however, it only prints `<a href="dog.com">` Here's my python code, I'm not sure if i'm doing something wrong or if something is lost in translation. I appreciate your help. ``` stories=[] response = urllib2.urlopen('http://apricotclub.org/duh.html') html = response.read().lower() p = re.compile('<h[0-9]>\\s?(<a href=\"[A-Za-z0-9.]*\">)?\\s?[A-Za-z0-9.,:\'\"=/?;\\s]*\\s?[A-Za-z0-9.,:\'\"=/?;\\s]?') stories=re.findall(p, html) for i in stories: if len(i) >= 5: print i ``` I should also note, that when i take out the `(<a href=\"[A-Za-z0-9.]*\">)?` from the regular expression it works fine for non-link `<hN>` lines.
This question has been asked in several forms over the last few days, so I'm going to say this very clearly. Q: How do I parse HTML with Regular Expressions? ================================================ A: Please Don't. ================ Use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/), [html5lib](http://code.google.com/p/html5lib/) or [lxml.html](http://codespeak.net/lxml/lxmlhtml.html). Please.
90,067
<p>I'm using the following html to load dojo from Google's hosting.</p> <pre><code>&lt;script src="http://www.google.com/jsapi"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt;google.load("dojo", "1.1.1");&lt;/script&gt; &lt;script type="text/javascript"&gt; dojo.require("dojox.gfx"); ... </code></pre> <p>This errors out on the requre line with an error like dojox.gfx is undefined. Is there a way to make this work, or does Google not support the dojox extensions?</p> <p>Alternatively, is there another common host I can use for standard dojo releases?</p>
[ { "answer_id": 90088, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 0, "selected": false, "text": "<p>I believe that google becomes the namespace for your imported libraries. Try: <code>google.dojo.require</code>.</p>\n\n<p>Oh! And as pointed out below, don't forget to use google.setOnLoadCallback instead of calling your function directly.</p>\n" }, { "answer_id": 90102, "author": "Alexandra Franks", "author_id": 16203, "author_profile": "https://Stackoverflow.com/users/16203", "pm_score": 0, "selected": false, "text": "<p>A better question is - why would you want to? If you are developing on your localhost then just use a relative path, if you're developing on an internet facing server - stick the dojo files on that.</p>\n\n<p>Also - make sure you're not falling foul of the <a href=\"http://developer.mozilla.org/En/Same_origin_policy_for_JavaScript\" rel=\"nofollow noreferrer\">same origin policy</a></p>\n" }, { "answer_id": 90169, "author": "Felipe", "author_id": 2333, "author_profile": "https://Stackoverflow.com/users/2333", "pm_score": 3, "selected": true, "text": "<p>Differently from when you reference the .js files directly from the &lt;script&gt; tag (note that google js api also supports this, see <a href=\"http://code.google.com/apis/ajaxlibs/documentation/#dojo\" rel=\"nofollow noreferrer\">here</a>), google.load is not synchronous. This means that when your code reach google.load, it will not wait for dojo to be fully loaded to keep parsing; it will go straight to your dojo.require line, and it will fail there because the <strong>dojo</strong> object will be undefined.</p>\n\n<p>The solution (if you don't want to use use the direct &lt;script&gt; tag), is to enclose all your code that references dojo in a <strong>start</strong> function, and set it will as a callback, by doing:</p>\n\n<pre><code>google.load(\"dojo\", \"1.1.1\", {callback: start});\n\nfunction start() {\n dojo.require(\"dojox.gfx\");\n ...\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>google.setOnLoadCallback(start);\ngoogle.load(\"dojo\", \"1.1.1\");\n\nfunction start() {\n dojo.require(\"dojox.gfx\");\n ...\n}\n</code></pre>\n" }, { "answer_id": 19840777, "author": "peterh", "author_id": 1783163, "author_profile": "https://Stackoverflow.com/users/1783163", "pm_score": 0, "selected": false, "text": "<p>dojox is practically unmaintained, and will be taken out from dojo-2. There are major problems with most widgets in dojox, there is only a few good.</p>\n\n<p>IMHO dojo should be self-hosted, because there are always things what you need to overwrite - for example, you need some fix in this dojox.gfx.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17209/" ]
I'm using the following html to load dojo from Google's hosting. ``` <script src="http://www.google.com/jsapi"></script> <script type="text/javascript">google.load("dojo", "1.1.1");</script> <script type="text/javascript"> dojo.require("dojox.gfx"); ... ``` This errors out on the requre line with an error like dojox.gfx is undefined. Is there a way to make this work, or does Google not support the dojox extensions? Alternatively, is there another common host I can use for standard dojo releases?
Differently from when you reference the .js files directly from the <script> tag (note that google js api also supports this, see [here](http://code.google.com/apis/ajaxlibs/documentation/#dojo)), google.load is not synchronous. This means that when your code reach google.load, it will not wait for dojo to be fully loaded to keep parsing; it will go straight to your dojo.require line, and it will fail there because the **dojo** object will be undefined. The solution (if you don't want to use use the direct <script> tag), is to enclose all your code that references dojo in a **start** function, and set it will as a callback, by doing: ``` google.load("dojo", "1.1.1", {callback: start}); function start() { dojo.require("dojox.gfx"); ... } ``` or ``` google.setOnLoadCallback(start); google.load("dojo", "1.1.1"); function start() { dojo.require("dojox.gfx"); ... } ```