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
240,765
<p>I've got a lot of similar oracle jobs I need to create, and I'd like to do it programatically. </p> <p>Where does the Oracle store the job library (schema/table)?</p> <p>(yes, I know I might be running with scissors)</p>
[ { "answer_id": 240779, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 0, "selected": false, "text": "<p>Views: USER_JOBS, DBA_JOBS or ALL_JOBS</p>\n" }, { "answer_id": 240943, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 4, "selected": true, "text": "<p>For <a href=\"http://www.psoug.org/reference/dbms_job.html\" rel=\"nofollow noreferrer\">DBMS_JOBS</a> you can use...</p>\n\n<pre><code>dbms_job.submit(\nJOB OUT BINARY_INTEGER,\nWHAT IN VARCHAR2,\nNEXT_DATE IN DATE DEFAULT SYSDATE,\nINTERVAL IN VARCHAR2 DEFAULT 'NULL',\nNO_PARSE IN BOOLEAN DEFAULT FALSE,\nINSTANCE IN BINARY_INTEGER DEFAULT 0,\nFORCE IN BOOLEAN DEFAULT FALSE);\n</code></pre>\n\n<p>For the newer <a href=\"http://www.psoug.org/reference/dbms_scheduler.html\" rel=\"nofollow noreferrer\">DBMS_SCHEDULER</a> jobs you can use...</p>\n\n<pre><code>dbms_scheduler.create_job(\njob_name IN VARCHAR2,\njob_type IN VARCHAR2,\njob_action IN VARCHAR2,\nnumber_of_arguments IN PLS_INTEGER DEFAULT 0,\nstart_date IN TIMESTAMP WITH TIME ZONE DEFAULT NULL,\nrepeat_interval IN VARCHAR2 DEFAULT NULL,\nend_date IN TIMESTAMP WITH TIME ZONE DEFAULT NULL,\njob_class IN VARCHAR2 DEFAULT 'DEFAULT_JOB_CLASS',\nenabled IN BOOLEAN DEFAULT FALSE,\nauto_drop IN BOOLEAN DEFAULT TRUE,\ncomments IN VARCHAR2 DEFAULT NULL);\n</code></pre>\n\n<p>I haven't found a way to add a Grid Control job using SQL. I may ask that as a separate question if the answer doesn't show up here.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/685/" ]
I've got a lot of similar oracle jobs I need to create, and I'd like to do it programatically. Where does the Oracle store the job library (schema/table)? (yes, I know I might be running with scissors)
For [DBMS\_JOBS](http://www.psoug.org/reference/dbms_job.html) you can use... ``` dbms_job.submit( JOB OUT BINARY_INTEGER, WHAT IN VARCHAR2, NEXT_DATE IN DATE DEFAULT SYSDATE, INTERVAL IN VARCHAR2 DEFAULT 'NULL', NO_PARSE IN BOOLEAN DEFAULT FALSE, INSTANCE IN BINARY_INTEGER DEFAULT 0, FORCE IN BOOLEAN DEFAULT FALSE); ``` For the newer [DBMS\_SCHEDULER](http://www.psoug.org/reference/dbms_scheduler.html) jobs you can use... ``` dbms_scheduler.create_job( job_name IN VARCHAR2, job_type IN VARCHAR2, job_action IN VARCHAR2, number_of_arguments IN PLS_INTEGER DEFAULT 0, start_date IN TIMESTAMP WITH TIME ZONE DEFAULT NULL, repeat_interval IN VARCHAR2 DEFAULT NULL, end_date IN TIMESTAMP WITH TIME ZONE DEFAULT NULL, job_class IN VARCHAR2 DEFAULT 'DEFAULT_JOB_CLASS', enabled IN BOOLEAN DEFAULT FALSE, auto_drop IN BOOLEAN DEFAULT TRUE, comments IN VARCHAR2 DEFAULT NULL); ``` I haven't found a way to add a Grid Control job using SQL. I may ask that as a separate question if the answer doesn't show up here.
240,774
<p>I'm having a small problem in Java. I have an interface called Modifiable. Objects implementing this interface are Modifiable.</p> <p>I also have a ModifyCommand class (with the Command pattern) that receive two Modifiable objects (to swap them in a list further on - that's not my question, I designed that solution already).</p> <p>The ModifyCommand class starts by making clones of the Modifiable objects. Logically, I made my Modifiable interface extends Cloneable. The interface then defines a clone() method that its implementing classes must redefine.</p> <p>Then, in ModifyCommand, I can do : firstModifiableObject.clone(). My logic is that classes implementing Modifiable will have to redefine the clone method from Object, as they will be Cloneable (that's what I want to do).</p> <p>The thing is, when I define classes implements Modifiable and I want to override clone(), it won't let me, stating that the clone() method from the Object class hides the one from Modifiable.</p> <p>What should I do? I'm under the impression that "I'm doing it wrong"...</p> <p>Thanks,</p> <p>Guillaume.</p> <p>Edit : it think I will forget the clone() thing. I will either a) assume that the object passed to the Modifiable object (implementing the interface) is already cloned or b) make another method called, for example, copy(), that would basically do a deep-copy of the Modifiable object (or maybe the Generic solution will work...).</p>
[ { "answer_id": 240806, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 0, "selected": false, "text": "<p>Did you define the signature exactly as it is in object?</p>\n\n<pre><code>public Object clone() throws CloneNotSupportedException {\n return super.clone();\n}\n</code></pre>\n\n<p>This should compile - add custom code to the body. <a href=\"http://en.wikipedia.org/wiki/Clone_(Java_method)\" rel=\"nofollow noreferrer\">Wikipedia</a> was surprisingly helpful on this one.</p>\n" }, { "answer_id": 240809, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 0, "selected": false, "text": "<p>What does your method signature for your clone method look like? For it to match the Clonable interface it would have to return an Object. If you're declaring it as returning a Modifiable then that could be the problem.</p>\n" }, { "answer_id": 240821, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 1, "selected": false, "text": "<p>You don't need to redefine the clone method on the interface Modifiable.</p>\n\n<p>Check the documentation: <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html</a></p>\n\n<p>I understand that you are trying to force everyone to override clone method(), but you can't do it.</p>\n\n<p>In another way, you cannot override a class on a interface:</p>\n\n<p>The clone() method is always associated whit the Object.class and not the cloneable interface. You just can override it on another object, not in a interface.</p>\n" }, { "answer_id": 240895, "author": "Sean Reilly", "author_id": 8313, "author_profile": "https://Stackoverflow.com/users/8313", "pm_score": 4, "selected": true, "text": "<p>If you're using java 1.5 or higher, you can get the behavior you want and remove casting this way:</p>\n\n<pre><code>public interface Modifiable&lt;T extends Modifiable&lt;T&gt;&gt; extends Cloneable {\n T clone();\n}\n\npublic class Foo implements Modifiable&lt;Foo&gt; {\n public Foo clone() { //this is required\n return null; //todo: real work\n }\n}\n</code></pre>\n\n<p>Since Foo extends Object, this still satisfies the original contract of the Object class. Code that doesn't refine the clone() method correctly will not compile, because of the additional constraints imposed by the Modifiable interface. As a bonus, calling code doesn't have to cast the result of the clone method.</p>\n" }, { "answer_id": 388318, "author": "Hosam Aly", "author_id": 41283, "author_profile": "https://Stackoverflow.com/users/41283", "pm_score": 1, "selected": false, "text": "<p>Adding to Sean Reilly's answer, this should solve your problem, and is more type safe. It compiles and runs fine with me on JDK6:</p>\n\n<pre><code>public interface Modifiable&lt;T extends Modifiable&lt;T&gt;&gt; extends Cloneable {\n T clone();\n}\npublic class Test implements Modifiable&lt;Test&gt; {\n @Override\n public Test clone() {\n System.out.println(\"clone\");\n return null;\n }\n public static void main(String[] args) {\n Test t = new Test().clone();\n }\n}\n</code></pre>\n\n<p>I couldn't test it with Java 5 because I don't have it installed, but I guess it would work fine.</p>\n" }, { "answer_id": 861381, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>public class CloningExample implements Cloneable {</p>\n\n<pre><code>private LinkedList names = new LinkedList();\n\n\npublic CloningExample() {\n names.add(\"Alex\");\n names.add(\"Melody\");\n names.add(\"Jeff\");\n}\n\n\npublic String toString() {\n StringBuffer sb = new StringBuffer();\n Iterator i = names.iterator();\n while (i.hasNext()) {\n sb.append(\"\\n\\t\" + i.next());\n }\n return sb.toString();\n}\n\n\npublic Object clone() {\n try {\n return super.clone();\n } catch (CloneNotSupportedException e) {\n throw new Error(\"This should not occur since we implement Cloneable\");\n }\n}\n\n\npublic Object deepClone() {\n try {\n CloningExample copy = (CloningExample)super.clone();\n copy.names = (LinkedList)names.clone();\n return copy;\n } catch (CloneNotSupportedException e) {\n throw new Error(\"This should not occur since we implement Cloneable\");\n }\n}\n\npublic boolean equals(Object obj) {\n\n /* is obj reference this object being compared */\n if (obj == this) {\n return true;\n }\n\n /* is obj reference null */\n if (obj == null) {\n return false;\n }\n\n /* Make sure references are of same type */\n if (!(this.getClass() == obj.getClass())) {\n return false;\n } else {\n CloningExample tmp = (CloningExample)obj;\n if (this.names == tmp.names) {\n return true;\n } else {\n return false;\n }\n }\n\n}\n\n\npublic static void main(String[] args) {\n\n CloningExample ce1 = new CloningExample();\n System.out.println(\"\\nCloningExample[1]\\n\" + \n \"-----------------\" + ce1);\n\n CloningExample ce2 = (CloningExample)ce1.clone();\n System.out.println(\"\\nCloningExample[2]\\n\" +\n \"-----------------\" + ce2);\n\n System.out.println(\"\\nCompare Shallow Copy\\n\" +\n \"--------------------\\n\" +\n \" ce1 == ce2 : \" + (ce1 == ce2) + \"\\n\" +\n \" ce1.equals(ce2) : \" + ce1.equals(ce2));\n\n CloningExample ce3 = (CloningExample)ce1.deepClone();\n System.out.println(\"\\nCompare Deep Copy\\n\" +\n \"--------------------\\n\" +\n \" ce1 == ce3 : \" + (ce1 == ce3) + \"\\n\" +\n \" ce1.equals(ce3) : \" + ce1.equals(ce3));\n\n System.out.println();\n\n}\n</code></pre>\n\n<p>}</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10687/" ]
I'm having a small problem in Java. I have an interface called Modifiable. Objects implementing this interface are Modifiable. I also have a ModifyCommand class (with the Command pattern) that receive two Modifiable objects (to swap them in a list further on - that's not my question, I designed that solution already). The ModifyCommand class starts by making clones of the Modifiable objects. Logically, I made my Modifiable interface extends Cloneable. The interface then defines a clone() method that its implementing classes must redefine. Then, in ModifyCommand, I can do : firstModifiableObject.clone(). My logic is that classes implementing Modifiable will have to redefine the clone method from Object, as they will be Cloneable (that's what I want to do). The thing is, when I define classes implements Modifiable and I want to override clone(), it won't let me, stating that the clone() method from the Object class hides the one from Modifiable. What should I do? I'm under the impression that "I'm doing it wrong"... Thanks, Guillaume. Edit : it think I will forget the clone() thing. I will either a) assume that the object passed to the Modifiable object (implementing the interface) is already cloned or b) make another method called, for example, copy(), that would basically do a deep-copy of the Modifiable object (or maybe the Generic solution will work...).
If you're using java 1.5 or higher, you can get the behavior you want and remove casting this way: ``` public interface Modifiable<T extends Modifiable<T>> extends Cloneable { T clone(); } public class Foo implements Modifiable<Foo> { public Foo clone() { //this is required return null; //todo: real work } } ``` Since Foo extends Object, this still satisfies the original contract of the Object class. Code that doesn't refine the clone() method correctly will not compile, because of the additional constraints imposed by the Modifiable interface. As a bonus, calling code doesn't have to cast the result of the clone method.
240,778
<p>I have a 4 side convex Polygon defined by 4 points in 2D, and I want to be able to generate random points inside it.</p> <p>If it really simplifies the problem, I can limit the polygon to a parallelogram, but a more general answer is preferred.</p> <p>Generating random points until one is inside the polygon wouldn't work because it's really unpredictable the time it takes.</p>
[ { "answer_id": 240790, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 6, "selected": true, "text": "<p>A. If you can restrict your input to parallelogram, this is really simple:</p>\n\n<ol>\n<li>Take two random numbers between 0 and 1. We'll call then <code>u</code> and <code>v</code>.</li>\n<li><p>If your parallelogram is defined by the points ABCD such that AB, BC, CD and DA are the sides, then take your point as being:</p>\n\n<pre><code> p = A + (u * AB) + (v * AD)\n</code></pre></li>\n</ol>\n\n<p>Where <code>AB</code> is the vector from A to B and <code>AD</code> the vector from A to D.</p>\n\n<p>B. Now, if you cannot, you can still use the barycentric coordinates. The barycentric coordinates correspond, for a quad, to 4 coordinates <code>(a,b,c,d)</code> such that <code>a+b+c+d=1</code>. Then, any point <code>P</code> within the quad can be described by a 4-uple such that:</p>\n\n<pre><code>P = a A + b B + c C + d D\n</code></pre>\n\n<p>In your case, you can draw 4 random numbers and normalize them so that they add up to 1. That will give you a point. Note that the distribution of points will NOT be uniform in that case.</p>\n\n<p>C. You can also, as proposed elsewhere, decompose the quad into two triangles and use the half-parallelogram method (i.e., as the parallelogram but you add the condition <code>u+v=1</code>) or the barycentric coordinates for triangles. However, if you want uniform distribution, the probability of having a point in one of the triangle must be equal to the area of the triangle divided by the area of the quad.</p>\n" }, { "answer_id": 240793, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 2, "selected": false, "text": "<p>A somewhat less \"<a href=\"http://en.wikipedia.org/wiki/Na%C3%AFve_algorithm\" rel=\"nofollow noreferrer\">naïve</a>\" approach would be to use a <a href=\"http://alienryderflex.com/polygon_fill/\" rel=\"nofollow noreferrer\">polygon fill algorithm</a>, and then select points from the fill lines randomly.</p>\n\n<h2>C Code Sample</h2>\n\n<pre><code>// public-domain code by Darel Rex Finley, 2007\n\nint nodes, nodeX[MAX_POLY_CORNERS], pixelX, pixelY, i, j, swap ;\n\n// Loop through the rows of the image.\nfor (pixelY=IMAGE_TOP; pixelY&lt;IMAGE_BOT; pixelY++) {\n\n // Build a list of nodes.\n nodes=0; j=polyCorners-1;\n for (i=0; i&lt;polyCorners; i++) {\n if (polyY[i]&lt;(double) pixelY &amp;&amp; polyY[j]&gt;=(double) pixelY\n || polyY[j]&lt;(double) pixelY &amp;&amp; polyY[i]&gt;=(double) pixelY) {\n nodeX[nodes++]=(int) (polyX[i]+(pixelY-polyY[i])/(polyY[j]-polyY[i])\n *(polyX[j]-polyX[i])); }\n j=i; }\n\n // Sort the nodes, via a simple “Bubble” sort.\n i=0;\n while (i&lt;nodes-1) {\n if (nodeX[i]&gt;nodeX[i+1]) {\n swap=nodeX[i]; nodeX[i]=nodeX[i+1]; nodeX[i+1]=swap; if (i) i--; }\n else {\n i++; }}\n\n // Fill the pixels between node pairs.\n // Code modified by SoloBold 27 Oct 2008\n // The flagPixel method below will flag a pixel as a possible choice.\n for (i=0; i&lt;nodes; i+=2) {\n if (nodeX[i ]&gt;=IMAGE_RIGHT) break;\n if (nodeX[i+1]&gt; IMAGE_LEFT ) {\n if (nodeX[i ]&lt; IMAGE_LEFT ) nodeX[i ]=IMAGE_LEFT ;\n if (nodeX[i+1]&gt; IMAGE_RIGHT) nodeX[i+1]=IMAGE_RIGHT;\n for (j=nodeX[i]; j&lt;nodeX[i+1]; j++) flagPixel(j,pixelY); }}}\n\n // TODO pick a flagged pixel randomly and fill it, then remove it from the list.\n // Repeat until no flagged pixels remain.\n</code></pre>\n" }, { "answer_id": 240802, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": false, "text": "<p>Your polygon is two triangles, so why not randomly select one of those, then find a random point in the triangle.</p>\n\n<p>Probably not the best solution, but it'd work.</p>\n" }, { "answer_id": 240833, "author": "Chris Dodd", "author_id": 29759, "author_profile": "https://Stackoverflow.com/users/29759", "pm_score": 1, "selected": false, "text": "<p>Do the points need to be uniformly distributed, or is any distribution ok?</p>\n\n<p>Can the polygon be concave, or is it guarenteed to be convex?</p>\n\n<p>If the answer to both the above is no, then pick any two of the vertexes and pick a random point on the line segment between them. This is limited to the line segements connecting the vertexes (ie, VERY non-uniform); you can do a bit better by picking a third vertex and then picking a point between that and the first point -- still non-uniform, but at least any point in the polygon is possible</p>\n\n<p>Picking a random point on a line between two points is easy, just A + p(B-A), where A and B are the points and p is a random number between 0.0 and 1.0</p>\n" }, { "answer_id": 240893, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": "<p>What kind of distribution do you want the points to have? If you don't care, the above methods will work fine. If you want a uniform distribution, the following procedure will work: Divide the polygon into two triangles, a and b. Let A(a) and A(b) be their areas. Sample a point p from the uniform distribution on the interval between 0 and A(a)+A(b). If p &lt; A(a), choose triangle a. Otherwise, choose triangle b. Choose a vertex v of the chosen triangle, and let c and d be the vectors corresponding to the sides of the triangle. Sample two numbers x and y from the exponential distribution with unit average. Then the point (xc+yd)/(x+y) is a sample from the uniform distribution on the polygon.</p>\n" }, { "answer_id": 240896, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>By \"general\" do you mean all non-parallelogram 4-side polygons in general or all possible polygons?</p>\n\n<p>How about drawing a random line connecting the 4 sides e.g. If you have this:</p>\n\n<pre><code>.BBBB.\nA C\nA C\n.DDDD.\n</code></pre>\n\n<p>Then generate a random point on a unit square, then mark the point on the line B and D at the percentage of distance on the X axis. Do the same on line A and C using value from the Y axis.</p>\n\n<p>Then connect the point on line A to line C and line B to line D, the intersection point is then used as the random point.</p>\n\n<p>It's not uniform because rounding errors will aid certain points but it should be close if you are working with floating points values.</p>\n\n<p>Implementation should be rather easy, too, since you are already working with polygons. You should already have code that does those simple tasks.</p>\n\n<p>Here's a quick pseudocode:</p>\n\n<pre><code>void GetRandomPoint(Polygon p, ref float x, ref float y) {\n\n float xrand = random();\n float yrand = random();\n\n float h0 = p.Vertices[0] + xrand * p.Vertices[1];\n float h1 = p.Vertices[2] + yrand * p.Vertices[3];\n\n float v0 = p.Vertices[0] + xrand * p.Vertices[2];\n float v1 = p.Vertices[1] + yrand * p.Vertices[3];\n\n GetLineIntersection(h0, h1, v0, v1, x, y);\n\n}\n</code></pre>\n" }, { "answer_id": 240898, "author": "jakber", "author_id": 29812, "author_profile": "https://Stackoverflow.com/users/29812", "pm_score": 4, "selected": false, "text": "<p>Assuming you want a uniform distribution: Form two triangles from your polygon. Pick which triangle to generate the point in according to their area ratio.</p>\n\n<p>Call the corners of the triangle A, B, C, the side vectors AB, BC, AC and generate two random numbers in [0,1] called u and v. Let p = u * AB + v * AC. </p>\n\n<p>If A+p is inside the triangle, return A+p</p>\n\n<p>If A+p is outside the triangle, return A + AB + AC - p</p>\n\n<p>(This is basically PierreBdR's formula except for the preprocessing and the last step that folds the point back into a triangle, so it can handle other shapes than parallelograms).</p>\n" }, { "answer_id": 4687676, "author": "Not Sure", "author_id": 442839, "author_profile": "https://Stackoverflow.com/users/442839", "pm_score": 2, "selected": false, "text": "<p>This works for general, convex quadrilaterals:</p>\n\n<p>You can borrow some concepts from the Finite Element Method, specifically for quadrilateral (4-sided) elements (<a href=\"http://www.colorado.edu/engineering/cas/courses.d/IFEM.d/IFEM.Ch16.d/IFEM.Ch16.pdf\" rel=\"nofollow\"><strong>refer to section 16.5 here</strong></a>). Basically, there is a bilinear parameterization that maps a square in u-v space (for u, v \\in [-1, 1] in this case) to your quadrilateral that consists of points p_i (for i = 1,2,3,4). Note that In the provided reference, the parameters are called \\eta and \\xi.</p>\n\n<p>Basic recipe:</p>\n\n<ol>\n<li>Choose a suitable random number generator to generate well-distributed points in a square 2D domain</li>\n<li>Generate random u-v pairs in the range [-1, 1]</li>\n<li>For each u-v pair, the corresponding random point in your quad = 1/4 * ((1-u)(1-v) * p_1 + (1+u)(1-v) * p_2 + (1+u)(1+v) * p_3 + (1-u)(1+v) * p_4)</li>\n</ol>\n\n<p>The only problem is that uniformly distributed points in the u-v space won't produce uniformly distributed points in your quad (in the Euclidean sense). If that is important, you can work directly in 2D within the bounding box of the quad and write a point-in-quad (maybe by splitting the problem into two point in tris) test to cull random points that are outside.</p>\n" }, { "answer_id": 5648991, "author": "rapto", "author_id": 20545, "author_profile": "https://Stackoverflow.com/users/20545", "pm_score": 0, "selected": false, "text": "<p>For PostGIS, this is what I am using (you might want a ward for possible infinite loops). You might export the algorithm to your programming language:</p>\n\n<pre><code>CREATE or replace FUNCTION random_point(geometry)\nRETURNS geometry\nAS $$\nDECLARE \n env geometry;\n corner1 geometry;\n corner2 geometry;\n minx real;\n miny real;\n maxx real;\n maxy real;\n x real;\n y real;\n ret geometry;\nbegin\n\nselect ST_Envelope($1) into env;\nselect ST_PointN(ST_ExteriorRing(env),1) into corner1;\nselect ST_PointN(ST_ExteriorRing(env),3) into corner2;\nselect st_x(corner1) into minx;\nselect st_x(corner2) into maxx;\nselect st_y(corner1) into miny;\nselect st_y(corner2) into maxy;\nloop\n select minx+random()*(maxx-minx) into x;\n select miny+random()*(maxy-miny) into y;\n select ST_SetSRID(st_point(x,y), st_srid($1)) into ret;\n if ST_Contains($1,ret) then\n return ret ;\n end if;\nend loop;\nend;\n$$\nLANGUAGE plpgsql\nvolatile\nRETURNS NULL ON NULL INPUT;\n</code></pre>\n" }, { "answer_id": 8420395, "author": "cheshirekow", "author_id": 141023, "author_profile": "https://Stackoverflow.com/users/141023", "pm_score": 5, "selected": false, "text": "<p>The question by the OP is a bit ambiguous so the question I will answer is: <strong>How to generate a point from a uniform distribution within an arbitrary quadrilateral</strong>, which is actually a generalization of <strong>How to generate a point from a uniform distribution within an arbitrary (convex) polygon</strong>. The answer is based on the case of generating a sample from a uniform distribution in a triangle (see <a href=\"http://mathworld.wolfram.com/TrianglePointPicking.html\" rel=\"noreferrer\">http://mathworld.wolfram.com/TrianglePointPicking.html</a>, which has a very nice explanation).</p>\n\n<p>In order to accomplish this we:</p>\n\n<ol>\n<li><p>Triangulate the polygon (i.e. generate a collection of non-overlapping triangular regions which cover the polygon). For the case of a quadrilateral, create an edge across \nany two non-adjacent vertices. For other polygons, see <a href=\"http://en.wikipedia.org/wiki/Polygon_triangulation\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Polygon_triangulation</a> for a starting point, or <a href=\"http://www.cgal.org/\" rel=\"noreferrer\">http://www.cgal.org/</a> if you just need a library.</p>\n\n<p><img src=\"https://i.stack.imgur.com/CYaVQ.png\" alt=\"enter image description here\"></p></li>\n<li><p>To pick one of the triangles randomly, let us assign an index to each triangle (i.e. 0,1,2,...). For the quadrilateral, they will be 0,1. For each triangle we assign a weight equal as follows:</p>\n\n<p><img src=\"https://i.stack.imgur.com/Hqvqs.png\" alt=\"weight calculation\"></p></li>\n<li><p>Then generate a random index i from the finite distribution over indexes given their weights. For the quadrilateral, this is a Bernoulli distribution:</p>\n\n<p><img src=\"https://i.stack.imgur.com/onKl9.png\" alt=\"enter image description here\"></p></li>\n<li><p>Let v0, v1, v2 be vertices of the triangle (represented by their point locations, so that v0 = (x0,y0), etc. Then we generate two random numbers a0 and a1, both drawn uniformly from the interval [0,1]. Then we calculate the random point x by x = a0 (v1-v0) + a1 (v2-v0). </p>\n\n<p><img src=\"https://i.stack.imgur.com/stTLI.png\" alt=\"enter image description here\"></p></li>\n<li><p>Note that with probability 0.5, x lies outside outside the triangle, however if it does, it lies inside the parallelogram composed of the union of the triangle with it's image after a rotation of pi around the midpoint of (v1,v2) (dashed lines in the image). In that case, we can generate a new point x' = v0 + R(pi)(x - v3), where R(pi) is a rotation by pi (180 deg). The point x' will be inside the triangle. </p></li>\n<li><p>Further note that, if the quadrilateral was already a parallelogram, then we do not have to pick a triangle at random, we can pick either one deterministically, and then choose the point x without testing that it is inside it's source triangle. </p></li>\n</ol>\n" }, { "answer_id": 8770900, "author": "Tim Benham", "author_id": 1136105, "author_profile": "https://Stackoverflow.com/users/1136105", "pm_score": 1, "selected": false, "text": "<p>The MATLAB function <a href=\"http://www.mathworks.com.au/matlabcentral/fileexchange/34208-cprnd\" rel=\"nofollow\">cprnd</a> generates points from the uniform distribution on a general convex polytope. For your question a more specialized algorithm based on decomposing the quadrilateral into triangles is more efficient.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815/" ]
I have a 4 side convex Polygon defined by 4 points in 2D, and I want to be able to generate random points inside it. If it really simplifies the problem, I can limit the polygon to a parallelogram, but a more general answer is preferred. Generating random points until one is inside the polygon wouldn't work because it's really unpredictable the time it takes.
A. If you can restrict your input to parallelogram, this is really simple: 1. Take two random numbers between 0 and 1. We'll call then `u` and `v`. 2. If your parallelogram is defined by the points ABCD such that AB, BC, CD and DA are the sides, then take your point as being: ``` p = A + (u * AB) + (v * AD) ``` Where `AB` is the vector from A to B and `AD` the vector from A to D. B. Now, if you cannot, you can still use the barycentric coordinates. The barycentric coordinates correspond, for a quad, to 4 coordinates `(a,b,c,d)` such that `a+b+c+d=1`. Then, any point `P` within the quad can be described by a 4-uple such that: ``` P = a A + b B + c C + d D ``` In your case, you can draw 4 random numbers and normalize them so that they add up to 1. That will give you a point. Note that the distribution of points will NOT be uniform in that case. C. You can also, as proposed elsewhere, decompose the quad into two triangles and use the half-parallelogram method (i.e., as the parallelogram but you add the condition `u+v=1`) or the barycentric coordinates for triangles. However, if you want uniform distribution, the probability of having a point in one of the triangle must be equal to the area of the triangle divided by the area of the quad.
240,788
<p>Can I call a stored procedure in Oracle via a database link?</p> <p>The database link is functional so that syntax such as...</p> <pre><code>SELECT * FROM myTable@myRemoteDB </code></pre> <p>is functioning. But is there a syntax for...</p> <pre><code>EXECUTE mySchema.myPackage.myProcedure('someParameter')@myRemoteDB </code></pre>
[ { "answer_id": 240798, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 7, "selected": true, "text": "<p>The syntax is</p>\n\n<pre><code>EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );\n</code></pre>\n" }, { "answer_id": 9313996, "author": "tptp", "author_id": 1214182, "author_profile": "https://Stackoverflow.com/users/1214182", "pm_score": 1, "selected": false, "text": "<p>check <a href=\"http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html\" rel=\"nofollow\">http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html</a></p>\n\n<p>one needs to use something like </p>\n\n<pre><code>cmd.CommandText = \"BEGIN foo@v; END;\" \n</code></pre>\n\n<p>worked for me in vb.net, c#</p>\n" }, { "answer_id": 66373810, "author": "george fortech", "author_id": 11062891, "author_profile": "https://Stackoverflow.com/users/11062891", "pm_score": 0, "selected": false, "text": "<p>for me, this worked</p>\n<pre><code>exec utl_mail.send@myotherdb(\n sender =&gt; '[email protected]',recipients =&gt; '[email protected], \n cc =&gt; null, subject =&gt; 'my subject', message =&gt; 'my message'\n); \n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
Can I call a stored procedure in Oracle via a database link? The database link is functional so that syntax such as... ``` SELECT * FROM myTable@myRemoteDB ``` is functioning. But is there a syntax for... ``` EXECUTE mySchema.myPackage.myProcedure('someParameter')@myRemoteDB ```
The syntax is ``` EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' ); ```
240,836
<p>I'm currently working on a project where a section of the code looks like this:</p> <pre><code>Select Case oReader.Name Case &quot;NameExample1&quot; Me.Elements.NameExample1.Value = oReader.ReadString ' ... Case &quot;NameExampleN&quot; Me.Elements.NameExampleN.Value = oReader.ReadString ' ... End Select </code></pre> <p>It continues on for a while. The code is obviously verbose and it <em>feels</em> like it could be improved. Is there any way to dynamically invoke a property in VB.NET such that something like this can be done:</p> <pre><code>Dim sReadString As String = oReader.ReadString Me.Elements.InvokeProperty(sReadString).Value = sReadString </code></pre>
[ { "answer_id": 241143, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>Others have answered perfectly reasonably, but just in case this is a performance-sensitive piece of code, you might want to compile the reflective calls into delegates.</p>\n\n<p>I've got a <a href=\"http://codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates\" rel=\"nofollow noreferrer\">blog entry</a> about turning <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.invoke.aspx\" rel=\"nofollow noreferrer\">MethodBase.Invoke</a> into delegates. The code is in C#, but the same technique can be applied to VB.NET as well. To use this with properties, get the appropriate \"setter\" method with <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getsetmethod.aspx\" rel=\"nofollow noreferrer\">PropertyInfo.GetSetMethod</a> and then build a delegate which invokes that. You could have a map from field name to \"delegate to call to set the field\".</p>\n\n<p>Just to reiterate, this is only really necessary if it's in a performance-critical piece of code. Otherwise, you might still want to create a <code>Dictionary&lt;string, PropertyInfo&gt;</code> to avoid calling <code>GetProperty</code> many times, but the step to convert it into a delegate probably isn't worth worrying about.</p>\n" }, { "answer_id": 249393, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 5, "selected": false, "text": "<p>I can't believe the other posters told you to use reflection. VB as a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.interaction.callbyname?view=netcore-3.1\" rel=\"nofollow noreferrer\">CallByName</a> function that does exactly what you want.</p>\n" }, { "answer_id": 15602458, "author": "Jet", "author_id": 1906044, "author_profile": "https://Stackoverflow.com/users/1906044", "pm_score": 4, "selected": false, "text": "<p>Yes, CallByName is the best solution for you. Here's instruction of doing it: </p>\n\n<pre><code>CallByName(yourClassOrObjectName,\"NameExample1\",CallType.Set,oReader.ReadString)\n</code></pre>\n\n<p>You can write \"NameExample\" in place of \"NameExample1\".<br>\nMention, that third parameter lets you 'Get', 'Let' that parameter (and even invoke any method).<br>\nSo you can get your parameter's value using <code>CallType.Get</code>.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20/" ]
I'm currently working on a project where a section of the code looks like this: ``` Select Case oReader.Name Case "NameExample1" Me.Elements.NameExample1.Value = oReader.ReadString ' ... Case "NameExampleN" Me.Elements.NameExampleN.Value = oReader.ReadString ' ... End Select ``` It continues on for a while. The code is obviously verbose and it *feels* like it could be improved. Is there any way to dynamically invoke a property in VB.NET such that something like this can be done: ``` Dim sReadString As String = oReader.ReadString Me.Elements.InvokeProperty(sReadString).Value = sReadString ```
Others have answered perfectly reasonably, but just in case this is a performance-sensitive piece of code, you might want to compile the reflective calls into delegates. I've got a [blog entry](http://codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates) about turning [MethodBase.Invoke](http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.invoke.aspx) into delegates. The code is in C#, but the same technique can be applied to VB.NET as well. To use this with properties, get the appropriate "setter" method with [PropertyInfo.GetSetMethod](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getsetmethod.aspx) and then build a delegate which invokes that. You could have a map from field name to "delegate to call to set the field". Just to reiterate, this is only really necessary if it's in a performance-critical piece of code. Otherwise, you might still want to create a `Dictionary<string, PropertyInfo>` to avoid calling `GetProperty` many times, but the step to convert it into a delegate probably isn't worth worrying about.
240,850
<p>I am having an issue when using <code>LoadControl( type, Params )</code>. Let me explain...</p> <p>I have a super simple user control (ascx)</p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="True" Inherits="ErrorDisplay" Codebehind="ErrorDisplay.ascx.cs" EnableViewState="false" %&gt; &lt;asp:Label runat="server" ID="lblTitle" /&gt; &lt;asp:Label runat="server" ID="lblDescription" /&gt; </code></pre> <p>with code ( c# ) behind of:</p> <pre><code>public partial class ErrorDisplay : System.Web.UI.UserControl { private Message _ErrorMessage; public ErrorDisplay() { } public ErrorDisplay(Message ErrorMessage) { _ErrorMessage = ErrorMessage; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (_ErrorMessage != null) { lblTitle.Text = _ErrorMessage.Message; lblDescription.Text = _ErrorMessage.Description; } } } </code></pre> <p>Elsewhere in my web application I am adding an instance of the usercontrol to the page using the following code:</p> <pre><code>divValidationIssues.Controls.Add(LoadControl(typeof(ErrorDisplay), new object[] { MessageDetails })); </code></pre> <p>I am using the overloaded version of LoadControl because I want to pass the Message parameter to the constructor. All this <em>appears</em> to work ok.</p> <p>However, when the <code>OnPreRender()</code> is fired on the ErrorDisplay usercontrol the lblTitle and lblDescription variables are both <code>null</code>, despite them having a markup equivalent. The message variable has been correctly populated.</p> <p>Can anyone shed any light on why this may be happening?</p> <p>Thanks</p> <p><strong>EDIT:</strong></p> <p>Just for clarity I'll also add that the code which is programatically adding the usercontrol to the page is running in response to a button press, so the 'hosting page' has progressed through Init, Page_Load and is now processing the event handlers.</p> <p>I cannot add the usercontrols at an earlier asp lifecycle stage as they are being created in response to a button click event.</p>
[ { "answer_id": 240866, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": -1, "selected": false, "text": "<p>Per the asp.net page lifecycle your controls are not fully added in pre-render, why don't you just load the values in page_load?</p>\n" }, { "answer_id": 240926, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 0, "selected": false, "text": "<p>Agreeing with Mitchel, you should be able to put a page_load in the control code itself which would fire after the controls are completely available. </p>\n" }, { "answer_id": 240998, "author": "Ash", "author_id": 31128, "author_profile": "https://Stackoverflow.com/users/31128", "pm_score": 6, "selected": true, "text": "<p>I have tried the following code as well - which yields the same result (i.e. both lblTitle and lblDescription are null)</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n if (_ErrorMessage != null)\n {\n lblTitle.Text = _ErrorMessage.Message;\n lblDescription.Text = _ErrorMessage.Description;\n }\n}\n</code></pre>\n\n<p>I had the understanding that the LoadControl function brought the control it is loading up to the current 'state' of the page onto which it is being included on. hence the Init, Page_Load etc are all run as part of the LoadControl call.</p>\n\n<p>Interestingly this (unanswered) asp.net forums post exhibits the same problem as I am experiencing.</p>\n\n<p><a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2333625&amp;SiteID=1\" rel=\"noreferrer\">MSDN Forums Post</a></p>\n\n<p>Additionally - From the MSDN:</p>\n\n<blockquote>\n <p>When you load a control into a container control, the container raises all of the added control's events until it has caught up to the current event. However, the added control does not catch up with postback data processing. For an added control to participate in postback data processing, including validation, the control must be added in the Init event rather than in the Load event. </p>\n</blockquote>\n\n<p>Therefore shouldn't LoadControl correctly initalise the control?</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Ok, so I'm answering my own question here ..</p>\n\n<p>I found an answered version of the forum post I linked to above <a href=\"http://forums.asp.net/t/1174838.aspx\" rel=\"noreferrer\">Here</a> </p>\n\n<p>Essentially the answer is that the <code>LoadControl( type, params )</code> cannot infer the 'page infront' ascx to parse and hence it doesn't bother initalising any of the controls. When you use the <code>LoadControl( \"ascx path\" )</code> version it is given the page infront and hence does all the parsing and initalision.</p>\n\n<p>So in summary I need to change the code which is initalising the control and split it into seperate parts. I.e.</p>\n\n<pre><code>Control ErrorCntrl = LoadControl(\"ErrorDisplay.ascx\");\nErrorCntrl.ID = SomeID;\n(ErrorCntrl as ErrorDisplay).SetErrorMessage = MessageDetail;\ndivErrorContainer.Controls.Add(ErrorCntrl);\n</code></pre>\n\n<p>And it should work ok.. It isn't as neat as my previous attempt, but at least it will work.</p>\n\n<p>I am still open to suggestions to improve the above.</p>\n\n<p>Cheers</p>\n" }, { "answer_id": 241508, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 0, "selected": false, "text": "<p>Well there is always adding your own load event and calling it after you have ran the constructor and added the control to the page, but it's not a lot different than what you have, although I might choose it for style reasons.</p>\n\n<p>Glad you found an answer to your issue!</p>\n" }, { "answer_id": 20220236, "author": "bflemi3", "author_id": 547071, "author_profile": "https://Stackoverflow.com/users/547071", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.grumpydev.com/2009/01/05/passing-parameters-using-loadcontrol/\" rel=\"nofollow\">Here</a> is a blog post written by Steven Robbins. The post explains how to pass parameters for a user control using <code>LoadControl</code>, similar to what <code>LoadControl(Type, object[])</code> would do, <strong>except it works</strong> :)</p>\n" }, { "answer_id": 23184186, "author": "WebKing", "author_id": 3554213, "author_profile": "https://Stackoverflow.com/users/3554213", "pm_score": 0, "selected": false, "text": "<p>I had a similar issue with the Calendar control DayRender event, in that I wanted to add a user control to the e.Cell.Controls collection. After trying a couple of failed approaches with the user control page_load not firing or the listbox on the ascx throwing a null exception, I found that if I initialized my control on the form with LoadControl(ascx) and then start accessing the markup controls on the ascx, everything worked fine. This approach does not depend upon the Page_Load event on the ascx at all.</p>\n\n<p>ASCX markup</p>\n\n<p>\n \n</p>\n\n<p>code behind</p>\n\n<p>Public Class CPCalendarCell\n Inherits System.Web.UI.UserControl</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n\nEnd Sub\n\nPublic Sub Add(txt As String)\n Dim li As New ListItem(txt, txt)\n lstDay.Items.Add(li)\nEnd Sub\n</code></pre>\n\n<p>End Class</p>\n\n<p>page ASPX markup</p>\n\n<p>\n \n</p>\n\n<p>code behind Calendar DayRender event on the form</p>\n\n<pre><code>Private Sub Calendar1_DayRender(sender As Object, e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender\n Dim div As CPCalendarCell = LoadControl(\"~/UserControls/CPCalendarCell.ascx\")\n div.ID = \"dv_\" &amp; e.Day.Date.ToShortDateString.Replace(\" \", \"_\")\n\n **e.Cell.Controls.Add(div)**\n\n div.Add(e.Day.Date.Month.ToString &amp; \"/\" &amp; e.Day.Date.Day.ToString)\n div.Add(\"Item 1\")\n div.Add(\"Item 2\")\n e.Cell.Style.Add(\"background-color\", IIf(e.Day.IsWeekend, \"whitesmoke\", \"white\").ToString)\nEnd Sub\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31128/" ]
I am having an issue when using `LoadControl( type, Params )`. Let me explain... I have a super simple user control (ascx) ``` <%@ Control Language="C#" AutoEventWireup="True" Inherits="ErrorDisplay" Codebehind="ErrorDisplay.ascx.cs" EnableViewState="false" %> <asp:Label runat="server" ID="lblTitle" /> <asp:Label runat="server" ID="lblDescription" /> ``` with code ( c# ) behind of: ``` public partial class ErrorDisplay : System.Web.UI.UserControl { private Message _ErrorMessage; public ErrorDisplay() { } public ErrorDisplay(Message ErrorMessage) { _ErrorMessage = ErrorMessage; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (_ErrorMessage != null) { lblTitle.Text = _ErrorMessage.Message; lblDescription.Text = _ErrorMessage.Description; } } } ``` Elsewhere in my web application I am adding an instance of the usercontrol to the page using the following code: ``` divValidationIssues.Controls.Add(LoadControl(typeof(ErrorDisplay), new object[] { MessageDetails })); ``` I am using the overloaded version of LoadControl because I want to pass the Message parameter to the constructor. All this *appears* to work ok. However, when the `OnPreRender()` is fired on the ErrorDisplay usercontrol the lblTitle and lblDescription variables are both `null`, despite them having a markup equivalent. The message variable has been correctly populated. Can anyone shed any light on why this may be happening? Thanks **EDIT:** Just for clarity I'll also add that the code which is programatically adding the usercontrol to the page is running in response to a button press, so the 'hosting page' has progressed through Init, Page\_Load and is now processing the event handlers. I cannot add the usercontrols at an earlier asp lifecycle stage as they are being created in response to a button click event.
I have tried the following code as well - which yields the same result (i.e. both lblTitle and lblDescription are null) ``` protected void Page_Load(object sender, EventArgs e) { if (_ErrorMessage != null) { lblTitle.Text = _ErrorMessage.Message; lblDescription.Text = _ErrorMessage.Description; } } ``` I had the understanding that the LoadControl function brought the control it is loading up to the current 'state' of the page onto which it is being included on. hence the Init, Page\_Load etc are all run as part of the LoadControl call. Interestingly this (unanswered) asp.net forums post exhibits the same problem as I am experiencing. [MSDN Forums Post](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2333625&SiteID=1) Additionally - From the MSDN: > > When you load a control into a container control, the container raises all of the added control's events until it has caught up to the current event. However, the added control does not catch up with postback data processing. For an added control to participate in postback data processing, including validation, the control must be added in the Init event rather than in the Load event. > > > Therefore shouldn't LoadControl correctly initalise the control? **EDIT:** Ok, so I'm answering my own question here .. I found an answered version of the forum post I linked to above [Here](http://forums.asp.net/t/1174838.aspx) Essentially the answer is that the `LoadControl( type, params )` cannot infer the 'page infront' ascx to parse and hence it doesn't bother initalising any of the controls. When you use the `LoadControl( "ascx path" )` version it is given the page infront and hence does all the parsing and initalision. So in summary I need to change the code which is initalising the control and split it into seperate parts. I.e. ``` Control ErrorCntrl = LoadControl("ErrorDisplay.ascx"); ErrorCntrl.ID = SomeID; (ErrorCntrl as ErrorDisplay).SetErrorMessage = MessageDetail; divErrorContainer.Controls.Add(ErrorCntrl); ``` And it should work ok.. It isn't as neat as my previous attempt, but at least it will work. I am still open to suggestions to improve the above. Cheers
240,874
<p>When you have a derived class, is there an simpler way to refer to a variable from a method other than:</p> <pre><code>BaseClass::variable </code></pre> <p><strong>EDIT</strong> <br>As it so happens, I found a page that explained this issue using functions instead: <a href="http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19" rel="nofollow noreferrer">Template-Derived-Classes Errors</a>. Apparently it makes a difference when using templates classes.</p>
[ { "answer_id": 240881, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 4, "selected": true, "text": "<p>If the base class member variable is protected or public than you can just refer to it by name in any member function of the derived class. If it is private to the base class the compiler will not let the derived class access it at all. Example:</p>\n\n<pre><code>\nclass Base\n{\nprotected:\n int a;\n\nprivate:\n int b;\n};\n\nclass Derived : public Base\n{\n void foo()\n {\n a = 5; // works\n b = 10; // error!\n }\n};\n</code></pre>\n\n<p>There is also something to be said for keeping all member variables private, and providing getters and setters as needed.</p>\n\n<p>Also, beware of \"hiding\" data members:</p>\n\n<pre><code>\nclass Base\n{\npublic:\n int a;\n};\n\nclass Derived : public Base\n{\npublic:\n int a;\n};\n</code></pre>\n\n<p>This will create two variables named <code>a</code>: one in <code>Base</code>, one in <code>Derived</code>, and it will likely lead to confusion and bugs. </p>\n" }, { "answer_id": 240922, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 1, "selected": false, "text": "<p>Related: <a href=\"https://stackoverflow.com/questions/180601/using-super-in-c\">Using “super” in C++</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73/" ]
When you have a derived class, is there an simpler way to refer to a variable from a method other than: ``` BaseClass::variable ``` **EDIT** As it so happens, I found a page that explained this issue using functions instead: [Template-Derived-Classes Errors](http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19). Apparently it makes a difference when using templates classes.
If the base class member variable is protected or public than you can just refer to it by name in any member function of the derived class. If it is private to the base class the compiler will not let the derived class access it at all. Example: ``` class Base { protected: int a; private: int b; }; class Derived : public Base { void foo() { a = 5; // works b = 10; // error! } }; ``` There is also something to be said for keeping all member variables private, and providing getters and setters as needed. Also, beware of "hiding" data members: ``` class Base { public: int a; }; class Derived : public Base { public: int a; }; ``` This will create two variables named `a`: one in `Base`, one in `Derived`, and it will likely lead to confusion and bugs.
240,876
<p>I have this code</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main(int argc,char **argv) { unsigned long long num1 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999995LL; unsigned long long num2 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996LL; unsigned long long num3 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997LL; unsigned long long num4 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998LL; unsigned long long num5 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999LL; cout &lt;&lt; (unsigned long long)(num1 * num2 * num3 * num4 * num5) &lt;&lt; endl; return 0; } </code></pre> <p>As you can see the numbers are enormous, but when I do the math there I get this: 18446744073709551496</p> <p>At compile time I get these warnings:</p> <pre><code>warning: integer constant is too large for its type| In function `int main(int, char**)':| warning: this decimal constant is unsigned only in ISO C90| ... </code></pre>
[ { "answer_id": 240888, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>unsigned int represents a system word. Today, that word will max out at either 2^32 -1 or 2^64 - 1, depending on whether your system is 32 bit or 64 bit. You're hitting the cap.</p>\n\n<p>You have to write a bignum class or use one off the 'net.</p>\n\n<p>Why are you doing this problem anyway?</p>\n" }, { "answer_id": 240891, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 3, "selected": false, "text": "<p>Those numbers won't fit into any C++ data types. If you just want to print them, store the numbers in a string. If you want to do math on it, find an arbitrary precision math library and use that.</p>\n" }, { "answer_id": 240892, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 6, "selected": true, "text": "<p>Your result is larger than the long long type - you need to look at a <a href=\"http://mattmccutchen.net/bigint/\" rel=\"noreferrer\">BigInteger</a> or arbitrary precision library, something like <a href=\"http://gmplib.org/\" rel=\"noreferrer\">gmp</a></p>\n" }, { "answer_id": 241098, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 1, "selected": false, "text": "<p>The answer that you got, 18446744073709551496, is due to your 999...9s being truncated when assigned to a long long, plus the multiple operations overflowing. Its deterministic, but effectively just a random collection of bits. </p>\n" }, { "answer_id": 241116, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 2, "selected": false, "text": "<p>If you want literals this big in your code, you'll have to enter them as string literals and load them into a BigInt class of some sort. There's no way to express integer literals that big in source code right now (although C++0x will hopefully address that shortfall).</p>\n\n<p>If you're using the <a href=\"http://mattmccutchen.net/bigint/\" rel=\"nofollow noreferrer\">BigInteger</a> library, take a look at the <code>stringToBigUnsigned</code> function in <code>BigIntegerUtils.hh</code> for building a big integer from a string.</p>\n\n<pre><code>#include \"BigUnsigned.hh\"\n#include \"BigIntegerUtils.hh\" \n\n BigUnsigned num1 = stringToBigUnsigned (\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999995\"\n );\n</code></pre>\n" }, { "answer_id": 241908, "author": "old_timer", "author_id": 16007, "author_profile": "https://Stackoverflow.com/users/16007", "pm_score": 2, "selected": false, "text": "<p>What is it you are trying to do? Do you understand the basics of binary and decimal numbers? Why 8 bits only holds the values 0 to 255, 12 bits 0 - 4095, etc? How many bits does it take to hold the number you are interested in? Or better, how big of a number are you interested in creating? And are you using 9s to make the number bigger? What about hex 0xF... instead? If you want the biggest unsigned number (within one of the standard integer types) why not:</p>\n\n<p>unsigned long long a,b;</p>\n\n<p>a = -1; //which just seems wrong mixing signed and unsigned but it is valid, the number is converted to unsigned before storing</p>\n\n<p>b = 0; b--; //does the same thing as above </p>\n\n<p>Do you really need precision at that level? You realize that multiplies can require a result twice the size of each operand? 0xFF * 0xFF = 0xFE01, if in this case you were using 8 bit integers you could not do the math. It only gets worse as you continue to multiply 0xFF * 0xFF * 0xFF = 0xFD02FF.</p>\n\n<p>What are trying to do? </p>\n\n<hr>\n\n<p>Seeing your response:</p>\n\n<p>I have not seen euler number 8 before. Sounds like a good interview question as it only takes a few lines of code to solve.</p>\n\n<hr>\n\n<p>Your other response:</p>\n\n<p>Numbers...</p>\n\n<p>Likely because we have 10 fingers (and perhaps 10 toes) we grow up with \"base 10\". Our clocks are base 60 for the most part but it has been mixed with base 10 to make it more confusing. Anyway, base 10, means for each number placeholder you have one of 10 unique digits, when you reach the maximum in that place you roll over to the next place. This is all elementary school stuff.</p>\n\n<p>000<br>\n001<br>\n002<br>\n003<br>\n...<br>\n008<br>\n009<br>\n010<br>\n011<br>\n012<br>\n... </p>\n\n<p>See how the right most digit has 10 symbols (0,1,2,3,4,5,6,7,8,9) and when it reaches the last symbol it starts over and the one to the left of it increments by one. This rule is true for all base numbering systems.</p>\n\n<p>It is true for base 2 except there are only two symbols, 0 and 1</p>\n\n<p>000<br>\n001<br>\n010<br>\n011<br>\n100<br>\n101<br>\n... </p>\n\n<p>Same is true for octal, but 8 symbols (0,1,2,3,4,5,6,7)</p>\n\n<p>000<br>\n001<br>\n002<br>\n003<br>\n004<br>\n005<br>\n006<br>\n007<br>\n010<br>\n011<br>\n012<br>\n013<br>\n... </p>\n\n<p>And the same is true for hexadecimal, 16 symbols(0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f)</p>\n\n<p>000<br>\n001<br>\n002<br>\n003<br>\n004<br>\n005<br>\n006<br>\n007<br>\n008<br>\n009<br>\n00a<br>\n00b<br>\n00c<br>\n00d<br>\n00e<br>\n00f<br>\n010<br>\n011<br>\n012<br>\n013<br>\n... </p>\n\n<p>I was about to go into the whys of using binary over other bases (like 10) in computers. The bottom line it is easy to have two states on or off, or high and low. Two states is like two symbols 1 and 0 in base 2. Trying to keep electronics tuned to more than two states within the available voltage is tough, at least it used to be, keeping it near zero volts or above some small number of volts is relatively easy, so digital electronics use two states, binary. </p>\n\n<p>Even a simple task for a human in binary is long winded, simple second grade math is still a lot of ones and zeros. So octal became popular because it allowed you to think in groups of three bits and you could use symbols we are familiar with as numbers 0,1,2,3,4,5,6,7. But groups of four which is another power of 2, gives the humans a lot more mental computing power than octal, hex is based on 4 bits which is also a power of 2. We had to add more symbols to the 10 we borrowed from the traditial arabic base 10, so the first 6 of the alphabet was used. Octal is rarely if ever used, you can tell someones age if they think octal instead of hex. (I am from the hex generation but have worked with those from the octal generation that struggle with hex because they cannot get from octal to binary to hex in their mind).</p>\n\n<p>Base 10 in a computer is like the average human thinking in hex. computers dont do base 10 (well for lazy humans they used to do bcd), they do base 2. The decimal number 1234 in a computer is really 0x4D2 or 0b010011010010. That is as a value, say you want to add 1234 plus some other number you need that value which has nothing to do with the symbos 1, 2, 3, and 4. But to post this answer on stackoverflow we dont use the number we use ASCII, so 1234 in ascii is 0x31, 0x32, 0x33, 0x34, which is important to know for your euler solution assuming the 1000 digit number was provided as an ascii string, which it would have to be or you would have to convert it from binary to ascii since the problem is a base 10 problem and not base 2 by definition.</p>\n\n<p>So back to what I had asked. Say you had 4 bits of memory to store a number, how big of a number could you store? If you think base 10 only you might think that number is a 9, because you are trained to think of using the biggest symbol in each storage location, 99999 is the biggest number if you have 5 storage locations in base 10. Back to four bits though, the biggest symbol for a single bit is 1, put that number in each storage location you get 1111 (four ones). Just by looking at those four ones you should be able to in your mind easily see the octal and hex version of that same number 17 octal or F hex. To see decimal takes math, or in this case memorization, that number is 15 decimal. So the biggest four bit number you can have is 0xF or 15 not 9. What about an 8 bit number? 0xFF or 255 (2 to the 8th power minus one). Biggest 16 bit number? 65535, etc.</p>\n\n<p>So when I ask how many bits are you trying to use this is what I mean. Look at this number 99999. Again base 10 you would think that is the biggest number, but to a computer it is only part way there, 99999 decimal is 0x1869F, which takes 17 bits of memory to store, the biggest 17 bit number you can store is 0x1FFFF which is 131071 which is a bit bigger than 99999. So when you want to think big numbers and math on a computer you have to think binary (or hex).</p>\n\n<p>Originally you were doing multiplications, which is still part of the euler problem, but what was I was asking about was related to precision and bit storage. Here are some fundamentals, and I wont get into it but you can see why we rely on floating point units in computers.</p>\n\n<p>Take the largest 4 bit number 1111(binary), which is 15 decimal. Add that with the largest four bit number and you get 15+15 = 30 = 0x1E or 11110 binary. So to add two four bit numbers you need five bits to hold your answer. Computers keep a \"carry\" bit for this extra bit. Essentially the add/subtract integer math functions in the computer allow you to have N+1 bits. So if it is an 32 bit computer you basically have 33 bits for add/sub math. </p>\n\n<p>The problem is multiply and divide, which even today many processors do not support (yes many have no fpu and only do add and subtract, sometimes multiply, but divide is rare. Multiply and divide take a lot of electronics the trade off is you can do them with adds and subtracts in software). Take the worst case multiply for a four bit system\n1111 * 1111 = 11100001 so it takes 8 bits to store the result of a 4 bit multiply, you will quickly find that if you had a 4 bit system MOST of the multiplies you want to do will result a number that cannot be stored in 4 bits. So when I saw you taking 64 bit integers (the unsigned long long is often 64 bits) and multiplying four times, that means you need 64*5 or a 320 bit integer to store your answer, you were trying to put that answer in a 64 big result, which quite often, depending on the compiler and computer will happily do and will truncate the upper bits leaving you with the lower 64 bits of the result which can easily look smaller than any of your operands, which is what I had thought you might have done at first.</p>\n\n<p>Floating point is not much more than scientific notation but in binary, if you wanted to multiply the number 1234 and 5678 using scientific notation you would take 1.234*10^3 times 5.678*10^3 and get 7.007*10^6. You keep your precision and are able to represent a wider range of numbers. I wont get into how this works in binary. But it doesnt work for your original question.</p>\n\n<p>Ahh, the last thing to clarify what I was doing in my question/response. Negative integers in binary. Because of the relationships between addition and subtraction and base systems you can play some tricks. Say I wanted to subtract 1 from the number 7(decimal) using binary. Well there is no such thing as a subtract circuit, you instead add a negative number so instead of 7 - 1 it is really 7 + (-1), it makes a difference:</p>\n\n<p>0111 + ???? = 0110</p>\n\n<p>What number could you add to 7 to get 6...in binary?</p>\n\n<p>0111 + 1111 = 0110</p>\n\n<p>Negative numbers in binary are called \"twos complement\", long story short the answer is \"invert and add 1\". How do you represent minus 1 in binary? take plus one 0001 then invert it meaning make the ones zeros and the zeros ones (also known as ones complement) 1110 then add one 1111. Minus one is a special number in computers (well everywhere) as no matter how many bits you have it is represented as all ones. So when you see someone do this:</p>\n\n<p>unsigned char a;</p>\n\n<p>a = -1;</p>\n\n<p>The compiler first looks at that -1 and thinks ...11111(binary) then it looks at the equals sign and the other side, oh, you want a to be all ones, it sees that you have a signed integer and an unsigned but the conversion is to just move the bits over so you are saying above that you want a = 0xFF; (assuming an 8 bit unsigned char).</p>\n\n<p>Some compilers may complain that you are trying to store a negative number in an unsigned number. Other compilers will look at that -1 and see it as a 32 bit or these days maybe 64 bit signed integer constant and then when it evaluates the equals into an 8 bit unsigned you will get a warning that you cannot store -1 in a signed or unsigned char without a typecast. But if you do this:</p>\n\n<p>a = 0; a--;</p>\n\n<p>All compilers will like that. and wont complain, it just burns computing cycles at runtime instead of compile time.</p>\n\n<p>Now somewhere a friend told me of a book that does binary math serially. For example to negate a number, usually you do the invert and ad one trick, but with pencil and paper some may tell you the other trick. Starting from the right copy the zeros up to and including the first 1 then invert after that, so minus 2</p>\n\n<p>0010<br>\n1110 </p>\n\n<p>Starting from the right copy the 0 then the first one, then invert the remaining bits as you go left.</p>\n\n<p>minus 6</p>\n\n<p>0110<br>\n1010 </p>\n\n<p>minus 4</p>\n\n<p>0100<br>\n1100 </p>\n\n<p>Supposedly there are tricks to do add and subtract (well duh, those are easy) but also multiply and divide. If you do them serially then you can do infinitely long math in binary with the same alu. If you were to know how to do that you could implement that in software and your original question of multiplying big constants (with the assumption of retaining all the precision) is trivial on any computer.</p>\n" }, { "answer_id": 12458092, "author": "Anshul garg", "author_id": 692846, "author_profile": "https://Stackoverflow.com/users/692846", "pm_score": 0, "selected": false, "text": "<p>The numbers can't fit in <code>unsigned long long</code> range so either you could use GMP library or use string to represent big numbers like I did for calculating factorial of number like 50:</p>\n\n<p><a href=\"http://codepad.org/bkWNV0JC\" rel=\"nofollow\">http://codepad.org/bkWNV0JC</a> </p>\n\n<pre><code>#include &lt;cmath&gt;\n#include &lt;iostream&gt;\nusing namespace std;\nint main()\n{\n unsigned int nd, nz; \n unsigned char *ca; \n unsigned int j, n=50, q, temp;\n int i;\n double p;\n p = 0.0;\n for(j = 2; j &lt;= n; j++)\n {\n p += log10((double)j); \n }\n nd = (int)p + 1;\n\n ca = new unsigned char[nd+1];\n if (!ca)\n {\n cout &lt;&lt; \"Could not allocate memory!!!\";\n exit(0);\n }\n for (i = 1; (unsigned)i &lt; nd; i++)\n {\n ca[i] = 0;\n }\n ca[0] = 1;\n\n p = 0.0;\n for (j = 2; j &lt;= n; j++)\n {\n p += log10((double)j); \n nz = (int)p + 1; \n q = 0; \n for (i = 0;(unsigned) i &lt;= nz; i++)\n {\n temp = (ca[i] * j) + q;\n q = (temp / 10);\n ca[i] = (char)(temp % 10);\n }\n }\n\n cout &lt;&lt; \"\\nThe Factorial of \" &lt;&lt; n &lt;&lt; \" is: \";\n for( i = nd - 1; i &gt;= 0; i--)\n {\n cout &lt;&lt; (int)ca[i];\n }\n // delete []ca; \n return 0;\n}\n</code></pre>\n" }, { "answer_id": 59005646, "author": "jav", "author_id": 972910, "author_profile": "https://Stackoverflow.com/users/972910", "pm_score": 0, "selected": false, "text": "<p>If you can use Boost you can try <a href=\"https://www.boost.org/doc/libs/1_71_0/libs/multiprecision/doc/html/boost_multiprecision/tut/ints/cpp_int.html\" rel=\"nofollow noreferrer\">cpp_int</a>. It might be a bit slower than GMP but it is a header only library.</p>\n\n<pre><code>#include &lt;boost/multiprecision/cpp_int.hpp&gt;\n#include &lt;iostream&gt;\n\nint main()\n{\n using namespace boost::multiprecision;\n// Repeat at arbitrary precision:\n cpp_int u = 1;\n for(unsigned i = 1; i &lt;= 100; ++i)\n u *= i;\n\n // prints 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 (i.e. 100!)\n std::cout &lt;&lt; u &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8715/" ]
I have this code ``` #include <iostream> using namespace std; int main(int argc,char **argv) { unsigned long long num1 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999995LL; unsigned long long num2 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996LL; unsigned long long num3 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997LL; unsigned long long num4 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998LL; unsigned long long num5 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999LL; cout << (unsigned long long)(num1 * num2 * num3 * num4 * num5) << endl; return 0; } ``` As you can see the numbers are enormous, but when I do the math there I get this: 18446744073709551496 At compile time I get these warnings: ``` warning: integer constant is too large for its type| In function `int main(int, char**)':| warning: this decimal constant is unsigned only in ISO C90| ... ```
Your result is larger than the long long type - you need to look at a [BigInteger](http://mattmccutchen.net/bigint/) or arbitrary precision library, something like [gmp](http://gmplib.org/)
240,903
<p>I'm looking for a library that can deal with RDF and OWL data.</p> <p>So far I have found:</p> <ul> <li><a href="http://razor.occams.info/code/semweb/" rel="nofollow noreferrer">semweb</a> (no owl support for all I know)</li> <li><a href="http://rowlex.nc3a.nato.int/HowToUse.aspx" rel="nofollow noreferrer">rowlex</a> (more of a 'browser' application)</li> </ul> <p>Your recommendations:</p> <ul> <li><a href="https://code.google.com/p/linqtordf/" rel="nofollow noreferrer">LinqToRdf</a> (very interesting, thanks mark!)</li> </ul>
[ { "answer_id": 240966, "author": "IAdapter", "author_id": 30453, "author_profile": "https://Stackoverflow.com/users/30453", "pm_score": 2, "selected": false, "text": "<p>I researched this just a bit several months ago. One of the more interesting\nprojects I could find is:\n<a href=\"http://www.hookedonlinq.com/linqtordf.ashx\" rel=\"nofollow noreferrer\">http://www.hookedonlinq.com/linqtordf.ashx</a></p>\n" }, { "answer_id": 545739, "author": "Mr. Lame", "author_id": 24451, "author_profile": "https://Stackoverflow.com/users/24451", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://rowlex.nc3a.nato.int\" rel=\"noreferrer\">ROWLEX</a> is actually very cool (uses <a href=\"http://razor.occams.info/code/semweb/\" rel=\"noreferrer\">SemWeb</a> internally). It is not just a browser app but rather an SDK written in C#. If you use ROWLEX, you do not directly interact with the tripples of RDF anymore (though you can), but gives an object oriented look&amp;feel. There are two main usage scenarios:</p>\n<ol>\n<li><strong>Business class first:</strong> You have your .NET business classes. You declaratively add attributes to your classes similarly as you do with XML serialization attributes. After this, ROWLEX can extract the ontology corresponding your business classes and/or can serialize your business objects into RDF.</li>\n<li><strong>Ontology first:</strong> You have your ontology(s) and <a href=\"http://rowlex.nc3a.nato.int\" rel=\"noreferrer\">ROWLEX</a> generates .NET classes for you that you can use to build/browse RDF documents. The great thing is that these autogenerated classes are far better then the typical results of codegenerators. They are comfortable to use and mimic the multiple inheritence feature of OWL by providing implicit and explicit cast operators to cover the entire inheritence graph.</li>\n</ol>\n<p>The typical usage is the Ontology first approach. For example, let us say that your ontology describes the following multiple inheritence scenario:</p>\n<blockquote>\n<p>Car isSubClassOf Vehicle</p>\n<p>Car isSubClassOf CompanyAsset</p>\n</blockquote>\n<p>Using ROWLEX, you will get .NET classes for Car, Vehicle, and CompanyAsset. The following C# code will compile without any problem:</p>\n<pre><code> RdfDocument rdfDoc = new RdfDocument();\n Car car = new Car(&quot;myCarUri&quot;, rdfDoc);\n Vehicle vehicle = car; // implicit casting\n CompanyAsset companyAsset = car; // implicit casting \n vehicle.WheelCount = 4;\n companyAsset.MonetaryValue = 15000;\n Console.WriteLine(rdfDoc.ToN3());\n</code></pre>\n<p>This would print:</p>\n<pre><code>myCarUri typeOf Car \nmyCarUri WheelCount 4 \nmyCarUri MonetaryValue 15000\n</code></pre>\n<p>The &quot;car&quot; business object is represented inside the RdfDocument as triples. The autogenerated C#/VB classes behave as a views. You can have several C# views - each of a completely different type - on the same business object. When you interact with these views, you actually modifying the RdfDocument.</p>\n" }, { "answer_id": 3548627, "author": "RobV", "author_id": 107591, "author_profile": "https://Stackoverflow.com/users/107591", "pm_score": 3, "selected": false, "text": "<p>I produce an open source library <a href=\"http://www.dotnetrdf.org\" rel=\"noreferrer\">dotNetRDF</a> - OWL support is currently somewhat limited though so may not be ideal for your uses</p>\n" }, { "answer_id": 9517792, "author": "Graham Moore", "author_id": 1242862, "author_profile": "https://Stackoverflow.com/users/1242862", "pm_score": 3, "selected": false, "text": "<p>BrightstarDB is a native, .NET NoSQL RDF triple store, with SPARQL support, a .NET entity framework with LINQ and OData support. It is free for developers and open source projects and has a small runtime cost for commercial use.</p>\n\n<p>BrightstarDB provide three levels of API.</p>\n\n<ol>\n<li>SPARQL query and simple transaction API.</li>\n<li>A generic object api that groups collections of triples into data objects</li>\n<li>A Visual Studio integration that takes Interface definitions and generated a strongly typed .NET domain model that stores its data as RDF in a BrightstarDB instance. The .NET model has LINQ support and can also be exposed as an OData service.</li>\n</ol>\n\n<p>All BrightstarDB documentation is online and the software is available for download with no registration at <a href=\"http://www.brightstardb.com\">http://www.brightstardb.com</a></p>\n" }, { "answer_id": 11403230, "author": "janet", "author_id": 1513131, "author_profile": "https://Stackoverflow.com/users/1513131", "pm_score": 2, "selected": false, "text": "<p>Try <a href=\"http://rdfsharp.codeplex.com\" rel=\"nofollow\">RDFSharp</a> at Codeplex. Seems young but promising.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13466/" ]
I'm looking for a library that can deal with RDF and OWL data. So far I have found: * [semweb](http://razor.occams.info/code/semweb/) (no owl support for all I know) * [rowlex](http://rowlex.nc3a.nato.int/HowToUse.aspx) (more of a 'browser' application) Your recommendations: * [LinqToRdf](https://code.google.com/p/linqtordf/) (very interesting, thanks mark!)
[ROWLEX](http://rowlex.nc3a.nato.int) is actually very cool (uses [SemWeb](http://razor.occams.info/code/semweb/) internally). It is not just a browser app but rather an SDK written in C#. If you use ROWLEX, you do not directly interact with the tripples of RDF anymore (though you can), but gives an object oriented look&feel. There are two main usage scenarios: 1. **Business class first:** You have your .NET business classes. You declaratively add attributes to your classes similarly as you do with XML serialization attributes. After this, ROWLEX can extract the ontology corresponding your business classes and/or can serialize your business objects into RDF. 2. **Ontology first:** You have your ontology(s) and [ROWLEX](http://rowlex.nc3a.nato.int) generates .NET classes for you that you can use to build/browse RDF documents. The great thing is that these autogenerated classes are far better then the typical results of codegenerators. They are comfortable to use and mimic the multiple inheritence feature of OWL by providing implicit and explicit cast operators to cover the entire inheritence graph. The typical usage is the Ontology first approach. For example, let us say that your ontology describes the following multiple inheritence scenario: > > Car isSubClassOf Vehicle > > > Car isSubClassOf CompanyAsset > > > Using ROWLEX, you will get .NET classes for Car, Vehicle, and CompanyAsset. The following C# code will compile without any problem: ``` RdfDocument rdfDoc = new RdfDocument(); Car car = new Car("myCarUri", rdfDoc); Vehicle vehicle = car; // implicit casting CompanyAsset companyAsset = car; // implicit casting vehicle.WheelCount = 4; companyAsset.MonetaryValue = 15000; Console.WriteLine(rdfDoc.ToN3()); ``` This would print: ``` myCarUri typeOf Car myCarUri WheelCount 4 myCarUri MonetaryValue 15000 ``` The "car" business object is represented inside the RdfDocument as triples. The autogenerated C#/VB classes behave as a views. You can have several C# views - each of a completely different type - on the same business object. When you interact with these views, you actually modifying the RdfDocument.
240,918
<p>I'd like to create a view in Sharepoint that has a filter based on a date field. </p> <p>The filter should be >= Today and &lt;- Today + 90 days. </p> <p>I found a reference to the </p> <pre><code>&lt;Today OffsetDays=”5” /&gt; </code></pre> <p>CAML function and could probably use this by setting the view using the API. </p> <p>My question is how do i set this using the browser based admin page? </p> <p><a href="http://www.isuppli.com/Img/Development/CreateViewSample.gif" rel="nofollow noreferrer">alt text http://www.isuppli.com/Img/Development/CreateViewSample.gif</a></p>
[ { "answer_id": 241075, "author": "AdamBT", "author_id": 22426, "author_profile": "https://Stackoverflow.com/users/22426", "pm_score": 3, "selected": true, "text": "<p>This can be done OTB using the filter dropdowns when modifying or creating a view:</p>\n\n<p><a href=\"http://img91.imageshack.us/my.php?image=filterew5.png\" rel=\"nofollow noreferrer\">Filter Image</a></p>\n\n<p><a href=\"http://img91.imageshack.us/my.php?image=filterew5.png\" rel=\"nofollow noreferrer\">alt text http://img91.imageshack.us/my.php?image=filterew5.png</a></p>\n\n<p>Edit: Fixed image</p>\n" }, { "answer_id": 249613, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Ok... when you using formula for the column...\nIt cant using [Today] because it doesnt exsist on the list column...]</p>\n\n<p>So i suggest that you must required the column Today first, so you can use [Today] At the formula..</p>\n\n<p>i think u just dont have using CAML or column formula, but it can do from filtering like AdamBT says...</p>\n\n<p>Hehehe...</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31679/" ]
I'd like to create a view in Sharepoint that has a filter based on a date field. The filter should be >= Today and <- Today + 90 days. I found a reference to the ``` <Today OffsetDays=”5” /> ``` CAML function and could probably use this by setting the view using the API. My question is how do i set this using the browser based admin page? [alt text http://www.isuppli.com/Img/Development/CreateViewSample.gif](http://www.isuppli.com/Img/Development/CreateViewSample.gif)
This can be done OTB using the filter dropdowns when modifying or creating a view: [Filter Image](http://img91.imageshack.us/my.php?image=filterew5.png) [alt text http://img91.imageshack.us/my.php?image=filterew5.png](http://img91.imageshack.us/my.php?image=filterew5.png) Edit: Fixed image
240,946
<p>I want my WPF ComboBox's ItemsSource property to be bound to MyListObject's MyList property. The problem is that when I update the MyList property in code, the WPF ComboBox is not reflecting the update. I am raising the PropertyChanged event after I perform the update, and I thought WPF was supposed to automatically respond by updating the UI. Am I missing something? </p> <p>Here's the CLR object:</p> <pre><code>Imports System.ComponentModel Public Class MyListObject Implements INotifyPropertyChanged Private _mylist As New List(Of String) Public Sub New() _mylist.Add("Joe") _mylist.Add("Steve") End Sub Public Property MyList() As List(Of String) Get Return _mylist End Get Set(ByVal value As List(Of String)) _mylist = value End Set End Property Public Sub AddName(ByVal name As String) _mylist.Add(name) NotifyPropertyChanged("MyList") End Sub Private Sub NotifyPropertyChanged(ByVal info As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info)) End Sub Public Event PropertyChanged(ByVal sender As Object, _ ByVal e As System.ComponentModel.PropertyChangedEventArgs) _ Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged End Class </code></pre> <p>Here is the XAML:</p> <pre><code>&lt;Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" xmlns:local="clr-namespace:WpfApplication1" &gt; &lt;Window.Resources&gt; &lt;ObjectDataProvider x:Key="MyListObject" ObjectType="{x:Type local:MyListObject}"/&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;ComboBox Height="23" Margin="24,91,53,0" Name="ComboBox1" VerticalAlignment="Top" ItemsSource="{Binding Path=MyList, Source={StaticResource MyListObject}}" /&gt; &lt;TextBox Height="23" Margin="24,43,134,0" Name="TextBox1" VerticalAlignment="Top" /&gt; &lt;Button Height="23" HorizontalAlignment="Right" Margin="0,43,53,0" Name="btn_AddName" VerticalAlignment="Top" Width="75"&gt;Add&lt;/Button&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>And here's the simple code-behind:</p> <pre><code>Class Window1 Private obj As New MyListObject Private Sub btn_AddName_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) _ Handles btn_AddName.Click obj.AddName(TextBox1.Text) End Sub End Class </code></pre> <p>Thanks!</p>
[ { "answer_id": 240983, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 3, "selected": true, "text": "<p>You are binding to a list of strings. That list class does not implement Inotifyproperty. You should use an observablecollection instead.\nI also notice in your code behind you declare </p>\n\n<pre><code>Private obj As New MyListObject\n</code></pre>\n\n<p>This is not the static resource you bound the combo box to. So your add call would not be reflected in your view.</p>\n" }, { "answer_id": 240991, "author": "Chris Porter", "author_id": 13495, "author_profile": "https://Stackoverflow.com/users/13495", "pm_score": 0, "selected": false, "text": "<p>Try using a <a href=\"http://msdn.microsoft.com/en-us/library/ms132679.aspx\" rel=\"nofollow noreferrer\">BindingList(Of T)</a> instead of a List(Of T).</p>\n\n<p>Edit: I am new to WPF and it does look like BindingList isn't a complete solution to your problem, but it might be a step in the right direction. I was able to test the MyListObject converted to BindingList in WinForm and the ListChanged event was raised to the ComboBox which then updated its list.</p>\n\n<p>I found this (possible) solution to wrap your class in an ObservableCollection that might help you solve your problem</p>\n\n<p><a href=\"http://blogs.sqlxml.org/bryantlikes/archive/2006/09/20/Enabling-WPF-Magic-Using-WCF-_2D00_-Part-1.aspx\" rel=\"nofollow noreferrer\">Enabling WPF Magic Using WCF - Part 1</a></p>\n\n<p>This is the code to update your object to a BindingList. Combine your code with the code from that resource and you should be good to go.</p>\n\n<pre><code>Public Class MyListObject\n ...\n\n 'Private _mylist As New List(Of String)\n Private _mylist As New BindingList(Of String)\n\n ...\n\n 'Public Property MyList() As List(Of String)\n ' Get\n ' Return _mylist\n ' End Get\n ' Set(ByVal value As List(Of String))\n ' _mylist = value\n ' End Set\n 'End Property\n\n Public Property MyList() As BindingList(Of String)\n Get\n Return _mylist\n End Get\n Set(ByVal value As BindingList(Of String))\n _mylist = value\n End Set\n End Property\n\n ...\n\nEnd Class\n</code></pre>\n" }, { "answer_id": 241013, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "<p>The ObservableCollection is most likely the solution, but if it still gives you grief, you can directly access your static resource by calling the following code after your list gets updated:</p>\n\n<pre><code>DirectCast(Me.FindResource(\"MyListObject\"), ObjectDataProvider).Source = _myList\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
I want my WPF ComboBox's ItemsSource property to be bound to MyListObject's MyList property. The problem is that when I update the MyList property in code, the WPF ComboBox is not reflecting the update. I am raising the PropertyChanged event after I perform the update, and I thought WPF was supposed to automatically respond by updating the UI. Am I missing something? Here's the CLR object: ``` Imports System.ComponentModel Public Class MyListObject Implements INotifyPropertyChanged Private _mylist As New List(Of String) Public Sub New() _mylist.Add("Joe") _mylist.Add("Steve") End Sub Public Property MyList() As List(Of String) Get Return _mylist End Get Set(ByVal value As List(Of String)) _mylist = value End Set End Property Public Sub AddName(ByVal name As String) _mylist.Add(name) NotifyPropertyChanged("MyList") End Sub Private Sub NotifyPropertyChanged(ByVal info As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info)) End Sub Public Event PropertyChanged(ByVal sender As Object, _ ByVal e As System.ComponentModel.PropertyChangedEventArgs) _ Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged End Class ``` Here is the XAML: ``` <Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" xmlns:local="clr-namespace:WpfApplication1" > <Window.Resources> <ObjectDataProvider x:Key="MyListObject" ObjectType="{x:Type local:MyListObject}"/> </Window.Resources> <Grid> <ComboBox Height="23" Margin="24,91,53,0" Name="ComboBox1" VerticalAlignment="Top" ItemsSource="{Binding Path=MyList, Source={StaticResource MyListObject}}" /> <TextBox Height="23" Margin="24,43,134,0" Name="TextBox1" VerticalAlignment="Top" /> <Button Height="23" HorizontalAlignment="Right" Margin="0,43,53,0" Name="btn_AddName" VerticalAlignment="Top" Width="75">Add</Button> </Grid> </Window> ``` And here's the simple code-behind: ``` Class Window1 Private obj As New MyListObject Private Sub btn_AddName_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) _ Handles btn_AddName.Click obj.AddName(TextBox1.Text) End Sub End Class ``` Thanks!
You are binding to a list of strings. That list class does not implement Inotifyproperty. You should use an observablecollection instead. I also notice in your code behind you declare ``` Private obj As New MyListObject ``` This is not the static resource you bound the combo box to. So your add call would not be reflected in your view.
240,948
<p>I'm working on a small app where I can generate a list of barcodes. I have the correct fonts installed on my computer. Right now I am printing them directly to a webpage and it works properly in Chrome and IE 7, but not Firefox. Does anyone know what Firefox would be doing differently than IE and Chrome?</p> <p>Here is my code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Barcode Font Test&lt;/title&gt; &lt;style type="text/css" media="screen"&gt; .barcode { font-family: "wasp 39 m", verdana, calibri; font-size: 36pt; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="barcode"&gt;*574656*&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>EDIT:</strong> I probably should have mentioned that this is more of a personal project at the moment and not meant to be released to the world. While I will take a solution that works, I would like something that does not involve Javascript/Flash/etc.</p>
[ { "answer_id": 240956, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>Using non-standard fonts on web pages is a big pain in the ass. To make it easier you can use <a href=\"http://wiki.novemberborn.net/sifr\" rel=\"nofollow noreferrer\">sIFR</a> or the new <a href=\"http://typeface.neocracy.org/\" rel=\"nofollow noreferrer\">typeface.js</a>.</p>\n\n<p>Edit: This was valid 4 years ago when it was posted, but isn't anymore. I'll leave it here for posterity, but don't take it as a correct answer.</p>\n" }, { "answer_id": 240977, "author": "Norbert B.", "author_id": 2605840, "author_profile": "https://Stackoverflow.com/users/2605840", "pm_score": 2, "selected": false, "text": "<p>At the company i'm working at now we use BarCode.dll of lesnikowski.com.\nIt generates barcode images. It doesn't depend whether or not the font is installed on the client pc and works with all browser.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 241060, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>The Mozilla developers made a choice for symbol fonts to not work. You can enable them in the config as described in <a href=\"http://nothing.golddave.com/?p=53\" rel=\"nofollow noreferrer\">Getting Symbol Fonts to Work in Mozilla Firefox</a></p>\n" }, { "answer_id": 241069, "author": "Chad Braun-Duin", "author_id": 5458, "author_profile": "https://Stackoverflow.com/users/5458", "pm_score": 1, "selected": false, "text": "<p>We have the same problem at my company. Luckily, only 1-2 people ever need to use the barcode fonts.</p>\n\n<p>We have found that when they received new a PC, the fonts didn't work through any browsers. They had to open up a client application (like Word), choose a barcode font, and do some typing to \"initialize\" that font. </p>\n\n<p>The best solution, I think, is to create a barcode image on the server on demand. The problem with this solution could be cleaning up old images. This solution requires more work up-front but pays off with less on-going issues and maintenance than the client side solution, in my opinion.</p>\n" }, { "answer_id": 241208, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 3, "selected": true, "text": "<p>A simpler solution might be to generate images server side to generate the bar codes. That way you don't have to rely on the user having a font installed and you don't have to access the font in your html.</p>\n" }, { "answer_id": 241468, "author": "Doug L.", "author_id": 19179, "author_profile": "https://Stackoverflow.com/users/19179", "pm_score": 3, "selected": false, "text": "<p>There are several barcode formats. Some are simple and some can get very complex. One of the easiest to use, if it fits your application, is the 3 of 9 barcode. It is not compressed and there is a 1 to 1 relation to the chars in the barcode. There are two variants of this, numeric only and the extended set that includes alpha. I'll go forward with the asumption that you can use this format. (From your sample code, it looks like that's what you are using) For the easiest implementation, stick with the numeric only. Then, you will only require eleven chars (0-9 and the astrisk). Look at the definition of an existing 3 of 9 font. (For non-commercial use, search for a font called FREE3OF9. You can use that as the base for your app...)</p>\n\n<p>Next, the tedious part - more work for you up front but displays in almost any browser. If you can't find any on-line, crerate a GIF (or BMP or PNG) image for each char. (Remeber to include the proper white-space on the right side of the char to distance it from the next char in line!) It only needs to be one pixel high. When the time comes to display the barcode, string the chars together as <code>&lt;IMG&gt;</code>'s that are next to each other. 3 of 9 requires that the chars in the barcode are surrounded or wrapped with an astrisk (it's the astrisk in the FREE3OF9 font anyway) on each end. Set the height of the <code>&lt;IMG&gt;</code>'s to something tall enough to suit your printout.</p>\n\n<p>This way, no font installation required at the client, but most barcode decoders can read the resulting graphic.</p>\n\n<p>Your example (<code>*574656*</code>) might look like this:\n<img src=\"https://i.stack.imgur.com/BHHHr.png\" alt=\"574656\"></p>\n\n<p><em>(well, not exactly like that - it's a solid graphic instead of a composition of several in-line single graphics, but you get the idea)</em></p>\n\n<p>The individual numeric graphics look like this: \n(although, these are not \"cleaned up\" yet)</p>\n\n<p><code>*</code> <img src=\"https://i.imgur.com/Q3m0MFb.gif\" alt=\"*\"></p>\n\n<p><code>0</code> <img src=\"https://i.stack.imgur.com/uEDiK.png\" alt=\"0\"></p>\n\n<p><code>1</code> <img src=\"https://i.stack.imgur.com/K80Pf.png\" alt=\"1\"></p>\n\n<p><code>2</code> <img src=\"https://i.stack.imgur.com/2hLvE.png\" alt=\"2\"></p>\n\n<p><code>3</code> <img src=\"https://i.stack.imgur.com/tkHYt.png\" alt=\"3\"></p>\n\n<p><code>4</code> <img src=\"https://i.stack.imgur.com/XhBTx.png\" alt=\"4\"></p>\n\n<p><code>5</code> <img src=\"https://i.stack.imgur.com/QFN6e.png\" alt=\"5\"></p>\n\n<p><code>6</code> <img src=\"https://i.stack.imgur.com/HKf4y.png\" alt=\"6\"></p>\n\n<p><code>7</code> <img src=\"https://i.stack.imgur.com/8L2qi.png\" alt=\"7\"></p>\n\n<p><code>8</code> <a href=\"https://i.stack.imgur.com/ui3Ms.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ui3Ms.png\" alt=\"8\"></a>\n</p>\n\n<p><code>9</code> <a href=\"https://i.stack.imgur.com/neRmn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/neRmn.png\" alt=\"9\"></a>\n</p>\n\n<p>and the code changes might look like this:</p>\n\n<pre><code>&lt;html&gt; \n &lt;head&gt; \n &lt;title&gt;Barcode Font Test&lt;/title&gt; \n &lt;/head&gt; \n &lt;body&gt; \n &lt;img src=\"3o9cb_ast.png\" alt=\"*\"/&gt; \n &lt;img src=\"3o9cb_5.png\" alt=\"5\"/&gt;\n &lt;img src=\"3o9cb_7.png\" alt=\"7\"/&gt;\n &lt;img src=\"3o9cb_4.png\" alt=\"4\"/&gt;\n &lt;img src=\"3o9cb_6.png\" alt=\"6\"/&gt;\n &lt;img src=\"3o9cb_5.png\" alt=\"5\"/&gt;\n &lt;img src=\"3o9cb_6.png\" alt=\"6\"/&gt;\n &lt;img src=\"3o9cb_ast.png\" alt=\"*\"/&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<hr>\n\n<p>I used <a href=\"http://www.searchfreefonts.com\" rel=\"nofollow noreferrer\">SearchFreeFonts.com</a> as a resource to refresh my memory of how 3 of 9 barcode chars were formatted. These graphics are initially from that site.</p>\n" }, { "answer_id": 478571, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Fonts tend to have problems because it relies on the browser to do the rendering. Image is better. I use <a href=\"http://www.morovia.com/activex/barcode-lite.asp\" rel=\"nofollow noreferrer\">Morovia Barcode Active Lite</a> to create barcodes from IIS.</p>\n\n<p><a href=\"http://www.morovia.com/activex/active-demo/barcode.asp?Symbology=7&amp;ShowHRText=1&amp;NarrowBarWidth=20&amp;BarHeight=750&amp;Message=0+07+70007+07723\" rel=\"nofollow noreferrer\">an example barcode http://www.morovia.com/activex/active-demo/barcode.asp?Symbology=7&amp;ShowHRText=1&amp;NarrowBarWidth=20&amp;BarHeight=750&amp;Message=0+07+70007+07723</a></p>\n" }, { "answer_id": 37280666, "author": "Richard Osenga", "author_id": 6346634, "author_profile": "https://Stackoverflow.com/users/6346634", "pm_score": 0, "selected": false, "text": "<p>Just do this: <a href=\"http://davidscotttufts.com/2009/03/31/how-to-create-barcodes-in-php/\" rel=\"nofollow\">http://davidscotttufts.com/2009/03/31/how-to-create-barcodes-in-php/</a>\nDavid created a super-simple way to implement bar codes. You will need the GD library running in MySQL. (MAMP &amp; LAMP should already have this installed)</p>\n" }, { "answer_id": 61853068, "author": "broc.seib", "author_id": 516910, "author_profile": "https://Stackoverflow.com/users/516910", "pm_score": 2, "selected": false, "text": "<p>Much has changed since this question was originally asked. Today, it is fairly simple to use a barcode font on the web and render it directly.</p>\n\n<p>Run the code snippet below to see a live example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.barcode39 {\r\n font-family: 'Libre Barcode 39 Extended Text', cursive;\r\n font-size: 40px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link href=\"https://fonts.googleapis.com/css2?family=Libre+Barcode+39+Extended+Text&amp;display=swap\" rel=\"stylesheet\"&gt;\r\n\r\n&lt;div class=\"barcode39\"&gt;\r\n *hello world*\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1444511/" ]
I'm working on a small app where I can generate a list of barcodes. I have the correct fonts installed on my computer. Right now I am printing them directly to a webpage and it works properly in Chrome and IE 7, but not Firefox. Does anyone know what Firefox would be doing differently than IE and Chrome? Here is my code: ``` <html> <head> <title>Barcode Font Test</title> <style type="text/css" media="screen"> .barcode { font-family: "wasp 39 m", verdana, calibri; font-size: 36pt; } </style> </head> <body> <div class="barcode">*574656*</div> </body> </html> ``` **EDIT:** I probably should have mentioned that this is more of a personal project at the moment and not meant to be released to the world. While I will take a solution that works, I would like something that does not involve Javascript/Flash/etc.
A simpler solution might be to generate images server side to generate the bar codes. That way you don't have to rely on the user having a font installed and you don't have to access the font in your html.
240,949
<p>I have a set of templates for emails that my app sends out. The templates have codes embedded in them that correspond to properties of my business object. </p> <p>Is there a more elegant way than calling </p> <pre><code>string.Replace("{!MyProperty!}", item.MyProperty.ToString()) </code></pre> <p>a zillion times? Maybe XMLTransform, regular expressions, or some other magic? I'm using C# 3.5 .</p>
[ { "answer_id": 240953, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": false, "text": "<p>First of all, when I do this I use StringBuilder.Replace() as I have found that its performance is much better suited when working with 3 or more replacements.</p>\n\n<p>Of course there are other ways of doing it, but I've found that it is not usually worth the extra effort to try other items.</p>\n\n<p>You might be able to use Reflection I guess to automate the replacement, that might be the only \"better\" way.</p>\n" }, { "answer_id": 240973, "author": "Wim", "author_id": 30874, "author_profile": "https://Stackoverflow.com/users/30874", "pm_score": 1, "selected": false, "text": "<p>You could do it using a regex, but your regex replace differs also for each property. I would stick with the <code>string.Replace</code>.</p>\n\n<p>Use reflection to retrieve the properties and replace it in a loop:</p>\n\n<pre><code>foreach (string property in properties)\n{\n string.Replace(\"{!\"+property+\"!}\",ReflectionHelper.GetStringValue(item,property));\n}\n</code></pre>\n\n<p>Just implement your <code>ReflectionHelper.GetStringValue</code> method and use reflection to retrieve all the properties on your item object type.</p>\n" }, { "answer_id": 241170, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": false, "text": "<pre><code>public static string Translate(string pattern, object context)\n{\n return Regex.Replace(pattern, @\"\\{!(\\w+)!}\", match =&gt; {\n string tag = match.Groups[1].Value;\n if (context != null)\n {\n PropertyInfo prop = context.GetType().GetProperty(tag);\n if (prop != null)\n {\n object value = prop.GetValue(context);\n if (value != null)\n {\n return value.ToString();\n }\n }\n }\n return \"\";\n });\n}\n</code></pre>\n\n\n\n<pre><code>Translate(\"Hello {!User!}. Welcome to {!GroupName!}!\", new {\n User = \"John\",\n GroupName = \"The Community\"\n}); // -&gt; \"Hello John. Welcome to The Community!\"\n</code></pre>\n\n<p><a href=\"https://ideone.com/D9J31c\" rel=\"nofollow noreferrer\">https://ideone.com/D9J31c</a></p>\n" }, { "answer_id": 241433, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>There's a built in WebControl, <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.maildefinition.aspx\" rel=\"nofollow noreferrer\">System.Web.UI.WebControls.MailDefinition</a> that does <a href=\"http://msdn.microsoft.com/en-us/library/ms156159.aspx\" rel=\"nofollow noreferrer\">string replacements</a> (among other things). Pity they tightly coupled it to the Smtp settings in app.config and a web control, and then made it sealed to foil inheritors.</p>\n\n<p>But, it does handle a few things you'd most likely want in a mail template engine - body text from a file, html email, embedded objects, etc. Reflector shows the actual replacement is handled with a foreach loop and Regex.Replace - which seems a reasonable choice to me as well.</p>\n\n<p>A quick glance through shows that if you can live with the from address being in the app.config (you can change it on the returned MailMessage afterwards), you only need the owner control for embedded resources or the BodyFileName.</p>\n\n<p>If you're using ASP.NET or can live with the limitations - I'd choose MailDefinition. Otherwise, just do a foreach over a dictionary and a Regex.Replace. It's a little memory hungry, because of the repeated allocations of body - but they're short lived and shouldn't pose much of a problem.</p>\n\n<pre><code>var replacements = new Dictionary&lt;string, object&gt;() {\n { \"Property1\", obj.Property1 },\n { \"Property2\", obj.Property2 },\n { \"Property3\", obj.Property3 },\n { \"Property4\", obj.Property4 },\n}\n\nforeach (KeyValuePair&lt;string, object&gt; kvp in replacement) {\n body = Regex.Replace(body, kvp.Key, kvp.Value.ToString());\n}\n</code></pre>\n\n<p>If you really have <em>a lot</em> of properties, then read your body first with Regex.Match and reflect to the properties instead.</p>\n" }, { "answer_id": 53965013, "author": "Brad Bruce", "author_id": 5008, "author_profile": "https://Stackoverflow.com/users/5008", "pm_score": 0, "selected": false, "text": "<p>After looking at the examples previously included, I thought I'd look at the real code.\n@mark-brackett You were closer than you knew.</p>\n\n<pre><code>//The guts of MailDefinition.CreateMailMessage\n//from https://github.com/Microsoft/referencesource/blob/master/System.Web/UI/WebControls/MailDefinition.cs\n\nif (replacements != null &amp;&amp; !String.IsNullOrEmpty(body)) {\n foreach (object key in replacements.Keys) {\n string fromString = key as string;\nstring toString = replacements[key] as string;\n\n if ((fromString == null) || (toString == null)) {\n throw new ArgumentException(SR.GetString(SR.MailDefinition_InvalidReplacements));\n }\n // DevDiv 151177\n // According to http://msdn2.microsoft.com/en-us/library/ewy2t5e0.aspx, some special \n // constructs (starting with \"$\") are recognized in the replacement patterns. References of\n // these constructs will be replaced with predefined strings in the final output. To use the \n // character \"$\" as is in the replacement patterns, we need to replace all references of single \"$\"\n // with \"$$\", because \"$$\" in replacement patterns are replaced with a single \"$\" in the \n // final output. \n toString = toString.Replace(\"$\", \"$$\");\n body = Regex.Replace(body, fromString, toString, RegexOptions.IgnoreCase);\n }\n }\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a set of templates for emails that my app sends out. The templates have codes embedded in them that correspond to properties of my business object. Is there a more elegant way than calling ``` string.Replace("{!MyProperty!}", item.MyProperty.ToString()) ``` a zillion times? Maybe XMLTransform, regular expressions, or some other magic? I'm using C# 3.5 .
First of all, when I do this I use StringBuilder.Replace() as I have found that its performance is much better suited when working with 3 or more replacements. Of course there are other ways of doing it, but I've found that it is not usually worth the extra effort to try other items. You might be able to use Reflection I guess to automate the replacement, that might be the only "better" way.
241,003
<p>Is there some way to get a value from the last inserted row?</p> <p>I am inserting a row where the PK will automatically increase, and I would like to get this PK. Only the PK is guaranteed to be unique in the table.</p> <p>I am using Java with a JDBC and PostgreSQL.</p>
[ { "answer_id": 241016, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 3, "selected": false, "text": "<p>The sequences in postgresql are transaction safe. So you can use the </p>\n\n<pre><code>currval(sequence)\n</code></pre>\n\n<p><a href=\"http://www.postgresql.org/docs/7.4/interactive/functions-sequence.html\" rel=\"nofollow noreferrer\">Quote:</a></p>\n\n<blockquote>\n <p>currval</p>\n \n <blockquote>\n <p>Return the value most recently obtained by nextval for this sequence\n in the current session. (An error is\n reported if nextval has never been\n called for this sequence in this\n session.) Notice that because this is\n returning a session-local value, it\n gives a predictable answer even if\n other sessions are executing nextval\n meanwhile.</p>\n </blockquote>\n</blockquote>\n" }, { "answer_id": 241019, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 1, "selected": false, "text": "<p>Use sequences in postgres for id columns:</p>\n\n<pre><code>INSERT mytable(myid) VALUES (nextval('MySequence'));\n\nSELECT currval('MySequence');\n</code></pre>\n\n<p>currval will return the current value of the sequence in the same session.</p>\n\n<p>(In MS SQL, you would use @@identity or SCOPE_IDENTITY())</p>\n" }, { "answer_id": 241242, "author": "Luc M", "author_id": 14673, "author_profile": "https://Stackoverflow.com/users/14673", "pm_score": 7, "selected": true, "text": "<p>With PostgreSQL you can do it via the RETURNING keyword:</p>\n\n<p><a href=\"http://www.postgresql.org/docs/8.3/interactive/sql-insert.html\" rel=\"noreferrer\">PostgresSQL - RETURNING</a></p>\n\n<pre><code>INSERT INTO mytable( field_1, field_2,... )\nVALUES ( value_1, value_2 ) RETURNING anyfield\n</code></pre>\n\n<p>It will return the value of \"anyfield\". \"anyfield\" may be a sequence or not.</p>\n\n<p>To use it with JDBC, do:</p>\n\n<pre><code>ResultSet rs = statement.executeQuery(\"INSERT ... RETURNING ID\");\nrs.next();\nrs.getInt(1);\n</code></pre>\n" }, { "answer_id": 241377, "author": "Andrew Watt", "author_id": 31650, "author_profile": "https://Stackoverflow.com/users/31650", "pm_score": 5, "selected": false, "text": "<p>See the API docs for <a href=\"http://java.sun.com/javase/6/docs/api/java/sql/Statement.html\" rel=\"noreferrer\">java.sql.Statement</a>.</p>\n\n<p>Basically, when you call <code>executeUpdate()</code> or <code>executeQuery()</code>, use the <code>Statement.RETURN_GENERATED_KEYS</code> constant. You can then call <code>getGeneratedKeys</code> to get the auto-generated keys of all rows created by that execution. (Assuming your JDBC driver provides it.)</p>\n\n<p>It goes something along the lines of this:</p>\n\n<pre><code>Statement stmt = conn.createStatement();\nstmt.execute(sql, Statement.RETURN_GENERATED_KEYS);\nResultSet keyset = stmt.getGeneratedKeys();\n</code></pre>\n" }, { "answer_id": 241573, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 4, "selected": false, "text": "<p>If you're using JDBC 3.0, then you can get the value of the PK as soon as you inserted it. </p>\n\n<p>Here's an article that talks about how : <a href=\"https://www.ibm.com/developerworks/java/library/j-jdbcnew/\" rel=\"noreferrer\">https://www.ibm.com/developerworks/java/library/j-jdbcnew/</a></p>\n\n<pre><code>Statement stmt = conn.createStatement();\n// Obtain the generated key that results from the query.\nstmt.executeUpdate(\"INSERT INTO authors \" +\n \"(first_name, last_name) \" +\n \"VALUES ('George', 'Orwell')\",\n Statement.RETURN_GENERATED_KEYS);\nResultSet rs = stmt.getGeneratedKeys();\nif ( rs.next() ) {\n // Retrieve the auto generated key(s).\n int key = rs.getInt(1);\n}\n</code></pre>\n" }, { "answer_id": 242966, "author": "eflles", "author_id": 26567, "author_profile": "https://Stackoverflow.com/users/26567", "pm_score": 3, "selected": false, "text": "<p>Here is how I solved it, based on the answers here:</p>\n\n<pre><code>Connection conn = ConnectToDB(); //ConnectToDB establishes a connection to the database.\nString sql = \"INSERT INTO \\\"TableName\\\"\" +\n \"(\\\"Column1\\\", \\\"Column2\\\",\\\"Column3\\\",\\\"Column4\\\")\" +\n \"VALUES ('value1',value2, 'value3', 'value4') RETURNING \n \\\"TableName\\\".\\\"TableId\\\"\";\nPreparedStatement prpState = conn.prepareStatement(sql);\nResultSet rs = prpState.executeQuery();\nif(rs.next()){\n System.out.println(rs.getInt(1));\n }\n</code></pre>\n" }, { "answer_id": 2908219, "author": "smilek", "author_id": 350297, "author_profile": "https://Stackoverflow.com/users/350297", "pm_score": 0, "selected": false, "text": "<p>Don't use SELECT currval('MySequence') - the value gets incremented on inserts that fail.</p>\n" }, { "answer_id": 2953469, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 4, "selected": false, "text": "<p>Since PostgreSQL JDBC driver version <a href=\"http://jdbc.postgresql.org/changes.html#version_8.4-701\" rel=\"noreferrer\">8.4-701</a> the <a href=\"http://java.sun.com/javase/6/docs/api/java/sql/Statement.html#getGeneratedKeys%28%29\" rel=\"noreferrer\"><code>PreparedStatement#getGeneratedKeys()</code></a> is finally fully functional. We use it here almost one year in production to our full satisfaction.</p>\n\n<p>In \"plain JDBC\" the <code>PreparedStatement</code> needs to be created as follows to make it to return the keys:</p>\n\n<pre><code>statement = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);\n</code></pre>\n\n<p>You can download the current JDBC driver version <a href=\"http://jdbc.postgresql.org/download.html#current\" rel=\"noreferrer\">here</a> (which is at the moment still 8.4-701).</p>\n" }, { "answer_id": 4623844, "author": "abdurrahim dagdelen", "author_id": 566630, "author_profile": "https://Stackoverflow.com/users/566630", "pm_score": 1, "selected": false, "text": "<pre><code>PreparedStatement stmt = getConnection(PROJECTDB + 2)\n .prepareStatement(\"INSERT INTO fonts (font_size) VALUES(?) RETURNING fonts.*\");\nstmt.setString(1, \"986\");\nResultSet res = stmt.executeQuery();\nwhile (res.next()) {\n System.out.println(\"Generated key: \" + res.getLong(1));\n System.out.println(\"Generated key: \" + res.getInt(2));\n System.out.println(\"Generated key: \" + res.getInt(3));\n}\nstmt.close();\n</code></pre>\n" }, { "answer_id": 5689400, "author": "emicklei", "author_id": 514308, "author_profile": "https://Stackoverflow.com/users/514308", "pm_score": 0, "selected": false, "text": "<p>For MyBatis 3.0.4 with Annotations and Postgresql driver 9.0-801.jdbc4 you define an interface method in your Mapper like</p>\n\n<pre><code>public interface ObjectiveMapper {\n\n@Select(\"insert into objectives\" +\n \" (code,title,description) values\" +\n \" (#{code}, #{title}, #{description}) returning id\")\nint insert(Objective anObjective);\n</code></pre>\n\n<p>Note that @Select is used instead of @Insert.</p>\n" }, { "answer_id": 6182585, "author": "fernando", "author_id": 549278, "author_profile": "https://Stackoverflow.com/users/549278", "pm_score": 0, "selected": false, "text": "<p>for example:</p>\n\n<pre>\n Connection conn = null;\n PreparedStatement sth = null;\n ResultSet rs =null;\n try {\n conn = delegate.getConnection();\n sth = conn.prepareStatement(INSERT_SQL);\n sth.setString(1, pais.getNombre());\n sth.executeUpdate();\n rs=sth.getGeneratedKeys();\n if(rs.next()){\n Integer id = (Integer) rs.getInt(1);\n pais.setId(id);\n }\n } \n</pre>\n\n<p>with <code>,Statement.RETURN_GENERATED_KEYS);\"</code> no found.</p>\n" }, { "answer_id": 11244794, "author": "danigonlinea", "author_id": 1196978, "author_profile": "https://Stackoverflow.com/users/1196978", "pm_score": 0, "selected": false, "text": "<p>Use that simple code:</p>\n\n<pre><code>// Do your insert code\n\nmyDataBase.execSQL(\"INSERT INTO TABLE_NAME (FIELD_NAME1,FIELD_NAME2,...)VALUES (VALUE1,VALUE2,...)\");\n\n// Use the sqlite function \"last_insert_rowid\"\n\nCursor last_id_inserted = yourBD.rawQuery(\"SELECT last_insert_rowid()\", null);\n\n// Retrieve data from cursor.\n\nlast_id_inserted.moveToFirst(); // Don't forget that!\n\nultimo_id = last_id_inserted.getLong(0); // For Java, the result is returned on Long type (64)\n</code></pre>\n" }, { "answer_id": 16319938, "author": "Priyadharshani", "author_id": 2284850, "author_profile": "https://Stackoverflow.com/users/2284850", "pm_score": 2, "selected": false, "text": "<p>If you are using <code>Statement</code>, go for the following</p>\n\n<pre><code>//MY_NUMBER is the column name in the database \nString generatedColumns[] = {\"MY_NUMBER\"};\nStatement stmt = conn.createStatement();\n\n//String sql holds the insert query\nstmt.executeUpdate(sql, generatedColumns);\n\nResultSet rs = stmt.getGeneratedKeys();\n\n// The generated id\n\nif(rs.next())\nlong key = rs.getLong(1);\n</code></pre>\n\n<p>If you are using <code>PreparedStatement</code>, go for the following</p>\n\n<pre><code>String generatedColumns[] = {\"MY_NUMBER\"};\nPreparedStatement pstmt = conn.prepareStatement(sql,generatedColumns);\npstmt.setString(1, \"qwerty\");\n\npstmt.execute();\nResultSet rs = pstmt.getGeneratedKeys();\nif(rs.next())\nlong key = rs.getLong(1);\n</code></pre>\n" }, { "answer_id": 22832032, "author": "mihu86", "author_id": 1732450, "author_profile": "https://Stackoverflow.com/users/1732450", "pm_score": 0, "selected": false, "text": "<p>If you are in a transaction you can use <code>SELECT lastval()</code> after an insert to get the last generated id.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26567/" ]
Is there some way to get a value from the last inserted row? I am inserting a row where the PK will automatically increase, and I would like to get this PK. Only the PK is guaranteed to be unique in the table. I am using Java with a JDBC and PostgreSQL.
With PostgreSQL you can do it via the RETURNING keyword: [PostgresSQL - RETURNING](http://www.postgresql.org/docs/8.3/interactive/sql-insert.html) ``` INSERT INTO mytable( field_1, field_2,... ) VALUES ( value_1, value_2 ) RETURNING anyfield ``` It will return the value of "anyfield". "anyfield" may be a sequence or not. To use it with JDBC, do: ``` ResultSet rs = statement.executeQuery("INSERT ... RETURNING ID"); rs.next(); rs.getInt(1); ```
241,009
<p>In a Visual Basic project, I created a homemade TabControl in order to fix a visual bug. The control works properly, however whenever I modify the form using my tab, Visual Studio adds MyProject in front of the control in its declaration:</p> <pre><code>Me.tabMenu = New MyProject.MyClass 'Gives a BC30002 compile error </code></pre> <p>If I remove the <code>MyProject.</code>, the project compiles properly.</p> <p>MyClass is in a separate file MyClass.vb and looks mostly like this:</p> <pre><code>Public Class MyClass Inherits System.Windows.Forms.TabControl Public Sub New() InitializeComponent() MyBase.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed End Sub Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs) //OnDrawItem code End Sub Private Sub My_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Me.DrawItem //My_DrawItem code End Sub End Class </code></pre> <p>I tried removing the file and adding it again, copy and pasting the class inside <code>MyForm.designer.vb</code>, adding <code>MyProject.</code> to the class name, but nothing stopped Visual Studio from adding this so-hated <code>MyProject</code>.</p> <p><strong>Edit regarding <a href="https://stackoverflow.com/questions/241009/myprojectmyclass-vbnet-custom-controls#241077">this answer</a>:</strong></p> <p>I understand the thing about the namespace, however my problem is mostly that the compiler does not recognize the class with the project name appended but still adds it everytime.</p>
[ { "answer_id": 241077, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "<p>By default, Visual Basic .NET assigned a default namespace to your project. (I believe the default is, in fact, <code>MyProject</code>.)</p>\n\n<p>This is what's being prepended, and it's being done to explicitly identify your class in the designer. </p>\n\n<p>No matter what your default namespace is for your project, the WinForms designer will add the namespace name to the .designer.vb file.</p>\n\n<p>To change the default namespace, go to your project properties; it should appear on the first tab.</p>\n\n<p>Also, generally, don't modify the .designer.vb files if you can avoid it. Those files get completely blown away and rebuilt by Visual Studio <em>often</em>, so your changes will more likely than not be eliminated.</p>\n" }, { "answer_id": 270041, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 1, "selected": false, "text": "<p>What is the actual compile error you are getting? Is it possable that the VB compiler is interpreting MyProject as something other than a namespace identifier? You could also try changing the default namespace for the project, then see what it does, it might give you a hint as to what the actual problem is.\nYou could also try changing the offending line to</p>\n\n<pre><code>Me.tabMenu = New Global.MyProject.MyClass\n</code></pre>\n\n<p>then let us know what the results are.</p>\n" }, { "answer_id": 281030, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": true, "text": "<p>I've seen this before when you have a public module with the same name as your default namespace (project name). If that's the case, either rename the module or the default namespace and the problem should go away,.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25818/" ]
In a Visual Basic project, I created a homemade TabControl in order to fix a visual bug. The control works properly, however whenever I modify the form using my tab, Visual Studio adds MyProject in front of the control in its declaration: ``` Me.tabMenu = New MyProject.MyClass 'Gives a BC30002 compile error ``` If I remove the `MyProject.`, the project compiles properly. MyClass is in a separate file MyClass.vb and looks mostly like this: ``` Public Class MyClass Inherits System.Windows.Forms.TabControl Public Sub New() InitializeComponent() MyBase.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed End Sub Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs) //OnDrawItem code End Sub Private Sub My_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Me.DrawItem //My_DrawItem code End Sub End Class ``` I tried removing the file and adding it again, copy and pasting the class inside `MyForm.designer.vb`, adding `MyProject.` to the class name, but nothing stopped Visual Studio from adding this so-hated `MyProject`. **Edit regarding [this answer](https://stackoverflow.com/questions/241009/myprojectmyclass-vbnet-custom-controls#241077):** I understand the thing about the namespace, however my problem is mostly that the compiler does not recognize the class with the project name appended but still adds it everytime.
I've seen this before when you have a public module with the same name as your default namespace (project name). If that's the case, either rename the module or the default namespace and the problem should go away,.
241,015
<p>I have a backup server that automatically backs up my live site, both files and database.</p> <p>On the live site, the text looks fine, but when you view the mirrored version of it, it displays '?' within some of the text. This text is stored within the news database table.</p> <p>Here is a screenshot of it being on the live server and of it on the mirrored server.</p> <p>What could happen within the process of backing it up to the mirrored server?</p> <p><img src="https://i.stack.imgur.com/ftKNy.jpg" alt="Alt text" /></p> <p>The live server is <a href="https://en.wikipedia.org/wiki/Solaris_%28operating_system%29" rel="nofollow noreferrer">Solaris</a>, and the mirrored server is Linux <a href="https://en.wikipedia.org/wiki/Red_Hat_Linux" rel="nofollow noreferrer">Red Hat Linux</a> 5.</p>
[ { "answer_id": 241024, "author": "Benjamin Lee", "author_id": 29009, "author_profile": "https://Stackoverflow.com/users/29009", "pm_score": 1, "selected": false, "text": "<p>Unicode or other character set characters falling through?</p>\n\n<p>I have seen similar \"strange\" characters show up on sites I have worked on often when the text is copied from an email or some other document format (e.g. word) into a text editor. The editor can display the non ASCII characters but the browser can't. For the website, I would suggest looking up the HTML entity code for the character and inserting that instead ... or switch to more standard ones.</p>\n" }, { "answer_id": 241025, "author": "JamShady", "author_id": 11905, "author_profile": "https://Stackoverflow.com/users/11905", "pm_score": 1, "selected": false, "text": "<p>Your browser hasn't interpreted the encoding of the page correctly (either because you've forced it to a particular setting, or the page is set incorrectly), and thus cannot display some of the characters.</p>\n" }, { "answer_id": 241028, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 1, "selected": false, "text": "<p>This is going to be something to do with character encodings.</p>\n\n<p>Are you sure the mirrored site has the same properties with regards to character encodings as your main server?</p>\n\n<p>Depending on what sort of server you have, this may be a property of the server process itself, or it could be an environment variable.</p>\n\n<p>For example, if this is a UNIX environment, perhaps try comparing LANG or LC_ALL?</p>\n\n<p>See also <a href=\"http://www.opengroup.org/onlinepubs/007908799/xbd/envvar.html\" rel=\"nofollow noreferrer\">here</a> </p>\n" }, { "answer_id": 241030, "author": "IAdapter", "author_id": 30453, "author_profile": "https://Stackoverflow.com/users/30453", "pm_score": 6, "selected": true, "text": "<p>The following articles will be useful:</p>\n<p><em><a href=\"http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html\" rel=\"nofollow noreferrer\">10.3 Specifying Character Sets and Collations</a></em></p>\n<p><em><a href=\"http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html\" rel=\"nofollow noreferrer\">10.4 Connection Character Sets and Collations</a></em></p>\n<p>After you connect to the database, issue the following command:</p>\n<pre><code>SET NAMES 'utf8';\n</code></pre>\n<p>Ensure that your web page also uses the UTF-8 encoding:</p>\n<pre><code>&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;\n</code></pre>\n<p>PHP also offers several functions that will be useful for conversions:</p>\n<ul>\n<li><em><a href=\"http://us3.php.net/manual/en/function.iconv.php\" rel=\"nofollow noreferrer\">iconv</a></em></li>\n<li><em><a href=\"http://us.php.net/mb_convert_encoding\" rel=\"nofollow noreferrer\">mb_convert_encoding</a></em></li>\n</ul>\n" }, { "answer_id": 241037, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "<p>Check the character set being emitted by your mirrored server. There appears to be a difference from that to the main server -- the live site appears to be outputting Unicode, where the mirror is not. Also, it's usually a good idea to scrub Unicode characters in your incoming content and replace them with their appropriate HTML entities.</p>\n\n<p>Your specific issue regards \"smart quotes,\" \"em dashes\" and \"en dashes.\" I know you can replace em dashes with <code>&amp;mdash;</code> and n-dashes with <code>&amp;ndash;</code> (which should be done on the input side of your database); I don't know what the correct replacement for the smart quotes would be. (I usually just replace all curly single quotes with ' and all curly double quotes with \" ... Typography geeks may feel free to shoot me on sight.)</p>\n\n<p>I should note that some browsers are more forgiving than others with this issue -- Internet Explorer on Windows tends to auto-magically detect and \"fix\" this; Firefox and most other browsers display the question marks.</p>\n" }, { "answer_id": 241099, "author": "Nick Van Brunt", "author_id": 30470, "author_profile": "https://Stackoverflow.com/users/30470", "pm_score": 0, "selected": false, "text": "<p>I usually curse MS Word and then run the following <a href=\"https://en.wikipedia.org/wiki/Windows_Script_Host\" rel=\"nofollow noreferrer\">Windows Script Host</a> script.</p>\n<pre class=\"lang-none prettyprint-override\"><code>// Replace with path to a file that needs cleaning\nPATH = &quot;test.html&quot;\n\nvar go = WScript.CreateObject(&quot;Scripting.FileSystemObject&quot;);\nvar content = go.GetFile(PATH).OpenAsTextStream().ReadAll();\nvar out = go.CreateTextFile(&quot;clean-&quot;+PATH, true);\n\n// Symbols\ncontent = content.replace(/“/g, '&quot;');\ncontent = content.replace(/”/g, '&quot;');\ncontent = content.replace(/’/g, &quot;'&quot;);\ncontent = content.replace(/–/g, &quot;-&quot;);\ncontent = content.replace(/©/g, &quot;&amp;copy;&quot;);\ncontent = content.replace(/®/g, &quot;&amp;reg;&quot;);\ncontent = content.replace(/°/g, &quot;&amp;deg;&quot;);\ncontent = content.replace(/¶/g, &quot;&lt;p&gt;&quot;);\ncontent = content.replace(/¿/g, &quot;&amp;iquest;&quot;);\ncontent = content.replace(/¡/g, '&amp;iexcl;');\ncontent = content.replace(/¢/g, '&amp;cent;');\ncontent = content.replace(/£/g, '&amp;pound;');\ncontent = content.replace(/¥/g, '&amp;yen;');\n\nout.Write(content);\n</code></pre>\n" }, { "answer_id": 10265960, "author": "Dave Burton", "author_id": 562862, "author_profile": "https://Stackoverflow.com/users/562862", "pm_score": 4, "selected": false, "text": "<p>Edit your Apache configuration file on the &quot;mirror&quot; server (the server with the problem), and comment-out the following line:</p>\n<pre><code>AddDefaultCharset UTF-8\n</code></pre>\n<p>Then restart Apache:</p>\n<pre><code>service httpd restart\n</code></pre>\n<p>The problem is that the &quot;AddDefaultCharset UTF-8&quot; line overrides the <em>Content-Type</em> specified in the <em>.html</em> files; e.g.:</p>\n<pre><code>&lt;meta http-equiv=Content-Type content=&quot;text/html; charset=windows-1252&quot;&gt;\n</code></pre>\n<p>The most common symptom is that character codes above 127 display as black diamonds with question marks on them (in Chrome, Safari or Firefox), or as little boxes (in Internet Explorer and <a href=\"https://en.wikipedia.org/wiki/Opera_%28web_browser%29\" rel=\"nofollow noreferrer\">Opera</a>).</p>\n<p>HTML files generated by Microsoft Word usually have many such characters, the most common one being character code 160 = 0xA0, which is equivalent to &quot;&amp;nbsp;&quot; in the <a href=\"https://en.wikipedia.org/wiki/Windows-1252\" rel=\"nofollow noreferrer\">Windows-1252</a> encoding, and is often found between span tags, like this:</p>\n<pre><code>&lt;span style=&quot;mso-spacerun: yes&quot;&gt;ááá &lt;/span&gt;\n</code></pre>\n" }, { "answer_id": 14777276, "author": "Leniel Maccaferri", "author_id": 114029, "author_profile": "https://Stackoverflow.com/users/114029", "pm_score": 3, "selected": false, "text": "<p>I got here looking for a solution for JavaScript displayed in the browser and although not directly related with a database...</p>\n<p>In my case I copied and pasted some text I found on the Internet into a JavaScript file and saved it with Windows <a href=\"https://en.wikipedia.org/wiki/Notepad_%28software%29\" rel=\"nofollow noreferrer\">Notepad</a>.</p>\n<p>When the page that uses that JavaScript file output the strings, there were question marks (like the ones shown in the question) instead of the special characters like accented letters, etc.</p>\n<p>I opened the file using <a href=\"http://notepad-plus-plus.org/\" rel=\"nofollow noreferrer\">Notepad++</a>. Right after opening the file I saw that the character encoding was set as <em>ANSI</em> as you can see (mouse cursor on footer) in the following screenshot:</p>\n<p><img src=\"https://i.stack.imgur.com/UxtX7.png\" alt=\"Enter image description here\" /></p>\n<p>To solve the issue, click the <em>Encoding</em> menu in Notepad++ and select <em>Encode in UTF-8</em>. You should be good to go. :)</p>\n" }, { "answer_id": 62098130, "author": "ola.rogula", "author_id": 3285183, "author_profile": "https://Stackoverflow.com/users/3285183", "pm_score": 0, "selected": false, "text": "<p>I had this issue so I just took all my content, copy/pasted it into <a href=\"https://en.wikipedia.org/wiki/Notepad_%28software%29\" rel=\"nofollow noreferrer\">Notepad</a>, made a new PHP file, pasted back in, re-saved and overwrote, and.. that worked!</p>\n<p>It really was some relic of Microsoft Word editing...</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
I have a backup server that automatically backs up my live site, both files and database. On the live site, the text looks fine, but when you view the mirrored version of it, it displays '?' within some of the text. This text is stored within the news database table. Here is a screenshot of it being on the live server and of it on the mirrored server. What could happen within the process of backing it up to the mirrored server? ![Alt text](https://i.stack.imgur.com/ftKNy.jpg) The live server is [Solaris](https://en.wikipedia.org/wiki/Solaris_%28operating_system%29), and the mirrored server is Linux [Red Hat Linux](https://en.wikipedia.org/wiki/Red_Hat_Linux) 5.
The following articles will be useful: *[10.3 Specifying Character Sets and Collations](http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html)* *[10.4 Connection Character Sets and Collations](http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html)* After you connect to the database, issue the following command: ``` SET NAMES 'utf8'; ``` Ensure that your web page also uses the UTF-8 encoding: ``` <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> ``` PHP also offers several functions that will be useful for conversions: * *[iconv](http://us3.php.net/manual/en/function.iconv.php)* * *[mb\_convert\_encoding](http://us.php.net/mb_convert_encoding)*
241,034
<p>I have a very simple Java RMI Server that looks like the following:</p> <pre><code> import java.rmi.*; import java.rmi.server.*; public class CalculatorImpl extends UnicastRemoteObject implements Calculator { private String mServerName; public CalculatorImpl(String serverName) throws RemoteException { super(); mServerName = serverName; } public int calculate(int op1, int op2) throws RemoteException { return op1 + op2; } public void exit() throws RemoteException { try{ Naming.unbind(mServerName); System.out.println("CalculatorServer exiting."); } catch(Exception e){} System.exit(1); } public static void main(String args[]) throws Exception { System.out.println("Initializing CalculatorServer."); String serverObjName = "rmi://localhost/Calculator"; Calculator calc = new CalculatorImpl(serverObjName); Naming.rebind(serverObjName, calc); System.out.println("CalculatorServer running."); } } </code></pre> <p>When I call the exit method, System.exit(1) throws the following exception:</p> <pre><code>CalculatorServer exiting. java.rmi.UnmarshalException: Error unmarshaling return header; nested exception is: java.io.EOFException at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:203) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:126) at CalculatorImpl_Stub.exit(Unknown Source) at CalculatorClient.&lt;init&gt;(CalculatorClient.java:17) at CalculatorClient.main(CalculatorClient.java:29) Caused by: java.io.EOFException at java.io.DataInputStream.readByte(DataInputStream.java:243) at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:189) ... 4 more [2]+ Exit 1 java CalculatorImpl </code></pre> <p>What am I doing wrong in this method?</p>
[ { "answer_id": 241214, "author": "Clayton", "author_id": 1449, "author_profile": "https://Stackoverflow.com/users/1449", "pm_score": 5, "selected": true, "text": "<p>In case anyone is having a similar problem, I figured out the answer myself. Here is my exit() method:</p>\n\n<pre><code>public void exit() throws RemoteException\n{\n try{\n // Unregister ourself\n Naming.unbind(mServerName);\n\n // Unexport; this will also remove us from the RMI runtime\n UnicastRemoteObject.unexportObject(this, true);\n\n System.out.println(\"CalculatorServer exiting.\");\n }\n catch(Exception e){}\n}\n</code></pre>\n" }, { "answer_id": 1315814, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 2, "selected": false, "text": "<p>Actually just unregistering and immediately calling System.exit doesn't shut down cleanly. It basically breaks the connection before informing the client that the message was completed. What works is to start a small thread that shuts down the system like:</p>\n\n<pre><code>public void quit() throws RemoteException {\n System.out.println(\"quit\");\n Registry registry = LocateRegistry.getRegistry();\n try {\n registry.unbind(_SERVICENAME);\n UnicastRemoteObject.unexportObject(this, false);\n } catch (NotBoundException e) {\n throw new RemoteException(\"Could not unregister service, quiting anyway\", e);\n }\n\n new Thread() {\n @Override\n public void run() {\n System.out.print(\"Shutting down...\");\n try {\n sleep(2000);\n } catch (InterruptedException e) {\n // I don't care\n }\n System.out.println(\"done\");\n System.exit(0);\n }\n\n }.start();\n}\n</code></pre>\n\n<p>The thread is needed to be able to let something happen in the future while still returning from the quit method.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1449/" ]
I have a very simple Java RMI Server that looks like the following: ``` import java.rmi.*; import java.rmi.server.*; public class CalculatorImpl extends UnicastRemoteObject implements Calculator { private String mServerName; public CalculatorImpl(String serverName) throws RemoteException { super(); mServerName = serverName; } public int calculate(int op1, int op2) throws RemoteException { return op1 + op2; } public void exit() throws RemoteException { try{ Naming.unbind(mServerName); System.out.println("CalculatorServer exiting."); } catch(Exception e){} System.exit(1); } public static void main(String args[]) throws Exception { System.out.println("Initializing CalculatorServer."); String serverObjName = "rmi://localhost/Calculator"; Calculator calc = new CalculatorImpl(serverObjName); Naming.rebind(serverObjName, calc); System.out.println("CalculatorServer running."); } } ``` When I call the exit method, System.exit(1) throws the following exception: ``` CalculatorServer exiting. java.rmi.UnmarshalException: Error unmarshaling return header; nested exception is: java.io.EOFException at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:203) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:126) at CalculatorImpl_Stub.exit(Unknown Source) at CalculatorClient.<init>(CalculatorClient.java:17) at CalculatorClient.main(CalculatorClient.java:29) Caused by: java.io.EOFException at java.io.DataInputStream.readByte(DataInputStream.java:243) at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:189) ... 4 more [2]+ Exit 1 java CalculatorImpl ``` What am I doing wrong in this method?
In case anyone is having a similar problem, I figured out the answer myself. Here is my exit() method: ``` public void exit() throws RemoteException { try{ // Unregister ourself Naming.unbind(mServerName); // Unexport; this will also remove us from the RMI runtime UnicastRemoteObject.unexportObject(this, true); System.out.println("CalculatorServer exiting."); } catch(Exception e){} } ```
241,040
<p>I have a rich-text editor on my site that I'm trying to protect against XSS attacks. I think I have pretty much everything handled, but I'm still unsure about what to do with images. Right now I'm using the following regex to validate image URLs, which I'm assuming will block inline javascript XSS attacks: </p> <pre><code>"https?://[-A-Za-z0-9+&amp;@#/%?=~_|!:,.;]+" </code></pre> <p>What I'm not sure of is how open this leaves me to XSS attacks from the remote image. Is linking to an external image a serious security threat?</p> <p>The only thing I can think of is that the URL entered references a resource that returns "<code>text/javascript</code>" as its MIME type instead of some sort of image, and that javascript is then executed.</p> <p>Is that possible? Is there any other security threat I should consider?</p>
[ { "answer_id": 241068, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 2, "selected": false, "text": "<p>Another thing to worry about is that you can easily embed PHP code inside an image and upload that most of the time. The only thing an attack would then have to be able to do is find a way to include the image. (Only the PHP code will get executed, the rest is just echoed). Check the MIME-type won't help you with this because the attacker can easily just upload an image with the correct first few bytes, followed by arbitrary PHP code. (The same is somewhat true for HTML and Javascript code).</p>\n" }, { "answer_id": 241161, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 1, "selected": false, "text": "<p>In that case, look at the context around it: do users only supply a URL? In that case it's fine to just validate the URLs semantics and MIME-type. If the user also gets to input tags of some sort you'll have to make sure that they are not manipulatable to do anything other then display images.</p>\n" }, { "answer_id": 242311, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "<p>If the end-viewer is in a password protected area and your app contains Urls that initiate actions based on GET requests, you can make a request on the user's behalf.</p>\n\n<p>Examples:</p>\n\n<ul>\n<li>src=\"http://yoursite.com/deleteuser.xxx?userid=1234\"</li>\n<li>src=\"http://yoursite.com/user/delete/1234\"</li>\n<li>src=\"http://yoursite.com/dosomethingdangerous\"</li>\n</ul>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I have a rich-text editor on my site that I'm trying to protect against XSS attacks. I think I have pretty much everything handled, but I'm still unsure about what to do with images. Right now I'm using the following regex to validate image URLs, which I'm assuming will block inline javascript XSS attacks: ``` "https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+" ``` What I'm not sure of is how open this leaves me to XSS attacks from the remote image. Is linking to an external image a serious security threat? The only thing I can think of is that the URL entered references a resource that returns "`text/javascript`" as its MIME type instead of some sort of image, and that javascript is then executed. Is that possible? Is there any other security threat I should consider?
Another thing to worry about is that you can easily embed PHP code inside an image and upload that most of the time. The only thing an attack would then have to be able to do is find a way to include the image. (Only the PHP code will get executed, the rest is just echoed). Check the MIME-type won't help you with this because the attacker can easily just upload an image with the correct first few bytes, followed by arbitrary PHP code. (The same is somewhat true for HTML and Javascript code).
241,051
<p>I have nant set up to build my ASP.NET MVC project and it works fine locally. I add nant to a tools folder and add it to version control. TeamCity picks up my changes and starts the build but it fails.</p> <p>I believe I'm using the latest version of Nant and I have added the .net framework 3.5 to the nant.exe.config. What am I missing on the server and yes the .net framework is installed on the server as the asp.net mvc app does work if I manually build and deploy there? </p> <p>The build file is as follows: </p> <pre><code>&lt;target name="compile" description="Compiles using the AutomatedDebug Configuration"&gt; &lt;msbuild project="Tolt.Sims.sln" /&gt; &lt;/target&gt; </code></pre> <p></p> <p>Here is the error:</p> <pre> BUILD FAILED Failed to initialize the 'Microsoft .NET Framework 2.0' (net-2.0) target framework. Property evaluation failed. Expression: ${path::combine(sdkInstallRoot, 'bin')} ^^^^^^^^^^^^^^ Property 'sdkInstallRoot' has not been set. For more information regarding the cause of the build failure, run the build again in debug mode. Try 'nant -help' for more information </pre>
[ { "answer_id": 241318, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 3, "selected": true, "text": "<p>If you're using the beta version of NAnt (which currently is the only way you'll get support for targeting anything greater than the 2.0 framework), you maybe running into a registry problem. A similar problem was <a href=\"http://www.timbarcz.com/blog/NantSetupForVisualStudio2008AndNet35.aspx\" rel=\"nofollow noreferrer\">reported by Tim Barcz</a>. </p>\n\n<p>Things pretty much boiled down to NAntContrib (provider of msbuild task) pointing to the 2.0 version of msbuild. Check out his solution to see if it applies to your scenario.</p>\n" }, { "answer_id": 423817, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>See <a href=\"http://www.mail-archive.com/[email protected]/msg07519.html\" rel=\"nofollow noreferrer\">http://www.mail-archive.com/[email protected]/msg07519.html</a>; it's a known bug in 0.86 beta1.</p>\n" }, { "answer_id": 633990, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Potentially, you dont have the .NET Framework 2.0 SDK installed.</p>\n\n<p>You can install it from \n<a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=fe6f2099-b7b4-4f47-a244-c96d69c35dec&amp;displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?familyid=fe6f2099-b7b4-4f47-a244-c96d69c35dec&amp;displaylang=en</a></p>\n" }, { "answer_id": 755345, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I fixed this by adding the following in the registry:</p>\n\n<p>New string value at: HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft.NETFramework</p>\n\n<p>Named: sdkInstallRootv2.0</p>\n\n<p>With the value: C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\</p>\n\n<p>Seemed to spring into life...</p>\n\n<p>w://</p>\n" }, { "answer_id": 2037800, "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 with NAnt. I know this isn't the <em>Best</em> solution, but it is one that works if you need to get your project moving. </p>\n\n<p>I've found that installing a development environment (C# Express didn't work for me, but VS 2008 did) on the server makes this issue go away. (Yes, I realize this goes against normal best practices, but it works and lets my scripts run so I can get back to coding.)</p>\n\n<p>Just figured I'd share incase anyone else is in a similar situation..(this has worked for me both with CruiseControl.Net and with Hudson).</p>\n" }, { "answer_id": 3153659, "author": "Matt Scully", "author_id": 380555, "author_profile": "https://Stackoverflow.com/users/380555", "pm_score": 2, "selected": false, "text": "<p>This was fixed after the 0.86 beta1 release. On April 1, 2010, 0.90 was released with the fix in case upgrading nant is an option for you. To provide further detail, the fix release in 0.90 appears to have been simple changes to the nant.exe.config file. The bolded text below was added and will likely fix the problem without having to install the 2.0 SDK.</p>\n\n<blockquote>\n <p><code>&lt;directory name=\"${path::combine(sdkInstallRoot, 'bin')}\"</code> <strong>if=\"${property::exists('sdkInstallRoot')}\"</strong> /></p>\n</blockquote>\n\n<p>Update the net-2.0 section to fix it.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9938/" ]
I have nant set up to build my ASP.NET MVC project and it works fine locally. I add nant to a tools folder and add it to version control. TeamCity picks up my changes and starts the build but it fails. I believe I'm using the latest version of Nant and I have added the .net framework 3.5 to the nant.exe.config. What am I missing on the server and yes the .net framework is installed on the server as the asp.net mvc app does work if I manually build and deploy there? The build file is as follows: ``` <target name="compile" description="Compiles using the AutomatedDebug Configuration"> <msbuild project="Tolt.Sims.sln" /> </target> ``` Here is the error: ``` BUILD FAILED Failed to initialize the 'Microsoft .NET Framework 2.0' (net-2.0) target framework. Property evaluation failed. Expression: ${path::combine(sdkInstallRoot, 'bin')} ^^^^^^^^^^^^^^ Property 'sdkInstallRoot' has not been set. For more information regarding the cause of the build failure, run the build again in debug mode. Try 'nant -help' for more information ```
If you're using the beta version of NAnt (which currently is the only way you'll get support for targeting anything greater than the 2.0 framework), you maybe running into a registry problem. A similar problem was [reported by Tim Barcz](http://www.timbarcz.com/blog/NantSetupForVisualStudio2008AndNet35.aspx). Things pretty much boiled down to NAntContrib (provider of msbuild task) pointing to the 2.0 version of msbuild. Check out his solution to see if it applies to your scenario.
241,063
<p>I have a site that uses paypal to collect payments for electronically displayed data. Variables can't be passed with the URL through paypal (or I can't get them to work) so I have used cookies to pass the item number. However, a crafty user could, after the cookie writing part, enter the paypal redirect URL directly into the address bar and get the e-data for free. Bypassing paypal. How can I get around this?</p> <p>Here is some of the code. You will see I have tried to make it difficult for the user by passing straight through the cookie writing (pre_contact.php) and the paypal redirect URL (step.php).</p> <pre><code>//pre_contact.php &lt;?PHP global $id; setcookie("property", $id, time()+1800); echo "&lt;META HTTP-EQUIV=Refresh CONTENT=\"0; URL=contact.php\"&gt;"; ?&gt; //contact.php - paypal pay button echo "&lt;form action='https://www.paypal.com/cgi-bin/webscr' method='post'&gt;"; echo "&lt;input type='hidden' name='cmd' value='_s-xclick'&gt;"; echo "&lt;input type='hidden' name='hosted_button_id' value='156320'&gt;"; echo "&lt;input type='image' src='https://www.paypal.com/en_GB/i/btn/btn_paynowCC_LG.gif' border='0' name='submit' alt='Click to pay'&gt;"; echo "&lt;img alt='' border='0' src='https://www.paypal.com/en_GB/i/scr/pixel.gif' width='1' height='1'&gt;"; echo "&lt;/form&gt;"; //step.php - paypal redirect on successful payment &lt;?PHP require("generate_url.php"); ?&gt; //generate_url.php - This generates a unique URL so the info can only be accessed once &lt;?PHP if (eregi("generate_url.php", $_SERVER['SCRIPT_NAME'])) { Header("Location: index.php"); die(); } $token = md5(uniqid(rand(),1)); setcookie("token", $token, time()+4); $cwd = substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'],"/")); Header("Location: $cwd/get_file.php?q=$token"); die(); ?&gt; //get_file.php - displays the file after payment $qtoken = $_GET['q']; if ($qtoken===$_COOKIE["token"]){ $id=$_COOKIE["property"]; DISPLAY FILE HERE!! </code></pre> <p>Thanks in advance</p>
[ { "answer_id": 241074, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 4, "selected": false, "text": "<p>I don't think you're going to be able to do what you want in a single step with the approach you're taking because your code has no way of knowing if the transaction actually finished successfully or not.</p>\n<p>I think the only way the above approach will work is if you don't automatically send them over to the file they paid for.</p>\n<p>Instead, they have to wait for you to verify their transaction through Paypal and then email them a download link.</p>\n<hr />\n<p>It could probably all be done automatically using the <a href=\"https://developer.paypal.com/\" rel=\"nofollow noreferrer\">Paypal API</a>. I'm not that familiar with the Paypal API but it should work something like this.</p>\n<ol>\n<li>User decides to buy something from you</li>\n<li>You start a transaction which sends the user over to Paypal and, presumably, generates some sort of transaction id.</li>\n<li>The user pays (or decides to cancel and/or not pay)</li>\n<li>The user comes back to your site</li>\n<li>You take the transaction id and verify that the payment was successful</li>\n<li>If the payment was successful, give the user the stuff they paid for.</li>\n</ol>\n<hr />\n<h2><a href=\"https://www.paypal.com/IntegrationCenter/ic_api-reference.html\" rel=\"nofollow noreferrer\">Paypal API Reference</a></h2>\n" }, { "answer_id": 241226, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 4, "selected": false, "text": "<p>What your probably looking for is called Paypal IPN (Instant payment notification).. basically someone buys a product from you.. Paypal POSTS data to a script/url that you specify (only you and them know it).. Then what you do is post back data to paypal to confirm that the post they sent is real and not simulated/faked by someone.. At this point you know the transaction is valid.</p>\n\n<p>Once you get notified of a valid payment, you can do something like send a download url via email, or wrap all that into a small login/password system using something simple like HTACCESS auth, and you've good to go. </p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 1283077, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 0, "selected": false, "text": "<p>There is plenty of information about PayPal IPN in other questions, start with <a href=\"https://stackoverflow.com/questions/1115822/setting-up-paypal-to-connect-to-script\">Setting up Paypal to connect to script</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a site that uses paypal to collect payments for electronically displayed data. Variables can't be passed with the URL through paypal (or I can't get them to work) so I have used cookies to pass the item number. However, a crafty user could, after the cookie writing part, enter the paypal redirect URL directly into the address bar and get the e-data for free. Bypassing paypal. How can I get around this? Here is some of the code. You will see I have tried to make it difficult for the user by passing straight through the cookie writing (pre\_contact.php) and the paypal redirect URL (step.php). ``` //pre_contact.php <?PHP global $id; setcookie("property", $id, time()+1800); echo "<META HTTP-EQUIV=Refresh CONTENT=\"0; URL=contact.php\">"; ?> //contact.php - paypal pay button echo "<form action='https://www.paypal.com/cgi-bin/webscr' method='post'>"; echo "<input type='hidden' name='cmd' value='_s-xclick'>"; echo "<input type='hidden' name='hosted_button_id' value='156320'>"; echo "<input type='image' src='https://www.paypal.com/en_GB/i/btn/btn_paynowCC_LG.gif' border='0' name='submit' alt='Click to pay'>"; echo "<img alt='' border='0' src='https://www.paypal.com/en_GB/i/scr/pixel.gif' width='1' height='1'>"; echo "</form>"; //step.php - paypal redirect on successful payment <?PHP require("generate_url.php"); ?> //generate_url.php - This generates a unique URL so the info can only be accessed once <?PHP if (eregi("generate_url.php", $_SERVER['SCRIPT_NAME'])) { Header("Location: index.php"); die(); } $token = md5(uniqid(rand(),1)); setcookie("token", $token, time()+4); $cwd = substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'],"/")); Header("Location: $cwd/get_file.php?q=$token"); die(); ?> //get_file.php - displays the file after payment $qtoken = $_GET['q']; if ($qtoken===$_COOKIE["token"]){ $id=$_COOKIE["property"]; DISPLAY FILE HERE!! ``` Thanks in advance
I don't think you're going to be able to do what you want in a single step with the approach you're taking because your code has no way of knowing if the transaction actually finished successfully or not. I think the only way the above approach will work is if you don't automatically send them over to the file they paid for. Instead, they have to wait for you to verify their transaction through Paypal and then email them a download link. --- It could probably all be done automatically using the [Paypal API](https://developer.paypal.com/). I'm not that familiar with the Paypal API but it should work something like this. 1. User decides to buy something from you 2. You start a transaction which sends the user over to Paypal and, presumably, generates some sort of transaction id. 3. The user pays (or decides to cancel and/or not pay) 4. The user comes back to your site 5. You take the transaction id and verify that the payment was successful 6. If the payment was successful, give the user the stuff they paid for. --- [Paypal API Reference](https://www.paypal.com/IntegrationCenter/ic_api-reference.html) --------------------------------------------------------------------------------------
241,083
<p>I used to have a class in 1.1 for the Datagrid that inherited from the DataGridColumn class. This allowed me to create a check box column with a client-side un/check-all box in the header. Then as I designed my grid I would just add my custom column.</p> <p>I am currently on a project where I need similar functionality for the grid view, however, there does not seem to be a way to inherit or add functionality to a column.</p> <p>So my question is, Is there a way to override a column? or Does this code already exist, in a reusable way?</p> <p>Needs are simple: I would like for it to just register the JavaScript on the page and render a column of check boxes.</p> <p>I have come across the 4guys sample already, but they have just put all the code into the code behind, I am looking for something a little less copy/paste.</p>
[ { "answer_id": 241127, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 1, "selected": false, "text": "<p>I derived classes from System.Web.UI.WebControls.BoundField and .HyperLinkField\nYou might be interested in inheriting from CheckBoxField class <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkboxfield.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkboxfield.aspx</a></p>\n" }, { "answer_id": 241617, "author": "AndyG", "author_id": 27678, "author_profile": "https://Stackoverflow.com/users/27678", "pm_score": 0, "selected": false, "text": "<p>Could you just use a TemplateColumn with an ItemTemplate containing your CheckBox in your DataGrid Columns?</p>\n\n<p>Something like:</p>\n\n<pre><code>&lt;asp:DataGrid id=\"DG1\" runat = \"server\" DataKeyField = \"ID\"&gt;\n&lt;Columns&gt;\n&lt;asp:TemplateColumn HeaderText=\"ProductName\"&gt;\n&lt;ItemTemplate&gt;\n&lt;asp:CheckBox id=\"chkBox1\" runat=\"server\" \nText =&lt;%# DataBinder.Eval(Container.DataItem,\"yourDataToBind\") %&gt;\nchecked='&lt;%# DataBinder.Eval(Container.DataItem,\"yourBoolToBind\") %&gt;'&gt;\n&lt;/asp:CheckBox&gt;\n&lt;/ItemTemplate&gt;\n&lt;/asp:TemplateColumn&gt;\n&lt;/Columns&gt;\n&lt;/asp:DataGrid&gt;\n</code></pre>\n" }, { "answer_id": 243395, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 1, "selected": true, "text": "<p>I inherited the BoundField and came up with this:</p>\n\n<p>Page Code:</p>\n\n<pre><code>&lt;%@ register tagprefix=\"CAC\" namespace=\"UI.Controls\" assembly=\"UI.Controls\" %&gt; \n&lt;asp:gridview id=\"grdPrint\" runat=\"server\" autogeneratecolumns=\"False\"&gt;\n &lt;columns&gt;\n &lt;cac:checkallcolumn /&gt;\n &lt;asp:boundfield datafield=\"CompanyName\" headertext=\"Company Name\" /&gt;\n &lt;/columns&gt;\n&lt;/asp:gridview&gt;\n</code></pre>\n\n<p>And this is the control:</p>\n\n<pre><code>Imports system.Web.UI\nImports system.Web.UI.WebControls\n\nPublic Class CheckAllColumn\n Inherits BoundField\n\n Public Sub New()\n MyBase.New()\n End Sub\n\n Public ReadOnly Property SelectedIndexes() As List(Of Int32)\n Get\n Dim selectedIndexList As New List(Of Int32)\n Dim grdParent As GridView = CType(Me.Control, GridView)\n For Each item As GridViewRow In grdParent.Rows\n Dim chkBox As CheckBox = CType(item.FindControl(\"checkboxCol\"), CheckBox)\n If ((Not (chkBox) Is Nothing) _\n AndAlso chkBox.Checked) Then\n selectedIndexList.Add(item.DataItemIndex)\n End If\n Next\n Return selectedIndexList\n End Get\n End Property\n\n Public ReadOnly Property SelectedDataKeys() As Object()\n Get\n Dim dataKeyList As ArrayList = New ArrayList\n Dim grdParent As GridView = CType(Me.Control, GridView)\n If (grdParent.DataKeys.Count &gt; 0) Then\n For Each selectedIndex As Int32 In SelectedIndexes\n Dim DataKey As Object = grdParent.DataKeys(selectedIndex).ToString\n dataKeyList.Add(DataKey)\n Next\n End If\n Return CType(dataKeyList.ToArray(GetType(System.Object)), Object())\n End Get\n End Property\n\n Public Overrides Sub InitializeCell(ByVal cell As DataControlFieldCell, ByVal cellType As DataControlCellType, ByVal rowState As DataControlRowState, ByVal rowIndex As Integer)\n If cell Is Nothing Then\n Throw New ArgumentNullException(\"cell\", \"cell is null.\")\n End If\n MyBase.InitializeCell(cell, cellType, rowState, rowIndex)\n If (cellType = DataControlCellType.Header) OrElse (cellType = DataControlCellType.DataCell) Then\n Dim checkbox As CheckBox = New CheckBox\n If cellType = DataControlCellType.Header Then\n checkbox.ID = \"checkboxHead\"\n Else\n checkbox.ID = \"checkboxCol\"\n End If\n cell.Controls.Add(checkbox)\n End If\n End Sub\n\n Public Shared Sub RegisterClientCheckEvents(ByVal pg As Page, ByVal formID As String)\n If pg Is Nothing Then\n Throw New ArgumentNullException(\"pg\", \"pg is null.\")\n End If\n If formID Is Nothing OrElse formID.Length = 0 Then\n Throw New ArgumentException(\"formID is null or empty.\", \"formID\")\n End If\n Dim strCol As String = GetCheckColScript()\n Dim strHead As String = GetCheckHeadScript()\n If Not pg.ClientScript.IsClientScriptBlockRegistered(\"clientScriptCheckAll\") Then\n pg.ClientScript.RegisterClientScriptBlock(pg.GetType, \"clientScriptCheckAll\", strHead.Replace(\"[frmID]\", formID))\n End If\n If Not pg.ClientScript.IsClientScriptBlockRegistered(\"clientScriptCheckChanged\") Then\n pg.ClientScript.RegisterClientScriptBlock(pg.GetType, \"clientScriptCheckChanged\", strCol.Replace(\"[frmID]\", formID))\n End If\n RegisterAttributes(pg)\n End Sub\n\n Private Shared Sub RegisterAttributes(ByVal ctrl As Control)\n For Each wc As Control In ctrl.Controls\n If wc.HasControls Then\n RegisterAttributes(wc)\n End If\n If TypeOf (wc) Is CheckBox Then\n Dim chk As CheckBox = DirectCast(wc, CheckBox)\n If Not chk Is Nothing AndAlso chk.ID = \"checkboxCol\" Then\n chk.Attributes.Add(\"onclick\", \"CheckChanged()\")\n ElseIf Not chk Is Nothing AndAlso chk.ID = \"checkboxHead\" Then\n chk.Attributes.Add(\"onclick\", \"CheckAll(this)\")\n End If\n End If\n Next\n End Sub\n\n Private Shared Function GetCheckColScript() As String\n Dim strScript As String\n strScript = \" &lt;script language=JavaScript&gt;\"\n strScript &amp;= \" function CheckAll( checkAllBox )\"\n strScript &amp;= \" {\"\n strScript &amp;= \" var frm = document.[frmID];\"\n strScript &amp;= \" var ChkState=checkAllBox.checked;\"\n strScript &amp;= \" for(i=0;i&lt; frm.length;i++)\"\n strScript &amp;= \" {\"\n strScript &amp;= \" e=frm.elements[i];\"\n strScript &amp;= \" if(e.type=='checkbox' &amp;&amp; e.name.indexOf('checkboxCol') != -1)\"\n strScript &amp;= \" e.checked= ChkState ;\"\n strScript &amp;= \" }\"\n strScript &amp;= \" }\"\n strScript &amp;= \" &lt;/script&gt;\"\n Return strScript\n End Function\n\n Private Shared Function GetCheckHeadScript() As String\n Dim strScript As String\n strScript = \"&lt;script language=JavaScript&gt;\"\n strScript &amp;= \"function CheckChanged()\"\n strScript &amp;= \"{\"\n strScript &amp;= \" var frm = document.[frmID];\"\n strScript &amp;= \" var boolAllChecked;\"\n strScript &amp;= \" boolAllChecked=true;\"\n strScript &amp;= \" for(i=0;i&lt; frm.length;i++)\"\n strScript &amp;= \" {\"\n strScript &amp;= \" e=frm.elements[i];\"\n strScript &amp;= \" if ( e.type=='checkbox' &amp;&amp; e.name.indexOf('checkboxCol') != -1 )\"\n strScript &amp;= \" if(e.checked== false)\"\n strScript &amp;= \" {\"\n strScript &amp;= \" boolAllChecked=false;\"\n strScript &amp;= \" break;\"\n strScript &amp;= \" }\"\n strScript &amp;= \" }\"\n strScript &amp;= \" for(i=0;i&lt; frm.length;i++)\"\n strScript &amp;= \" {\"\n strScript &amp;= \" e=frm.elements[i];\"\n strScript &amp;= \" if ( e.type=='checkbox' &amp;&amp; e.name.indexOf('checkboxHead') != -1 )\"\n strScript &amp;= \" {\"\n strScript &amp;= \" if( boolAllChecked==false)\"\n strScript &amp;= \" e.checked= false ;\"\n strScript &amp;= \" else\"\n strScript &amp;= \" e.checked= true;\"\n strScript &amp;= \" break;\"\n strScript &amp;= \" }\"\n strScript &amp;= \" }\"\n strScript &amp;= \" }\"\n strScript &amp;= \" &lt;/script&gt;\"\n Return strScript\n End Function\nEnd Class\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30492/" ]
I used to have a class in 1.1 for the Datagrid that inherited from the DataGridColumn class. This allowed me to create a check box column with a client-side un/check-all box in the header. Then as I designed my grid I would just add my custom column. I am currently on a project where I need similar functionality for the grid view, however, there does not seem to be a way to inherit or add functionality to a column. So my question is, Is there a way to override a column? or Does this code already exist, in a reusable way? Needs are simple: I would like for it to just register the JavaScript on the page and render a column of check boxes. I have come across the 4guys sample already, but they have just put all the code into the code behind, I am looking for something a little less copy/paste.
I inherited the BoundField and came up with this: Page Code: ``` <%@ register tagprefix="CAC" namespace="UI.Controls" assembly="UI.Controls" %> <asp:gridview id="grdPrint" runat="server" autogeneratecolumns="False"> <columns> <cac:checkallcolumn /> <asp:boundfield datafield="CompanyName" headertext="Company Name" /> </columns> </asp:gridview> ``` And this is the control: ``` Imports system.Web.UI Imports system.Web.UI.WebControls Public Class CheckAllColumn Inherits BoundField Public Sub New() MyBase.New() End Sub Public ReadOnly Property SelectedIndexes() As List(Of Int32) Get Dim selectedIndexList As New List(Of Int32) Dim grdParent As GridView = CType(Me.Control, GridView) For Each item As GridViewRow In grdParent.Rows Dim chkBox As CheckBox = CType(item.FindControl("checkboxCol"), CheckBox) If ((Not (chkBox) Is Nothing) _ AndAlso chkBox.Checked) Then selectedIndexList.Add(item.DataItemIndex) End If Next Return selectedIndexList End Get End Property Public ReadOnly Property SelectedDataKeys() As Object() Get Dim dataKeyList As ArrayList = New ArrayList Dim grdParent As GridView = CType(Me.Control, GridView) If (grdParent.DataKeys.Count > 0) Then For Each selectedIndex As Int32 In SelectedIndexes Dim DataKey As Object = grdParent.DataKeys(selectedIndex).ToString dataKeyList.Add(DataKey) Next End If Return CType(dataKeyList.ToArray(GetType(System.Object)), Object()) End Get End Property Public Overrides Sub InitializeCell(ByVal cell As DataControlFieldCell, ByVal cellType As DataControlCellType, ByVal rowState As DataControlRowState, ByVal rowIndex As Integer) If cell Is Nothing Then Throw New ArgumentNullException("cell", "cell is null.") End If MyBase.InitializeCell(cell, cellType, rowState, rowIndex) If (cellType = DataControlCellType.Header) OrElse (cellType = DataControlCellType.DataCell) Then Dim checkbox As CheckBox = New CheckBox If cellType = DataControlCellType.Header Then checkbox.ID = "checkboxHead" Else checkbox.ID = "checkboxCol" End If cell.Controls.Add(checkbox) End If End Sub Public Shared Sub RegisterClientCheckEvents(ByVal pg As Page, ByVal formID As String) If pg Is Nothing Then Throw New ArgumentNullException("pg", "pg is null.") End If If formID Is Nothing OrElse formID.Length = 0 Then Throw New ArgumentException("formID is null or empty.", "formID") End If Dim strCol As String = GetCheckColScript() Dim strHead As String = GetCheckHeadScript() If Not pg.ClientScript.IsClientScriptBlockRegistered("clientScriptCheckAll") Then pg.ClientScript.RegisterClientScriptBlock(pg.GetType, "clientScriptCheckAll", strHead.Replace("[frmID]", formID)) End If If Not pg.ClientScript.IsClientScriptBlockRegistered("clientScriptCheckChanged") Then pg.ClientScript.RegisterClientScriptBlock(pg.GetType, "clientScriptCheckChanged", strCol.Replace("[frmID]", formID)) End If RegisterAttributes(pg) End Sub Private Shared Sub RegisterAttributes(ByVal ctrl As Control) For Each wc As Control In ctrl.Controls If wc.HasControls Then RegisterAttributes(wc) End If If TypeOf (wc) Is CheckBox Then Dim chk As CheckBox = DirectCast(wc, CheckBox) If Not chk Is Nothing AndAlso chk.ID = "checkboxCol" Then chk.Attributes.Add("onclick", "CheckChanged()") ElseIf Not chk Is Nothing AndAlso chk.ID = "checkboxHead" Then chk.Attributes.Add("onclick", "CheckAll(this)") End If End If Next End Sub Private Shared Function GetCheckColScript() As String Dim strScript As String strScript = " <script language=JavaScript>" strScript &= " function CheckAll( checkAllBox )" strScript &= " {" strScript &= " var frm = document.[frmID];" strScript &= " var ChkState=checkAllBox.checked;" strScript &= " for(i=0;i< frm.length;i++)" strScript &= " {" strScript &= " e=frm.elements[i];" strScript &= " if(e.type=='checkbox' && e.name.indexOf('checkboxCol') != -1)" strScript &= " e.checked= ChkState ;" strScript &= " }" strScript &= " }" strScript &= " </script>" Return strScript End Function Private Shared Function GetCheckHeadScript() As String Dim strScript As String strScript = "<script language=JavaScript>" strScript &= "function CheckChanged()" strScript &= "{" strScript &= " var frm = document.[frmID];" strScript &= " var boolAllChecked;" strScript &= " boolAllChecked=true;" strScript &= " for(i=0;i< frm.length;i++)" strScript &= " {" strScript &= " e=frm.elements[i];" strScript &= " if ( e.type=='checkbox' && e.name.indexOf('checkboxCol') != -1 )" strScript &= " if(e.checked== false)" strScript &= " {" strScript &= " boolAllChecked=false;" strScript &= " break;" strScript &= " }" strScript &= " }" strScript &= " for(i=0;i< frm.length;i++)" strScript &= " {" strScript &= " e=frm.elements[i];" strScript &= " if ( e.type=='checkbox' && e.name.indexOf('checkboxHead') != -1 )" strScript &= " {" strScript &= " if( boolAllChecked==false)" strScript &= " e.checked= false ;" strScript &= " else" strScript &= " e.checked= true;" strScript &= " break;" strScript &= " }" strScript &= " }" strScript &= " }" strScript &= " </script>" Return strScript End Function End Class ```
241,086
<p>I am setting up an Oracle connection for NHibernate for the first time. I have copied the Oracle.DataAccess.dll file into my bin folder. No matter what I try, I keep getting the same error:</p> <pre><code>Could not load type &gt;NHibernate.Driver.OracleDataClientDriver. Possible cause: no assembly name specified. </code></pre> <p>I am using the following configuration:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"&gt; &lt;session-factory name="DefaultSessionFactory"&gt; &lt;property name="connection.provider"&gt;NHibernate.Connection.DriverConnectionProvider&lt;/property&gt; &lt;property name="dialect"&gt;NHibernate.Dialect.Oracle9Dialect&lt;/property&gt; &lt;property name="connection.driver_class"&gt;&gt;NHibernate.Driver.OracleDataClientDriver&lt;/property&gt; &lt;property name="connection.connection_string"&gt;Data Source=DB;User ID=USERPassword=****;&lt;/property&gt; &lt;property name="show_sql"&gt;true&lt;/property&gt; &lt;mapping assembly="NHibernateExample.DataAccess"/&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p>I have previously only set up NHibernate for SQL Server. Am I missing anything here?</p>
[ { "answer_id": 241129, "author": "Miki Watts", "author_id": 16172, "author_profile": "https://Stackoverflow.com/users/16172", "pm_score": 4, "selected": true, "text": "<p>Did you copy and paste the code? because there's an extra > in there, in the connection.driver_class line</p>\n" }, { "answer_id": 241154, "author": "Nelson Miranda", "author_id": 1130097, "author_profile": "https://Stackoverflow.com/users/1130097", "pm_score": 0, "selected": false, "text": "<p>Once I had a similar problem, and I fixed it by adding <code>hibernate</code> to the property names, in your case:</p>\n\n<pre><code>&lt;property name=\"hibernate.connection.provider\"&gt;NHibernate.Connection.DriverConnectionProvider&lt;/property&gt;\n&lt;property name=\"hibernate.dialect\"&gt;NHibernate.Dialect.Oracle9Dialect&lt;/property&gt;\n&lt;property name=\"hibernate.connection.driver_class\"&gt;NHibernate.Driver.OracleDataClientDriver&lt;/property&gt;\n&lt;property name=\"hibernate.connection.connection_string\"&gt;Data Source=DB;User ID=USERPassword=****;&lt;/property&gt; \n</code></pre>\n\n<p>Hope it helps </p>\n" }, { "answer_id": 490335, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Semi colon seperator missed between user id value and password.</p>\n" }, { "answer_id": 3919373, "author": "Ran Avnon", "author_id": 473870, "author_profile": "https://Stackoverflow.com/users/473870", "pm_score": 2, "selected": false, "text": "<p>Excellent step by step tutorial on connecting NHibernate to Oracle:\n<a href=\"http://nhbwithoracle.blogspot.com/\" rel=\"nofollow\">http://nhbwithoracle.blogspot.com/</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
I am setting up an Oracle connection for NHibernate for the first time. I have copied the Oracle.DataAccess.dll file into my bin folder. No matter what I try, I keep getting the same error: ``` Could not load type >NHibernate.Driver.OracleDataClientDriver. Possible cause: no assembly name specified. ``` I am using the following configuration: ``` <?xml version="1.0" encoding="utf-8" ?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory name="DefaultSessionFactory"> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="dialect">NHibernate.Dialect.Oracle9Dialect</property> <property name="connection.driver_class">>NHibernate.Driver.OracleDataClientDriver</property> <property name="connection.connection_string">Data Source=DB;User ID=USERPassword=****;</property> <property name="show_sql">true</property> <mapping assembly="NHibernateExample.DataAccess"/> </session-factory> </hibernate-configuration> ``` I have previously only set up NHibernate for SQL Server. Am I missing anything here?
Did you copy and paste the code? because there's an extra > in there, in the connection.driver\_class line
241,088
<p>I have some Java code that uses curly braces in two ways</p> <pre><code>// Curly braces attached to an 'if' statement: if(node.getId() != null) { node.getId().apply(this); } // Curly braces by themselves: { List&lt;PExp&gt; copy = new ArrayList&lt;PExp&gt;(node.getArgs()); for(PExp e : copy) { e.apply(this); } } outAMethodExp(node); </code></pre> <p>What do those stand-alone curly braces after the first <code>if</code> statement mean?</p>
[ { "answer_id": 241090, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 2, "selected": false, "text": "<p>They make an inner scope. Variable declared inside these braces is not visible outside of them. This also applies to C/C++.</p>\n" }, { "answer_id": 241091, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I think they just define an unnamed level of scope.</p>\n" }, { "answer_id": 241095, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 0, "selected": false, "text": "<p>They define a new scope which means that everything declared in this scope is not visible outside the curly braces.</p>\n" }, { "answer_id": 241097, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 8, "selected": true, "text": "<p>The only purpose of the extra braces is to provide scope-limit. The <code>List&lt;PExp&gt; copy</code> will only exist within those braces, and will have no scope outside of them.</p>\n\n<p>If this is generated code, I assume the code-generator does this so it can insert some code (such as this) without having to worry about how many times it has inserted a <code>List&lt;PExp&gt; copy</code> and without having to worry about possibly renaming the variables if this snippet is inserted into the same method more than once.</p>\n" }, { "answer_id": 241103, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 3, "selected": false, "text": "<p>I'd actually guess that someone forgot an else statement.</p>\n\n<p>There's rarely a good reason to even bother with creating additional block scopes. In this, and most cases, it's far more likely someone may have forgotten to type their control statement than it is that they were doing something clever.</p>\n" }, { "answer_id": 241104, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 0, "selected": false, "text": "<p>The bring a scope, <strong>copy</strong> will not be visible outside of it, so you can declare another variable with same name later. And it can be gathered by the garbage collector right after you exit that scope. In this case <strong>copy</strong> serves as a temporary variable, so it is a good example.</p>\n" }, { "answer_id": 241182, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 0, "selected": false, "text": "<p>As an interesting note: the braces actually enable a class of statements: declarations.</p>\n\n<p>This is illegal: <code>if(a) int f;</code></p>\n\n<p>but this is legal: <code>if(a) { int f; }</code></p>\n" }, { "answer_id": 241950, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 5, "selected": false, "text": "<p>I second what matt b wrote, and I'll add that another use I've seen of anonymous braces is to declare an implicit constructor in anonymous classes. For example:</p>\n\n<pre><code> List&lt;String&gt; names = new ArrayList&lt;String&gt;() {\n // I want to initialize this ArrayList instace in-line,\n // but I can't define a constructor for an anonymous class:\n {\n add(\"Adam\");\n add(\"Eve\");\n }\n\n };\n</code></pre>\n\n<p>Some unit-testing frameworks have taken this syntax to another level, which does allow some slick things which look totally uncompilable to work. Since they <em>look</em> unfamiliar, I am not such a big fan myself, but it is worthwhile to at least recognize what is going on if you run across this use.</p>\n" }, { "answer_id": 241957, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 3, "selected": false, "text": "<p>I agree with the scope limit answer, but would add one thing.</p>\n\n<p>Sometimes you see a construct like that in the code of people who like to fold sections of their code and have editors that will fold braces automatically. They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up.</p>\n" }, { "answer_id": 4466081, "author": "Gabriel", "author_id": 263306, "author_profile": "https://Stackoverflow.com/users/263306", "pm_score": 1, "selected": false, "text": "<p>It is also used for <a href=\"http://download.oracle.com/javase/tutorial/java/javaOO/initial.html\" rel=\"nofollow noreferrer\">initialization blocks</a>.</p>\n" }, { "answer_id": 29074419, "author": "Philipp", "author_id": 76024, "author_profile": "https://Stackoverflow.com/users/76024", "pm_score": 1, "selected": false, "text": "<p>Braces are also useful to reduce the scope in switch/case statements.</p>\n\n<pre><code>switch(foo) {\n case BAR:\n int i = ...\n ...\n case BAZ:\n int i = ... // error, \"i\" already defined in scope\n}\n</code></pre>\n\n<p>But you can write</p>\n\n<pre><code>switch(foo) {\n case BAR:{\n int i = ...\n ...\n }\n case BAZ:{\n int i = ... // OK\n }\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
I have some Java code that uses curly braces in two ways ``` // Curly braces attached to an 'if' statement: if(node.getId() != null) { node.getId().apply(this); } // Curly braces by themselves: { List<PExp> copy = new ArrayList<PExp>(node.getArgs()); for(PExp e : copy) { e.apply(this); } } outAMethodExp(node); ``` What do those stand-alone curly braces after the first `if` statement mean?
The only purpose of the extra braces is to provide scope-limit. The `List<PExp> copy` will only exist within those braces, and will have no scope outside of them. If this is generated code, I assume the code-generator does this so it can insert some code (such as this) without having to worry about how many times it has inserted a `List<PExp> copy` and without having to worry about possibly renaming the variables if this snippet is inserted into the same method more than once.
241,100
<p>I have a DataGridView with one DataGridViewComboBoxColumn in my WinForms application. I need to drop down (open) this DataGridViewComboBoxColumn manually, let's say after a button is clicked.</p> <p>The reason I need this is I have set SelectionMode to FullRowSelect and I need to click 2-3 times to open the combo box. I want to click on the combobox cell and it should drop down immediately. I want to do this with CellClick event, or is there any other way?</p> <p>I am searching in Google and VS help, but I haven't found any information yet.</p> <p>Can anybody help please?</p>
[ { "answer_id": 241218, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 6, "selected": true, "text": "<p>I know this can't be the ideal solution but it does create a single click combo box that works within the cell.</p>\n\n<pre><code> Private Sub cell_Click(ByVal sender As System.Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick\n DataGridView1.BeginEdit(True)\n If DataGridView1.Rows(e.RowIndex).Cells(ddl.Name).Selected = True Then\n DirectCast(DataGridView1.EditingControl, DataGridViewComboBoxEditingControl).DroppedDown = True\n End If\n End Sub\n</code></pre>\n\n<p>where \"ddl\" is the combobox cell I added in the gridview. </p>\n" }, { "answer_id": 241275, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 4, "selected": false, "text": "<p>I have been able to get close to what you're looking for by setting </p>\n\n<pre><code>DataGridView1.EditMode = DataGridViewEditMode.EditOnEnter\n</code></pre>\n\n<p>As long as no other cell's dropdown is shown it should display the selected cell's dropdown immediately.</p>\n\n<p>I'll keep thinking and update if anything comes up.</p>\n" }, { "answer_id": 242760, "author": "user20353", "author_id": 20353, "author_profile": "https://Stackoverflow.com/users/20353", "pm_score": 4, "selected": false, "text": "<p>Thanks ThisMat, your solution works perfectly.</p>\n\n<p>My code in C#:</p>\n\n<pre><code>private void dataGridViewWeighings_CellClick(object sender, DataGridViewCellEventArgs e) {\n if (e.RowIndex &lt; 0) {\n return; // Header\n }\n if (e.ColumnIndex != 5) {\n return; // Filter out other columns\n }\n\n dataGridViewWeighings.BeginEdit(true);\n ComboBox comboBox = (ComboBox)dataGridViewWeighings.EditingControl;\n comboBox.DroppedDown = true;\n}\n</code></pre>\n" }, { "answer_id": 6752071, "author": "Sting", "author_id": 782991, "author_profile": "https://Stackoverflow.com/users/782991", "pm_score": 2, "selected": false, "text": "<p>Thanks for the C# version. Here's my contribution to search by combo column names:</p>\n\n<pre><code>private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)\n{\n string Weekdays = @\"MondayTuesdayWednesdayThursdayFridaySaturdaySunday\";\n if (Weekdays.IndexOf(dgv.Columns[e.ColumnIndex].Name) != -1)\n {\n dgv.BeginEdit(true);\n ComboBox comboBox = (ComboBox)dgv.EditingControl;\n comboBox.DroppedDown = true;\n }\n}\n</code></pre>\n" }, { "answer_id": 27793969, "author": "Paul Hitchcock", "author_id": 4308977, "author_profile": "https://Stackoverflow.com/users/4308977", "pm_score": 2, "selected": false, "text": "<p>I was looking for an answer to this as well. I ended up writing a generic sub that could be called from any DataGridView since I had plenty in my apps and I wanted them all to behave the same way. This worked well for me so I wanted to share it with anyone else who stumbled across this post.</p>\n\n<p>In the MouseClick event for the DGV I add the code</p>\n\n<pre><code>Private Sub SomeGrid_MouseClick(sender As Object, e As MouseEventArgs) Handles SomeGrid.MouseClick\n DGV_MouseClick(sender, e)\nEnd Sub\n</code></pre>\n\n<p>Which calls the following sub that I store in a shared module</p>\n\n<pre><code>Public Sub DGV_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)\n Try\n Dim dgv As DataGridView = sender\n Dim h As DataGridView.HitTestInfo = dgv.HitTest(e.X, e.Y)\n If h.RowIndex &gt; -1 AndAlso h.ColumnIndex &gt; -1 AndAlso dgv.Columns(h.ColumnIndex).CellType Is GetType(DataGridViewComboBoxCell) Then\n Dim cell As DataGridViewComboBoxCell = dgv.Rows(h.RowIndex).Cells(h.ColumnIndex)\n If Not dgv.CurrentCell Is cell Then dgv.CurrentCell = cell\n If Not dgv.IsCurrentCellInEditMode Then\n dgv.BeginEdit(True)\n CType(dgv.EditingControl, ComboBox).DroppedDown = True\n End If\n End If\n Catch ex As Exception\n End Try\nEnd Sub\n</code></pre>\n\n<p>I never caught any errors, I only include the Try..Catch code for some rare instance I couldn't think of that might throw an exception. I didn't want the user bothered by error messages for this scenario. If the sub fails, then most likely the DGV will just behave like it normally does anyways.</p>\n" }, { "answer_id": 32224097, "author": "nvivekgoyal", "author_id": 1005063, "author_profile": "https://Stackoverflow.com/users/1005063", "pm_score": 2, "selected": false, "text": "<p>I was able to activate combo box and drop down it using a single mouse click by setting <strong>EditMode</strong> property of DataGridView to <strong>EditOnEnter</strong>\nand creating <strong>EditingControlShowing</strong> event and added code to drop down the combo box in this event. Here is the sample code -</p>\n\n<pre><code>//to get the correct cell get value of row and column indexs of the cell\n ColIndex = 1;\n RowIndex = 1;\n\n DataGridViewComboBoxCell ComboBoxCell = new DataGridViewComboBoxCell();\n ComboBoxCell.Items.AddRange(\"XYZ\", \"ABC\", \"PQR\");\n ComboBoxCell.Value = \"XYZ\";\n datagridview1[ColIndex, RowIndex] = ComboBoxCell;\n</code></pre>\n\n<p>From the above code DataGirdCell at the location (1,1) will be converted to a \"DataGridViewComboBoxCell\" and combo box will be shown in the cell.</p>\n\n<p>It might be possible that to dropdown the combo box multiple mouse clicks are required. To activate combo box on single click following steps are required -</p>\n\n<ol>\n<li>Set ReadOnly property of the combobox cell to false</li>\n<li>Set EditMode property of DataGridView to EditOnEnter</li>\n<li>Create EditingControlShowing event and add code to drop down the combo box</li>\n</ol>\n\n<p>Here is the sample code to drop down the combo box and activate it on single click - </p>\n\n<pre><code>private void datagridview1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n {\nComboBox ctrl = e.Control as ComboBox;\nctrl.Enter -= new EventHandler(ctrl_Enter);\nctrl.Enter += new EventHandler(ctrl_Enter); \n}\nvoid ctrl_Enter(object sender, EventArgs e)\n{\n(sender as ComboBox).DroppedDown = true;\n}\n</code></pre>\n\n<p>For more detail please check -\n<a href=\"http://newapputil.blogspot.in/2015/08/add-combo-box-in-cell-of-datagridview.html\" rel=\"nofollow noreferrer\">http://newapputil.blogspot.in/2015/08/add-combo-box-in-cell-of-datagridview.html</a></p>\n" }, { "answer_id": 50277060, "author": "gridtrak", "author_id": 3519108, "author_profile": "https://Stackoverflow.com/users/3519108", "pm_score": 0, "selected": false, "text": "<p>FYI: Here is <a href=\"https://stackoverflow.com/users/1005063/nvivekgoyal\">nvivekgoyal</a>'s code from the reference in his <a href=\"https://stackoverflow.com/a/32224097/3519108\">answer</a>:</p>\n\n<pre><code>private void datagridview1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n{\n ComboBox ctrl = e.Control as ComboBox;\n ctrl.Enter -= new EventHandler(ctrl_Enter);\n ctrl.Enter += new EventHandler(ctrl_Enter);\n}\n\nvoid ctrl_Enter(object sender, EventArgs e)\n{\n (sender as ComboBox).DroppedDown = true;\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20353/" ]
I have a DataGridView with one DataGridViewComboBoxColumn in my WinForms application. I need to drop down (open) this DataGridViewComboBoxColumn manually, let's say after a button is clicked. The reason I need this is I have set SelectionMode to FullRowSelect and I need to click 2-3 times to open the combo box. I want to click on the combobox cell and it should drop down immediately. I want to do this with CellClick event, or is there any other way? I am searching in Google and VS help, but I haven't found any information yet. Can anybody help please?
I know this can't be the ideal solution but it does create a single click combo box that works within the cell. ``` Private Sub cell_Click(ByVal sender As System.Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick DataGridView1.BeginEdit(True) If DataGridView1.Rows(e.RowIndex).Cells(ddl.Name).Selected = True Then DirectCast(DataGridView1.EditingControl, DataGridViewComboBoxEditingControl).DroppedDown = True End If End Sub ``` where "ddl" is the combobox cell I added in the gridview.
241,134
<p>I was recently working with a <code>DateTime</code> object, and wrote something like this:</p> <pre><code>DateTime dt = DateTime.Now; dt.AddDays(1); return dt; // still today's date! WTF? </code></pre> <p>The intellisense documentation for <code>AddDays()</code> says it adds a day to the date, which it doesn't - it actually <em>returns</em> a date with a day added to it, so you have to write it like:</p> <pre><code>DateTime dt = DateTime.Now; dt = dt.AddDays(1); return dt; // tomorrow's date </code></pre> <p>This one has bitten me a number of times before, so I thought it would be useful to catalog the worst C# gotchas.</p>
[ { "answer_id": 241138, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 6, "selected": false, "text": "<p>I saw this one posted the other day, and I think it is pretty obscure, and painful for those that don't know</p>\n\n<pre><code>int x = 0;\nx = x++;\nreturn x;\n</code></pre>\n\n<p>As that will return 0 and not 1 as most would expect</p>\n" }, { "answer_id": 241155, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<pre><code>mystring.Replace(\"x\",\"y\")\n</code></pre>\n\n<p>While it looks like it should do the replacement on the string it's being invoked on it actually returns a new string with the replacements made without changing the string it's invoked on. You need to remember that strings are immutable.</p>\n" }, { "answer_id": 241180, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": false, "text": "<p><strong>Type.GetType</strong></p>\n<p>The one which I've seen bite lots of people is <a href=\"http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx\" rel=\"nofollow noreferrer\"><code>Type.GetType(string)</code></a>. They wonder why it works for types in their own assembly, and some types like <code>System.String</code>, but not <code>System.Windows.Forms.Form</code>. The answer is that it only looks in the current assembly and in <code>mscorlib</code>.</p>\n<hr />\n<p><strong>Anonymous methods</strong></p>\n<p>C# 2.0 introduced anonymous methods, leading to nasty situations like this:</p>\n<pre><code>using System;\nusing System.Threading;\n\nclass Test\n{\n static void Main()\n {\n for (int i=0; i &lt; 10; i++)\n {\n ThreadStart ts = delegate { Console.WriteLine(i); };\n new Thread(ts).Start();\n }\n }\n}\n</code></pre>\n<p>What will that print out? Well, it entirely depends on the scheduling. It will print 10 numbers, but it probably won't print 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 which is what you might expect. The problem is that it's the <code>i</code> variable which has been captured, not its value at the point of the creation of the delegate. This can be solved easily with an extra local variable of the right scope:</p>\n<pre><code>using System;\nusing System.Threading;\n\nclass Test\n{\n static void Main()\n {\n for (int i=0; i &lt; 10; i++)\n {\n int copy = i;\n ThreadStart ts = delegate { Console.WriteLine(copy); };\n new Thread(ts).Start();\n }\n }\n}\n</code></pre>\n<hr />\n<p><strong>Deferred execution of iterator blocks</strong></p>\n<p>This &quot;poor man's unit test&quot; doesn't pass - why not?</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nclass Test\n{\n static IEnumerable&lt;char&gt; CapitalLetters(string input)\n {\n if (input == null)\n {\n throw new ArgumentNullException(input);\n }\n foreach (char c in input)\n {\n yield return char.ToUpper(c);\n }\n }\n \n static void Main()\n {\n // Test that null input is handled correctly\n try\n {\n CapitalLetters(null);\n Console.WriteLine(&quot;An exception should have been thrown!&quot;);\n }\n catch (ArgumentNullException)\n {\n // Expected\n }\n }\n}\n</code></pre>\n<p>The answer is that the code within the source of the <code>CapitalLetters</code> code doesn't get executed until the iterator's <code>MoveNext()</code> method is first called.</p>\n<p>I've got some other oddities on my <a href=\"https://jonskeet.uk/csharp/teasers.html\" rel=\"nofollow noreferrer\">brainteasers page</a>.</p>\n" }, { "answer_id": 241181, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 6, "selected": false, "text": "<p>overloaded == operators and untyped containers (arraylists, datasets, etc.):</p>\n\n<pre><code>string my = \"my \";\nDebug.Assert(my+\"string\" == \"my string\"); //true\n\nvar a = new ArrayList();\na.Add(my+\"string\");\na.Add(\"my string\");\n\n// uses ==(object) instead of ==(string)\nDebug.Assert(a[1] == \"my string\"); // true, due to interning magic\nDebug.Assert(a[0] == \"my string\"); // false\n</code></pre>\n\n<p>Solutions? </p>\n\n<ul>\n<li><p>always use <code>string.Equals(a, b)</code> when you are comparing string types </p></li>\n<li><p>using generics like <code>List&lt;string&gt;</code> to ensure that both operands are strings.</p></li>\n</ul>\n" }, { "answer_id": 241189, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 7, "selected": false, "text": "<p>Here's another time one that gets me:</p>\n\n<pre><code>static void PrintHowLong(DateTime a, DateTime b)\n{\n TimeSpan span = a - b;\n Console.WriteLine(span.Seconds); // WRONG!\n Console.WriteLine(span.TotalSeconds); // RIGHT!\n}\n</code></pre>\n\n<hr>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.timespan.seconds.aspx\" rel=\"noreferrer\">TimeSpan.Seconds</a> is the seconds portion of the timespan (2 minutes and 0 seconds has a seconds value of 0). </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.timespan.totalseconds.aspx\" rel=\"noreferrer\">TimeSpan.TotalSeconds</a> is the entire timespan measured in seconds (2 minutes has a total seconds value of 120).</p>\n" }, { "answer_id": 241194, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 9, "selected": true, "text": "<pre><code>private int myVar;\npublic int MyVar\n{\n get { return MyVar; }\n}\n</code></pre>\n\n<p>Blammo. Your app crashes with no stack trace. Happens all the time.</p>\n\n<p>(Notice capital <code>MyVar</code> instead of lowercase <code>myVar</code> in the getter.)</p>\n" }, { "answer_id": 241220, "author": "Jeff Kotula", "author_id": 1382162, "author_profile": "https://Stackoverflow.com/users/1382162", "pm_score": 4, "selected": false, "text": "<p>Garbage collection and Dispose(). Although you don't have to do anything to free up <em>memory</em>, you still have to free up <em>resources</em> via Dispose(). This is an immensely easy thing to forget when you are using WinForms, or tracking objects in any way.</p>\n" }, { "answer_id": 241307, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Some code:</p>\n\n<pre><code> List&lt;int&gt; a = new List&lt;int&gt;();\n for (int i = 0; i &lt; 10; i++)\n {\n a.Add(i);\n }\n\n var q1 = (from aa in a\n where aa == 2\n select aa).Single();\n\n var q2 = (from aa in a\n where aa == 2\n select aa).First();\n</code></pre>\n\n<p>q1 - in this query check all integers in List;\nq2 - check integers until find \"right\" integer.</p>\n" }, { "answer_id": 241326, "author": "cciotti", "author_id": 16834, "author_profile": "https://Stackoverflow.com/users/16834", "pm_score": 3, "selected": false, "text": "<p>If you're coding for MOSS and you get a site reference this way:</p>\n\n<pre><code>SPSite oSiteCollection = SPContext.Current.Site;\n</code></pre>\n\n<p>and later in your code you say:</p>\n\n<pre><code>oSiteCollection.Dispose();\n</code></pre>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.dispose.aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<blockquote>\nIf you create an SPSite object, you can use the Dispose method to close the object. However, if you have a reference to a shared resource, such as when the object is provided by the GetContextSite method or Site property (for example, SPContext.Current.Site), do not use the Dispose method to close the object, but instead allow Windows SharePoint Services or your portal application to manage the object. For more information about object disposal, see Best Practices: Using Disposable Windows SharePoint Services Objects.\n</blockquote>\n\n<p>This happens to every MOSS programmer and some point. </p>\n" }, { "answer_id": 241357, "author": "user25306", "author_id": 25306, "author_profile": "https://Stackoverflow.com/users/25306", "pm_score": 5, "selected": false, "text": "<p>When you start a process (using System.Diagnostics) that writes to the console, but you never read the Console.Out stream, after a certain amount of output your app will appear to hang.</p>\n" }, { "answer_id": 241406, "author": "Brian J Cardiff", "author_id": 30948, "author_profile": "https://Stackoverflow.com/users/30948", "pm_score": 4, "selected": false, "text": "<p>foreach loops variables scope!</p>\n\n<pre><code>var l = new List&lt;Func&lt;string&gt;&gt;();\nvar strings = new[] { \"Lorem\" , \"ipsum\", \"dolor\", \"sit\", \"amet\" };\nforeach (var s in strings)\n{\n l.Add(() =&gt; s);\n}\n\nforeach (var a in l)\n Console.WriteLine(a());\n</code></pre>\n\n<p>prints five \"amet\", while the following example works fine</p>\n\n<pre><code>var l = new List&lt;Func&lt;string&gt;&gt;();\nvar strings = new[] { \"Lorem\" , \"ipsum\", \"dolor\", \"sit\", \"amet\" };\nforeach (var s in strings)\n{\n var t = s;\n l.Add(() =&gt; t);\n}\n\nforeach (var a in l)\n Console.WriteLine(a());\n</code></pre>\n" }, { "answer_id": 241421, "author": "jcollum", "author_id": 30946, "author_profile": "https://Stackoverflow.com/users/30946", "pm_score": 3, "selected": false, "text": "<p>I frequently have to remind myself that DateTime is a value type, not a ref type. Just seems too weird to me, especially considering the variety of constructors for it.</p>\n" }, { "answer_id": 241424, "author": "MikeJ", "author_id": 10676, "author_profile": "https://Stackoverflow.com/users/10676", "pm_score": 3, "selected": false, "text": "<p>There is a whole book on <a href=\"http://oreilly.com/catalog/9780596009090/\" rel=\"noreferrer\">.NET Gotchas</a></p>\n\n<p>My favourite is the one where you create a class in C#, inherit it to VB and then attempt to re-inherit back to C# and it doesnt work. ARGGH</p>\n" }, { "answer_id": 241504, "author": "Bjarke Ebert", "author_id": 31890, "author_profile": "https://Stackoverflow.com/users/31890", "pm_score": 5, "selected": false, "text": "<h2>Value objects in mutable collections</h2>\n\n<pre><code>struct Point { ... }\nList&lt;Point&gt; mypoints = ...;\n\nmypoints[i].x = 10;\n</code></pre>\n\n<p>has no effect. </p>\n\n<p><code>mypoints[i]</code> returns a copy of a <code>Point</code> value object. C# happily lets you modify a field of the copy. Silently doing nothing.</p>\n\n<hr>\n\n<p><strong>Update:</strong>\nThis appears to be fixed in C# 3.0:</p>\n\n<pre><code>Cannot modify the return value of 'System.Collections.Generic.List&lt;Foo&gt;.this[int]' because it is not a variable\n</code></pre>\n" }, { "answer_id": 241614, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 6, "selected": false, "text": "<p>If you count ASP.NET, I'd say the webforms lifecycle is a pretty big gotcha to me. I've spent countless hours debugging poorly written webforms code, just because a lot of developers just don't really understand when to use which event handler (me included, sadly).</p>\n" }, { "answer_id": 241849, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 8, "selected": false, "text": "<h1>Re-throwing exceptions</h1>\n\n<p>A gotcha that gets lots of new developers, is the re-throw exception semantics. </p>\n\n<p>Lots of time I see code like the following</p>\n\n<pre><code>catch(Exception e) \n{\n // Do stuff \n throw e; \n}\n</code></pre>\n\n<p>The problem is that it wipes the stack trace and makes diagnosing issues much harder, cause you can not track where the exception originated. </p>\n\n<p>The correct code is either the throw statement with no args:</p>\n\n<pre><code>catch(Exception)\n{\n throw;\n}\n</code></pre>\n\n<p>Or wrapping the exception in another one, and using inner exception to get the original stack trace:</p>\n\n<pre><code>catch(Exception e) \n{\n // Do stuff \n throw new MySpecialException(e); \n}\n</code></pre>\n" }, { "answer_id": 242207, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 1, "selected": false, "text": "<p>The following will not catch the exception in .Net. Instead it results in a StackOverflow exception.</p>\n\n<pre><code>private void button1_Click( object sender, EventArgs e ) {\n try {\n CallMe(234);\n } catch (Exception ex) {\n label1.Text = ex.Message.ToString();\n }\n}\nprivate void CallMe( Int32 x ) {\n CallMe(x);\n}\n</code></pre>\n\n<p><strong>For the commenters (and downvotes):</strong><br>\nIt would be extremely rare for a stack overflow to be this obvious. However, if one occurs you aren't going to catch the exception and will likely spend several hours trying to hunt down exactly where the problem is. It can be compounded if the SO occurs in little used logic paths, especially on a web app where you might not know the exact conditions that kicked off the issue.</p>\n\n<p>This is the exact same situation as the accepted answer to this question (<a href=\"https://stackoverflow.com/a/241194/2424\">https://stackoverflow.com/a/241194/2424</a>). The property getter on that answer is essentially doing the exact same thing as the above code and crashing with no stack trace.</p>\n" }, { "answer_id": 350782, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 3, "selected": false, "text": "<p><code>MemoryStream.GetBuffer()</code> vs <code>MemoryStream.ToArray()</code>. The former returns the whole buffer, the latter just the used portion. Yuck.</p>\n" }, { "answer_id": 497149, "author": "GWLlosa", "author_id": 18071, "author_profile": "https://Stackoverflow.com/users/18071", "pm_score": 3, "selected": false, "text": "<p>My worst one so far I just figured out today... If you override object.Equals(object obj), you can wind up discovering that:</p>\n\n<pre><code>((MyObject)obj).Equals(this);\n</code></pre>\n\n<p>does not behave the same as:</p>\n\n<pre><code>((MyObject)obj) == this;\n</code></pre>\n\n<p>One will call your overriden function, the other will NOT.</p>\n" }, { "answer_id": 640594, "author": "Matt Davis", "author_id": 51170, "author_profile": "https://Stackoverflow.com/users/51170", "pm_score": 5, "selected": false, "text": "<p>For C/C++ programmers, the transition to C# is a natural one. However, the biggest gotcha I've run into personally (and have seen with others making the same transition) is not fully understanding the difference between classes and structs in C#.</p>\n\n<p>In C++, classes and structs are identical; they only differ in the default visibility, where classes default to private visibility and structs default to public visibility. In C++, this class definition</p>\n\n<pre><code> class A\n {\n public:\n int i;\n };\n</code></pre>\n\n<p>is functionally equivalent to this struct definition.</p>\n\n<pre><code> struct A\n {\n int i;\n };\n</code></pre>\n\n<p>In C#, however, classes are reference types while structs are value types. This makes a <strong>BIG</strong> difference in (1) deciding when to use one over the other, (2) testing object equality, (3) performance (e.g., boxing/unboxing), etc.</p>\n\n<p>There is all kinds of information on the web related to the differences between the two (e.g., <a href=\"http://msdn.microsoft.com/en-us/library/ms173109.aspx\" rel=\"noreferrer\">here</a>). I would highly encourage anyone making the transition to C# to at least have a working knowledge of the differences and their implications.</p>\n" }, { "answer_id": 1047889, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 3, "selected": false, "text": "<p>Dictionary&lt;,>: \"The order in which the items are returned is undefined\". This is horrible, because it can bite you sometimes, but work others, and if you've just blindly assumed that Dictionary is going to play nice (\"why shouldn't it? I thought, List does\"), you really have to have your nose in it before you finally start to question your assumption.</p>\n\n<p>(Similar question <a href=\"https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net/311831#311831\">here</a>.)</p>\n" }, { "answer_id": 1048056, "author": "Maltrap", "author_id": 10644, "author_profile": "https://Stackoverflow.com/users/10644", "pm_score": 6, "selected": false, "text": "<p><strong>DateTime.ToString(\"dd/MM/yyyy\")</strong>; This will actually <strong>not</strong> always give you dd/MM/yyyy but instead it will take into account the regional settings and replace your date separator depending on where you are. So you might get dd-MM-yyyy or something alike.</p>\n\n<p>The right way to do this is to use <strong>DateTime.ToString(\"dd'/'MM'/'yyyy\");</strong></p>\n\n<hr>\n\n<p><strong>DateTime.ToString(\"r\")</strong> is supposed to convert to RFC1123, which uses GMT. GMT is within a fraction of a second from UTC, and yet the \"r\" format specifier <a href=\"http://msdn.microsoft.com/en-us/library/az4se3k1.aspx#RFC1123\" rel=\"noreferrer\">does not convert to UTC</a>, even if the DateTime in question is specified as Local.</p>\n\n<p>This results in the following gotcha (varies depending on how far your local time is from UTC):</p>\n\n<pre><code>DateTime.Parse(\"Tue, 06 Sep 2011 16:35:12 GMT\").ToString(\"r\")\n&gt; \"Tue, 06 Sep 2011 17:35:12 GMT\"\n</code></pre>\n\n<p>Whoops!</p>\n" }, { "answer_id": 1097354, "author": "softveda", "author_id": 11711, "author_profile": "https://Stackoverflow.com/users/11711", "pm_score": 4, "selected": false, "text": "<p>Today I fixed a bug that eluded for long time. The bug was in a generic class that was used in multi threaded scenario and a static int field was used to provide lock free synchronisation using Interlocked. The bug was caused because each instantiation of the generic class for a type has its own static. So each thread got its own static field and it wasn't used a lock as intended.</p>\n\n<pre><code>class SomeGeneric&lt;T&gt;\n{\n public static int i = 0;\n}\n\nclass Test\n{\n public static void main(string[] args)\n {\n SomeGeneric&lt;int&gt;.i = 5;\n SomeGeneric&lt;string&gt;.i = 10;\n Console.WriteLine(SomeGeneric&lt;int&gt;.i);\n Console.WriteLine(SomeGeneric&lt;string&gt;.i);\n Console.WriteLine(SomeGeneric&lt;int&gt;.i);\n }\n}\n</code></pre>\n\n<p>This prints\n5\n10\n5</p>\n" }, { "answer_id": 1097745, "author": "kentaromiura", "author_id": 27340, "author_profile": "https://Stackoverflow.com/users/27340", "pm_score": 2, "selected": false, "text": "<p>The worst thing it happen to me was the webBrowser documentText issue:</p>\n<p><a href=\"https://web.archive.org/web/20200217201946/http://geekswithblogs.net:80/paulwhitblog/archive/2005/12/12/62961.aspx#107062\" rel=\"nofollow noreferrer\">Link</a></p>\n<p>the AllowNavigation solutions works in Windows forms...</p>\n<p>but in compact framework the property doesn't exists...</p>\n<p>...so far the only workaround I found was to rebuild the browser control:</p>\n<p><a href=\"http://social.msdn.microsoft.com/Forums/it-IT/netfxcompact/thread/5637037f-96fa-48e7-8ddb-6d4b1e9d7db9\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/it-IT/netfxcompact/thread/5637037f-96fa-48e7-8ddb-6d4b1e9d7db9</a></p>\n<p>But doing so, you need to handle the browser history at hands ... :P</p>\n" }, { "answer_id": 1141114, "author": "Damovisa", "author_id": 77546, "author_profile": "https://Stackoverflow.com/users/77546", "pm_score": 5, "selected": false, "text": "<p>I'm a bit late to this party, but I have two gotchas that have both bitten me recently:</p>\n\n<h1>DateTime resolution</h1>\n\n<p>The Ticks property measures time in 10-millionths of a second (100 nanosecond blocks), however the resolution is not 100 nanoseconds, it's about 15ms.</p>\n\n<p>This code:</p>\n\n<pre><code>long now = DateTime.Now.Ticks;\nfor (int i = 0; i &lt; 10; i++)\n{\n System.Threading.Thread.Sleep(1);\n Console.WriteLine(DateTime.Now.Ticks - now);\n}\n</code></pre>\n\n<p>will give you an output of (for example):</p>\n\n<pre><code>0\n0\n0\n0\n0\n0\n0\n156254\n156254\n156254\n</code></pre>\n\n<p>Similarly, if you look at DateTime.Now.Millisecond, you'll get values in rounded chunks of 15.625ms: 15, 31, 46, etc.</p>\n\n<p>This particular behaviour <a href=\"https://stackoverflow.com/questions/307582/how-frequent-is-datetime-now-updated-or-is-there-a-more-precise-api-to-get-the/4962857#4962857\">varies from system to system</a>, but <a href=\"https://stackoverflow.com/questions/4672359/why-does-timespan-fromsecondsdouble-round-to-milliseconds\">there are other resolution-related gotchas</a> in this date/time API.</p>\n\n<hr>\n\n<h1>Path.Combine</h1>\n\n<p>A great way to combine file paths, but it doesn't always behave the way you'd expect.</p>\n\n<p>If the second parameter starts with a <code>\\</code> character, it won't give you a complete path:</p>\n\n<p>This code:</p>\n\n<pre><code>string prefix1 = \"C:\\\\MyFolder\\\\MySubFolder\";\nstring prefix2 = \"C:\\\\MyFolder\\\\MySubFolder\\\\\";\nstring suffix1 = \"log\\\\\";\nstring suffix2 = \"\\\\log\\\\\";\n\nConsole.WriteLine(Path.Combine(prefix1, suffix1));\nConsole.WriteLine(Path.Combine(prefix1, suffix2));\nConsole.WriteLine(Path.Combine(prefix2, suffix1));\nConsole.WriteLine(Path.Combine(prefix2, suffix2));\n</code></pre>\n\n<p>Gives you this output:</p>\n\n<pre><code>C:\\MyFolder\\MySubFolder\\log\\\n\\log\\\nC:\\MyFolder\\MySubFolder\\log\\\n\\log\\\n</code></pre>\n" }, { "answer_id": 1394752, "author": "Nicolas Dorier", "author_id": 19803, "author_profile": "https://Stackoverflow.com/users/19803", "pm_score": 6, "selected": false, "text": "<pre><code>[Serializable]\nclass Hello\n{\n readonly object accountsLock = new object();\n}\n\n//Do stuff to deserialize Hello with BinaryFormatter\n//and now... accountsLock == null ;)\n</code></pre>\n\n<p>Moral of the story : Field initialisers are not run when deserializing an object</p>\n" }, { "answer_id": 1404302, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 3, "selected": false, "text": "<p><strong>ASP.NET:</strong></p>\n\n<p>If you are using Linq-To-SQL, you call <code>SubmitChanges()</code> on the data context and it throws an exception (e.g. duplicate key or other constraint violation), the offending object values remain in your memory while you are debugging, and will be resubmitted every time you subsequently call <code>SubmitChanges()</code>.</p>\n\n<p>Now here's the <strong>real</strong> kicker: the bad values will remain in memory <strong>even if you push the \"stop\" button in your IDE and restart!</strong> I don't understand why anyone thought this was a good idea - but that little ASP.NET icon that pops up in your system tray stays running, and it appears to save your object cache. If you want to flush your memory space, you have to right-click that icon and forcibly shut it down! <strong>GOTCHA!</strong></p>\n" }, { "answer_id": 1404311, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 4, "selected": false, "text": "<p>MS SQL Server can't handle dates before 1753. Significantly, that is out of synch with the .NET <code>DateTime.MinDate</code> constant, which is 1/1/1. So if you try to save a mindate, a malformed date (as recently happened to me in a data import) or simply the birth date of William the Conqueror, you're gonna be in trouble. There is no built-in workaround for this; if you're likely to need to work with dates before 1753, you need to write your own workaround.</p>\n" }, { "answer_id": 1404321, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 2, "selected": false, "text": "<p><strong>LINQ to SQL and One-To-Many Relationships</strong></p>\n\n<p>This is a lovely one that has bitten me a couple times, and MS left it to one of their own developers to put it in <a href=\"http://blogs.msdn.com/bethmassi/archive/2007/10/02/linq-to-sql-and-one-to-many-relationships.aspx\" rel=\"nofollow noreferrer\">her blog</a>. I can't put it any better than she did, so take a look there.</p>\n" }, { "answer_id": 1404344, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 2, "selected": false, "text": "<p><strong>Linq-To-Sql and the database/local code ambiguity</strong></p>\n\n<p>Sometimes Linq just can't work out whether a certain method is meant to be executed on the DB or in local code.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/1264985/linq-could-not-translate-expression-into-sql-and-could-not-treat-it-as-a-loca\">here</a> and <a href=\"https://stackoverflow.com/questions/1358218/why-linq-cant-translate-expression-treat-as-local-expression-and-throws-an-excep\">here</a> for the problem statement and the solution.</p>\n" }, { "answer_id": 1404987, "author": "Timothy Walters", "author_id": 14454, "author_profile": "https://Stackoverflow.com/users/14454", "pm_score": 6, "selected": false, "text": "<p>Leaking memory because you didn't un-hook events.</p>\n\n<p>This even caught out some senior developers I know.</p>\n\n<p>Imagine a WPF form with lots of things in it, and somewhere in there you subscribe to an event. If you don't unsubscribe then the entire form is kept around in memory after being closed and de-referenced.</p>\n\n<p>I believe the issue I saw was creating a DispatchTimer in the WPF form and subscribing to the Tick event, if you don't do a -= on the timer your form leaks memory!</p>\n\n<p>In this example your teardown code should have </p>\n\n<pre><code>timer.Tick -= TimerTickEventHandler;\n</code></pre>\n\n<p>This one is especially tricky since you created the instance of the DispatchTimer inside the WPF form, so you would think that it would be an internal reference handled by the Garbage Collection process... unfortunately the DispatchTimer uses a static internal list of subscriptions and services requests on the UI thread, so the reference is 'owned' by the static class.</p>\n" }, { "answer_id": 1499314, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 4, "selected": false, "text": "<p><strong>The Nasty Linq Caching Gotcha</strong></p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/1499015/linq-caching-data-values-major-concurrency-problem\">my question</a> that led to this discovery, and <a href=\"http://www.rocksthoughts.com/blog/archive/2008/01/14/linq-to-sql-caching-gotcha.aspx\" rel=\"nofollow noreferrer\">the blogger</a> who discovered the problem.</p>\n\n<p>In short, the DataContext keeps a cache of all Linq-to-Sql objects that you have ever loaded. If anyone else makes any changes to a record that you have previously loaded, you will not be able to get the latest data, <strong>even if you explicitly reload the record!</strong></p>\n\n<p>This is because of a property called <code>ObjectTrackingEnabled</code> on the DataContext, which by default is true. If you set that property to false, the record will be loaded anew every time... <strong>BUT</strong>... you can't persist any changes to that record with SubmitChanges().</p>\n\n<p><strong>GOTCHA!</strong></p>\n" }, { "answer_id": 1571906, "author": "jdehaan", "author_id": 170443, "author_profile": "https://Stackoverflow.com/users/170443", "pm_score": 6, "selected": false, "text": "<p>Maybe not really a gotcha because the behavior is written clearly in MSDN, but has broken my neck once because I found it rather counter-intuitive:</p>\n\n<pre><code>Image image = System.Drawing.Image.FromFile(\"nice.pic\");\n</code></pre>\n\n<p>This guy leaves the <code>\"nice.pic\"</code> file locked until the image is disposed. At the time I faced it I though it would be nice to load icons on the fly and didn't realize (at first) that I ended up with dozens of open and locked files! Image keeps track of where it had loaded the file from...</p>\n\n<p>How to solve this? I thought a one liner would do the job. I expected an extra parameter for <code>FromFile()</code>, but had none, so I wrote this...</p>\n\n<pre><code>using (Stream fs = new FileStream(\"nice.pic\", FileMode.Open, FileAccess.Read))\n{\n image = System.Drawing.Image.FromStream(fs);\n}\n</code></pre>\n" }, { "answer_id": 1855090, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 5, "selected": false, "text": "<p><strong>No operator shortcuts in Linq-To-Sql</strong></p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/1855056/conditional-shortcuts-in-linq-query\">here</a>.</p>\n\n<p>In short, inside the conditional clause of a Linq-To-Sql query, you cannot use conditional shortcuts like <code>||</code> and <code>&amp;&amp;</code> to avoid null reference exceptions; Linq-To-Sql evaluates both sides of the OR or AND operator even if the first condition obviates the need to evaluate the second condition!</p>\n" }, { "answer_id": 1969664, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 4, "selected": false, "text": "<p><strong>Enumerables can be evaluated more than once</strong></p>\n\n<p>It'll bite you when you have a lazily-enumerated enumerable and you iterate over it twice and get different results. (or you get the same results but it executes twice unnecessarily)</p>\n\n<p>For example, while writing a certain test, I needed a few temp files to test the logic:</p>\n\n<pre><code>var files = Enumerable.Range(0, 5)\n .Select(i =&gt; Path.GetTempFileName());\n\nforeach (var file in files)\n File.WriteAllText(file, \"HELLO WORLD!\");\n\n/* ... many lines of codes later ... */\n\nforeach (var file in files)\n File.Delete(file);\n</code></pre>\n\n<p>Imagine my surprise when <code>File.Delete(file)</code> throws <code>FileNotFound</code>!!</p>\n\n<p>What's happening here is that the <code>files</code> enumerable got iterated <em>twice</em> (the results from the first iteration are simply <em>not</em> remembered) and on each new iteration you'd be re-calling <code>Path.GetTempFilename()</code> so you'll get a different set of temp filenames.</p>\n\n<p>The solution is, of course, to eager-enumerate the value by using <code>ToArray()</code> or <code>ToList()</code>:</p>\n\n<pre><code>var files = Enumerable.Range(0, 5)\n .Select(i =&gt; Path.GetTempFileName())\n .ToArray();\n</code></pre>\n\n<p>This is even scarier when you're doing something multi-threaded, like:</p>\n\n<pre><code>foreach (var file in files)\n content = content + File.ReadAllText(file);\n</code></pre>\n\n<p>and you find out <code>content.Length</code> is still 0 after all the writes!! You then begin to rigorously checks that you don't have a race condition when.... after one wasted hour... you figured out it's just that tiny little Enumerable gotcha thing you forgot....</p>\n" }, { "answer_id": 2172307, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 2, "selected": false, "text": "<p><strong>Related object and foreign key out of sync</strong></p>\n\n<p><a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/529623/linq-to-sql-related-object-and-fk-not-in-synch?wa=wsignin1.0#tabs\" rel=\"nofollow noreferrer\">Microsoft have admitted to this bug</a>.</p>\n\n<p>I have a class <code>Thing</code>, which has a FK to <code>Category</code>. Category does not have a defined relationship to Thing, so as not to pollute the interface.</p>\n\n<pre><code>var thing = CreateThing(); // does stuff to create a thing\nvar category = GetCategoryByID(123); // loads the Category with ID 123\nthing.Category = category;\nConsole.WriteLine(\"Category ID: {0}\", thing.CategoryID); \n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Category ID: 0\n</code></pre>\n\n<p>Similarly:</p>\n\n<pre><code>var thing = CreateThing();\nthing.CategoryID = 123;\nConsole.WriteLine(\"Category name: {0}\", order.Category.Name);\n</code></pre>\n\n<p>throws a <code>NullReferenceException</code>. Related object <code>Category</code> does not load the Category record with ID 123.</p>\n\n<p>After you submit changes to the DB, though, these values do get synched. But before you visit the DB, the FK value and related object function practically independently!</p>\n\n<p>(Interestingly, the failure to synch the FK value with the related object only seems to happen when there is no child relationship defined, i.e. Category has no \"Things\" property. But the \"load on demand\" when you just set the FK value NEVER works.)</p>\n\n<p><strong>GOTCHA!</strong></p>\n" }, { "answer_id": 2245370, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 8, "selected": false, "text": "<p><strong>The Heisenberg Watch Window</strong></p>\n\n<p>This can bite you badly if you're doing load-on-demand stuff, like this:</p>\n\n<pre><code>private MyClass _myObj;\npublic MyClass MyObj {\n get {\n if (_myObj == null)\n _myObj = CreateMyObj(); // some other code to create my object\n return _myObj;\n }\n}\n</code></pre>\n\n<p>Now let's say you have some code elsewhere using this:</p>\n\n<pre><code>// blah\n// blah\nMyObj.DoStuff(); // Line 3\n// blah\n</code></pre>\n\n<p>Now you want to debug your <code>CreateMyObj()</code> method. So you put a breakpoint on Line 3 above, with intention to step into the code. Just for good measure, you also put a breakpoint on the line above that says <code>_myObj = CreateMyObj();</code>, and even a breakpoint inside <code>CreateMyObj()</code> itself.</p>\n\n<p>The code hits your breakpoint on Line 3. You step into the code. You expect to enter the conditional code, because <code>_myObj</code> is obviously null, right? Uh... so... why did it skip the condition and go straight to <code>return _myObj</code>?! You hover your mouse over _myObj... and indeed, it does have a value! How did THAT happen?!</p>\n\n<p>The answer is that your IDE caused it to get a value, because you have a \"watch\" window open - especially the \"Autos\" watch window, which displays the values of all variables/properties relevant to the current or previous line of execution. When you hit your breakpoint on Line 3, the watch window decided that you would be interested to know the value of <code>MyObj</code> - so behind the scenes, <strong>ignoring any of your breakpoints</strong>, it went and calculated the value of <code>MyObj</code> for you - <strong>including the call to <code>CreateMyObj()</code> that sets the value of _myObj!</strong></p>\n\n<p>That's why I call this the Heisenberg Watch Window - you cannot observe the value without affecting it... :)</p>\n\n<p><strong>GOTCHA!</strong></p>\n\n<hr/>\n\n<p><strong>Edit</strong> - I feel @ChristianHayter's comment deserves inclusion in the main answer, because it looks like an effective workaround for this issue. So anytime you have a lazy-loaded property...</p>\n\n<blockquote>\n <p>Decorate your property with [DebuggerBrowsable(DebuggerBrowsableState.Never)] or [DebuggerDisplay(\"&lt;loaded on demand&gt;\")]. – Christian Hayter</p>\n</blockquote>\n" }, { "answer_id": 2456832, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 1, "selected": false, "text": "<p><strong>LinqToSQL and the empty set aggregate</strong></p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/2455500/how-to-do-linq-aggregates-when-there-might-be-an-empty-set\">this question</a>.</p>\n\n<p>If you have a LinqToSql query on which you are running an aggregate - if your resultset is empty, Linq can't work out what the data type is, even though it's been declared.</p>\n\n<p>e.g. Suppose you have a table <code>Claim</code> with a field <code>Amount</code>, which in LinqToSql is of type <code>decimal</code>.</p>\n\n<pre><code>var sum = Claims.Where(c =&gt; c.ID &lt; 0).Sum(c =&gt; c.Amount);\n</code></pre>\n\n<p>Obviously no claims have an ID less than zero, so you'd expect to see sum = null, right? <strong>Wrong!</strong> You get an <code>InvalidOperationException</code>, because the SQL query underlying the Linq query doesn't have a data type. You have to tell Linq explicitly that it's a decimal! Thus:</p>\n\n<pre><code>var sum = Claims.Where(c =&gt; c.ID &lt; 0).Sum(c =&gt; (decimal?)c.Amount);\n</code></pre>\n\n<p>This is really dumb and IMO a design bug on Microsoft's part.</p>\n\n<p><strong>GOTCHA!</strong></p>\n" }, { "answer_id": 2542277, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 3, "selected": false, "text": "<p>For both LINQ-to-SQL and LINQ-to-Entities</p>\n\n<pre><code>return result = from o in table\n where o.column == null\n select o;\n//Returns all rows where column is null\n\nint? myNullInt = null;\nreturn result = from o in table\n where o.column == myNullInt\n select o;\n//Never returns anything!\n</code></pre>\n\n<p>There's a bug-report for LINQ-to-Entites <a href=\"https://connect.microsoft.com/data/feedback/details/607404/entity-framework-and-linq-to-sql-incorrectly-handling-nullable-variables\" rel=\"nofollow noreferrer\">here</a>, though they don't seem to check that forum often. Perhaps someone should file one for LINQ-to-SQL as well?</p>\n" }, { "answer_id": 2542285, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 3, "selected": false, "text": "<pre><code>TextInfo textInfo = Thread.CurrentThread.CurrentCulture.TextInfo;\n\ntextInfo.ToTitleCase(\"hello world!\"); //Returns \"Hello World!\"\ntextInfo.ToTitleCase(\"hElLo WoRld!\"); //Returns \"Hello World!\"\ntextInfo.ToTitleCase(\"Hello World!\"); //Returns \"Hello World!\"\ntextInfo.ToTitleCase(\"HELLO WORLD!\"); //Returns \"HELLO WORLD!\"\n</code></pre>\n\n<p>Yes, this behavior is documented, but that certainly doesn't make it right.</p>\n" }, { "answer_id": 2556347, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 5, "selected": false, "text": "<p>Perhaps not the worst, but some parts of the .net framework <a href=\"http://msdn.microsoft.com/en-us/library/a0z3f662.aspx\" rel=\"noreferrer\">use degrees</a> while others use <a href=\"http://msdn.microsoft.com/en-us/library/system.math.tan.aspx\" rel=\"noreferrer\">radians</a> <em>(and the documentation that appears with Intellisense never tells you which, you have to visit MSDN to find out)</em></p>\n\n<p>All of this could have been avoided by having an <code>Angle</code> class instead...</p>\n" }, { "answer_id": 2595746, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.visiblechanged.aspx\" rel=\"nofollow noreferrer\">VisibleChanged</a> is <a href=\"http://memprofiler.com/articles/thecontrolvisiblechangedevent.aspx\" rel=\"nofollow noreferrer\">not usually called</a> when Visible changes.</p>\n" }, { "answer_id": 2731387, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.designmode.aspx\" rel=\"noreferrer\">DesignMode</a> property in all UserControls does <a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/309922/designmode-property-doesnt-behave-as-anticipated\" rel=\"noreferrer\">not actually tell you</a> if you are in design mode.</p>\n" }, { "answer_id": 2731527, "author": "Will Vousden", "author_id": 58635, "author_profile": "https://Stackoverflow.com/users/58635", "pm_score": 3, "selected": false, "text": "<p>The <code>base</code> keyword doesn't work as expected when evaluated in a debugging environment: the method call still uses virtual dispatch.</p>\n\n<p>This wasted a lot of my time when I stumbled across it and I thought I'd encountered some kind of rift in the CLR's space-time, but I then realized it's a known (and even somewhat intentional) bug:</p>\n\n<p><a href=\"http://blogs.msdn.com/jmstall/archive/2006/06/29/funceval-does-virtual-dispatch.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/jmstall/archive/2006/06/29/funceval-does-virtual-dispatch.aspx</a></p>\n" }, { "answer_id": 2773292, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 0, "selected": false, "text": "<p><strong>LinqToSql batches get slower with the square of the batch size</strong></p>\n\n<p><a href=\"https://stackoverflow.com/questions/2767341/how-to-avoid-geometric-slowdown-with-large-linq-transactions\">Here's the question</a> (and <a href=\"https://stackoverflow.com/questions/2767341/how-to-avoid-geometric-slowdown-with-large-linq-transactions/2773207#2773207\">answer</a>) where I explored this problem. </p>\n\n<p>In a nutshell, if you try to build up too many objects in memory before calling <code>DataContext.SubmitChanges()</code>, you start experiencing sluggishness at a geometric rate. I have not confirmed 100% that this is the case, but it appears to me that the call to <code>DataContext.GetChangeSet()</code> causes the data context to perform an equivalence evaluation (<code>.Equals()</code>) on every single combination of 2 items in the change set, probably to make sure it's not double-inserting or causing other concurrency issues. Problem is that if you have very large batches, the number of comparisons increases proportionately with the square of <em>n</em>, i.e. <em>(n^2+n)/2</em>. 1,000 items in memory means over 500,000 comparisons... and that can take a heckuva long time.</p>\n\n<p>To avoid this, you have to ensure that for any batches where you anticipate large numbers of items, you do the whole thing within transaction boundaries, saving each individual item as it is created, rather than in one big save at the end.</p>\n" }, { "answer_id": 2837357, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 5, "selected": false, "text": "<p><strong>Using default parameters with virtual methods</strong></p>\n\n<pre><code>abstract class Base\n{\n public virtual void foo(string s = \"base\") { Console.WriteLine(\"base \" + s); }\n}\n\nclass Derived : Base\n{\n public override void foo(string s = \"derived\") { Console.WriteLine(\"derived \" + s); }\n}\n\n...\n\nBase b = new Derived();\nb.foo();\n</code></pre>\n\n<blockquote>\n <p>Output:<br>\n derived base</p>\n</blockquote>\n" }, { "answer_id": 3045173, "author": "Stefan Steinegger", "author_id": 2658202, "author_profile": "https://Stackoverflow.com/users/2658202", "pm_score": 4, "selected": false, "text": "<p><strong>Arrays implement <code>IList</code></strong></p>\n\n<p>But don't implement it. When you call Add, it tells you that it doesn't work. So why does a class implement an interface when it can't support it?</p>\n\n<p>Compiles, but doesn't work:</p>\n\n<pre><code>IList&lt;int&gt; myList = new int[] { 1, 2, 4 };\nmyList.Add(5);\n</code></pre>\n\n<p>We have this issue a lot, because the serializer (WCF) turns all the ILists into arrays and we get runtime errors.</p>\n" }, { "answer_id": 3045200, "author": "Stefan Steinegger", "author_id": 2658202, "author_profile": "https://Stackoverflow.com/users/2658202", "pm_score": 4, "selected": false, "text": "<p><strong>Events</strong></p>\n\n<p>I never understood why events are a language feature. They are complicated to use: you need to check for null before calling, you need to unregister (yourself), you can't find out who is registered (eg: did I register?). Why isn't an event just a class in the library? Basically a specialized <code>List&lt;delegate&gt;</code>?</p>\n" }, { "answer_id": 3626947, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 2, "selected": false, "text": "<p><strong>The recursive property gotcha</strong></p>\n\n<p>Not specific to C#, I think, and I'm sure I've seen it mentioned elsewhere on SO (<a href=\"https://stackoverflow.com/questions/3626833/inotifypropertychanged-on-a-usercontrol-return-an-infinite-loop\">this</a> is the question that reminded me of it)</p>\n\n<p>It can happen two ways, but the end result is the same:</p>\n\n<p>Forgetting to reference <code>base.</code> when overriding a property:</p>\n\n<pre><code> public override bool IsRecursive\n {\n get { return IsRecursive; }\n set { IsRecursive = value; }\n }\n</code></pre>\n\n<p>Changing from auto- to backed- properties, but not quite going all the way:</p>\n\n<pre><code>public bool IsRecursive\n{\n get { return IsRecursive; }\n set { IsRecursive = value; }\n}\n</code></pre>\n" }, { "answer_id": 3877065, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 3, "selected": false, "text": "<p><strong>Oracle parameters have to added in order</strong></p>\n\n<p>This is a major gotcha in the ODP .Net implementation of parameterized queries for Oracle.</p>\n\n<p>When you add parameters to a query, the default behavior is that the parameter names are <strong>ignored</strong>, and the values are used in the order in which they were added.</p>\n\n<p>The solution is to set the <code>BindByName</code> property of the <code>OracleCommand</code> object to <code>true</code> - it's <code>false</code> by default... which is qualitatively (if not quite quantitatively) something like having a property called <code>DropDatabaseOnQueryExecution</code> with a default value of <code>true</code>.</p>\n\n<p><a href=\"http://download.oracle.com/docs/cd/E11882_01/win.112/e12249/OracleCommandClass.htm#i997666\" rel=\"nofollow noreferrer\">They call it a feature</a>; <a href=\"https://stackoverflow.com/questions/3876856/oracle-ignores-parameter-names-and-works-in-order-of-adding-parameters\">I call it a pit in the public domain</a>.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/3876856/oracle-ignores-parameter-names-and-works-in-order-of-adding-parameters\">here</a> for more details.</p>\n" }, { "answer_id": 4638668, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 0, "selected": false, "text": "<p><strong>Linq2SQL: The mapping of interface member [...] is not supported.</strong></p>\n\n<p>If you do a Linq2Sql query on an object that implements an interface, you get a very odd behavior. Let's say you have a class <code>MyClass</code> that implements an interface <code>IHasDescription</code>, thus:</p>\n\n<pre><code>public interface IHasDescription {\n string Description { get; set; }\n}\n\npublic partial class MyClass : IHasDescription { }\n</code></pre>\n\n<p>(The other half of <code>MyClass</code> is a Linq2Sql generated class, including the property <code>Description</code>.)</p>\n\n<p>Now you write some code (usually this happens in a generic method):</p>\n\n<pre><code>public static T GetByDescription&lt;T&gt;(System.Data.Linq.Table&lt;T&gt; table, string desc) \n where T : class, IHasDescription {\n return table.Where(t =&gt; t.Description == desc).FirstOrDefault();\n}\n</code></pre>\n\n<p>Compiles fine - but you get a runtime error:</p>\n\n<pre><code>NotSupportedException: The mapping of interface member IHasDescription.Description is not supported.\n</code></pre>\n\n<p>Now whaddaya do about that? Well, it's obvious really: just change your <code>==</code> to <code>.Equals()</code>, thus:</p>\n\n<pre><code>return table.Where(t =&gt; t.Description.Equals(desc)).FirstOrDefault();\n</code></pre>\n\n<p>And everything works fine now!</p>\n\n<p>See <a href=\"http://social.msdn.microsoft.com/Forums/en/linqtosql/thread/bc2fbbce-eb63-4735-9b2d-26b4ab8fe589\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 4833796, "author": "Roman Starkov", "author_id": 33080, "author_profile": "https://Stackoverflow.com/users/33080", "pm_score": 4, "selected": false, "text": "<p><strong>The contract on Stream.Read</strong> is something that I've seen trip up a lot of people:</p>\n\n<pre><code>// Read 8 bytes and turn them into a ulong\nbyte[] data = new byte[8];\nstream.Read(data, 0, 8); // &lt;-- WRONG!\nulong data = BitConverter.ToUInt64(data);\n</code></pre>\n\n<p>The reason this is wrong is that <code>Stream.Read</code> will read <strong>at most</strong> the specified number of bytes, but is <strong>entirely free</strong> to read just 1 byte, even if another 7 bytes are available before end of stream.</p>\n\n<p>It doesn't help that this looks so similar to <code>Stream.Write</code>, which <em>is</em> guaranteed to have written all the bytes if it returns with no exception. It also doesn't help that the above code <em>works almost all the time</em>. And of course it doesn't help that there is no ready-made, convenient method for reading exactly N bytes correctly.</p>\n\n<p>So, to plug the hole, and increase awareness of this, here is an example of a correct way to do this:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Attempts to fill the buffer with the specified number of bytes from the\n /// stream. If there are fewer bytes left in the stream than requested then\n /// all available bytes will be read into the buffer.\n /// &lt;/summary&gt;\n /// &lt;param name=\"stream\"&gt;Stream to read from.&lt;/param&gt;\n /// &lt;param name=\"buffer\"&gt;Buffer to write the bytes to.&lt;/param&gt;\n /// &lt;param name=\"offset\"&gt;Offset at which to write the first byte read from\n /// the stream.&lt;/param&gt;\n /// &lt;param name=\"length\"&gt;Number of bytes to read from the stream.&lt;/param&gt;\n /// &lt;returns&gt;Number of bytes read from the stream into buffer. This may be\n /// less than requested, but only if the stream ended before the\n /// required number of bytes were read.&lt;/returns&gt;\n public static int FillBuffer(this Stream stream,\n byte[] buffer, int offset, int length)\n {\n int totalRead = 0;\n while (length &gt; 0)\n {\n var read = stream.Read(buffer, offset, length);\n if (read == 0)\n return totalRead;\n offset += read;\n length -= read;\n totalRead += read;\n }\n return totalRead;\n }\n\n /// &lt;summary&gt;\n /// Attempts to read the specified number of bytes from the stream. If\n /// there are fewer bytes left before the end of the stream, a shorter\n /// (possibly empty) array is returned.\n /// &lt;/summary&gt;\n /// &lt;param name=\"stream\"&gt;Stream to read from.&lt;/param&gt;\n /// &lt;param name=\"length\"&gt;Number of bytes to read from the stream.&lt;/param&gt;\n public static byte[] Read(this Stream stream, int length)\n {\n byte[] buf = new byte[length];\n int read = stream.FillBuffer(buf, 0, length);\n if (read &lt; length)\n Array.Resize(ref buf, read);\n return buf;\n }\n</code></pre>\n" }, { "answer_id": 5088558, "author": "Shekhar_Pro", "author_id": 399722, "author_profile": "https://Stackoverflow.com/users/399722", "pm_score": 2, "selected": false, "text": "<p>I always thought <code>value</code> types were always on <code>stack</code> and <code>reference</code> types on <code>heap</code>. </p>\n\n<p>Well it is <strong>not so</strong>. When i saw <a href=\"https://stackoverflow.com/q/5088216/399722\">this question</a> recently on SO (and arguably answered incorrectly) i came to know its not the case. </p>\n\n<p>As <a href=\"https://stackoverflow.com/questions/5088216/where-these-are-stored/5088328#5088328\">Jon Skeet</a> answered (giving a reference to <a href=\"http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx\" rel=\"nofollow noreferrer\">Eric Lippert's Blog post</a> ) its a <strong>Myth</strong>.</p>\n\n<p>Considerably Important Links:</p>\n\n<p><a href=\"http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx\" rel=\"nofollow noreferrer\">The truth about Value Types</a></p>\n\n<p><a href=\"http://blogs.msdn.com/b/ericlippert/archive/2009/02/17/references-are-not-addresses.aspx\" rel=\"nofollow noreferrer\">References are not aAddress</a></p>\n\n<p><a href=\"http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx\" rel=\"nofollow noreferrer\">The Stack is an Implementation Detail Part 1</a></p>\n\n<p><a href=\"http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx\" rel=\"nofollow noreferrer\">The Stack is an Implementation Detail Part 2</a></p>\n" }, { "answer_id": 5800045, "author": "Boris Lipschitz", "author_id": 87475, "author_profile": "https://Stackoverflow.com/users/87475", "pm_score": 3, "selected": false, "text": "<p>Static constructors are executed under lock. As a result, calling threading code from static constructor might result in deadlock.\nHere is an example that demonstrates it:</p>\n\n<pre><code>using System.Threading;\nclass Blah\n{\n static void Main() { /* Won’t run because the static constructor deadlocks. */ }\n\n static Blah()\n {\n Thread thread = new Thread(ThreadBody);\n thread.Start();\n thread.Join();\n }\n\n static void ThreadBody() { }\n}\n</code></pre>\n" }, { "answer_id": 12502678, "author": "Roboblob", "author_id": 125718, "author_profile": "https://Stackoverflow.com/users/125718", "pm_score": 3, "selected": false, "text": "<p>Check this one out:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n var originalNumbers = new List&lt;int&gt; { 1, 2, 3, 4, 5, 6 };\n\n var list = new List&lt;int&gt;(originalNumbers);\n var collection = new Collection&lt;int&gt;(originalNumbers);\n\n originalNumbers.RemoveAt(0);\n\n DisplayItems(list, \"List items: \");\n DisplayItems(collection, \"Collection items: \");\n\n Console.ReadLine();\n }\n\n private static void DisplayItems(IEnumerable&lt;int&gt; items, string title)\n {\n Console.WriteLine(title);\n foreach (var item in items)\n Console.Write(item);\n Console.WriteLine();\n }\n}\n</code></pre>\n\n<p>And output is:</p>\n\n<pre><code>List items: 123456\nCollection items: 23456\n</code></pre>\n\n<p>Collection constructor that accepts IList creates a wrapper around original List, while List constructor creates a new List and copies all references from original to the new List.</p>\n\n<p>See more here:\n<a href=\"http://blog.roboblob.com/2012/09/19/dot-net-gotcha-nr1-list-versus-collection-constructor/\" rel=\"noreferrer\">http://blog.roboblob.com/2012/09/19/dot-net-gotcha-nr1-list-versus-collection-constructor/</a></p>\n" }, { "answer_id": 13724876, "author": "Trident D'Gao", "author_id": 139667, "author_profile": "https://Stackoverflow.com/users/139667", "pm_score": 3, "selected": false, "text": "<p>This is a super-gotcha that I wasted 2 days troubleshooting. It didn't throw any exceptions it just crashed the web-server with some <a href=\"http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/84da7fd7-30b8-4e5f-b82c-3e340170a1c6/\" rel=\"nofollow noreferrer\">weird error messages</a>. I could not reproduce the problem in DEV. Moreover the experiments with the project build settings somehow made it go away in the PROD, then it came back. Finally I got it.</p>\n\n<p>Tell me if you see a problem in the following piece of code:</p>\n\n<pre><code>private void DumpError(Exception exception, Stack&lt;String&gt; context)\n{\n if (context.Any())\n {\n Trace.WriteLine(context.Pop());\n Trace.Indent();\n this.DumpError(exception, context);\n Trace.Unindent();\n }\n else\n {\n Trace.WriteLine(exception.Message);\n }\n}\n</code></pre>\n\n<p>So if you value your sanity:</p>\n\n<p><strong>!!! Never ever ever put any logic to Trace methods !!!</strong></p>\n\n<p>The code must have looked like this:</p>\n\n<pre><code>private void DumpError(Exception exception, Stack&lt;String&gt; context)\n{\n if (context.Any())\n {\n var popped = context.Pop();\n Trace.WriteLine(popped);\n Trace.Indent();\n this.DumpError(exception, context);\n Trace.Unindent();\n }\n else\n {\n Trace.WriteLine(exception.Message);\n }\n}\n</code></pre>\n" }, { "answer_id": 13737981, "author": "Mahdi Tahsildari", "author_id": 1471381, "author_profile": "https://Stackoverflow.com/users/1471381", "pm_score": 3, "selected": false, "text": "<pre><code>enum Seasons\n{\n Spring = 1, Summer = 2, Automn = 3, Winter = 4\n}\n\npublic string HowYouFeelAbout(Seasons season)\n{\n switch (season)\n {\n case Seasons.Spring:\n return \"Nice.\";\n case Seasons.Summer:\n return \"Hot.\";\n case Seasons.Automn:\n return \"Cool.\";\n case Seasons.Winter:\n return \"Chilly.\";\n }\n}\n</code></pre>\n\n<p>Error?<br>\n<strong>not all code paths return a value ...</strong><br>\nare you kidding me? I bet all code paths do return a value because every <code>Seasons</code> member is mentioned here. It should have been checking all enum members and if a member was absent in switch cases then such error would be meaningful, but now I should add a <code>Default</code> case which is redundant and never gets reached by code. </p>\n\n<p><strong>EDIT :</strong><br>\nafter more research on this Gotcha I came to <a href=\"http://blogs.msdn.com/b/ericlippert/archive/2009/08/13/four-switch-oddities.aspx\" rel=\"noreferrer\">Eric Lippert's nice written and useful post</a> but it is still kind of weird. Do you agree?</p>\n" }, { "answer_id": 15831225, "author": "guruprasath", "author_id": 1862239, "author_profile": "https://Stackoverflow.com/users/1862239", "pm_score": 1, "selected": false, "text": "<p>Sometimes the line numbers in the stack trace do not match the line numbers in the source code. This might happen due to inlining of simple(single-line) functions for optimization. This is a serious source of confusion for people debugging using logs. </p>\n\n<p>Edit: Example: Sometimes you see a null reference exception in the stack trace where it points to a line of code with absolutely no chance of null reference exception, like a simple integer assignment. </p>\n" }, { "answer_id": 16546439, "author": "DevDave", "author_id": 896631, "author_profile": "https://Stackoverflow.com/users/896631", "pm_score": 4, "selected": false, "text": "<p>Just found a weird one that had me stuck in debug for a while:</p>\n\n<p>You can increment null for a nullable int without throwing an excecption and the value stays null.</p>\n\n<pre><code>int? i = null;\ni++; // I would have expected an exception but runs fine and stays as null\n</code></pre>\n" }, { "answer_id": 21197312, "author": "Chuu", "author_id": 459975, "author_profile": "https://Stackoverflow.com/users/459975", "pm_score": 1, "selected": false, "text": "<p>Not the worst, but one that hasn't been brought up yet. Factory methods passed as arguments to System.Collections.Concurrent methods can be called multiple times even if only one return value is ever used. Considering how strongly .NET tries to protect you from spurious wake-up in threading primitives this can come as a surprise.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Collections.Concurrent;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace ValueFactoryBehavingBadlyExample\n{\n class Program\n {\n static ConcurrentDictionary&lt;int, int&gt; m_Dict = new ConcurrentDictionary&lt;int, int&gt;();\n static ManualResetEventSlim m_MRES = new ManualResetEventSlim(false);\n static void Main(string[] args)\n {\n for (int i = 0; i &lt; 8; ++i)\n {\n Task.Factory.StartNew(ThreadGate, TaskCreationOptions.LongRunning);\n }\n Thread.Sleep(1000);\n m_MRES.Set();\n Thread.Sleep(1000);\n Console.WriteLine(\"Dictionary Size: \" + m_Dict.Count);\n Console.Read();\n }\n\n static void ThreadGate()\n {\n m_MRES.Wait();\n int value = m_Dict.GetOrAdd(0, ValueFactory);\n }\n\n static int ValueFactory(int key)\n {\n Thread.Sleep(1000);\n Console.WriteLine(\"Value Factory Called\");\n return key;\n }\n }\n}\n</code></pre>\n\n<p>(Possible) Output:</p>\n\n<pre><code>Value Factory Called\nValue Factory Called\nValue Factory Called\nValue Factory Called\nDictionary Size: 0\nValue Factory Called\nValue Factory Called\nValue Factory Called\nValue Factory Called\n</code></pre>\n" }, { "answer_id": 22555441, "author": "SkeetJon", "author_id": 831108, "author_profile": "https://Stackoverflow.com/users/831108", "pm_score": 1, "selected": false, "text": "<p><strong>Passing a capacity to <code>List&lt;int&gt;</code> instead of using the collection initializer.</strong></p>\n\n<pre><code>var thisOnePasses = new List&lt;int&gt; {2}; // collection initializer\nvar thisOneFails = new List&lt;int&gt; (2); // oops, use capacity by mistake #gotcha#\n\nthisOnePasses.Count.Should().Be(1);\nthisOnePasses.First().Should().Be(2);\n\nthisOneFails.Count.Should().Be(1); // it's zero\nthisOneFails.First().Should().Be(2); // Sequence contains no elements...\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
I was recently working with a `DateTime` object, and wrote something like this: ``` DateTime dt = DateTime.Now; dt.AddDays(1); return dt; // still today's date! WTF? ``` The intellisense documentation for `AddDays()` says it adds a day to the date, which it doesn't - it actually *returns* a date with a day added to it, so you have to write it like: ``` DateTime dt = DateTime.Now; dt = dt.AddDays(1); return dt; // tomorrow's date ``` This one has bitten me a number of times before, so I thought it would be useful to catalog the worst C# gotchas.
``` private int myVar; public int MyVar { get { return MyVar; } } ``` Blammo. Your app crashes with no stack trace. Happens all the time. (Notice capital `MyVar` instead of lowercase `myVar` in the getter.)
241,142
<p>i want to be a good developer citizen, <a href="http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx" rel="nofollow noreferrer">pay my taxes</a>, and disable things if we're running over Remote Desktop, or running on battery.</p> <p>If we're running over remote desktop (or equivalently in a Terminal server session), we must disable animations and double-buffering. You can check this with:</p> <pre><code>/// &lt;summary&gt; /// Indicates if we're running in a remote desktop session. /// If we are, then you MUST disable animations and double buffering i.e. Pay your taxes! /// /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Boolean IsRemoteSession { //This is just a friendly wrapper around the built-in way get { return System.Windows.Forms.SystemInformation.TerminalServerSession; } } </code></pre> <p>Now i need to find out if the user is running on battery power. If they are, i don't want to blow through their battery. i want to do things such as</p> <ul> <li>disable animations</li> <li>disable background spell-checking</li> <li>disable background printing</li> <li>turn off gradients </li> <li>use <code>graphics.SmoothingMode = SmoothingMode.HighSpeed;</code> </li> <li>use <code>graphics.InterpolationMode = InterpolationMode.Low;</code></li> <li>use <code>graphics.CompositingQuality = CompositingQuality.HighSpeed;</code></li> <li>minimize hard drive access - to avoid spin up</li> <li>minimize network access - to save WiFi power</li> </ul> <p>Is there a managed way to see if the machine is <strong>currently</strong> running on battery?</p> <h2>Bonus Reading</h2> <ul> <li><a href="http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx" rel="nofollow noreferrer">How do you convince developers to pay their "taxes"?</a> <em>(<a href="https://archive.fo/iNVg5" rel="nofollow noreferrer">archive.is</a>)</em></li> <li><a href="http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx" rel="nofollow noreferrer">Taxes: Remote Desktop Connection and painting</a> <em>(<a href="https://archive.fo/lJx1u" rel="nofollow noreferrer">archive.is</a>)</em></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx" rel="nofollow noreferrer">GetSystemMetrics(SM_REMOTESESSION)</a> <em>(<a href="https://archive.fo/Ywbw7" rel="nofollow noreferrer">archive.is</a>)</em></li> </ul>
[ { "answer_id": 241157, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 0, "selected": false, "text": "<p>You could use WMI (Windows Management Instrumentation) to query the operating system about the battery status.</p>\n\n<p>You could find more information here:</p>\n\n<ul>\n<li><a href=\"http://69.10.233.10/KB/system/Wmi_Processor_infoWrapper.aspx\" rel=\"nofollow noreferrer\">http://69.10.233.10/KB/system/Wmi_Processor_infoWrapper.aspx</a></li>\n<li><a href=\"http://www.microsoft.com/technet/scriptcenter/resources/qanda/apr07/hey0409.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/scriptcenter/resources/qanda/apr07/hey0409.mspx</a></li>\n<li><a href=\"http://www.codeproject.com/KB/cs/EverythingInWmi03.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/EverythingInWmi03.aspx</a></li>\n</ul>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 241159, "author": "driis", "author_id": 13627, "author_profile": "https://Stackoverflow.com/users/13627", "pm_score": 3, "selected": false, "text": "<p>You could use the GetSystemPowerStatus function using P/Invoke. See:\n<a href=\"http://msdn.microsoft.com/en-gb/library/aa372693.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-gb/library/aa372693.aspx</a></p>\n\n<p>Here's an example:</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nnamespace PowerStateExample\n{\n [StructLayout(LayoutKind.Sequential)]\n public class PowerState\n {\n public ACLineStatus ACLineStatus;\n public BatteryFlag BatteryFlag;\n public Byte BatteryLifePercent;\n public Byte Reserved1;\n public Int32 BatteryLifeTime;\n public Int32 BatteryFullLifeTime;\n\n // direct instantation not intended, use GetPowerState.\n private PowerState() {}\n\n public static PowerState GetPowerState()\n {\n PowerState state = new PowerState();\n if (GetSystemPowerStatusRef(state))\n return state;\n\n throw new ApplicationException(\"Unable to get power state\");\n }\n\n [DllImport(\"Kernel32\", EntryPoint = \"GetSystemPowerStatus\")]\n private static extern bool GetSystemPowerStatusRef(PowerState sps);\n }\n\n // Note: Underlying type of byte to match Win32 header\n public enum ACLineStatus : byte\n {\n Offline = 0, Online = 1, Unknown = 255\n }\n\n public enum BatteryFlag : byte\n {\n High = 1, Low = 2, Critical = 4, Charging = 8,\n NoSystemBattery = 128, Unknown = 255\n }\n\n // Program class with main entry point to display an example.\n class Program\n { \n static void Main(string[] args)\n {\n PowerState state = PowerState.GetPowerState();\n Console.WriteLine(\"AC Line: {0}\", state.ACLineStatus);\n Console.WriteLine(\"Battery: {0}\", state.BatteryFlag);\n Console.WriteLine(\"Battery life %: {0}\", state.BatteryLifePercent);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 241163, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 6, "selected": true, "text": "<p>I believe you can check <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.powerstatus(VS.80).aspx\" rel=\"noreferrer\">SystemInformation.PowerStatus</a> to see if it's on battery or not.</p>\n\n<pre><code>Boolean isRunningOnBattery =\n (System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus == \n PowerLineStatus.Offline);\n</code></pre>\n\n<p>Edit: In addition to the above, there's also a System.Windows.Forms.<a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus(VS.80).aspx\" rel=\"noreferrer\">PowerStatus</a> class. One of its methods is <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus.powerlinestatus(VS.80).aspx\" rel=\"noreferrer\">PowerLineStatus</a>, which will equal PowerLineStatus.Online if it's on AC Power.</p>\n" }, { "answer_id": 241164, "author": "Andrew Grant", "author_id": 1043, "author_profile": "https://Stackoverflow.com/users/1043", "pm_score": -1, "selected": false, "text": "<p>I don't believe it's exposed in managed code, but you can use the Win32 GetSystemPowerStatus via pinvoke to get this info.</p>\n\n<p>As an aside, you may want to consider using the GetCurrentPowerPolicies or similar to determine the users preferences relating to performance/power management. </p>\n" }, { "answer_id": 241174, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 3, "selected": false, "text": "<p>R. Bemrose found the managed call. Here's some sample code:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Indicates if we're running on battery power.\n/// If we are, then disable CPU wasting things like animations, background operations, network, I/O, etc\n/// &lt;/summary&gt;\npublic static Boolean IsRunningOnBattery\n{\n get\n {\n PowerLineStatus pls = System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus;\n\n //Offline means running on battery\n return (pls == PowerLineStatus.Offline);\n }\n}\n</code></pre>\n" }, { "answer_id": 51645890, "author": "Byte11", "author_id": 6515420, "author_profile": "https://Stackoverflow.com/users/6515420", "pm_score": 0, "selected": false, "text": "<p>Powerlord's answer doesn't seem to work, probably because it was answered in 2008. </p>\n\n<p>Here is a version that worked for me:</p>\n\n<pre><code>Boolean x = (System.Windows.SystemParameters.PowerLineStatus == System.Windows.PowerLineStatus.Offline);\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
i want to be a good developer citizen, [pay my taxes](http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx), and disable things if we're running over Remote Desktop, or running on battery. If we're running over remote desktop (or equivalently in a Terminal server session), we must disable animations and double-buffering. You can check this with: ``` /// <summary> /// Indicates if we're running in a remote desktop session. /// If we are, then you MUST disable animations and double buffering i.e. Pay your taxes! /// /// </summary> /// <returns></returns> public static Boolean IsRemoteSession { //This is just a friendly wrapper around the built-in way get { return System.Windows.Forms.SystemInformation.TerminalServerSession; } } ``` Now i need to find out if the user is running on battery power. If they are, i don't want to blow through their battery. i want to do things such as * disable animations * disable background spell-checking * disable background printing * turn off gradients * use `graphics.SmoothingMode = SmoothingMode.HighSpeed;` * use `graphics.InterpolationMode = InterpolationMode.Low;` * use `graphics.CompositingQuality = CompositingQuality.HighSpeed;` * minimize hard drive access - to avoid spin up * minimize network access - to save WiFi power Is there a managed way to see if the machine is **currently** running on battery? Bonus Reading ------------- * [How do you convince developers to pay their "taxes"?](http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx) *([archive.is](https://archive.fo/iNVg5))* * [Taxes: Remote Desktop Connection and painting](http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx) *([archive.is](https://archive.fo/lJx1u))* * [GetSystemMetrics(SM\_REMOTESESSION)](http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx) *([archive.is](https://archive.fo/Ywbw7))*
I believe you can check [SystemInformation.PowerStatus](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.powerstatus(VS.80).aspx) to see if it's on battery or not. ``` Boolean isRunningOnBattery = (System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Offline); ``` Edit: In addition to the above, there's also a System.Windows.Forms.[PowerStatus](http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus(VS.80).aspx) class. One of its methods is [PowerLineStatus](http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus.powerlinestatus(VS.80).aspx), which will equal PowerLineStatus.Online if it's on AC Power.
241,144
<p>I know that this is a very specific C++ and Qt related question, but maybe someone can help me, anyway ...</p> <p>See the code below: I want to display an image within a scroll area. The view port of the scroll area shall have a defined initial size. That means, if the image's size is bigger than the initial size of the view port, scroll bars will be visible, otherwise not.</p> <pre><code>// create label for displaying an image QImage image( ":/test.png" ); QLabel *label = new QLabel( this ); label-&gt;setPixmap( image.toPixmap() ); // put label into scroll area QScollArea *area = new QScrollArea( this ); area-&gt;setWidget( label ); // set the initial size of the view port // NOTE: This is what I'd like to do, but this method does not exist :( area-&gt;setViewPortSize( QSize( 300, 300 ) ); </code></pre> <p>It shall be possible to resize the whole application so that the view port will get another size than the initial one.</p> <p>Unfortunatelly I was not able to find out, how to set the size of the view port. Qt's layout mechanism seems to set a default size for the view port, but up to now I was not able to change it. Setting a new size with </p> <pre><code>area-&gt;setMinimumSize( QSize( 300, 300 ) ); </code></pre> <p>will actually set the demanded size, but then the scroll area looses the ability to get resized to a size smaller than 300x300.</p> <p>Any ideas?</p>
[ { "answer_id": 243561, "author": "Caleb Huitt - cjhuitt", "author_id": 9876, "author_profile": "https://Stackoverflow.com/users/9876", "pm_score": 0, "selected": false, "text": "<p>I don't think you can do exactly that very easily, which is (if I'm reading correctly), size the widget so that the internal area is 300x300. You might be able to fudge it, however, since a scroll area is a type of frame, which inherits from QWidget. This means you could just call <code>area-&gt;resize( 300 + fudge, 300 + fudge )</code>, where your fudge values account for the extra bit taken up by the frame's drawing.</p>\n\n<p>I'm not sure this would work in a dynamically resizable dialog, however. I haven't ever done anything quite like this.</p>\n" }, { "answer_id": 250257, "author": "mxcl", "author_id": 6444, "author_profile": "https://Stackoverflow.com/users/6444", "pm_score": 2, "selected": false, "text": "<p>You can try:</p>\n\n<pre><code>class MyScrollArea : public QScrollArea\n{\n virtual QSize sizeHint() const { return QSize( 300, 300 ); }\n};\n\n// create label for displaying an image\nQImage image( \":/test.png\" );\nLabel *label = new QLabel;\nlabel-&gt;setPixmap( image.toPixmap() );\n\n// put label into scroll area\nQScollArea *area = new MyScrollArea( this );\narea-&gt;setWidget( label );\n</code></pre>\n\n<p>However layout and Qt is amazingly Voodoo. It is IMO its least functional part.</p>\n\n<p>if that doesn't work, try calling QWidget::resize() on various widgets.</p>\n" }, { "answer_id": 251586, "author": "Dusty Campbell", "author_id": 2174, "author_profile": "https://Stackoverflow.com/users/2174", "pm_score": 3, "selected": true, "text": "<p>I think that you are looking at the problem the wrong way. The QScrollArea is just a widget that you put in a frame or QMainWindow. The size of the widget is controlled by the layout of the widget that contains it.</p>\n\n<p>Take a look at this example from Trolltech: <a href=\"http://doc.qt.io/qt-5/qtwidgets-widgets-imageviewer-example.html\" rel=\"nofollow noreferrer\">Image Viewer Example</a></p>\n" }, { "answer_id": 263766, "author": "Bob", "author_id": 34467, "author_profile": "https://Stackoverflow.com/users/34467", "pm_score": 0, "selected": false, "text": "<p>If you're trying to display an image inside a scroll area, your best bet isn't going with a label. </p>\n\n<p>You should try using a QGraphicsView/QGraphicsScene/QGraphicPixmapItem (instead of the Scroll Area and label). The performance is far better when displaying images. The scroll area and label will re-draw the image very poorly as you move around using the scroll bars.</p>\n\n<p>For example, you have a \".ui\" file with a QGraphicsView on the gui called \"qgvImageView\" and a QImage called \"image\"...</p>\n\n<pre><code>QGraphicsScene *scene = new QGraphicsScene(qgvImageView);\nQPixmap pixTmp(QPixmap::fromImage(image));\nQGraphicsPixmapItem * ppixItem = scene-&gt;addPixmap( pixTmp );\nppixItem-&gt;setPos(0,0);\n</code></pre>\n\n<p>Check out the QT Documentation. BTW: This was introduced in Qt 4.2</p>\n\n<p>I'm not sure if this will specifically fix the problem, but there is a chance that the QGraphicsView will react better to what you're trying to do.</p>\n" }, { "answer_id": 407857, "author": "Henrik Hartz", "author_id": 50830, "author_profile": "https://Stackoverflow.com/users/50830", "pm_score": 2, "selected": false, "text": "<p>Is the scroll area the top level widget? If so, simply call </p>\n\n<pre><code>area-&gt;resize(300,300);\n</code></pre>\n\n<p>If it's inside a hierarchy you need to resize the toplevel appropriately (complex), or set the minimumSize of the area. You could also try to experiment with the LayoutPolicy - assuming the sizeHint is QSize(300,300) you can give it the appropriate size policy according to what's defined in <a href=\"https://doc.qt.io/qt-5/qsizepolicy.html#Policy-enum\" rel=\"nofollow noreferrer\">https://doc.qt.io/qt-5/qsizepolicy.html#Policy-enum</a></p>\n" }, { "answer_id": 409595, "author": "Alpants", "author_id": 48923, "author_profile": "https://Stackoverflow.com/users/48923", "pm_score": 0, "selected": false, "text": "<p>How about using</p>\n\n<pre><code>area-&gt;setGeometry(int x, int y, int w, int h);\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ]
I know that this is a very specific C++ and Qt related question, but maybe someone can help me, anyway ... See the code below: I want to display an image within a scroll area. The view port of the scroll area shall have a defined initial size. That means, if the image's size is bigger than the initial size of the view port, scroll bars will be visible, otherwise not. ``` // create label for displaying an image QImage image( ":/test.png" ); QLabel *label = new QLabel( this ); label->setPixmap( image.toPixmap() ); // put label into scroll area QScollArea *area = new QScrollArea( this ); area->setWidget( label ); // set the initial size of the view port // NOTE: This is what I'd like to do, but this method does not exist :( area->setViewPortSize( QSize( 300, 300 ) ); ``` It shall be possible to resize the whole application so that the view port will get another size than the initial one. Unfortunatelly I was not able to find out, how to set the size of the view port. Qt's layout mechanism seems to set a default size for the view port, but up to now I was not able to change it. Setting a new size with ``` area->setMinimumSize( QSize( 300, 300 ) ); ``` will actually set the demanded size, but then the scroll area looses the ability to get resized to a size smaller than 300x300. Any ideas?
I think that you are looking at the problem the wrong way. The QScrollArea is just a widget that you put in a frame or QMainWindow. The size of the widget is controlled by the layout of the widget that contains it. Take a look at this example from Trolltech: [Image Viewer Example](http://doc.qt.io/qt-5/qtwidgets-widgets-imageviewer-example.html)
241,145
<p>How do you create a simple, custom rule using the jQuery Validate plugin (using <a href="http://jqueryvalidation.org/jQuery.validator.addMethod" rel="noreferrer"><code>addMethod</code></a>) that doesn't use a regex?</p> <p>For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?</p>
[ { "answer_id": 241202, "author": "Mark Spangler", "author_id": 456684, "author_profile": "https://Stackoverflow.com/users/456684", "pm_score": 9, "selected": false, "text": "<p>You can create a simple rule by doing something like this:</p>\n\n<pre><code>jQuery.validator.addMethod(\"greaterThanZero\", function(value, element) {\n return this.optional(element) || (parseFloat(value) &gt; 0);\n}, \"* Amount must be greater than zero\");\n</code></pre>\n\n<p>And then applying this like so:</p>\n\n<pre><code>$('validatorElement').validate({\n rules : {\n amount : { greaterThanZero : true }\n }\n});\n</code></pre>\n\n<p>Just change the contents of the 'addMethod' to validate your checkboxes.</p>\n" }, { "answer_id": 243647, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Thanks, it worked!</p>\n\n<p>Here's the final code:</p>\n\n<pre><code>$.validator.addMethod(\"greaterThanZero\", function(value, element) {\n var the_list_array = $(\"#some_form .super_item:checked\");\n return the_list_array.length &gt; 0;\n}, \"* Please check at least one check box\");\n</code></pre>\n" }, { "answer_id": 2289990, "author": "Tracy", "author_id": 276236, "author_profile": "https://Stackoverflow.com/users/276236", "pm_score": 7, "selected": false, "text": "<pre><code>$(document).ready(function(){\n var response;\n $.validator.addMethod(\n \"uniqueUserName\", \n function(value, element) {\n $.ajax({\n type: \"POST\",\n url: \"http://\"+location.host+\"/checkUser.php\",\n data: \"checkUsername=\"+value,\n dataType:\"html\",\n success: function(msg)\n {\n //If username exists, set response to true\n response = ( msg == 'true' ) ? true : false;\n }\n });\n return response;\n },\n \"Username is Already Taken\"\n );\n\n $(\"#regFormPart1\").validate({\n username: {\n required: true,\n minlength: 8,\n uniqueUserName: true\n },\n messages: {\n username: {\n required: \"Username is required\",\n minlength: \"Username must be at least 8 characters\",\n uniqueUserName: \"This Username is taken already\"\n }\n }\n });\n});\n</code></pre>\n" }, { "answer_id": 4258174, "author": "commonpike", "author_id": 95733, "author_profile": "https://Stackoverflow.com/users/95733", "pm_score": 6, "selected": false, "text": "<pre><code>// add a method. calls one built-in method, too.\njQuery.validator.addMethod(\"optdate\", function(value, element) {\n return jQuery.validator.methods['date'].call(\n this,value,element\n )||value==(\"0000/00/00\");\n }, \"Please enter a valid date.\"\n);\n\n// connect it to a css class\njQuery.validator.addClassRules({\n optdate : { optdate : true } \n});\n</code></pre>\n" }, { "answer_id": 33941303, "author": "BenG", "author_id": 1000934, "author_profile": "https://Stackoverflow.com/users/1000934", "pm_score": 6, "selected": false, "text": "<h2>Custom Rule and data attribute</h2>\n\n<p>You are able to create a custom rule and attach it to an element using the <code>data</code> attribute using the syntax <code>data-rule-rulename=\"true\";</code></p>\n\n<p>So to check if at least one of a group of checkboxes is checked:</p>\n\n<p><strong>data-rule-oneormorechecked</strong></p>\n\n<pre><code>&lt;input type=\"checkbox\" name=\"colours[]\" value=\"red\" data-rule-oneormorechecked=\"true\" /&gt;\n</code></pre>\n\n<p><strong>addMethod</strong></p>\n\n<pre><code>$.validator.addMethod(\"oneormorechecked\", function(value, element) {\n return $('input[name=\"' + element.name + '\"]:checked').length &gt; 0;\n}, \"Atleast 1 must be selected\");\n</code></pre>\n\n<p>And you can also override the message of a rule <em>(ie: Atleast 1 must be selected)</em> by using the syntax <code>data-msg-rulename=\"my new message\"</code>.</p>\n\n<p><strong>NOTE</strong></p>\n\n<p>If you use the <code>data-rule-rulename</code> method then you will need to make sure the rule name is all lowercase. This is because the jQuery validation function <code>dataRules</code> applies <code>.toLowerCase()</code> to compare and the <a href=\"http://www.w3.org/html/wg/drafts/html/master/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes\"><strong>HTML5</strong></a> spec does not allow uppercase.</p>\n\n<p><strong>Working Example</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$.validator.addMethod(\"oneormorechecked\", function(value, element) {\r\n return $('input[name=\"' + element.name + '\"]:checked').length &gt; 0;\r\n}, \"Atleast 1 must be selected\");\r\n\r\n$('.validate').validate();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js\"&gt;&lt;/script&gt;\r\n\r\n&lt;form class=\"validate\"&gt;\r\n red&lt;input type=\"checkbox\" name=\"colours[]\" value=\"red\" data-rule-oneormorechecked=\"true\" data-msg-oneormorechecked=\"Check one or more!\" /&gt;&lt;br/&gt;\r\n blue&lt;input type=\"checkbox\" name=\"colours[]\" value=\"blue\" /&gt;&lt;br/&gt;\r\n green&lt;input type=\"checkbox\" name=\"colours[]\" value=\"green\" /&gt;&lt;br/&gt;\r\n &lt;input type=\"submit\" value=\"submit\"/&gt;\r\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 37562968, "author": "Bogdan Mates", "author_id": 5068697, "author_profile": "https://Stackoverflow.com/users/5068697", "pm_score": 4, "selected": false, "text": "<p>You can add a custom rule like this: </p>\n\n<pre><code>$.validator.addMethod(\n 'booleanRequired',\n function (value, element, requiredValue) {\n return value === requiredValue;\n },\n 'Please check your input.'\n);\n</code></pre>\n\n<p>And add it as a rule like this: </p>\n\n<pre><code>PhoneToggle: {\n booleanRequired: 'on'\n} \n</code></pre>\n" }, { "answer_id": 48074571, "author": "Siwei", "author_id": 445908, "author_profile": "https://Stackoverflow.com/users/445908", "pm_score": 2, "selected": false, "text": "<p>For this case: user signup form, user must choose a username that is not taken. </p>\n\n<p>This means we have to create a customized validation rule, which will send async http request with remote server. </p>\n\n<ol>\n<li>create a input element in your html: </li>\n</ol>\n\n<pre><code>&lt;input name=\"user_name\" type=\"text\" &gt;\n</code></pre>\n\n<ol start=\"2\">\n<li>declare your form validation rules: </li>\n</ol>\n\n<pre class=\"lang-js prettyprint-override\"><code> $(\"form\").validate({\n rules: {\n 'user_name': {\n // here jquery validate will start a GET request, to \n // /interface/users/is_username_valid?user_name=&lt;input_value&gt;\n // the response should be \"raw text\", with content \"true\" or \"false\" only\n remote: '/interface/users/is_username_valid'\n },\n },\n</code></pre>\n\n\n\n<ol start=\"3\">\n<li>the remote code should be like: </li>\n</ol>\n\n<pre><code>class Interface::UsersController &lt; ActionController::Base\n def is_username_valid\n render :text =&gt; !User.exists?(:user_name =&gt; params[:user_name])\n end\nend\n</code></pre>\n" }, { "answer_id": 65966205, "author": "Devang Hire", "author_id": 9956618, "author_profile": "https://Stackoverflow.com/users/9956618", "pm_score": -1, "selected": false, "text": "<p><strong>Step 1</strong> Included the cdn like</p>\n<pre><code> &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js&quot;&gt;&lt;/script&gt;\n\n &lt;script src=&quot;http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js&quot;&gt;&lt;/script&gt;\n</code></pre>\n<p><strong>Step 2</strong> Code Like</p>\n<pre><code> $(document).ready(function(){\n $(&quot;#submit&quot;).click(function () {\n $('#myform').validate({ // initialize the plugin\n rules: {\n id: {\n required: true,\n email: true\n },\n password: {\n required: true,\n minlength: 1\n }\n },\n messages: {\n id: {\n required: &quot;Enter Email Id&quot;\n\n },\n password: {\n required: &quot;Enter Email Password&quot;\n\n }\n },\n submitHandler: function (form) { // for demo\n alert('valid form submitted'); // for demo\n return false; // for demo\n }\n });\n }):\n }); \n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31869/" ]
How do you create a simple, custom rule using the jQuery Validate plugin (using [`addMethod`](http://jqueryvalidation.org/jQuery.validator.addMethod)) that doesn't use a regex? For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?
You can create a simple rule by doing something like this: ``` jQuery.validator.addMethod("greaterThanZero", function(value, element) { return this.optional(element) || (parseFloat(value) > 0); }, "* Amount must be greater than zero"); ``` And then applying this like so: ``` $('validatorElement').validate({ rules : { amount : { greaterThanZero : true } } }); ``` Just change the contents of the 'addMethod' to validate your checkboxes.
241,150
<p>I want to filter the selectable dates on a datepicker. I basically need to filter by work days - i.e. make holidays and weekends not selectable.</p> <p>I know you can specify dates using a function in the beforeShowDate: and you can also use $.datepicker.noWeekends.</p> <p>Question is: can you do both?</p>
[ { "answer_id": 241244, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 4, "selected": true, "text": "<p>$.datepicker.noWeekends is a pretty simple bit of code:</p>\n\n<pre><code>function (date) { \n var day = date.getDay(); \n return [day &gt; 0 &amp;&amp; day &lt; 6, \"\"]; \n}\n</code></pre>\n\n<p>Since you're going to have to write up the function for holidays, you can just include this logic in that function too.</p>\n" }, { "answer_id": 344579, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Can you do the opposite and have the input what dates are selectable and leave all the rest filtered out?</p>\n" }, { "answer_id": 1427087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Yes you can.</p>\n\n<p>i.e. If you only want the user to be able to select Mondays you would add something like:</p>\n\n<pre><code>onlyMondays: function(date){\n var day = date.getDay();\n return [(day == 1), \"\"]\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
I want to filter the selectable dates on a datepicker. I basically need to filter by work days - i.e. make holidays and weekends not selectable. I know you can specify dates using a function in the beforeShowDate: and you can also use $.datepicker.noWeekends. Question is: can you do both?
$.datepicker.noWeekends is a pretty simple bit of code: ``` function (date) { var day = date.getDay(); return [day > 0 && day < 6, ""]; } ``` Since you're going to have to write up the function for holidays, you can just include this logic in that function too.
241,166
<p>Question: Is there any reason Autocomplete=off on a ASP:Textbox would not be working in IE 7?</p> <p>In case this is the best term for it, the IE Autocomplete feature is that drop down list like thing that drops down from textboxes and shows you past things you have typed in.</p> <p>I need the IE Autocomplete feature to not work at this point for a textbox that is part of a user control that works like an Ajax Autocomplete control. Problem is, when the Ajax Autocomplete selection list shows up, so does the IE Autocomplete selection box. (In cases where I might double click the textbox) I'm using this:</p> <pre><code>someTextbox.AutoCompleteType = AutoCompleteType.Disabled; </code></pre> <p>But it stills shows up. I've tried removing the items from the IE Autocomplete, but the next time I type something in and press enter, the problem reappears. Any ideas?</p> <p>Note: The textbox is rendered with the Autocomplete=off tag when viewing the source.</p> <p>Note 2: Have tried someTextbox.Attributes.Add("autocomplete", "off"); also without success</p> <p><strong>* Update, figured it out a while ago but forgot *</strong></p> <pre><code>test.AutoCompleteType = AutoCompleteType.None; </code></pre> <p>That actually works. I'm not sure what the difference is though. Suppose Ill look that up sometime.</p>
[ { "answer_id": 241172, "author": "BoboTheCodeMonkey", "author_id": 30532, "author_profile": "https://Stackoverflow.com/users/30532", "pm_score": 1, "selected": false, "text": "<p>Try this one:</p>\n\n<pre><code>someTextbox.Attributes.Add(\"autocomplete\", \"off\");\n</code></pre>\n" }, { "answer_id": 241184, "author": "Lea Cohen", "author_id": 278, "author_profile": "https://Stackoverflow.com/users/278", "pm_score": 3, "selected": false, "text": "<p>Try adding AUTOCOMPLETE=\"off\" to your form tag too: </p>\n\n<pre><code>&lt;form name=\"form1\" id=\"form1\" method=\"post\" autocomplete=\"off\"&gt;\n</code></pre>\n" }, { "answer_id": 355341, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>in Page Load</p>\n\n<pre><code>txtusername.AutoCompleteType = AutoCompleteType.Disabled;\n</code></pre>\n" }, { "answer_id": 863517, "author": "Programmin Tool", "author_id": 21691, "author_profile": "https://Stackoverflow.com/users/21691", "pm_score": 4, "selected": true, "text": "<p>Trying to clear out my unanswered questions that I've answered in the original post.</p>\n\n<pre><code>test.AutoCompleteType = AutoCompleteType.None;\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21691/" ]
Question: Is there any reason Autocomplete=off on a ASP:Textbox would not be working in IE 7? In case this is the best term for it, the IE Autocomplete feature is that drop down list like thing that drops down from textboxes and shows you past things you have typed in. I need the IE Autocomplete feature to not work at this point for a textbox that is part of a user control that works like an Ajax Autocomplete control. Problem is, when the Ajax Autocomplete selection list shows up, so does the IE Autocomplete selection box. (In cases where I might double click the textbox) I'm using this: ``` someTextbox.AutoCompleteType = AutoCompleteType.Disabled; ``` But it stills shows up. I've tried removing the items from the IE Autocomplete, but the next time I type something in and press enter, the problem reappears. Any ideas? Note: The textbox is rendered with the Autocomplete=off tag when viewing the source. Note 2: Have tried someTextbox.Attributes.Add("autocomplete", "off"); also without success **\* Update, figured it out a while ago but forgot \*** ``` test.AutoCompleteType = AutoCompleteType.None; ``` That actually works. I'm not sure what the difference is though. Suppose Ill look that up sometime.
Trying to clear out my unanswered questions that I've answered in the original post. ``` test.AutoCompleteType = AutoCompleteType.None; ```
241,185
<p>I'd like to write a MessageConverter class that can wrap another MessageConverter. This MessageConverter would call the child converter, which is assumed to generate a TextMessage. It would take the payload and GZIP compress it, creating a BytesMessage which is ultimately returned to the sender.</p> <p>The problem is in writing fromMessage(). I can convert the payload back into the string, but then I want to create a "dummy" TextMessage to stuff the string into to then pass to the child MessageConverter's fromMessage() method. There I'm hitting a brick wall because I can't create a TextMessage without a JMS session object, and it appears that there is no way at all to get a session in this context.</p> <p>I could create additional properties to wire up more stuff to this class, but it doesn't look like I can easily even obtain a session from a JMSTemplate object, and I can't imagine what else I'd need to have.</p> <p>I am on the verge of creating a private TextMessage implementation within this code just for the purpose of wrapping a string for the child MessageConverter. That class will require tons of dummy methods to flesh out the Interface, and all of that typing makes baby Jesus cry.</p> <p>Can anyone suggest a better way?</p>
[ { "answer_id": 241695, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 2, "selected": true, "text": "<p>So I did, in fact, make one of these:</p>\n\n<pre><code> private static class FakeTextMessage implements TextMessage {\n public FakeTextMessage(Message m) { this.childMessage = m; }\n private String text;\n private Message childMessage;\n public void setText(String t) { this.text = t; }\n public String getText() { return this.text; }\n\n // All the rest of the methods are simply pass-through\n // implementations of the rest of the interface, handing off to the child message.\n public void acknowledge() throws JMSException { this.childMessage.acknowledge(); }\n public void clearBody() throws JMSException { this.childMessage.clearBody(); }\n public void clearProperties() throws JMSException { this.childMessage.clearProperties(); }\n public Enumeration getPropertyNames() throws JMSException { return this.childMessage.getPropertyNames(); }\n public boolean propertyExists(String pn) throws JMSException { return this.childMessage.propertyExists(pn); }\n\n // and so on and so on\n }\n</code></pre>\n\n<p>Makes me long for Objective C. How is THAT possible? :)</p>\n" }, { "answer_id": 242375, "author": "James Strachan", "author_id": 2068211, "author_profile": "https://Stackoverflow.com/users/2068211", "pm_score": 2, "selected": false, "text": "<p>Do you really wanna wrap MessageConverter instances inside other MessageConverter instances? The whole point of a MessageConverter is to turn a Message into something else (that is not a JMS Message). Its not really designed to chain them (each step making a fake JMS message).</p>\n\n<p>Why not just introduce your own interface</p>\n\n<pre><code>interface MessageBodyConverter {\n /** return a converted body of the original message */\n Object convert(Object body, Message originalMessage);\n}\n</code></pre>\n\n<p>You then can create a MessageConverter invoking one of these (which can then nest as deep as you like)</p>\n\n<pre><code>class MyMessageConverter implements MessageConverter {\n private final MessageBodyConverter converter;\n\n public Object fromMessage(Message message) {\n if (message instanceof ObjectMessage) {\n return converter.convert(objectMessage.getObject(), message);\n ...\n }\n}\n</code></pre>\n\n<p>You can then chain those MessageBodyConverter objects as deep as you like - plus you have access to the original JMS message (to get headers and so forth) without having to try create pseudo (probably not JMS compliant) implementations of Message?</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13757/" ]
I'd like to write a MessageConverter class that can wrap another MessageConverter. This MessageConverter would call the child converter, which is assumed to generate a TextMessage. It would take the payload and GZIP compress it, creating a BytesMessage which is ultimately returned to the sender. The problem is in writing fromMessage(). I can convert the payload back into the string, but then I want to create a "dummy" TextMessage to stuff the string into to then pass to the child MessageConverter's fromMessage() method. There I'm hitting a brick wall because I can't create a TextMessage without a JMS session object, and it appears that there is no way at all to get a session in this context. I could create additional properties to wire up more stuff to this class, but it doesn't look like I can easily even obtain a session from a JMSTemplate object, and I can't imagine what else I'd need to have. I am on the verge of creating a private TextMessage implementation within this code just for the purpose of wrapping a string for the child MessageConverter. That class will require tons of dummy methods to flesh out the Interface, and all of that typing makes baby Jesus cry. Can anyone suggest a better way?
So I did, in fact, make one of these: ``` private static class FakeTextMessage implements TextMessage { public FakeTextMessage(Message m) { this.childMessage = m; } private String text; private Message childMessage; public void setText(String t) { this.text = t; } public String getText() { return this.text; } // All the rest of the methods are simply pass-through // implementations of the rest of the interface, handing off to the child message. public void acknowledge() throws JMSException { this.childMessage.acknowledge(); } public void clearBody() throws JMSException { this.childMessage.clearBody(); } public void clearProperties() throws JMSException { this.childMessage.clearProperties(); } public Enumeration getPropertyNames() throws JMSException { return this.childMessage.getPropertyNames(); } public boolean propertyExists(String pn) throws JMSException { return this.childMessage.propertyExists(pn); } // and so on and so on } ``` Makes me long for Objective C. How is THAT possible? :)
241,193
<p>Is there a .dll version of the <a href="http://t3.dotgnu.info/blog/php/messy-programmers-beware.html" rel="nofollow noreferrer">inclued</a> extension for <a href="http://us2.php.net/manual/en/intro.inclued.php" rel="nofollow noreferrer">PHP</a>? The manual's link for <a href="http://pecl4win.php.net/ext.php/php_inclued.dll" rel="nofollow noreferrer">Inclued on PECL4WIN</a> doesn't help. I don't have a compiler to build my own DLL.</p> <p>NOTE: The spelling "inclued" is correct!</p> <p>Edit: I don't have a compiler, but do know someone with one... that's really a last resort though.</p>
[ { "answer_id": 241219, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Isn't this their DLL download site? <a href=\"http://pecl4win.php.net/list_dlls.php\" rel=\"nofollow noreferrer\">http://pecl4win.php.net/list_dlls.php</a></p>\n\n<p>Unless I'm off on my browsing of the site?</p>\n" }, { "answer_id": 241221, "author": "kevtrout", "author_id": 1149, "author_profile": "https://Stackoverflow.com/users/1149", "pm_score": 0, "selected": false, "text": "<p>Is this the page you are looking for?</p>\n\n<p><a href=\"http://pecl4win.php.net/list_dlls.php\" rel=\"nofollow noreferrer\">http://pecl4win.php.net/list_dlls.php</a></p>\n\n<p>..edit: (man, we are fast. I swear these two duplicate answers were posted simultaniously)</p>\n" }, { "answer_id": 241239, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p>As best as I can tell, the Windows version doesn't exist anymore. Maybe whoever was maintaining it before had to stop for some reason.</p>\n\n<p>I wonder what it takes to compile a PECL extension under Windows.</p>\n\n<hr>\n\n<p><strong>Edit</strong></p>\n\n<p>Here's some info on compiling a different PECL extension <a href=\"http://groups.google.co.uk/group/phpsoa/web/build-the-sca-sdo-pecl-extension\" rel=\"nofollow noreferrer\">on Windows</a>. You may be able to extrapolate to the inclued extension.</p>\n\n<hr>\n\n<p><strong>Edit</strong></p>\n\n<p><a href=\"http://www.wampserver.com/en/\" rel=\"nofollow noreferrer\">WAMP Server</a> comes with PECL &amp; PEAR. I can actually run the command <strong>pecl install inclued-alpha</strong> from the Windows command-line and it goes out and tries to grab the inclued extension from the PECL site.</p>\n\n<p>Unfortunately it dies when it unpacks the .tgz file and tries to compile it</p>\n\n<pre><code>ERROR: The DSP inclued.dsp does not exist.\n</code></pre>\n" }, { "answer_id": 243004, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": true, "text": "<p>Which version of PHP are you running? I know someone that can compile you a version.</p>\n<h2>update</h2>\n<p>Alright, got this compiled - I've tested on my 5.2.6 build and it seems to work fine.</p>\n<p>I've been told there may be problems using it in a threaded environment (e.g. Windows) but that's only a maybe. Also:</p>\n<pre><code>[13:10] &lt;g0pz&gt; the inclued dumpfiles will collide, because it uses PID # + increments\n[13:11] &lt;g0pz&gt; but command line should work ok\n[13:12] &lt;g0pz&gt; is the threaded apache version which'll have the same PID and well, a &quot;possible&quot; collision \n</code></pre>\n<p>So good luck with it :)</p>\n<h3><a href=\"http://www.uvshock.co.uk/php_inclued.dll\" rel=\"nofollow noreferrer\">download</a></h3>\n" }, { "answer_id": 250176, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Poke me if you have any issues with inclued. </p>\n\n<p>I'm just on the verge of putting out a release, I'll do a mkstemp() in windows instead of picking the PID + count.</p>\n\n<p>Hopefully also with a gensvg.php which'll render the di-graph in-browser with pear::Image::GraphViz.</p>\n" }, { "answer_id": 11339305, "author": "Dmitry Leskov", "author_id": 127430, "author_profile": "https://Stackoverflow.com/users/127430", "pm_score": 0, "selected": false, "text": "<p>The official <a href=\"http://windows.php.net/\" rel=\"nofollow\">PHP for Windows</a> site says:</p>\n\n<blockquote>\n <p><strong>PECL For Windows</strong></p>\n \n <p>PECL extensions for Windows is being worked on. The interface on the\n pecl website will most likely be updated to offer Windows DLL download\n right from that website. In the meantime, some extensions can be found\n <strong><a href=\"http://downloads.php.net/pierre/\" rel=\"nofollow\">here</a></strong>.</p>\n</blockquote>\n\n<p>That \"here\" link leads to <a href=\"http://downloads.php.net/pierre/\" rel=\"nofollow\">http://downloads.php.net/pierre/</a>, where you will find, among the multitude of other extensions, builds of inclued for PHP 5.2 and 5.3, VC6 and VC9, thread-safe and non-thread-safe. The one matching my version of PHP seems to be working.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24181/" ]
Is there a .dll version of the [inclued](http://t3.dotgnu.info/blog/php/messy-programmers-beware.html) extension for [PHP](http://us2.php.net/manual/en/intro.inclued.php)? The manual's link for [Inclued on PECL4WIN](http://pecl4win.php.net/ext.php/php_inclued.dll) doesn't help. I don't have a compiler to build my own DLL. NOTE: The spelling "inclued" is correct! Edit: I don't have a compiler, but do know someone with one... that's really a last resort though.
Which version of PHP are you running? I know someone that can compile you a version. update ------ Alright, got this compiled - I've tested on my 5.2.6 build and it seems to work fine. I've been told there may be problems using it in a threaded environment (e.g. Windows) but that's only a maybe. Also: ``` [13:10] <g0pz> the inclued dumpfiles will collide, because it uses PID # + increments [13:11] <g0pz> but command line should work ok [13:12] <g0pz> is the threaded apache version which'll have the same PID and well, a "possible" collision ``` So good luck with it :) ### [download](http://www.uvshock.co.uk/php_inclued.dll)
241,236
<p>I'm trying to use the Grid from WPFToolkit, but I'm getting the error:</p> <pre><code>DisplayDataMapping.xaml (9,89): errorMC1000: Unknown build error, 'Could not load type 'System.Windows.Controls.Primitives.MultiSelector' from assembly 'PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Line 9 Position 89.' </code></pre> <p>Here is the xaml: <pre> &lt;UserControl x:Class="DisplayDataMapping" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"&gt; &lt;StackPanel Margin="10"&gt; &lt;Border CornerRadius="5" BorderThickness="1" Padding="5" BorderBrush="WhiteSmoke"&gt; &lt;toolkit:DataGrid x:Name="dataGridPostings" Background="Transparent" AlternatingRowBackground="LightSteelBlue" RowBackground="White" GridLinesVisibility="None" HorizontalGridLinesBrush="SlateGray"&gt; &lt;/toolkit:DataGrid&gt; &lt;/Border&gt; &lt;/StackPanel&gt; &lt;/UserControl&gt; </pre></p>
[ { "answer_id": 242381, "author": "Alex Janzik", "author_id": 22038, "author_profile": "https://Stackoverflow.com/users/22038", "pm_score": 2, "selected": false, "text": "<p>The WPF Toolkit is dependent on .NET Framework 3.5 SP1 (just in case you don't know already).</p>\n" }, { "answer_id": 382136, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Try to install VS08 SP1</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to use the Grid from WPFToolkit, but I'm getting the error: ``` DisplayDataMapping.xaml (9,89): errorMC1000: Unknown build error, 'Could not load type 'System.Windows.Controls.Primitives.MultiSelector' from assembly 'PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Line 9 Position 89.' ``` Here is the xaml: ``` <UserControl x:Class="DisplayDataMapping" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"> <StackPanel Margin="10"> <Border CornerRadius="5" BorderThickness="1" Padding="5" BorderBrush="WhiteSmoke"> <toolkit:DataGrid x:Name="dataGridPostings" Background="Transparent" AlternatingRowBackground="LightSteelBlue" RowBackground="White" GridLinesVisibility="None" HorizontalGridLinesBrush="SlateGray"> </toolkit:DataGrid> </Border> </StackPanel> </UserControl> ```
The WPF Toolkit is dependent on .NET Framework 3.5 SP1 (just in case you don't know already).
241,238
<p>Could someone supply some code that would get the xpath of a System.Xml.XmlNode instance?</p> <p>Thanks!</p>
[ { "answer_id": 241251, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>There's no such thing as \"the\" xpath of a node. For any given node there may well be many xpath expressions which will match it.</p>\n\n<p>You can probably work up the tree to build up <em>an</em> expression which will match it, taking into account the index of particular elements etc, but it's not going to be terribly nice code.</p>\n\n<p>Why do you need this? There may be a better solution.</p>\n" }, { "answer_id": 241291, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>Okay, I couldn't resist having a go at it. It'll only work for attributes and elements, but hey... what can you expect in 15 minutes :) Likewise there may very well be a cleaner way of doing it.</p>\n\n<p>It is superfluous to include the index on every element (particularly the root one!) but it's easier than trying to work out whether there's any ambiguity otherwise.</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Xml;\n\nclass Test\n{\n static void Main()\n {\n string xml = @\"\n&lt;root&gt;\n &lt;foo /&gt;\n &lt;foo&gt;\n &lt;bar attr='value'/&gt;\n &lt;bar other='va' /&gt;\n &lt;/foo&gt;\n &lt;foo&gt;&lt;bar /&gt;&lt;/foo&gt;\n&lt;/root&gt;\";\n XmlDocument doc = new XmlDocument();\n doc.LoadXml(xml);\n XmlNode node = doc.SelectSingleNode(\"//@attr\");\n Console.WriteLine(FindXPath(node));\n Console.WriteLine(doc.SelectSingleNode(FindXPath(node)) == node);\n }\n\n static string FindXPath(XmlNode node)\n {\n StringBuilder builder = new StringBuilder();\n while (node != null)\n {\n switch (node.NodeType)\n {\n case XmlNodeType.Attribute:\n builder.Insert(0, \"/@\" + node.Name);\n node = ((XmlAttribute) node).OwnerElement;\n break;\n case XmlNodeType.Element:\n int index = FindElementIndex((XmlElement) node);\n builder.Insert(0, \"/\" + node.Name + \"[\" + index + \"]\");\n node = node.ParentNode;\n break;\n case XmlNodeType.Document:\n return builder.ToString();\n default:\n throw new ArgumentException(\"Only elements and attributes are supported\");\n }\n }\n throw new ArgumentException(\"Node was not in a document\");\n }\n\n static int FindElementIndex(XmlElement element)\n {\n XmlNode parentNode = element.ParentNode;\n if (parentNode is XmlDocument)\n {\n return 1;\n }\n XmlElement parent = (XmlElement) parentNode;\n int index = 1;\n foreach (XmlNode candidate in parent.ChildNodes)\n {\n if (candidate is XmlElement &amp;&amp; candidate.Name == element.Name)\n {\n if (candidate == element)\n {\n return index;\n }\n index++;\n }\n }\n throw new ArgumentException(\"Couldn't find element within parent\");\n }\n}\n</code></pre>\n" }, { "answer_id": 241492, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 5, "selected": false, "text": "<p>Jon's correct that there are any number of XPath expressions that will yield the same node in an an instance document. The simplest way to build an expression that unambiguously yields a specific node is a chain of node tests that use the node position in the predicate, e.g.:</p>\n\n<pre><code>/node()[0]/node()[2]/node()[6]/node()[1]/node()[2]\n</code></pre>\n\n<p>Obviously, this expression isn't using element names, but then if all you're trying to do is locate a node within a document, you don't need its name. It also can't be used to find attributes (because attributes aren't nodes and don't have position; you can only find them by name), but it will find all other node types.</p>\n\n<p>To build this expression, you need to write a method that returns a node's position in its parent's child nodes, because <code>XmlNode</code> doesn't expose that as a property:</p>\n\n<pre><code>static int GetNodePosition(XmlNode child)\n{\n for (int i=0; i&lt;child.ParentNode.ChildNodes.Count; i++)\n {\n if (child.ParentNode.ChildNodes[i] == child)\n {\n // tricksy XPath, not starting its positions at 0 like a normal language\n return i + 1;\n }\n }\n throw new InvalidOperationException(\"Child node somehow not found in its parent's ChildNodes property.\");\n}\n</code></pre>\n\n<p>(There's probably a more elegant way to do that using LINQ, since <code>XmlNodeList</code> implements <code>IEnumerable</code>, but I'm going with what I know here.)</p>\n\n<p>Then you can write a recursive method like this:</p>\n\n<pre><code>static string GetXPathToNode(XmlNode node)\n{\n if (node.NodeType == XmlNodeType.Attribute)\n {\n // attributes have an OwnerElement, not a ParentNode; also they have\n // to be matched by name, not found by position\n return String.Format(\n \"{0}/@{1}\",\n GetXPathToNode(((XmlAttribute)node).OwnerElement),\n node.Name\n ); \n }\n if (node.ParentNode == null)\n {\n // the only node with no parent is the root node, which has no path\n return \"\";\n }\n // the path to a node is the path to its parent, plus \"/node()[n]\", where \n // n is its position among its siblings.\n return String.Format(\n \"{0}/node()[{1}]\",\n GetXPathToNode(node.ParentNode),\n GetNodePosition(node)\n );\n}\n</code></pre>\n\n<p>As you can see, I hacked in a way for it to find attributes as well.</p>\n\n<p>Jon slipped in with his version while I was writing mine. There's something about his code that's going to make me rant a bit now, and I apologize in advance if it sounds like I'm ragging on Jon. (I'm not. I'm pretty sure that the list of things Jon has to learn from me is exceedingly short.) But I think the point I'm going to make is a pretty important one for anyone who works with XML to think about.</p>\n\n<p>I suspect that Jon's solution emerged from something I see a lot of developers do: thinking of XML documents as trees of elements and attributes. I think this largely comes from developers whose primary use of XML is as a serialization format, because all the XML they're used to using is structured this way. You can spot these developers because they're using the terms \"node\" and \"element\" interchangeably. This leads them to come up with solutions that treat all other node types as special cases. (I was one of these guys myself for a very long time.)</p>\n\n<p>This feels like it's a simplifying assumption while you're making it. But it's not. It makes problems harder and code more complex. It leads you to bypass the pieces of XML technology (like the <code>node()</code> function in XPath) that are specifically designed to treat all node types generically.</p>\n\n<p>There's a red flag in Jon's code that would make me query it in a code review even if I didn't know what the requirements are, and that's <code>GetElementsByTagName</code>. Whenever I see that method in use, the question that leaps to mind is always \"why does it have to be an element?\" And the answer is very often \"oh, does this code need to handle text nodes too?\"</p>\n" }, { "answer_id": 1033415, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is even easier</p>\n\n<pre><code> ''' &lt;summary&gt;\n ''' Gets the full XPath of a single node.\n ''' &lt;/summary&gt;\n ''' &lt;param name=\"node\"&gt;&lt;/param&gt;\n ''' &lt;returns&gt;&lt;/returns&gt;\n ''' &lt;remarks&gt;&lt;/remarks&gt;\n Private Function GetXPath(ByVal node As Xml.XmlNode) As String\n Dim temp As String\n Dim sibling As Xml.XmlNode\n Dim previousSiblings As Integer = 1\n\n 'I dont want to know that it was a generic document\n If node.Name = \"#document\" Then Return \"\"\n\n 'Prime it\n sibling = node.PreviousSibling\n 'Perculate up getting the count of all of this node's sibling before it.\n While sibling IsNot Nothing\n 'Only count if the sibling has the same name as this node\n If sibling.Name = node.Name Then\n previousSiblings += 1\n End If\n sibling = sibling.PreviousSibling\n End While\n\n 'Mark this node's index, if it has one\n ' Also mark the index to 1 or the default if it does have a sibling just no previous.\n temp = node.Name + IIf(previousSiblings &gt; 0 OrElse node.NextSibling IsNot Nothing, \"[\" + previousSiblings.ToString() + \"]\", \"\").ToString()\n\n If node.ParentNode IsNot Nothing Then\n Return GetXPath(node.ParentNode) + \"/\" + temp\n End If\n\n Return temp\n End Function\n</code></pre>\n" }, { "answer_id": 1925773, "author": "James Randle", "author_id": 234265, "author_profile": "https://Stackoverflow.com/users/234265", "pm_score": 2, "selected": false, "text": "<p>My 10p worth is a hybrid of Robert and Corey's answers. I can only claim credit for the actual typing of the extra lines of code.</p>\n\n<pre><code> private static string GetXPathToNode(XmlNode node)\n {\n if (node.NodeType == XmlNodeType.Attribute)\n {\n // attributes have an OwnerElement, not a ParentNode; also they have\n // to be matched by name, not found by position\n return String.Format(\n \"{0}/@{1}\",\n GetXPathToNode(((XmlAttribute)node).OwnerElement),\n node.Name\n );\n }\n if (node.ParentNode == null)\n {\n // the only node with no parent is the root node, which has no path\n return \"\";\n }\n //get the index\n int iIndex = 1;\n XmlNode xnIndex = node;\n while (xnIndex.PreviousSibling != null) { iIndex++; xnIndex = xnIndex.PreviousSibling; }\n // the path to a node is the path to its parent, plus \"/node()[n]\", where \n // n is its position among its siblings.\n return String.Format(\n \"{0}/node()[{1}]\",\n GetXPathToNode(node.ParentNode),\n iIndex\n );\n }\n</code></pre>\n" }, { "answer_id": 7255119, "author": "René Endress", "author_id": 921292, "author_profile": "https://Stackoverflow.com/users/921292", "pm_score": 2, "selected": false, "text": "<p>If you do this, you will get a Path with Names of der Nodes AND the Position, if you have Nodes with the same name like this:\n\"/Service[1]/System[1]/Group[1]/Folder[2]/File[2]\"</p>\n\n<pre><code>public string GetXPathToNode(XmlNode node)\n{ \n if (node.NodeType == XmlNodeType.Attribute)\n { \n // attributes have an OwnerElement, not a ParentNode; also they have \n // to be matched by name, not found by position \n return String.Format(\"{0}/@{1}\", GetXPathToNode(((XmlAttribute)node).OwnerElement), node.Name);\n }\n if (node.ParentNode == null)\n { \n // the only node with no parent is the root node, which has no path\n return \"\";\n }\n\n //get the index\n int iIndex = 1;\n XmlNode xnIndex = node;\n while (xnIndex.PreviousSibling != null &amp;&amp; xnIndex.PreviousSibling.Name == xnIndex.Name)\n {\n iIndex++;\n xnIndex = xnIndex.PreviousSibling; \n }\n\n // the path to a node is the path to its parent, plus \"/node()[n]\", where\n // n is its position among its siblings. \n return String.Format(\"{0}/{1}[{2}]\", GetXPathToNode(node.ParentNode), node.Name, iIndex);\n}\n</code></pre>\n" }, { "answer_id": 7563545, "author": "cjbarth", "author_id": 271351, "author_profile": "https://Stackoverflow.com/users/271351", "pm_score": 1, "selected": false, "text": "<p>I found that none of the above worked with <code>XDocument</code>, so I wrote my own code to support <code>XDocument</code> and used recursion. I think this code handles multiple identical nodes better than some of the other code here because it first tries to go as deep in to the XML path as it can and then backs up to build only what is needed. So if you have <code>/home/white/bob</code> and <code>/home/white/mike</code> and you want to create <code>/home/white/bob/garage</code> the code will know how to create that. However, I didn't want to mess with predicates or wildcards, so I explicitly disallowed those; but it would be easy to add support for them.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub NodeItterate(XDoc As XElement, XPath As String)\n 'get the deepest path\n Dim nodes As IEnumerable(Of XElement)\n\n nodes = XDoc.XPathSelectElements(XPath)\n\n 'if it doesn't exist, try the next shallow path\n If nodes.Count = 0 Then\n NodeItterate(XDoc, XPath.Substring(0, XPath.LastIndexOf(\"/\")))\n 'by this time all the required parent elements will have been constructed\n Dim ParentPath As String = XPath.Substring(0, XPath.LastIndexOf(\"/\"))\n Dim ParentNode As XElement = XDoc.XPathSelectElement(ParentPath)\n Dim NewElementName As String = XPath.Substring(XPath.LastIndexOf(\"/\") + 1, XPath.Length - XPath.LastIndexOf(\"/\") - 1)\n ParentNode.Add(New XElement(NewElementName))\n End If\n\n 'if we find there are more than 1 elements at the deepest path we have access to, we can't proceed\n If nodes.Count &gt; 1 Then\n Throw New ArgumentOutOfRangeException(\"There are too many paths that match your expression.\")\n End If\n\n 'if there is just one element, we can proceed\n If nodes.Count = 1 Then\n 'just proceed\n End If\n\nEnd Sub\n\nPublic Sub CreateXPath(ByVal XDoc As XElement, ByVal XPath As String)\n\n If XPath.Contains(\"//\") Or XPath.Contains(\"*\") Or XPath.Contains(\".\") Then\n Throw New ArgumentException(\"Can't create a path based on searches, wildcards, or relative paths.\")\n End If\n\n If Regex.IsMatch(XPath, \"\\[\\]()@='&lt;&gt;\\|\") Then\n Throw New ArgumentException(\"Can't create a path based on predicates.\")\n End If\n\n 'we will process this recursively.\n NodeItterate(XDoc, XPath)\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 11888005, "author": "rugg", "author_id": 372765, "author_profile": "https://Stackoverflow.com/users/372765", "pm_score": 2, "selected": false, "text": "<p>Here's a simple method that I've used, worked for me.</p>\n\n<pre><code> static string GetXpath(XmlNode node)\n {\n if (node.Name == \"#document\")\n return String.Empty;\n return GetXpath(node.SelectSingleNode(\"..\")) + \"/\" + (node.NodeType == XmlNodeType.Attribute ? \"@\":String.Empty) + node.Name;\n }\n</code></pre>\n" }, { "answer_id": 18184670, "author": "Roemer", "author_id": 2103218, "author_profile": "https://Stackoverflow.com/users/2103218", "pm_score": 3, "selected": false, "text": "<p>I know, old post but the version I liked the most (the one with names) was flawed:\nWhen a parent node has nodes with different names, it stopped counting the index after it found the first non-matching node-name.</p>\n\n<p>Here is my fixed version of it:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Gets the X-Path to a given Node\n/// &lt;/summary&gt;\n/// &lt;param name=\"node\"&gt;The Node to get the X-Path from&lt;/param&gt;\n/// &lt;returns&gt;The X-Path of the Node&lt;/returns&gt;\npublic string GetXPathToNode(XmlNode node)\n{\n if (node.NodeType == XmlNodeType.Attribute)\n {\n // attributes have an OwnerElement, not a ParentNode; also they have \n // to be matched by name, not found by position \n return String.Format(\"{0}/@{1}\", GetXPathToNode(((XmlAttribute)node).OwnerElement), node.Name);\n }\n if (node.ParentNode == null)\n {\n // the only node with no parent is the root node, which has no path\n return \"\";\n }\n\n // Get the Index\n int indexInParent = 1;\n XmlNode siblingNode = node.PreviousSibling;\n // Loop thru all Siblings\n while (siblingNode != null)\n {\n // Increase the Index if the Sibling has the same Name\n if (siblingNode.Name == node.Name)\n {\n indexInParent++;\n }\n siblingNode = siblingNode.PreviousSibling;\n }\n\n // the path to a node is the path to its parent, plus \"/node()[n]\", where n is its position among its siblings. \n return String.Format(\"{0}/{1}[{2}]\", GetXPathToNode(node.ParentNode), node.Name, indexInParent);\n}\n</code></pre>\n" }, { "answer_id": 24452184, "author": "Plasmabubble", "author_id": 2845705, "author_profile": "https://Stackoverflow.com/users/2845705", "pm_score": 1, "selected": false, "text": "<p>What about using class extension ? ;)\nMy version (building on others work) uses the syntaxe name[index]... with index omited is element has no \"brothers\".\nThe loop to get the element index is outside in an independant routine (also a class extension).</p>\n\n<p>Just past the following in any utility class (or in the main Program class)</p>\n\n<pre><code>static public int GetRank( this XmlNode node )\n{\n // return 0 if unique, else return position 1...n in siblings with same name\n try\n {\n if( node is XmlElement ) \n {\n int rank = 1;\n bool alone = true, found = false;\n\n foreach( XmlNode n in node.ParentNode.ChildNodes )\n if( n.Name == node.Name ) // sibling with same name\n {\n if( n.Equals(node) )\n {\n if( ! alone ) return rank; // no need to continue\n found = true;\n }\n else\n {\n if( found ) return rank; // no need to continue\n alone = false;\n rank++;\n }\n }\n\n }\n }\n catch{}\n return 0;\n}\n\nstatic public string GetXPath( this XmlNode node )\n{\n try\n {\n if( node is XmlAttribute )\n return String.Format( \"{0}/@{1}\", (node as XmlAttribute).OwnerElement.GetXPath(), node.Name );\n\n if( node is XmlText || node is XmlCDataSection )\n return node.ParentNode.GetXPath();\n\n if( node.ParentNode == null ) // the only node with no parent is the root node, which has no path\n return \"\";\n\n int rank = node.GetRank();\n if( rank == 0 ) return String.Format( \"{0}/{1}\", node.ParentNode.GetXPath(), node.Name );\n else return String.Format( \"{0}/{1}[{2}]\", node.ParentNode.GetXPath(), node.Name, rank );\n }\n catch{}\n return \"\";\n} \n</code></pre>\n" }, { "answer_id": 26939408, "author": "Sandy", "author_id": 4254194, "author_profile": "https://Stackoverflow.com/users/4254194", "pm_score": 1, "selected": false, "text": "<p>I produced VBA for Excel to do this for a work project. It outputs tuples of an Xpath and the associated text from an elemen or attribute. The purpose was to allow business analysts to identify and map some xml. Appreciate that this is a C# forum, but thought this may be of interest.</p>\n\n<pre><code>Sub Parse2(oSh As Long, inode As IXMLDOMNode, Optional iXstring As String = \"\", Optional indexes)\n\n\nDim chnode As IXMLDOMNode\nDim attr As IXMLDOMAttribute\nDim oXString As String\nDim chld As Long\nDim idx As Variant\nDim addindex As Boolean\nchld = 0\nidx = 0\naddindex = False\n\n\n'determine the node type:\nSelect Case inode.NodeType\n\n Case NODE_ELEMENT\n If inode.ParentNode.NodeType = NODE_DOCUMENT Then 'This gets the root node name but ignores all the namespace attributes\n oXString = iXstring &amp; \"//\" &amp; fp(inode.nodename)\n Else\n\n 'Need to deal with indexing. Where an element has siblings with the same nodeName,it needs to be indexed using [index], e.g swapstreams or schedules\n\n For Each chnode In inode.ParentNode.ChildNodes\n If chnode.NodeType = NODE_ELEMENT And chnode.nodename = inode.nodename Then chld = chld + 1\n Next chnode\n\n If chld &gt; 1 Then '//inode has siblings of the same nodeName, so needs to be indexed\n 'Lookup the index from the indexes array\n idx = getIndex(inode.nodename, indexes)\n addindex = True\n Else\n End If\n\n 'build the XString\n oXString = iXstring &amp; \"/\" &amp; fp(inode.nodename)\n If addindex Then oXString = oXString &amp; \"[\" &amp; idx &amp; \"]\"\n\n 'If type is element then check for attributes\n For Each attr In inode.Attributes\n 'If the element has attributes then extract the data pair XString + Element.Name, @Attribute.Name=Attribute.Value\n Call oSheet(oSh, oXString &amp; \"/@\" &amp; attr.Name, attr.Value)\n Next attr\n\n End If\n\n Case NODE_TEXT\n 'build the XString\n oXString = iXstring\n Call oSheet(oSh, oXString, inode.NodeValue)\n\n Case NODE_ATTRIBUTE\n 'Do nothing\n Case NODE_CDATA_SECTION\n 'Do nothing\n Case NODE_COMMENT\n 'Do nothing\n Case NODE_DOCUMENT\n 'Do nothing\n Case NODE_DOCUMENT_FRAGMENT\n 'Do nothing\n Case NODE_DOCUMENT_TYPE\n 'Do nothing\n Case NODE_ENTITY\n 'Do nothing\n Case NODE_ENTITY_REFERENCE\n 'Do nothing\n Case NODE_INVALID\n 'do nothing\n Case NODE_NOTATION\n 'do nothing\n Case NODE_PROCESSING_INSTRUCTION\n 'do nothing\nEnd Select\n\n'Now call Parser2 on each of inode's children.\nIf inode.HasChildNodes Then\n For Each chnode In inode.ChildNodes\n Call Parse2(oSh, chnode, oXString, indexes)\n Next chnode\nSet chnode = Nothing\nElse\nEnd If\n\nEnd Sub\n</code></pre>\n\n<p>Manages the counting of elements using:</p>\n\n<pre><code>Function getIndex(tag As Variant, indexes) As Variant\n'Function to get the latest index for an xml tag from the indexes array\n'indexes array is passed from one parser function to the next up and down the tree\n\nDim i As Integer\nDim n As Integer\n\nIf IsArrayEmpty(indexes) Then\n ReDim indexes(1, 0)\n indexes(0, 0) = \"Tag\"\n indexes(1, 0) = \"Index\"\nElse\nEnd If\nFor i = 0 To UBound(indexes, 2)\n If indexes(0, i) = tag Then\n 'tag found, increment and return the index then exit\n 'also destroy all recorded tag names BELOW that level\n indexes(1, i) = indexes(1, i) + 1\n getIndex = indexes(1, i)\n ReDim Preserve indexes(1, i) 'should keep all tags up to i but remove all below it\n Exit Function\n Else\n End If\nNext i\n\n'tag not found so add the tag with index 1 at the end of the array\nn = UBound(indexes, 2)\nReDim Preserve indexes(1, n + 1)\nindexes(0, n + 1) = tag\nindexes(1, n + 1) = 1\ngetIndex = 1\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 37302453, "author": "Andrei", "author_id": 2190351, "author_profile": "https://Stackoverflow.com/users/2190351", "pm_score": 1, "selected": false, "text": "<p>Another solution to your problem might be to 'mark' the xmlnodes which you will want to later identify with a custom attribute:</p>\n\n<pre><code>var id = _currentNode.OwnerDocument.CreateAttribute(\"some_id\");\nid.Value = Guid.NewGuid().ToString();\n_currentNode.Attributes.Append(id);\n</code></pre>\n\n<p>which you can store in a Dictionary for example.\nAnd you can later identify the node with an xpath query:</p>\n\n<pre><code>newOrOldDocument.SelectSingleNode(string.Format(\"//*[contains(@some_id,'{0}')]\", id));\n</code></pre>\n\n<p>I know this is not a direct answer to your question, but it can help if the reason you wish to know the xpath of a node is to have a way of 'reaching' the node later after you have lost the reference to it in code.</p>\n\n<p>This also overcomes problems when the document gets elements added/moved, which can mess up the xpath (or indexes, as suggested in other answers).</p>\n" }, { "answer_id": 44819948, "author": "Mabrouk MAHDHI", "author_id": 5536117, "author_profile": "https://Stackoverflow.com/users/5536117", "pm_score": -1, "selected": false, "text": "<pre><code> public static string GetFullPath(this XmlNode node)\n {\n if (node.ParentNode == null)\n {\n return \"\";\n }\n else\n {\n return $\"{GetFullPath(node.ParentNode)}\\\\{node.ParentNode.Name}\";\n }\n }\n</code></pre>\n" }, { "answer_id": 50077811, "author": "Art", "author_id": 3328922, "author_profile": "https://Stackoverflow.com/users/3328922", "pm_score": 0, "selected": false, "text": "<p>I had to do this recently. Only elements needed to be considered. This is what I came up with:</p>\n\n<pre><code> private string GetPath(XmlElement el)\n {\n List&lt;string&gt; pathList = new List&lt;string&gt;();\n XmlNode node = el;\n while (node is XmlElement)\n {\n pathList.Add(node.Name);\n node = node.ParentNode;\n }\n pathList.Reverse();\n string[] nodeNames = pathList.ToArray();\n return String.Join(\"/\", nodeNames);\n }\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
Could someone supply some code that would get the xpath of a System.Xml.XmlNode instance? Thanks!
Okay, I couldn't resist having a go at it. It'll only work for attributes and elements, but hey... what can you expect in 15 minutes :) Likewise there may very well be a cleaner way of doing it. It is superfluous to include the index on every element (particularly the root one!) but it's easier than trying to work out whether there's any ambiguity otherwise. ``` using System; using System.Text; using System.Xml; class Test { static void Main() { string xml = @" <root> <foo /> <foo> <bar attr='value'/> <bar other='va' /> </foo> <foo><bar /></foo> </root>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode node = doc.SelectSingleNode("//@attr"); Console.WriteLine(FindXPath(node)); Console.WriteLine(doc.SelectSingleNode(FindXPath(node)) == node); } static string FindXPath(XmlNode node) { StringBuilder builder = new StringBuilder(); while (node != null) { switch (node.NodeType) { case XmlNodeType.Attribute: builder.Insert(0, "/@" + node.Name); node = ((XmlAttribute) node).OwnerElement; break; case XmlNodeType.Element: int index = FindElementIndex((XmlElement) node); builder.Insert(0, "/" + node.Name + "[" + index + "]"); node = node.ParentNode; break; case XmlNodeType.Document: return builder.ToString(); default: throw new ArgumentException("Only elements and attributes are supported"); } } throw new ArgumentException("Node was not in a document"); } static int FindElementIndex(XmlElement element) { XmlNode parentNode = element.ParentNode; if (parentNode is XmlDocument) { return 1; } XmlElement parent = (XmlElement) parentNode; int index = 1; foreach (XmlNode candidate in parent.ChildNodes) { if (candidate is XmlElement && candidate.Name == element.Name) { if (candidate == element) { return index; } index++; } } throw new ArgumentException("Couldn't find element within parent"); } } ```
241,285
<p>I'm developing an algorithm to parse a number out of a series of short-ish strings. These strings are somewhat regular, but there's a few different general forms and several exceptions. I'm trying to build a set of regexes that will handle the various forms and exceptions; I'll apply them one after another to see if I get a match.</p> <p>One of these forms goes something like this:</p> <pre><code>X (Y) Z </code></pre> <p>Where:</p> <ul> <li><code>X</code> is a number I want to capture.</li> <li><code>Z</code> is static, pre-defined text. it's basically how I determine whether this particular form is applicable or not.</li> <li><code>Y</code> is a string of unknown length and content, surrounded by parenthesis.</li> </ul> <p>Also: <code>Y</code> is optional; it doesn't always appear in a string with <code>Z</code> and <code>X</code>. So, I want to be able to extract the numbers from all of these strings:</p> <ul> <li><code>10 Z</code></li> <li><code>20 (foo) Z</code></li> <li><code>30 (bar) Z</code></li> </ul> <p>Right now, I have a regex that will capture the first one:</p> <pre><code>([0-9]+) +Z </code></pre> <p>My problem is that I don't know how to construct a regex that will match a series of characters if and only if they're enclosed in parenthesis. Can this be done in a single regex?</p>
[ { "answer_id": 241288, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>X (\\(Y\\))? Z\n</code></pre>\n" }, { "answer_id": 241292, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>You can do this:</p>\n\n<pre><code>([0-9]+) (\\([^)]+\\))? Z\n</code></pre>\n\n<p>This will not work with nested parens for Y, however. Nesting requires recursion which isn't strictly regular any more (but context-free). Modern regexp engines can still handle it, albeit with some difficulties (back-references).</p>\n" }, { "answer_id": 241308, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 7, "selected": true, "text": "<pre><code>(\\d+)\\s+(\\(.*?\\))?\\s?Z\n</code></pre>\n\n<p>Note the escaped parentheses, and the <code>?</code> (zero or once) quantifiers. Any of the groups you don't want to capture can be (<code>?:</code> non-capture groups).</p>\n\n<p>I agree about the spaces. <code>\\s</code> is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a <code>^</code> at the front and a <code>$</code> at the end).</p>\n" }, { "answer_id": 241337, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": 5, "selected": false, "text": "<p>This ought to work:</p>\n\n<pre><code>^\\d+\\s?(\\([^\\)]+\\)\\s?)?Z$\n</code></pre>\n\n<p>Haven't tested it though, but let me give you the breakdown, so if there are any bugs left they should be pretty straightforward to find:</p>\n\n<p>First the beginning:</p>\n\n<pre><code>^ = beginning of string\n\\d+ = one or more decimal characters\n\\s? = one optional whitespace\n</code></pre>\n\n<p>Then this part:</p>\n\n<pre><code>(\\([^\\)]+\\)\\s?)?\n</code></pre>\n\n<p>Is actually:</p>\n\n<pre><code>(.............)?\n</code></pre>\n\n<p>Which makes the following contents optional, only if it exists fully</p>\n\n<pre><code>\\([^\\)]+\\)\\s?\n\n\\( = an opening bracket\n[^\\)]+ = a series of at least one character that is not a closing bracket\n\\) = followed by a closing bracket\n\\s? = followed by one optional whitespace\n</code></pre>\n\n<p>And the end is made up of</p>\n\n<pre><code>Z$\n</code></pre>\n\n<p>Where</p>\n\n<pre><code>Z = your constant string\n$ = the end of the string\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
I'm developing an algorithm to parse a number out of a series of short-ish strings. These strings are somewhat regular, but there's a few different general forms and several exceptions. I'm trying to build a set of regexes that will handle the various forms and exceptions; I'll apply them one after another to see if I get a match. One of these forms goes something like this: ``` X (Y) Z ``` Where: * `X` is a number I want to capture. * `Z` is static, pre-defined text. it's basically how I determine whether this particular form is applicable or not. * `Y` is a string of unknown length and content, surrounded by parenthesis. Also: `Y` is optional; it doesn't always appear in a string with `Z` and `X`. So, I want to be able to extract the numbers from all of these strings: * `10 Z` * `20 (foo) Z` * `30 (bar) Z` Right now, I have a regex that will capture the first one: ``` ([0-9]+) +Z ``` My problem is that I don't know how to construct a regex that will match a series of characters if and only if they're enclosed in parenthesis. Can this be done in a single regex?
``` (\d+)\s+(\(.*?\))?\s?Z ``` Note the escaped parentheses, and the `?` (zero or once) quantifiers. Any of the groups you don't want to capture can be (`?:` non-capture groups). I agree about the spaces. `\s` is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a `^` at the front and a `$` at the end).
241,311
<p>The question is if a database connection should be passed in by reference or by value?</p> <p>For me I'm specifically questioning a PHP to MySQL connection, but I think it applies to all databases.</p> <p>I have heard that in PHP when you pass a variable to a function or object, that it is copied in memory and therefore uses twice as much memory immediately. I have also heard that it's only copied once changes have been made to the value (such as a key being added/removed from an array).</p> <p>In a database connection, I would think it's being changed within the function as the query could change things like the last insert id or num rows. (I guess this is another question: are things like num rows and insert id stored within the connection or an actual call is made back to the database?)</p> <p>So, does it matter memory or speed wise if the connection is passed by reference or value? Does it make a difference PHP 4 vs 5?</p> <pre><code>// $connection is resource function DoSomething1(&amp;$connection) { ... } function DoSomething2($connection) { ... } </code></pre>
[ { "answer_id": 241330, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 3, "selected": false, "text": "<p>Call-time pass-by-reference is being depreciated,so I wouldn't use the method first described. Also, generally speaking, resources are passed by reference in PHP 5 by default. So having any references should not be required, and you should never open up more than one database connection unless you really need it.</p>\n\n<p>Personally, I use a singleton-factory class for my database connections, and whenever I need a database reference I just call Factory::database(), that way I don't have to worry about multiple connections or passing/receiving references.</p>\n\n<pre><code>&lt;?php\nClass Factory\n{\n private static $local_db;\n\n/**\n* Open new local database connection\n*\n* @return MySql\n*/\npublic static function localDatabase() {\n if (!is_a(self::$local_db, \"MySql\")) {\n self::$local_db = new MySql(false);\n self::$local_db-&gt;connect(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);\n self::$local_db-&gt;debugging = DEBUG;\n }\n return self::$local_db;\n}\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 241331, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 0, "selected": false, "text": "<p>i don't really have a specific answer for php, but in general it would seem to me that you would want to pass this by reference if you are not explicitly sure that you encounter performance issues when passing by value.</p>\n" }, { "answer_id": 241356, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 5, "selected": true, "text": "<p>A PHP resource is a special type that already is a reference in itself. Passing it by value or explicitly by reference won't make a difference (ie, it's still a reference). You can check this for yourself under PHP4:</p>\n\n<pre><code>function get_connection() {\n $test = mysql_connect('localhost', 'user', 'password');\n mysql_select_db('db');\n return $test;\n}\n\n$conn1 = get_connection();\n$conn2 = get_connection(); // \"copied\" resource under PHP4\n\n$query = \"INSERT INTO test_table (id, field) VALUES ('', 'test')\";\nmysql_query($query, $conn1);\nprint mysql_insert_id($conn1).\"&lt;br /&gt;\"; // prints 1\n\nmysql_query($query, $conn2);\nprint mysql_insert_id($conn2).\"&lt;br /&gt;\"; // prints 2\n\nprint mysql_insert_id($conn1); // prints 2, would print 1 if this was not a reference\n</code></pre>\n" }, { "answer_id": 241363, "author": "Larry OBrien", "author_id": 10116, "author_profile": "https://Stackoverflow.com/users/10116", "pm_score": 1, "selected": false, "text": "<p>A database <em>connection</em> does not actually hold the underlying values, so you don't have to worry about losing assignments made inside a function. Metaphorically, you can think of a DB <em>connection</em> as, say, a runway number -- \"OK, DB Connection 12 is cleared to be used for a query\" -- The query and result set <em>use</em> the connection, and may need exclusive access for awhile, but the connection does not know anything about the underlying data.</p>\n" }, { "answer_id": 241552, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "<p>Generally speaking, references are not faster in PHP. It's a common misconception, because they are semantically similar to C pointers, so people familiar with C often assume they work the same way. Not so. In fact, references are a tiny bit slower than copies, unless you actually assign to the variable (Which in any case is bad style, unless the variable is an object).</p>\n\n<p>PHP has a mechanism called copy-on-write, which means that a variable isn't <em>actually</em> copied before it needs to. You can pass a huge data structure to a function; As long as it just reads from it, it makes no difference. A reference however, needs an additional entry in the internal registers, so it would actually take some extra processing (Though barely noticeable).</p>\n" }, { "answer_id": 241611, "author": "MattBelanger", "author_id": 655, "author_profile": "https://Stackoverflow.com/users/655", "pm_score": 1, "selected": false, "text": "<p>A few people have said that you don't need to worry about this for PHP 5. This is incorrect, if you have a database OBJECT that you're using for all access. In that case, you do need to pass by reference, otherwise it instantiates a new DB object, which (often) creates a new connection to the database.</p>\n\n<p>I discovered this using XDebug &amp; WinCacheGrind, which kindly shows all the destructors that get called - in my case, a halfdozen or more database objects.</p>\n\n<p>To clarify: The reason I point this out is that this is a common way of using Database connections, instead of the raw connection resource.</p>\n" }, { "answer_id": 241613, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 3, "selected": false, "text": "<p>It isn't the speed you should be concerned with, but the memory.</p>\n\n<p>In PHP 4, things like database connections and resultsets should be explicitly passed by reference. In PHP 5, this is done automatically, so you don't have to make it explicit.</p>\n\n<p>BTW, singleton methods for creating database handles are a good idea: you can do <code>$db = &amp; Database::Connection();</code> and always get the correct handle. This saves you from using a global and the static method can do extra magic (like opening it automatically) for you. Just be careful of when your application scales enough that it needs multiple databases: then your magic function will have to know how to hand you back the correct one. IME this is not hugely difficult; the basic way to solve that is for the code layer that needs the DB handle to know how to ask for the correct one.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
The question is if a database connection should be passed in by reference or by value? For me I'm specifically questioning a PHP to MySQL connection, but I think it applies to all databases. I have heard that in PHP when you pass a variable to a function or object, that it is copied in memory and therefore uses twice as much memory immediately. I have also heard that it's only copied once changes have been made to the value (such as a key being added/removed from an array). In a database connection, I would think it's being changed within the function as the query could change things like the last insert id or num rows. (I guess this is another question: are things like num rows and insert id stored within the connection or an actual call is made back to the database?) So, does it matter memory or speed wise if the connection is passed by reference or value? Does it make a difference PHP 4 vs 5? ``` // $connection is resource function DoSomething1(&$connection) { ... } function DoSomething2($connection) { ... } ```
A PHP resource is a special type that already is a reference in itself. Passing it by value or explicitly by reference won't make a difference (ie, it's still a reference). You can check this for yourself under PHP4: ``` function get_connection() { $test = mysql_connect('localhost', 'user', 'password'); mysql_select_db('db'); return $test; } $conn1 = get_connection(); $conn2 = get_connection(); // "copied" resource under PHP4 $query = "INSERT INTO test_table (id, field) VALUES ('', 'test')"; mysql_query($query, $conn1); print mysql_insert_id($conn1)."<br />"; // prints 1 mysql_query($query, $conn2); print mysql_insert_id($conn2)."<br />"; // prints 2 print mysql_insert_id($conn1); // prints 2, would print 1 if this was not a reference ```
241,325
<p>When using <code>grep --color=always</code> I can get pretty color highlighting for regex matches.</p> <p>However, <code>grep</code> only returns lines with at least one match. Instead, I am looking for a way to simply highlight regex matches, while leaving all other input alone, without dropping lines without any matches.</p> <p>I have tried to get color working with <code>sed</code>, and read the <code>grep</code> documentation, but I can't seem to get what I want.</p> <p>In case my description isnt obvious, I want:</p> <p>INPUT:</p> <ul> <li>fred</li> <li>ted</li> <li>red</li> <li>lead</li> </ul> <p>Regex:</p> <ul> <li>".*red"</li> </ul> <p>OUTPUT:</p> <ul> <li>fred ( in red )</li> <li>ted</li> <li>red ( in red )</li> <li>lead</li> </ul> <p>So that I could do:</p> <pre><code>list_stuff | color_grep "make_this_stand_out_but_dont_hide_the_rest" </code></pre> <p>EDIT:</p> <p>I have found a solution, which isn't pretty, but it works:</p> <p>Thanks to: <a href="http://www.pixelbeat.org/docs/terminal_colours/" rel="noreferrer">http://www.pixelbeat.org/docs/terminal_colours/</a></p> <p>Particularly the script (which I modified/simplified): <a href="http://www.pixelbeat.org/talks/iitui/sedgrep" rel="noreferrer">http://www.pixelbeat.org/talks/iitui/sedgrep</a></p> <pre><code>function sedgrep () { C_PATT=`echo -e '\033[33;01m'` C_NORM=`echo -e '\033[m'` sed -s "s/$1/${C_PATT}&amp;${C_NORM}/gi" } </code></pre> <p>Still looking for an easier way to do this!</p>
[ { "answer_id": 241390, "author": "boxxar", "author_id": 15732, "author_profile": "https://Stackoverflow.com/users/15732", "pm_score": 2, "selected": false, "text": "<p>This little function works well in my ZShell:</p>\n\n<pre><code>function color_grep {\n sed s/$1/$fg[yellow]$1$terminfo[sgr0]/g\n}\n</code></pre>\n\n<p>(Needs</p>\n\n<pre><code>autoload colors zsh/terminfo\n</code></pre>\n\n<p>)</p>\n\n<p>Maybe you can do something similar?</p>\n\n<p>Edit: Sorry, this won't work with regexes. You will have to tweak it a bit ...</p>\n" }, { "answer_id": 241547, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 1, "selected": false, "text": "<p>The way you're doing this now is probably about as clean as you can expect to make this, unless of course you write your own grep tool. If you don't necessarily care about preserving the order of the output, here's the other way I can think of to do this:</p>\n\n<pre><code>function colormatch ()\n{\n tee - | grep --color=always $1 | sort | uniq\n}\n</code></pre>\n\n<p>Not as efficient as using sed (more processes created, and tee-ing the output), so I'd probably recommend sticking with your sed solution.</p>\n" }, { "answer_id": 241753, "author": "PiedPiper", "author_id": 19315, "author_profile": "https://Stackoverflow.com/users/19315", "pm_score": 1, "selected": false, "text": "<p>You could use the <code>-C&lt;num&gt;</code> option to grep which shows you <code>&lt;num&gt;</code> lines of context around your match. Just make sure <code>&lt;num&gt;</code> is as least as large as the number of lines in your file.</p>\n" }, { "answer_id": 428659, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I recently made something similar as a filter. I use it to color the \"headers\" in a tail with multiple files, like this:</p>\n\n<p>tail -f access.log error.log foo.log | logcol.sh</p>\n\n<p>The headers look like this:</p>\n\n<p>==> access.log &lt;==</p>\n\n<p>I got confused by the quick changes between the different logfiles, so this logcol.sh helps.\nThe ==> is hardcoded for the specific usage but could be a parameter as well.</p>\n\n<pre><code>#!/bin/sh\nwhile read line\ndo\n if test `expr \"$line\" : \"==&gt;.*\"` -eq 0 ;\n then\n printf '\\033[0m%s\\n' \"$line\"\n else\n printf '\\033[0;31m%s\\n' \"$line\"\n fi\ndone\n</code></pre>\n\n<p>Maybe not the most elegant but I think it's quite readable.\nI hope I don't have any typos ;-)\nHTH,\nrob</p>\n" }, { "answer_id": 2254291, "author": "TJR", "author_id": 728, "author_profile": "https://Stackoverflow.com/users/728", "pm_score": 0, "selected": false, "text": "<p>I'm digging this little python utility. If not on debian, use alien to convert to rpm.</p>\n\n<p><a href=\"http://korpus.juls.savba.sk/~garabik/software/grc.html\" rel=\"nofollow noreferrer\">http://korpus.juls.savba.sk/~garabik/software/grc.html</a></p>\n\n<pre><code>regexp=.*red\ncolours=\"\\033[38;5;160m\"\ncount=once\n</code></pre>\n\n<p>This is a nice page on terminal colors.</p>\n\n<p><a href=\"http://www.pixelbeat.org/docs/terminal_colours/\" rel=\"nofollow noreferrer\">http://www.pixelbeat.org/docs/terminal_colours/</a></p>\n\n<p>(Queen's english is so colourful.)</p>\n" }, { "answer_id": 8726738, "author": "crenate", "author_id": 1129848, "author_profile": "https://Stackoverflow.com/users/1129848", "pm_score": 5, "selected": false, "text": "<p>The simplest solution would be to use <code>egrep --color=always 'text|^'</code> which would match all line beginnings but only color the desired text.</p>\n" }, { "answer_id": 13593327, "author": "Pawel Wiejacha", "author_id": 1857778, "author_profile": "https://Stackoverflow.com/users/1857778", "pm_score": 3, "selected": false, "text": "<p>Here is a script I use to colorize output. </p>\n\n<p>I think I found the idea/snippet on some kind of blog or bash/sed tutorial - can't find it anymore, it was very long time ago.</p>\n\n<pre><code>#!/bin/bash\n\nred=$(tput bold;tput setaf 1) \ngreen=$(tput setaf 2) \nyellow=$(tput bold;tput setaf 3) \nfawn=$(tput setaf 3)\nblue=$(tput bold;tput setaf 4) \npurple=$(tput setaf 5)\npink=$(tput bold;tput setaf 5) \ncyan=$(tput bold;tput setaf 6) \ngray=$(tput setaf 7) \nwhite=$(tput bold;tput setaf 7) \nnormal=$(tput sgr0) \n\nsep=`echo -e '\\001'` # use \\001 as a separator instead of '/'\n\nwhile [ -n \"$1\" ] ; do\n color=${!1}\n pattern=\"$2\"\n shift 2\n\n rules=\"$rules;s$sep\\($pattern\\)$sep$color\\1$normal${sep}g\"\ndone\n\n#stdbuf -o0 -i0 sed -u -e \"$rules\"\nsed -u -e \"$rules\"\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>./colorize.sh color1 pattern1 color2 pattern2 ...\n</code></pre>\n\n<p>e.g.</p>\n\n<pre><code>dmesg | colorize.sh red '.*Hardware Error.*' red 'CPU[0-9]*: Core temperature above threshold' \\\ngreen 'wlan.: authenticated.*' yellow 'wlan.: deauthenticated.*'\n</code></pre>\n\n<p>Doesn't work well with overlapping patterns, but I've found it very useful anyway.</p>\n\n<p>HTH</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29701/" ]
When using `grep --color=always` I can get pretty color highlighting for regex matches. However, `grep` only returns lines with at least one match. Instead, I am looking for a way to simply highlight regex matches, while leaving all other input alone, without dropping lines without any matches. I have tried to get color working with `sed`, and read the `grep` documentation, but I can't seem to get what I want. In case my description isnt obvious, I want: INPUT: * fred * ted * red * lead Regex: * ".\*red" OUTPUT: * fred ( in red ) * ted * red ( in red ) * lead So that I could do: ``` list_stuff | color_grep "make_this_stand_out_but_dont_hide_the_rest" ``` EDIT: I have found a solution, which isn't pretty, but it works: Thanks to: <http://www.pixelbeat.org/docs/terminal_colours/> Particularly the script (which I modified/simplified): <http://www.pixelbeat.org/talks/iitui/sedgrep> ``` function sedgrep () { C_PATT=`echo -e '\033[33;01m'` C_NORM=`echo -e '\033[m'` sed -s "s/$1/${C_PATT}&${C_NORM}/gi" } ``` Still looking for an easier way to do this!
The simplest solution would be to use `egrep --color=always 'text|^'` which would match all line beginnings but only color the desired text.
241,327
<p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p> <p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p> <p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
[ { "answer_id": 241329, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "<p>C (and C++) comments cannot be nested. Regular expressions work well:</p>\n\n<pre><code>//.*?\\n|/\\*.*?\\*/\n</code></pre>\n\n<p>This requires the “Single line” flag (<code>Re.S</code>) because a C comment can span multiple lines.</p>\n\n<pre><code>def stripcomments(text):\n return re.sub('//.*?\\n|/\\*.*?\\*/', '', text, flags=re.S)\n</code></pre>\n\n<p>This code should work.</p>\n\n<p>/EDIT: Notice that my above code actually makes an assumption about line endings! This code won't work on a Mac text file. However, this can be amended relatively easily:</p>\n\n<pre><code>//.*?(\\r\\n?|\\n)|/\\*.*?\\*/\n</code></pre>\n\n<p>This regular expression should work on all text files, regardless of their line endings (covers Windows, Unix and Mac line endings).</p>\n\n<p>/EDIT: MizardX and Brian (in the comments) made a valid remark about the handling of strings. I completely forgot about that because the above regex is plucked from a parsing module that has additional handling for strings. MizardX's solution should work very well but it only handles double-quoted strings.</p>\n" }, { "answer_id": 241333, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": 2, "selected": false, "text": "<p>you may be able to leverage <a href=\"http://www.language-binding.net/pyplusplus/pyplusplus.html\" rel=\"nofollow noreferrer\">py++</a> to parse the C++ source with GCC.</p>\n\n<blockquote>\n <p>Py++ does not reinvent the wheel. It\n uses GCC C++ compiler to parse C++\n source files. To be more precise, the\n tool chain looks like this:</p>\n \n <p>source code is passed to GCC-XML\n GCC-XML passes it to GCC C++ compiler\n GCC-XML generates an XML description\n of a C++ program from GCC's internal\n representation. Py++ uses pygccxml\n package to read GCC-XML generated\n file. The bottom line - you can be\n sure, that all your declarations are\n read correctly.</p>\n</blockquote>\n\n<p>or, maybe not. regardless, this is not a trivial parse.</p>\n\n<p>@ RE based solutions - you are unlikely to find a RE that handles all possible 'awkward' cases correctly, unless you constrain input (e.g. no macros). for a bulletproof solution, you really have no choice than leveraging the real grammar.</p>\n" }, { "answer_id": 241506, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 7, "selected": false, "text": "<p>This handles C++-style comments, C-style comments, strings and simple nesting thereof.</p>\n\n<pre><code>def comment_remover(text):\n def replacer(match):\n s = match.group(0)\n if s.startswith('/'):\n return \" \" # note: a space and not an empty string\n else:\n return s\n pattern = re.compile(\n r'//.*?$|/\\*.*?\\*/|\\'(?:\\\\.|[^\\\\\\'])*\\'|\"(?:\\\\.|[^\\\\\"])*\"',\n re.DOTALL | re.MULTILINE\n )\n return re.sub(pattern, replacer, text)\n</code></pre>\n\n<p>Strings needs to be included, because comment-markers inside them does not start a comment.</p>\n\n<p><strong>Edit:</strong> re.sub didn't take any flags, so had to compile the pattern first.</p>\n\n<p><strong>Edit2:</strong> Added character literals, since they could contain quotes that would otherwise be recognized as string delimiters.</p>\n\n<p><strong>Edit3:</strong> Fixed the case where a legal expression <code>int/**/x=5;</code> would become <code>intx=5;</code> which would not compile, by replacing the comment with a space rather then an empty string.</p>\n" }, { "answer_id": 242107, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<p>Don't forget that in C, backslash-newline is eliminated before comments are processed, and trigraphs are processed before that (because ??/ is the trigraph for backslash). I have a C program called SCC (strip C/C++ comments), and here is part of the test code...</p>\n\n<pre><code>\" */ /* SCC has been trained to know about strings /* */ */\"!\n\"\\\"Double quotes embedded in strings, \\\\\\\" too\\'!\"\n\"And \\\nnewlines in them\"\n\n\"And escaped double quotes at the end of a string\\\"\"\n\naa '\\\\\nn' OK\naa \"\\\"\"\naa \"\\\n\\n\"\n\nThis is followed by C++/C99 comment number 1.\n// C++/C99 comment with \\\ncontinuation character \\\non three source lines (this should not be seen with the -C fla\nThe C++/C99 comment number 1 has finished.\n\nThis is followed by C++/C99 comment number 2.\n/\\\n/\\\nC++/C99 comment (this should not be seen with the -C flag)\nThe C++/C99 comment number 2 has finished.\n\nThis is followed by regular C comment number 1.\n/\\\n*\\\nRegular\ncomment\n*\\\n/\nThe regular C comment number 1 has finished.\n\n/\\\n\\/ This is not a C++/C99 comment!\n\nThis is followed by C++/C99 comment number 3.\n/\\\n\\\n\\\n/ But this is a C++/C99 comment!\nThe C++/C99 comment number 3 has finished.\n\n/\\\n\\* This is not a C or C++ comment!\n\nThis is followed by regular C comment number 2.\n/\\\n*/ This is a regular C comment *\\\nbut this is just a routine continuation *\\\nand that was not the end either - but this is *\\\n\\\n/\nThe regular C comment number 2 has finished.\n\nThis is followed by regular C comment number 3.\n/\\\n\\\n\\\n\\\n* C comment */\n</code></pre>\n\n<p>This does not illustrate trigraphs. Note that you can have multiple backslashes at the end of a line, but the line splicing doesn't care about how many there are, but the subsequent processing might. Etc. Writing a single regex to handle all these cases will be non-trivial (but that is different from impossible).</p>\n" }, { "answer_id": 242110, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "<p>The regular expression cases will fall down in some situations, like where a string literal contains a subsequence which matches the comment syntax. You really need a parse tree to deal with this.</p>\n" }, { "answer_id": 242226, "author": "zvoase", "author_id": 31600, "author_profile": "https://Stackoverflow.com/users/31600", "pm_score": 4, "selected": true, "text": "<p>I don't know if you're familiar with <code>sed</code>, the UNIX-based (but Windows-available) text parsing program, but I've found a sed script <a href=\"http://sed.sourceforge.net/grabbag/scripts/remccoms3.sed\" rel=\"noreferrer\">here</a> which will remove C/C++ comments from a file. It's very smart; for example, it will ignore '//' and '/*' if found in a string declaration, etc. From within Python, it can be used using the following code:</p>\n\n<pre><code>import subprocess\nfrom cStringIO import StringIO\n\ninput = StringIO(source_code) # source_code is a string with the source code.\noutput = StringIO()\n\nprocess = subprocess.Popen(['sed', '/path/to/remccoms3.sed'],\n input=input, output=output)\nreturn_code = process.wait()\n\nstripped_code = output.getvalue()\n</code></pre>\n\n<p>In this program, <code>source_code</code> is the variable holding the C/C++ source code, and eventually <code>stripped_code</code> will hold C/C++ code with the comments removed. Of course, if you have the file on disk, you could have the <code>input</code> and <code>output</code> variables be file handles pointing to those files (<code>input</code> in read-mode, <code>output</code> in write-mode). <code>remccoms3.sed</code> is the file from the above link, and it should be saved in a readable location on disk. <code>sed</code> is also available on Windows, and comes installed by default on most GNU/Linux distros and Mac OS X.</p>\n\n<p>This will probably be better than a pure Python solution; no need to reinvent the wheel.</p>\n" }, { "answer_id": 1078406, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 0, "selected": false, "text": "<p>You don't really need a parse tree to do this perfectly, but you do in effect need the token stream equivalent to what is produced by the compiler's front end. Such a token stream must necessarilyy take care of all the weirdness such as line-continued comment start, comment start in string, trigraph normalization, etc. If you have the token stream, deleting the comments is easy. (I have a tool that produces exactly such token streams, as, guess what, the front end of a real parser that produces a real parse tree :). </p>\n\n<p>The fact that the tokens are individually recognized by regular expressions suggests that you can, in principle, write a regular expression that will pick out the comment lexemes. The real complexity of the set regular expressions for the tokenizer (at least the one we wrote) suggests you can't do this in practice; writing them individually was hard enough. If you don't want to do it perfectly, well, then, most of the RE solutions above are just fine.</p>\n\n<p>Now, <em>why</em> you would want strip comments is beyond me, unless you are building a code obfuscator. In this case, you have to have it perfectly right.</p>\n" }, { "answer_id": 1078484, "author": "sigjuice", "author_id": 78720, "author_profile": "https://Stackoverflow.com/users/78720", "pm_score": 1, "selected": false, "text": "<p>I'm sorry this not a Python solution, but you could also use a tool that understands how to remove comments, like your C/C++ preprocessor. Here's how GNU CPP <a href=\"http://gcc.gnu.org/onlinedocs/cpp/Invocation.html#index-fpreprocessed-171\" rel=\"nofollow noreferrer\">does it</a>.</p>\n\n<pre><code>cpp -fpreprocessed foo.c\n</code></pre>\n" }, { "answer_id": 1294188, "author": "hlovdal", "author_id": 23118, "author_profile": "https://Stackoverflow.com/users/23118", "pm_score": 1, "selected": false, "text": "<p>There is also a non-python answer: use the program <a href=\"http://www.bdc.cx/software/stripcmt/\" rel=\"nofollow noreferrer\">stripcmt</a>:</p>\n\n<blockquote>\n <p>StripCmt is a simple utility written\n in C to remove comments from C, C++,\n and Java source files. In the grand\n tradition of Unix text processing\n programs, it can function either as a\n FIFO (First In - First Out) filter or\n accept arguments on the commandline.</p>\n</blockquote>\n" }, { "answer_id": 5221953, "author": "slottermoser", "author_id": 647627, "author_profile": "https://Stackoverflow.com/users/647627", "pm_score": -1, "selected": false, "text": "<p>I ran across this problem recently when I took a class where the professor required us to strip javadoc from our source code before submitting it to him for a code review. We had to do this several times, but we couldn't just remove the javadoc permanently because we were required to generate javadoc html files as well. Here is a little python script I made to do the trick. Since javadoc starts with /** and ends with */, the script looks for these tokens, but the script can be modified to suite your needs. It also handles single line block comments and cases where a block comment ends but there is still non-commented code on the same line as the block comment ending. I hope this helps!</p>\n\n<p><em>WARNING: This scripts modifies the contents of files passed in and saves them to the original files. It would be wise to have a backup somewhere else</em></p>\n\n<pre><code>#!/usr/bin/python\n\"\"\"\n A simple script to remove block comments of the form /** */ from files\n Use example: ./strip_comments.py *.java\n Author: holdtotherod\n Created: 3/6/11\n\"\"\"\nimport sys\nimport fileinput\n\nfor file in sys.argv[1:]:\n inBlockComment = False\n for line in fileinput.input(file, inplace = 1):\n if \"/**\" in line:\n inBlockComment = True\n if inBlockComment and \"*/\" in line:\n inBlockComment = False\n # If the */ isn't last, remove through the */\n if line.find(\"*/\") != len(line) - 3:\n line = line[line.find(\"*/\")+2:]\n else:\n continue\n if inBlockComment:\n continue\n sys.stdout.write(line)\n</code></pre>\n" }, { "answer_id": 18234680, "author": "Menno Rubingh", "author_id": 2682892, "author_profile": "https://Stackoverflow.com/users/2682892", "pm_score": 3, "selected": false, "text": "<p>This posting provides a coded-out version of the improvement to Markus Jarderot's code that was described by atikat, in a comment to Markus Jarderot's posting. (Thanks to both for providing the original code, which saved me a lot of work.)</p>\n\n<p>To describe the improvement somewhat more fully: The improvement keeps the line numbering intact. (This is done by keeping the newline characters intact in the strings by which the C/C++ comments are replaced.)</p>\n\n<p>This version of the C/C++ comment removal function is suitable when you want to generate error messages to your users (e.g. parsing errors) that contain line numbers (i.e. line numbers valid for the original text).</p>\n\n<pre><code>import re\n\ndef removeCCppComment( text ) :\n\n def blotOutNonNewlines( strIn ) : # Return a string containing only the newline chars contained in strIn\n return \"\" + (\"\\n\" * strIn.count('\\n'))\n\n def replacer( match ) :\n s = match.group(0)\n if s.startswith('/'): # Matched string is //...EOL or /*...*/ ==&gt; Blot out all non-newline chars\n return blotOutNonNewlines(s)\n else: # Matched string is '...' or \"...\" ==&gt; Keep unchanged\n return s\n\n pattern = re.compile(\n r'//.*?$|/\\*.*?\\*/|\\'(?:\\\\.|[^\\\\\\'])*\\'|\"(?:\\\\.|[^\\\\\"])*\"',\n re.DOTALL | re.MULTILINE\n )\n\n return re.sub(pattern, replacer, text)\n</code></pre>\n" }, { "answer_id": 18996903, "author": "Antonio Arredondo", "author_id": 2608051, "author_profile": "https://Stackoverflow.com/users/2608051", "pm_score": 1, "selected": false, "text": "<p>The following worked for me: </p>\n\n<pre><code>from subprocess import check_output\n\nclass Util:\n def strip_comments(self,source_code):\n process = check_output(['cpp', '-fpreprocessed', source_code],shell=False)\n return process \n\nif __name__ == \"__main__\":\n util = Util()\n print util.strip_comments(\"somefile.ext\")\n</code></pre>\n\n<p>This is a combination of the subprocess and the cpp preprocessor. For my project I have a utility class called \"Util\" that I keep various tools I use/need.</p>\n" }, { "answer_id": 65104145, "author": "Thiago Mata", "author_id": 456164, "author_profile": "https://Stackoverflow.com/users/456164", "pm_score": 1, "selected": false, "text": "<p>I have using the pygments to parse the string and then ignore all tokens that are comments from it. Works like a charm with any lexer on pygments list including Javascript, SQL, and C Like.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from pygments import lex\nfrom pygments.token import Token as ParseToken\n\ndef strip_comments(replace_query, lexer):\n generator = lex(replace_query, lexer)\n line = []\n lines = []\n for token in generator:\n token_type = token[0]\n token_text = token[1]\n if token_type in ParseToken.Comment:\n continue\n line.append(token_text)\n if token_text == '\\n':\n lines.append(''.join(line))\n line = []\n if line:\n line.append('\\n')\n lines.append(''.join(line))\n strip_query = &quot;\\n&quot;.join(lines)\n return strip_query\n</code></pre>\n<p>Working with C like languages:</p>\n<pre><code>from pygments.lexers.c_like import CLexer\n\nstrip_comments(&quot;class Bla /*; complicated // stuff */ example; // out&quot;,CLexer())\n# 'class Bla example; \\n'\n</code></pre>\n<p>Working with SQL languages:</p>\n<pre><code>from pygments.lexers.sql import SqlLexer\n\nstrip_comments(&quot;select * /* this is cool */ from table -- more comments&quot;,SqlLexer())\n# 'select * from table \\n'\n</code></pre>\n<p>Working with Javascript Like Languages:</p>\n<pre><code>from pygments.lexers.javascript import JavascriptLexer\nstrip_comments(&quot;function cool /* not cool*/(x){ return x++ } /** something **/ // end&quot;,JavascriptLexer())\n# 'function cool (x){ return x++ } \\n'\n</code></pre>\n<p>Since this code only removes the comments, any strange value will remain. So, this is a very robust solution that is able to deal even with invalid inputs.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26251/" ]
I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.) I realize that I could .match() substrings with a Regex, but that doesn't solve nesting `/*`, or having a `//` inside a `/* */`. Ideally, I would prefer a non-naive implementation that properly handles awkward cases.
I don't know if you're familiar with `sed`, the UNIX-based (but Windows-available) text parsing program, but I've found a sed script [here](http://sed.sourceforge.net/grabbag/scripts/remccoms3.sed) which will remove C/C++ comments from a file. It's very smart; for example, it will ignore '//' and '/\*' if found in a string declaration, etc. From within Python, it can be used using the following code: ``` import subprocess from cStringIO import StringIO input = StringIO(source_code) # source_code is a string with the source code. output = StringIO() process = subprocess.Popen(['sed', '/path/to/remccoms3.sed'], input=input, output=output) return_code = process.wait() stripped_code = output.getvalue() ``` In this program, `source_code` is the variable holding the C/C++ source code, and eventually `stripped_code` will hold C/C++ code with the comments removed. Of course, if you have the file on disk, you could have the `input` and `output` variables be file handles pointing to those files (`input` in read-mode, `output` in write-mode). `remccoms3.sed` is the file from the above link, and it should be saved in a readable location on disk. `sed` is also available on Windows, and comes installed by default on most GNU/Linux distros and Mac OS X. This will probably be better than a pure Python solution; no need to reinvent the wheel.
241,334
<p>I need to to iterate over the files in a directory and perform the following replacement.</p> <p><strong>Before:</strong></p> <blockquote> <p>Hello ${USER_NAME}, you live at ${HOME_ADDRESS}. It is now ${TIME}</p> </blockquote> <p><strong>After:</strong></p> <blockquote> <p>Hello ${userName}, you live at ${homeAddress}. It is now ${time}</p> </blockquote> <p>The number of different tokens that appear within ${} is large, so it's not really feasible to run:</p> <pre><code>find . -name '*' -exec sed -i 's/${USER_NAME}/${userName}/g' {} \; find . -name '*' -exec sed -i 's/${TIME}/${time}/g' {} \; </code></pre> <p>etc.</p> <p>I'm hoping it's possible to perform this replacement using a single command, that looks something like:</p> <pre><code>find . -name '*' -exec sed 's/XXX/YYY/g' {} \; </code></pre> <p>But I can't figure out what to substitute for XXX and YYY. Is it possible to do this in a single command?</p> <p>Cheers, Donal</p>
[ { "answer_id": 241350, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "<p>The <code>-i</code> flag to sed will edit a file in-place. For XXX and YYY, you would use something like:</p>\n\n<pre><code>sed -i 's/USER_NAME/userName/g'\n</code></pre>\n\n<p>and so on.</p>\n\n<p>Update: I see that your question was really about changing \"USER_NAME\" into \"userName\" automatically. You could try this Perl script:</p>\n\n<pre><code>sub convert {\n my $r = lc $_[0];\n $r =~ s/_(.)/\\U$1\\E/g;\n return $r;\n}\nwhile (&lt;&gt;) {\n s/\\${([A-Z_]+)}/\\${@{[convert $1]}}/g;\n print;\n}\n</code></pre>\n\n<p>Run it like this:</p>\n\n<pre><code>perl -i convert.pl inputfile.txt\n</code></pre>\n\n<p>Sample output:</p>\n\n<pre><code>$ cat inputfile.txt\nHello ${USER_NAME}, you live at ${HOME_ADDRESS}. It is now ${TIME}\n$ perl -i convert.pl inputfile.txt\n$ cat inputfile.txt\nHello ${userName}, you live at ${homeAddress}. It is now ${time}\n</code></pre>\n" }, { "answer_id": 241386, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "<p>Formatted for clarity:</p>\n\n<pre><code>sed -i '/^Hello/ { s/\\$\\{USER_NAME\\}/\\$\\{userName\\}/g \n s/\\$\\{HOME_ADDRESS\\}/\\$\\{homeAddress\\}/g \n s/\\$\\{TIME\\}/\\$\\{time\\}/g\n }'\n</code></pre>\n\n<p>Where <code>/^Hello/</code> identifies the lines you wish to act on (make it more specific if needed) and the rest substitutes each variable name. </p>\n\n<hr>\n\n<p>If writing this into a script consider the use of a HERE document to keep the formatting and make it easier to read and update...</p>\n" }, { "answer_id": 241414, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 0, "selected": false, "text": "<p>The answer above works really well. For completeness, I might add that you can do:</p>\n\n<pre><code>sed '/^Hello/ { s/\\$\\{USER_NAME\\}/\\$\\{userName\\}/g' &lt;filename&gt; \\\n | sed 's/\\$\\{HOME_ADDRESS\\}/\\$\\{homeAddress\\}/g' \\\n | sed 's/\\$\\{TIME\\}/\\$\\{time\\}/g'\n</code></pre>\n\n<p>They're functionally identical (except that mine dumps to stdout; you'll have to put it somewhere (but you get to keep the original in case, like e, you mess up regularly on your regexps). I like my formulation just because I can start with the one sed command, then add on more with</p>\n\n<pre><code>!! | sed 'yet-enother-regexp'\n</code></pre>\n\n<p>Arrow keys? vi-mode? Who needs that stuff? :)</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I need to to iterate over the files in a directory and perform the following replacement. **Before:** > > Hello ${USER\_NAME}, you live at > ${HOME\_ADDRESS}. It is now ${TIME} > > > **After:** > > Hello ${userName}, you live at > ${homeAddress}. It is now ${time} > > > The number of different tokens that appear within ${} is large, so it's not really feasible to run: ``` find . -name '*' -exec sed -i 's/${USER_NAME}/${userName}/g' {} \; find . -name '*' -exec sed -i 's/${TIME}/${time}/g' {} \; ``` etc. I'm hoping it's possible to perform this replacement using a single command, that looks something like: ``` find . -name '*' -exec sed 's/XXX/YYY/g' {} \; ``` But I can't figure out what to substitute for XXX and YYY. Is it possible to do this in a single command? Cheers, Donal
The `-i` flag to sed will edit a file in-place. For XXX and YYY, you would use something like: ``` sed -i 's/USER_NAME/userName/g' ``` and so on. Update: I see that your question was really about changing "USER\_NAME" into "userName" automatically. You could try this Perl script: ``` sub convert { my $r = lc $_[0]; $r =~ s/_(.)/\U$1\E/g; return $r; } while (<>) { s/\${([A-Z_]+)}/\${@{[convert $1]}}/g; print; } ``` Run it like this: ``` perl -i convert.pl inputfile.txt ``` Sample output: ``` $ cat inputfile.txt Hello ${USER_NAME}, you live at ${HOME_ADDRESS}. It is now ${TIME} $ perl -i convert.pl inputfile.txt $ cat inputfile.txt Hello ${userName}, you live at ${homeAddress}. It is now ${time} ```
241,339
<p>Here's what <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members" rel="noreferrer">MSDN has to say under <em>When to Use Static Classes</em></a>:</p> <blockquote> <pre><code>static class CompanyInfo { public static string GetCompanyName() { return "CompanyName"; } public static string GetCompanyAddress() { return "CompanyAddress"; } //... } </code></pre> <p>Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.</p> </blockquote> <p>To me, that example doesn't seem to cover very many possible usage scenarios for static classes. In the past I've used static classes for stateless suites of related functions, but that's about it. So, under what circumstances should (and shouldn't) a class be declared static? </p>
[ { "answer_id": 241351, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": false, "text": "<p>For C# 3.0, extension methods may only exist in top-level static classes.</p>\n" }, { "answer_id": 241369, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": false, "text": "<p>I only use static classes for helper methods, but with the advent of C# 3.0, I'd rather use extension methods for those.</p>\n\n<p>I rarely use static classes methods for the same reasons why I rarely use the singleton \"design pattern\".</p>\n" }, { "answer_id": 241372, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 11, "selected": true, "text": "<p>I wrote my thoughts of static classes in an earlier Stack Overflow answer:\n<em><a href=\"https://stackoverflow.com/questions/205689/class-with-single-method-best-approach#206481\">Class with single method -- best approach?</a></em></p>\n\n<p>I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service-oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.</p>\n\n<p><strong>Polymorphism</strong></p>\n\n<p>Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.</p>\n\n<p><strong>Interface woes</strong></p>\n\n<p>Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by <a href=\"https://learn.microsoft.com/archive/blogs/kirillosenkov/how-to-override-static-methods\" rel=\"noreferrer\">passing delegates instead of interfaces</a>.</p>\n\n<p><strong>Testing</strong></p>\n\n<p>This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up, but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.</p>\n\n<p><strong>Fosters blobs</strong></p>\n\n<p>As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.</p>\n\n<p><strong>Parameter creep</strong></p>\n\n<p>To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyway.</p>\n\n<p><strong>Demanding consumers to create an instance of classes for no reason</strong></p>\n\n<p>One of the most common arguments is: Why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns <code>new MyClass();</code></p>\n\n<p><strong>Only a Sith deals in absolutes</strong></p>\n\n<p>Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.</p>\n\n<p><strong>Standards, standards, standards!</strong></p>\n\n<p>Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.</p>\n" }, { "answer_id": 241387, "author": "Trap", "author_id": 7839, "author_profile": "https://Stackoverflow.com/users/7839", "pm_score": 3, "selected": false, "text": "<p>I use static classes as a means to define \"extra functionality\" that an object of a given type could use under a specific context. Usually they turn out to be utility classes.</p>\n\n<p>Other than that, I think that \"Use a static class as a unit of organization for methods not associated with particular objects.\" describe quite well their intended usage.</p>\n" }, { "answer_id": 241411, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 4, "selected": false, "text": "<p>I do tend to use static classes for factories. For example, this is the logging class in one of my projects:</p>\n\n<pre><code>public static class Log\n{\n private static readonly ILoggerFactory _loggerFactory =\n IoC.Resolve&lt;ILoggerFactory&gt;();\n\n public static ILogger For&lt;T&gt;(T instance)\n {\n return For(typeof(T));\n }\n\n public static ILogger For(Type type)\n {\n return _loggerFactory.GetLoggerFor(type);\n }\n}\n</code></pre>\n\n<p>You might have even noticed that IoC is called with a static accessor. <em>Most</em> of the time for me, if you can call static methods on a class, that's all you can do so I mark the class as static for extra clarity.</p>\n" }, { "answer_id": 241481, "author": "user25306", "author_id": 25306, "author_profile": "https://Stackoverflow.com/users/25306", "pm_score": 5, "selected": false, "text": "<p>If you use code analysis tools (e.g. <a href=\"https://en.wikipedia.org/wiki/FxCop\" rel=\"noreferrer\">FxCop</a>), it will recommend that you mark a method <code>static</code> if that method don't access instance data. The rationale is that there is a performance gain. <a href=\"https://msdn.microsoft.com/library/ms245046\" rel=\"noreferrer\">MSDN: CA1822 - Mark members as static</a>.</p>\n\n<p>It is more of a guideline than a rule, really...</p>\n" }, { "answer_id": 6546169, "author": "bentayloruk", "author_id": 418492, "author_profile": "https://Stackoverflow.com/users/418492", "pm_score": 4, "selected": false, "text": "<p>I've started using static classes when I wish to use functions, rather than classes, as my unit of reuse. Previously, I was all about the evil of static classes. However, learning <a href=\"http://en.wikipedia.org/wiki/F_Sharp_%28programming_language%29\" rel=\"noreferrer\">F#</a> has made me see them in a new light.</p>\n\n<p>What do I mean by this? Well, say when working up some super <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY</a> code, I end up with a bunch of one-method classes. I may just pull these methods into a static class and then inject them into dependencies using a delegate. This also plays nicely with my <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"noreferrer\">dependency injection</a> (DI) container of choice Autofac.</p>\n\n<p>Of course taking a direct dependency on a static method is still <em>usually</em> evil (there are some non-evil uses).</p>\n" }, { "answer_id": 9090068, "author": "Despertar", "author_id": 1160036, "author_profile": "https://Stackoverflow.com/users/1160036", "pm_score": 7, "selected": false, "text": "<p>When deciding whether to make a class static or non-static you need to look at what information you are trying to represent. This entails a more '<strong>bottom-up</strong>' style of programming where you focus on the data you are representing first. Is the class you are writing a real-world object like a rock, or a chair? These things are physical and have physical attributes such as color, weight which tells you that you may want to instantiate multiple objects with different properties. I may want a black chair AND a red chair at the same time. If you ever need two configurations at the same time then you instantly know you will want to instantiate it as an object so each object can be unique and exist at the same time.</p>\n\n<p>On the other end, static functions tend to lend more to actions which do not belong to a real-world object or an object that you can easily represent. Remember that C#'s predecessors are C++ and C where you can just define global functions that do not exist in a class. This lends more to '<strong>top-down</strong>' programming. Static methods can be used for these cases where it doesn't make sense that an 'object' performs the task. By forcing you to use classes this just makes it easier to group related functionality which helps you create more maintainable code.</p>\n\n<p>Most classes can be represented by either static or non-static, but when you are in doubt just go back to your OOP roots and try to think about what you are representing. Is this an object that is performing an action (a car that can speed up, slow down, turn) or something more abstract (like displaying output). </p>\n\n<p>Get in touch with your inner OOP and you can never go wrong! </p>\n" }, { "answer_id": 14166877, "author": "Don", "author_id": 1669344, "author_profile": "https://Stackoverflow.com/users/1669344", "pm_score": 4, "selected": false, "text": "<p>Static classes are very useful and have a place, for example libraries. </p>\n\n<p>The best example I can provide is the .Net Math class, a System namespace static class that contains a library of maths functions.</p>\n\n<p>It is like anything else, use the right tool for the job, and if not anything can be abused.</p>\n\n<p>Blankly dismissing static classes as wrong, don't use them, or saying \"there can be only one\" or none, is as wrong as over using the them. </p>\n\n<p>C#.Net contains a number of static classes that is uses just like the Math class. </p>\n\n<p>So given the correct implementation they are tremendously useful.</p>\n\n<p>We have a static TimeZone class that contains a number of business related timezone functions, there is no need to create multiple instances of the class so much like the Math class it contains a set of globally accesible TimeZone realated functions (methods) in a static class.</p>\n" }, { "answer_id": 26420286, "author": "ThunderGr", "author_id": 1145669, "author_profile": "https://Stackoverflow.com/users/1145669", "pm_score": 3, "selected": false, "text": "<p>This is another old but very hot question since OOP kicked in.\nThere are many reasons to use(or not) a static class, of course and most of them have been covered in the multitude of answers.</p>\n\n<p>I will just add my 2 cents to this, saying that, I make a class static, when this class is something that would be unique in the system and that would really make no sense to have any instances of it in the program. However, I reserve this usage for big classes. I never declare such small classes as in the MSDN example as \"static\" and, certainly, not classes that are going to be members of other classes.</p>\n\n<p>I also like to note that static <em>methods</em> and static <em>classes</em> are two different things to consider. The main disadvantages mentioned in the accepted answer are for static <em>methods</em>. static <em>classes</em> offer the same flexibility as normal classes(where properties and parameters are concerned), and all methods used in them should be relevant to the purpose of the existence of the class.</p>\n\n<p>A good example, in my opinion, of a candidate for a static class is a \"FileProcessing\" class, that would contain all methods and properties relevant for the program's various objects to perform complex FileProcessing operations. It hardly has any meaning to have more than one instance of this class and being static will make it readily available to everything in your program.</p>\n" }, { "answer_id": 27438449, "author": "Vicky", "author_id": 2996372, "author_profile": "https://Stackoverflow.com/users/2996372", "pm_score": 0, "selected": false, "text": "<p>Based on <a href=\"http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx\" rel=\"nofollow\">MSDN</a>:</p>\n\n<ol>\n<li>You cannot create the instance for static classes</li>\n<li>If the class declared as static, member variable should be static for that class</li>\n<li>Sealed [Cannot be Inherited]</li>\n<li>Cannot contains Instance constructor</li>\n<li>Memory Management</li>\n</ol>\n\n<p>Example: Math calculations (math values) does not changes [STANDARD CALCULATION FOR DEFINED VALUES]</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
Here's what [MSDN has to say under *When to Use Static Classes*](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members): > > > ``` > static class CompanyInfo > { > public static string GetCompanyName() { return "CompanyName"; } > public static string GetCompanyAddress() { return "CompanyAddress"; } > //... > } > > ``` > > Use a static class as a unit of > organization for methods not > associated with particular objects. > Also, a static class can make your > implementation simpler and faster > because you do not have to create an > object in order to call its methods. > It is useful to organize the methods > inside the class in a meaningful way, > such as the methods of the Math class > in the System namespace. > > > To me, that example doesn't seem to cover very many possible usage scenarios for static classes. In the past I've used static classes for stateless suites of related functions, but that's about it. So, under what circumstances should (and shouldn't) a class be declared static?
I wrote my thoughts of static classes in an earlier Stack Overflow answer: *[Class with single method -- best approach?](https://stackoverflow.com/questions/205689/class-with-single-method-best-approach#206481)* I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service-oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming. **Polymorphism** Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross. **Interface woes** Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by [passing delegates instead of interfaces](https://learn.microsoft.com/archive/blogs/kirillosenkov/how-to-override-static-methods). **Testing** This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up, but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects. **Fosters blobs** As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined. **Parameter creep** To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyway. **Demanding consumers to create an instance of classes for no reason** One of the most common arguments is: Why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns `new MyClass();` **Only a Sith deals in absolutes** Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however. **Standards, standards, standards!** Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.
241,341
<p>(Bear with me, I promise this gets to shebang and windows.)</p> <p>I have about the simplest of WEBRick servers put together:</p> <pre><code>require 'webrick' include WEBrick s = HTTPServer.new(:Port=&gt;2000, :DocumentRoot=&gt;Dir::pwd) s.start </code></pre> <p>Couldn't be simpler. This basic server does accept http connections (firefox, internet exploder, wget, TELENT) and deals with them appropriately, as long as I'm just fetching static documents. If, however, I set one of the files in the directory to have a .cgi extension, I get a 500 back and the following on the server's terminal:</p> <pre><code>ERROR CGIHandler: c:/rubyCGI/test.cgi: C:/...[snip]...webrick/httpservlet/cgi_runner.rb:45: in 'exec': Exec format error - ...[snip]... </code></pre> <p>I've done a few things on the command line to mimic what is going on in line 45 of cgi_runner.rb</p> <pre><code>c:\&gt;ruby exec "c:/rubyCGI/test.cgi" ^Z (same error erupts) c:\&gt;ruby exec "ruby c:/rubyCGI/test.cgi" ^Z Content-type: text/html Mares eat oats and does eat oats and I'll be home for Christmas. </code></pre> <p>Clearly, WEBrick hasn't been cleared for landing on windows. Your usual headaches of corporate paranoia prevent me from modifying webrick, so <strong>can I get the shebang notation in c:/rubyCGI/test.cgi recognized by the OS (windows) so I don't have to explicitly tell it each time which interpreter to use?</strong> I could assign all .cgi files to be associated with ruby, but that would be limiting in the long run.</p> <p>UPDATE: Since posting this, it has occurred to me that it may not be possible at all to run a cgi web server from ruby; ruby has no forking support. With no ability to fork a process, a cgi server would have to execute each cgi script one-at-a-time, neglecting all concurrent requests while the first one completed. While this may be acceptable for some, it would not work for my application. Nevertheless, I would still be very interested in an answer to my original question—that of getting shebang working under windows.</p>
[ { "answer_id": 241500, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 3, "selected": true, "text": "<p>I think what you want is to associate the file extension with Ruby. I don't think it's possible to get the !# notation to work on Windows but it is possible to get Windows to automatically launch a script with a particular interpreter (as in your second example). A good step by step discussion of what you'd want to do is <a href=\"http://support.microsoft.com/kb/307859\" rel=\"nofollow noreferrer\">here.</a> You specifically want the section headed: \"To create file associations for unassociated file types\". I think that will accomplish what you're trying to do. </p>\n" }, { "answer_id": 242567, "author": "William Yeung", "author_id": 16371, "author_profile": "https://Stackoverflow.com/users/16371", "pm_score": 0, "selected": false, "text": "<p>Not really to argue... but why bother webrick when mongrel is much faster and with native compiled with windows? And of coz, that means no shebang is needed.</p>\n" }, { "answer_id": 919848, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>A generic solution that works for both Ruby 1.8.6.pxxx and 1.9.1.p0 on \nWindows is the following:</p>\n\n<p>Edit the file: c:\\ruby\\lib\\ruby\\1.9.1\\webrick\\httpservlet\\cgi_runner.rb</p>\n\n<p>Add the following lines at the top of the file:</p>\n\n<pre>\nif \"1.9.1\" == RUBY_VERSION\n require 'rbconfig' #constants telling where Ruby runs from\nend\n</pre>\n\n<p>Now, locate the last line where is says: exec ENV[\"SCRIPT_FILENAME\"]\nComment that line out and add the following code:</p>\n\n<pre>\n# --- from here ---\nif \"1.9.1\" == RUBY_VERSION #use RbConfig\n Ruby = File::join(RbConfig::CONFIG['bindir'],\n RbConfig::CONFIG['ruby_install_name'])\n Ruby &lt;&lt; RbConfig::CONFIG['EXEEXT']\nelse # use ::Config\n Ruby = File::join(::Config::CONFIG['bindir'],\n ::Config::CONFIG['ruby_install_name'])\n Ruby &lt;&lt; ::Config::CONFIG['EXEEXT']\nend\n\nif /mswin|bccwin|mingw/ =~ RUBY_PLATFORM\n exec \"#{Ruby}\", ENV[\"SCRIPT_FILENAME\"]\nelse\n exec ENV[\"SCRIPT_FILENAME\"]\nend\n# --- to here ---\n</pre>\n\n<p>Save the file and restart the webrick server.</p>\n\n<p>Explanation:\nThis code just builds a variable 'Ruby' with the full path to \n\"ruby.exe\", and\n(if you're running on Windows) it passes the additional parameter\n\"c:\\ruby\\bin\\ruby.exe\" , to the Kernel.exec() method, so that your \nscript can be executed.</p>\n" }, { "answer_id": 3663261, "author": "totochto", "author_id": 441896, "author_profile": "https://Stackoverflow.com/users/441896", "pm_score": 0, "selected": false, "text": "<p>Actually, it is possible to get Windows to recognize shebang notation in script files. It can be done in a relatively short script in say, Ruby or AutoIt. Only a rather simple parser for the first line of a script file is required, along with some file manipulation. I have done this a couple times when either cross-compatibilty of script files was required or when Windows file extensions did not suffice.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30997/" ]
(Bear with me, I promise this gets to shebang and windows.) I have about the simplest of WEBRick servers put together: ``` require 'webrick' include WEBrick s = HTTPServer.new(:Port=>2000, :DocumentRoot=>Dir::pwd) s.start ``` Couldn't be simpler. This basic server does accept http connections (firefox, internet exploder, wget, TELENT) and deals with them appropriately, as long as I'm just fetching static documents. If, however, I set one of the files in the directory to have a .cgi extension, I get a 500 back and the following on the server's terminal: ``` ERROR CGIHandler: c:/rubyCGI/test.cgi: C:/...[snip]...webrick/httpservlet/cgi_runner.rb:45: in 'exec': Exec format error - ...[snip]... ``` I've done a few things on the command line to mimic what is going on in line 45 of cgi\_runner.rb ``` c:\>ruby exec "c:/rubyCGI/test.cgi" ^Z (same error erupts) c:\>ruby exec "ruby c:/rubyCGI/test.cgi" ^Z Content-type: text/html Mares eat oats and does eat oats and I'll be home for Christmas. ``` Clearly, WEBrick hasn't been cleared for landing on windows. Your usual headaches of corporate paranoia prevent me from modifying webrick, so **can I get the shebang notation in c:/rubyCGI/test.cgi recognized by the OS (windows) so I don't have to explicitly tell it each time which interpreter to use?** I could assign all .cgi files to be associated with ruby, but that would be limiting in the long run. UPDATE: Since posting this, it has occurred to me that it may not be possible at all to run a cgi web server from ruby; ruby has no forking support. With no ability to fork a process, a cgi server would have to execute each cgi script one-at-a-time, neglecting all concurrent requests while the first one completed. While this may be acceptable for some, it would not work for my application. Nevertheless, I would still be very interested in an answer to my original question—that of getting shebang working under windows.
I think what you want is to associate the file extension with Ruby. I don't think it's possible to get the !# notation to work on Windows but it is possible to get Windows to automatically launch a script with a particular interpreter (as in your second example). A good step by step discussion of what you'd want to do is [here.](http://support.microsoft.com/kb/307859) You specifically want the section headed: "To create file associations for unassociated file types". I think that will accomplish what you're trying to do.
241,388
<p>I'm looking at the following code snippet:</p> <pre><code>my @ret = &lt;someMethod&gt; return (undef) if( $DB_ERROR ); return (undef) unless ($#ret &gt;= 0); </code></pre> <p>Does <code>$#</code> just give you a count of elements in a array?</p>
[ { "answer_id": 241394, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 7, "selected": true, "text": "<p><code>$#arrayname</code> gives you the index of the last element, so if array <code>@ret</code> has 2 elements then <code>$#ret</code> is 1. </p>\n\n<p>And, as noted by Barry Brown, an empty array gives -1.</p>\n\n<p>To get the length you can use the array in scalar context:</p>\n\n<pre><code>print scalar @ret;\n</code></pre>\n" }, { "answer_id": 241456, "author": "Quantum Omega", "author_id": 31895, "author_profile": "https://Stackoverflow.com/users/31895", "pm_score": 3, "selected": false, "text": "<p>Be aware that the $#array expression will return -1 when array has zero elements.</p>\n" }, { "answer_id": 241462, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 5, "selected": false, "text": "<p>edg is correct, but the original code is unnecessarily obtuse. In most cases, <code>$#foo</code> is a red flag that the code could be written more simply using <code>scalar @foo</code>.</p>\n\n<pre><code>return (undef) unless ($#ret &gt;= 0);\n</code></pre>\n\n<p><code>unless foo &gt;= bar</code> is difficult to puzzle out. First, turn it into a positive statement.</p>\n\n<pre><code>return (undef) if ($#ret &lt; 0);\n</code></pre>\n\n<p>When is $#ret &lt; 0? When it's -1. A $#ret of -1 is an array of length 0. So the above can be written much more simply as...</p>\n\n<pre><code>return (undef) if scalar @ret &lt;= 0;\n</code></pre>\n\n<p>But you can't have a negative length array, so...</p>\n\n<pre><code>return (undef) if scalar @ret == 0;\n</code></pre>\n\n<p>And == is in scalar context, so that \"scalar\" is redundant...</p>\n\n<pre><code>return (undef) if @ret == 0;\n</code></pre>\n\n<p>But that's just a wordy way of saying \"if <code>@ret</code> is false\".</p>\n\n<pre><code>return (undef) if !@ret;\n</code></pre>\n\n<p>Which I think for simple statement modifiers is better expressed with unless.</p>\n\n<pre><code>return (undef) unless @ret;\n</code></pre>\n\n<p>Isn't that easier to follow?</p>\n\n<p>As a final side-note, <code>return undef</code> is discouraged because it does the wrong thing in list context. You get back a list containing one undef element, which is true. Instead, just use a blank return which returns undef in scalar context and an empty list in list context.</p>\n\n<pre><code>return unless @ret;\n</code></pre>\n" }, { "answer_id": 1991038, "author": "Rob Van Dam", "author_id": 232706, "author_profile": "https://Stackoverflow.com/users/232706", "pm_score": 2, "selected": false, "text": "<p>To summarize everyone else, that code is much more legible if written like this:</p>\n\n<pre><code>my @ret = someMethod();\nreturn if $DB_ERROR;\nreturn unless @ret;\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31301/" ]
I'm looking at the following code snippet: ``` my @ret = <someMethod> return (undef) if( $DB_ERROR ); return (undef) unless ($#ret >= 0); ``` Does `$#` just give you a count of elements in a array?
`$#arrayname` gives you the index of the last element, so if array `@ret` has 2 elements then `$#ret` is 1. And, as noted by Barry Brown, an empty array gives -1. To get the length you can use the array in scalar context: ``` print scalar @ret; ```
241,396
<p>I produce server software and have been fine with all Linux environments so far, both for production and as deployment target. However, I want to provide a broader choice of target environments in the future and I'm also planning features that would consume and produce Office documents.</p> <p>As a first step, I am looking for a good way to get a number of MS software products (XP, Vista, Server 2003 &amp; 2008, Office 2000, 2003 &amp; 2007 ...) to put on some VMs in my testing setup, so I can start to play around.</p> <p>So far, I get quite a good impression from what I read about MS's partner program (aka Action Pack). The only thing I'm missing from what the website tells me is older software versions. As I want to mimick possible customers' setups and there's always a lot of people that run older versions, that would be quite important for the testing scenario.</p> <p>Eventually, I'm going to face similar questions with Apple OS X, so if anybody has some hints on that, I'd be glad, too.</p>
[ { "answer_id": 241394, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 7, "selected": true, "text": "<p><code>$#arrayname</code> gives you the index of the last element, so if array <code>@ret</code> has 2 elements then <code>$#ret</code> is 1. </p>\n\n<p>And, as noted by Barry Brown, an empty array gives -1.</p>\n\n<p>To get the length you can use the array in scalar context:</p>\n\n<pre><code>print scalar @ret;\n</code></pre>\n" }, { "answer_id": 241456, "author": "Quantum Omega", "author_id": 31895, "author_profile": "https://Stackoverflow.com/users/31895", "pm_score": 3, "selected": false, "text": "<p>Be aware that the $#array expression will return -1 when array has zero elements.</p>\n" }, { "answer_id": 241462, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 5, "selected": false, "text": "<p>edg is correct, but the original code is unnecessarily obtuse. In most cases, <code>$#foo</code> is a red flag that the code could be written more simply using <code>scalar @foo</code>.</p>\n\n<pre><code>return (undef) unless ($#ret &gt;= 0);\n</code></pre>\n\n<p><code>unless foo &gt;= bar</code> is difficult to puzzle out. First, turn it into a positive statement.</p>\n\n<pre><code>return (undef) if ($#ret &lt; 0);\n</code></pre>\n\n<p>When is $#ret &lt; 0? When it's -1. A $#ret of -1 is an array of length 0. So the above can be written much more simply as...</p>\n\n<pre><code>return (undef) if scalar @ret &lt;= 0;\n</code></pre>\n\n<p>But you can't have a negative length array, so...</p>\n\n<pre><code>return (undef) if scalar @ret == 0;\n</code></pre>\n\n<p>And == is in scalar context, so that \"scalar\" is redundant...</p>\n\n<pre><code>return (undef) if @ret == 0;\n</code></pre>\n\n<p>But that's just a wordy way of saying \"if <code>@ret</code> is false\".</p>\n\n<pre><code>return (undef) if !@ret;\n</code></pre>\n\n<p>Which I think for simple statement modifiers is better expressed with unless.</p>\n\n<pre><code>return (undef) unless @ret;\n</code></pre>\n\n<p>Isn't that easier to follow?</p>\n\n<p>As a final side-note, <code>return undef</code> is discouraged because it does the wrong thing in list context. You get back a list containing one undef element, which is true. Instead, just use a blank return which returns undef in scalar context and an empty list in list context.</p>\n\n<pre><code>return unless @ret;\n</code></pre>\n" }, { "answer_id": 1991038, "author": "Rob Van Dam", "author_id": 232706, "author_profile": "https://Stackoverflow.com/users/232706", "pm_score": 2, "selected": false, "text": "<p>To summarize everyone else, that code is much more legible if written like this:</p>\n\n<pre><code>my @ret = someMethod();\nreturn if $DB_ERROR;\nreturn unless @ret;\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
I produce server software and have been fine with all Linux environments so far, both for production and as deployment target. However, I want to provide a broader choice of target environments in the future and I'm also planning features that would consume and produce Office documents. As a first step, I am looking for a good way to get a number of MS software products (XP, Vista, Server 2003 & 2008, Office 2000, 2003 & 2007 ...) to put on some VMs in my testing setup, so I can start to play around. So far, I get quite a good impression from what I read about MS's partner program (aka Action Pack). The only thing I'm missing from what the website tells me is older software versions. As I want to mimick possible customers' setups and there's always a lot of people that run older versions, that would be quite important for the testing scenario. Eventually, I'm going to face similar questions with Apple OS X, so if anybody has some hints on that, I'd be glad, too.
`$#arrayname` gives you the index of the last element, so if array `@ret` has 2 elements then `$#ret` is 1. And, as noted by Barry Brown, an empty array gives -1. To get the length you can use the array in scalar context: ``` print scalar @ret; ```
241,397
<p>How do you answer the following questions from managers, testers and other people in your team:</p> <p>In what build is bug #829 fixed? What tasks have been completed in our current test build?</p> <p>So simply put, how do you achieve traceability of your requirements, tasks and bugs right from them being reported reporting through to deployment? What processes, tools and techniques are you using to achieve this?</p>
[ { "answer_id": 241404, "author": "David Segonds", "author_id": 13673, "author_profile": "https://Stackoverflow.com/users/13673", "pm_score": 0, "selected": false, "text": "<p>We are tagging the source control check-in with the defect number that has been fixed or the enhancement number that has been implemented.</p>\n\n<p>By retrieving the check-in log between two builds, you can determine what has been implemented or fixed.</p>\n" }, { "answer_id": 241419, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 3, "selected": true, "text": "<p>We use <a href=\"http://trac.edgewall.org/\" rel=\"nofollow noreferrer\">TRAC</a> with <a href=\"http://subversion.tigris.org/\" rel=\"nofollow noreferrer\">SVN</a> in our Company and perform daily rolling builds to DEV / STAGING &amp; STABLE environments with regular scheduled deployments (once a month... ish) to a PRODUCTION Environment.</p>\n\n<p>When a bug is reported, it's entered into TRAC and given a Tickets number (e.g. #1001)</p>\n\n<p>When the bug is fixed, the code is checked back into SVN with the ticket number(#1001) in the SVN Checkin notes.</p>\n\n<p>The developer takes a note of the SVN Changeset number (e.g. [5000]) and opens the TRAC web ui. When closing the ticket, they put the changeset number in the notes of the ticket.</p>\n\n<p>This way, the SVN checkin reference the ticket... and the ticket references the SVN Checkin.</p>\n\n<p>Our daily builds are then performed against an SVN Changeset (e.g. todays build is everything up to changeset [5050]) and a note is made of this in our deployment notice.</p>\n\n<pre><code>Deployed On | Environment | Changeset\n--------------+-------------------------+--------------------------\n10-01-2008 | DEV | 5100\n10-01-2008 | STAGING | 5080\n10-01-2008 | STABLE | 5050\n01-01-2008 | PRODUCTION | 5000\n</code></pre>\n\n<p>That way the testers when reviewing fixes for testing know by the changeset in the ticket comments if the build they're looking at includes the fix.</p>\n" }, { "answer_id": 241432, "author": "Wim", "author_id": 30874, "author_profile": "https://Stackoverflow.com/users/30874", "pm_score": 1, "selected": false, "text": "<p>We use TFS in conjunction with JetBrains' TeamCity for CI.</p>\n\n<p>When associating check-ins with tasks, our custom check-in policy prepends the associated tasks and bugs with their ID's and titles to the check-in comments.</p>\n\n<p>These comments are then used to generate the release notes, which are automatically generated for each build.</p>\n" }, { "answer_id": 241463, "author": "Mark Brittingham", "author_id": 15592, "author_profile": "https://Stackoverflow.com/users/15592", "pm_score": 0, "selected": false, "text": "<p>We use a managed SVN service called Beanstalk (<a href=\"http://www.beanstalkapp.com/\" rel=\"nofollow noreferrer\">http://www.beanstalkapp.com/</a>) that allows you to easily tie in with a number of Bug/Feature management systems. In our case, we use Fog Creek's FogBugz for that end of things. SVN/Beanstalk permits you to make notes when you check in a build that will, in turn, affect the status of one or more <a href=\"http://www.fogcreek.com/FogBugz/\" rel=\"nofollow noreferrer\">FogBugz</a> cases.</p>\n\n<p>On the client end, we use Tortoise SVN and Visual SVN to manage the interaction of the local client and the Beanstalk SVN server (Tortoise provides the actual service, Visual SVN provides the integration between Tortoise SVN and MS Visual Studio).</p>\n\n<p>I highly recommend both services and the Tortoise/Visual SVN client.</p>\n" }, { "answer_id": 241514, "author": "ollifant", "author_id": 2078, "author_profile": "https://Stackoverflow.com/users/2078", "pm_score": 0, "selected": false, "text": "<p>We are using Fogbugz which has build-in subversion integration. Basically there is a plugin for Fogbugz which checks for SVN check-ins in the background. So if you supply a Fogbugz-case id at your check-in, it gets automatically linked with this check-in.</p>\n\n<p>As far as I know you don't need any special application (like Beanstalk for example).</p>\n\n<p>The other way round is little tricky. In our company there is a convention that for every (future or past) build there is a \"release\" in Fogbugz. If you fix a bug or implement a feature you assign the case to the right release.</p>\n\n<p>Then it's quite easy to get a list of all implemented features of build X.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30874/" ]
How do you answer the following questions from managers, testers and other people in your team: In what build is bug #829 fixed? What tasks have been completed in our current test build? So simply put, how do you achieve traceability of your requirements, tasks and bugs right from them being reported reporting through to deployment? What processes, tools and techniques are you using to achieve this?
We use [TRAC](http://trac.edgewall.org/) with [SVN](http://subversion.tigris.org/) in our Company and perform daily rolling builds to DEV / STAGING & STABLE environments with regular scheduled deployments (once a month... ish) to a PRODUCTION Environment. When a bug is reported, it's entered into TRAC and given a Tickets number (e.g. #1001) When the bug is fixed, the code is checked back into SVN with the ticket number(#1001) in the SVN Checkin notes. The developer takes a note of the SVN Changeset number (e.g. [5000]) and opens the TRAC web ui. When closing the ticket, they put the changeset number in the notes of the ticket. This way, the SVN checkin reference the ticket... and the ticket references the SVN Checkin. Our daily builds are then performed against an SVN Changeset (e.g. todays build is everything up to changeset [5050]) and a note is made of this in our deployment notice. ``` Deployed On | Environment | Changeset --------------+-------------------------+-------------------------- 10-01-2008 | DEV | 5100 10-01-2008 | STAGING | 5080 10-01-2008 | STABLE | 5050 01-01-2008 | PRODUCTION | 5000 ``` That way the testers when reviewing fixes for testing know by the changeset in the ticket comments if the build they're looking at includes the fix.
241,402
<p>I'm wanting to add a class to the body tag without waiting for the DOM to load, but I'm wanting to know if the following approach would be valid. I'm more concerned with validity than whether the browsers support it for now.</p> <pre><code>&lt;body&gt; $("body").addClass("active"); ... &lt;/body&gt; </code></pre> <p>Thanks, Steve</p>
[ { "answer_id": 241418, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>If the element doesn't exist in the DOM, the search will fail to find it and the action won't be applied. If you can't do it in the $(document).ready() function, you might want to try putting the code after the element being referenced. I believe this will work.</p>\n\n<pre><code>&lt;body&gt;\n &lt;div id='topStories'&gt;&lt;/div&gt;\n &lt;script type='text/javascript'&gt;\n $('div#topStories').addClass('active');\n &lt;/script&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>If you need to add the class to the body, I would definitely use $(document).ready().</p>\n" }, { "answer_id": 241529, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<p>Short answer: it depends. Apparently, according to my tests, the answer seems to be yes, depending on what you want. I just tested this:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n &lt;style type=\"text/css\"&gt;\n .foobar { background-color: #CCC; }\n &lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;script type=\"text/javascript\"&gt;\n window.document.body.className = \"foobar\";\n &lt;/script&gt;\n &lt;div style=\"border: solid 1px\"&gt;&lt;br /&gt;&lt;/div&gt;\n &lt;script type=\"text/javascript\"&gt;\n // happens before DOM is fully loaded:\n alert(window.document.body.className);\n &lt;/script&gt;\n &lt;span&gt;Appears after the alert() call.&lt;/span&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>In IE 7, when the <code>alert()</code> takes place, the value is set correctly, but the style hasn't yet been applied (it is quickly applied as soon as the DOM is finished loading). </p>\n\n<p>In Firefox, the style has been applied by the time the <code>alert()</code> takes place.</p>\n\n<p>Anyway, hope this is helpful to you.</p>\n" }, { "answer_id": 241548, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 0, "selected": false, "text": "<p>That was VERY helpful.</p>\n\n<p>To put a little real world to the question.</p>\n\n<p>I build with the assumption that JavaScript isn't supported and then override with the JavaScript. The problem is, that when I have to wait for the DOM to load before my overrides kick in the site goes through the flicker stage as it's built. I'm hoping that if I can add a class of \"active\" to the body element before the rest of the site's loaded I'll be able to apply JavaScript assumed styles before the page renders.</p>\n\n<p>What I don't want to do is to add this and then get a call when Firefox4 comes out that I shouldn't have done it.</p>\n\n<p>If you take a look at a site I built, you'll see that it degrades gracefully, but that ficker bugs me (especially if an ad hangs the site up). I could take the other guys approach and just build it with JS assumed, but come on - that's just lazy...</p>\n" }, { "answer_id": 241891, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 1, "selected": false, "text": "<p>Basically, the answer is no. In IE6 and Firefox 2 (the browsers I have the most experience in), the element isn't in the DOM until after the close tag (or the page is done rendering, for invalid XHTML). I know that jQuery provides a convenience methods that seems to react quickly enough to avoid \"flicker\" in most cases. You would use it like so:</p>\n\n<pre><code>&lt;script&gt;\n $(document).ready(function() {\n $(\"body\").addClass(\"active\");\n });\n&lt;/script&gt;\n&lt;body&gt;\n ..\n ..\n ..\n&lt;/body&gt;\n</code></pre>\n\n<p>But that's about it for javascript.</p>\n\n<p>Of course, in the example you provided, you could easily just accomplish the same effect with:</p>\n\n<pre><code>&lt;body class=\"active\"&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 241968, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 3, "selected": true, "text": "<p>The <a href=\"http://plugins.jquery.com/project/elementReady\" rel=\"nofollow noreferrer\">.elementReady() plugin</a> seems to be pretty close to what you're looking for.</p>\n\n<p>It operates by using a <code>setInterval</code> loop, that exits as soon as <code>document.getElementById()</code> returns an element for a given <code>id</code>.</p>\n\n<p>You could probably do a slight modification of that plugin (or commit an update/patch) to allow for generic selectors (at least for \"tagNames\") instead of just <code>id</code>s.</p>\n\n<p>I don't believe there is any truly reliable cross-browser compatible way to address an element before it's loaded - other than this sort of <code>setInterval</code> hacking</p>\n\n<p>Unless you are able to place your javascript command <em>inside</em> the target element like @JasonBunting suggests.</p>\n" }, { "answer_id": 246550, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 0, "selected": false, "text": "<p>Rather than adding a class to your &lt;body&gt; tag you might find it easier to add a class to the &lt;html&gt; tag by doing:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n document.documentElement.className = 'active';\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16124/" ]
I'm wanting to add a class to the body tag without waiting for the DOM to load, but I'm wanting to know if the following approach would be valid. I'm more concerned with validity than whether the browsers support it for now. ``` <body> $("body").addClass("active"); ... </body> ``` Thanks, Steve
The [.elementReady() plugin](http://plugins.jquery.com/project/elementReady) seems to be pretty close to what you're looking for. It operates by using a `setInterval` loop, that exits as soon as `document.getElementById()` returns an element for a given `id`. You could probably do a slight modification of that plugin (or commit an update/patch) to allow for generic selectors (at least for "tagNames") instead of just `id`s. I don't believe there is any truly reliable cross-browser compatible way to address an element before it's loaded - other than this sort of `setInterval` hacking Unless you are able to place your javascript command *inside* the target element like @JasonBunting suggests.
241,405
<p>I have a string that I need to convert to the equivalent array of bytes in .NET. </p> <p>This ought to be easy, but I am having a brain cramp.</p>
[ { "answer_id": 241408, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": true, "text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding?redirectedfrom=MSDN&amp;view=netframework-4.7.2\" rel=\"noreferrer\">You need to use an encoding</a> (<code>System.Text.Encoding</code>) to tell .NET what you expect as the output. For example, in <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.unicode?view=netframework-4.7.2#System_Text_Encoding_Unicode\" rel=\"noreferrer\">UTF-16 (= <code>System.Text.Encoding.Unicode</code>)</a>:</p>\n\n<pre><code>var result = System.Text.Encoding.Unicode.GetBytes(text);\n</code></pre>\n" }, { "answer_id": 241409, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 3, "selected": false, "text": "<p>Like this:</p>\n\n<pre><code> string test = \"text\";\n byte[] arr = Encoding.UTF8.GetBytes(test);\n</code></pre>\n" }, { "answer_id": 241459, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 4, "selected": false, "text": "<p>What Encoding are you using? Konrad's got it pretty much down, but there are others out there and you could get goofy results with the wrong one:</p>\n\n<pre><code>byte[] bytes = System.Text.Encoding.XXX.GetBytes(text)\n</code></pre>\n\n<p>Where <code>XXX</code> can be:</p>\n\n<pre><code>ASCII\nBigEndianUnicode\nDefault\nUnicode\nUTF32\nUTF7\nUTF8\n</code></pre>\n" }, { "answer_id": 241466, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>First work out which encoding you want: you need to know <a href=\"http://pobox.com/~skeet/csharp/unicode.html\" rel=\"noreferrer\">a bit about Unicode</a> first.</p>\n\n<p>Next work out which <a href=\"http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx\" rel=\"noreferrer\"><code>System.Text.Encoding</code></a> that corresponds to. My <a href=\"http://refcardz.dzone.com/refcardz/coredotnet\" rel=\"noreferrer\">Core .NET refcard</a> describes most of the common ones, and how to get an instance (e.g. by a static property of <code>Encoding</code> or by calling a <a href=\"http://msdn.microsoft.com/en-us/library/system.text.encoding.getencoding.aspx\" rel=\"noreferrer\"><code>Encoding.GetEncoding</code></a>.</p>\n\n<p>Finally, work out whether you want all the bytes at once (which is the easiest way of working - call <a href=\"http://msdn.microsoft.com/en-us/library/system.text.encoding.getbytes.aspx\" rel=\"noreferrer\">Encoding.GetBytes(string)</a> once and you're done) or whether you need to break it into chunks - in which case you'll want to use <a href=\"http://msdn.microsoft.com/en-us/library/system.text.encoding.getencoder.aspx\" rel=\"noreferrer\">Encoding.GetEncoder</a> and then encode a bit at a time. The encoder takes care of keeping the state between calls, in case you need to break off half way through a character, for example.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23862/" ]
I have a string that I need to convert to the equivalent array of bytes in .NET. This ought to be easy, but I am having a brain cramp.
[You need to use an encoding](https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding?redirectedfrom=MSDN&view=netframework-4.7.2) (`System.Text.Encoding`) to tell .NET what you expect as the output. For example, in [UTF-16 (= `System.Text.Encoding.Unicode`)](https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.unicode?view=netframework-4.7.2#System_Text_Encoding_Unicode): ``` var result = System.Text.Encoding.Unicode.GetBytes(text); ```
241,407
<p>For this xml (in a SQL 2005 XML column): </p> <pre><code>&lt;doc&gt; &lt;a&gt;1&lt;/a&gt; &lt;b ba="1" bb="2" bc="3" /&gt; &lt;c bd="3"/&gt; &lt;doc&gt; </code></pre> <p>I'd like to be able to retrieve the names of the attributes (ba, bb, bc, bd) rather than the values <em>inside SQL Server 2005</em>. Well, XPath certainly allows this with name() but SQL doesn't support that. This is my chief complaint with using XML in SQL; you have to figure out which parts of the XML/Xpath/XQuery spec are in there. </p> <p>The only way I can think of to do this is to build a CLR proc that loads the XML into an XML Document (iirc) and runs the XPath to extract the names of the nodes. I'm open to suggestions here. </p>
[ { "answer_id": 241687, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 4, "selected": true, "text": "<pre><code>DECLARE @xml as xml\nDECLARE @path as varchar(max)\nDECLARE @index int, @count int\n\nSET @xml = \n'&lt;doc&gt;\n &lt;a&gt;1&lt;/a&gt;\n &lt;b ba=\"1\" bb=\"2\" bc=\"3\" /&gt;\n &lt;c bd=\"3\"/&gt;\n&lt;/doc&gt;'\n\n\n\nSELECT @index = 1\n\nSET @count = @xml.query('count(/doc/b/@*)').value('.','int')\n\nWHILE @index &lt;= @count \nBEGIN\n SELECT @xml.value('local-name((/doc/b/@*[sql:variable(\"@index\")])[1])', 'varchar(max)')\n SET @index = @index + 1\nEND\n</code></pre>\n\n<p>for element 'b'</p>\n\n<p>it returns </p>\n\n<ul>\n<li>ba </li>\n<li>bb </li>\n<li>bc</li>\n</ul>\n\n<p>You can build a loop to get attributes for each element in the xml.</p>\n\n<p>BTW\nThe XML in your sample should be closed at closing doc tag. </p>\n" }, { "answer_id": 1667116, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>this:</p>\n\n<pre><code>declare @xml as xml\n\nset @xml = \n'&lt;doc&gt;\n &lt;a&gt;1&lt;/a&gt;\n &lt;b ba=\"1\" bb=\"2\" bc=\"3\" /&gt;\n &lt;c bd=\"3\"/&gt;\n&lt;/doc&gt;'\n\nselect @xml.query('\n for $attr in /doc/b/@*\n return local-name($attr)') \n</code></pre>\n\n<p>returns:</p>\n\n<p>ba bb bc</p>\n" }, { "answer_id": 4156566, "author": "Ben Davis", "author_id": 504746, "author_profile": "https://Stackoverflow.com/users/504746", "pm_score": 3, "selected": false, "text": "<pre><code>DECLARE @xml as xml\n\nSET @xml = \n'&lt;doc&gt;\n &lt;a&gt;1&lt;/a&gt;\n &lt;b ba=\"1\" bb=\"2\" bc=\"3\" /&gt;\n &lt;c bd=\"3\"/&gt;\n&lt;/doc&gt;'\n\nSELECT DISTINCT\n CAST(Attribute.Name.query('local-name(.)') AS VARCHAR(100)) Attribute,\n Attribute.Name.value('.','VARCHAR(100)') Value\nFROM @xml.nodes('//@*') Attribute(Name)\n</code></pre>\n\n<p>Returns:</p>\n\n<p>Attribute Value</p>\n\n<p>ba 1</p>\n\n<p>bb 2</p>\n\n<p>bc 3</p>\n\n<p>bd 3</p>\n" }, { "answer_id": 52220509, "author": "Mike Thompson", "author_id": 10330179, "author_profile": "https://Stackoverflow.com/users/10330179", "pm_score": 1, "selected": false, "text": "<pre><code>Declare @xml Xml = '&lt;doc&gt;&lt;a&gt;1&lt;/a&gt;&lt;b ba=\"1\" bb=\"2\" bc=\"3\" /&gt;&lt;c bd=\"3\"/&gt;&lt;/doc&gt;'\n\nSelect n.value('local-name(.)', 'varchar(max)') from @xml.nodes('/doc/*/@*') a(n)\n</code></pre>\n\n<p>Returns\nba\nbb\nbc\nbd</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30946/" ]
For this xml (in a SQL 2005 XML column): ``` <doc> <a>1</a> <b ba="1" bb="2" bc="3" /> <c bd="3"/> <doc> ``` I'd like to be able to retrieve the names of the attributes (ba, bb, bc, bd) rather than the values *inside SQL Server 2005*. Well, XPath certainly allows this with name() but SQL doesn't support that. This is my chief complaint with using XML in SQL; you have to figure out which parts of the XML/Xpath/XQuery spec are in there. The only way I can think of to do this is to build a CLR proc that loads the XML into an XML Document (iirc) and runs the XPath to extract the names of the nodes. I'm open to suggestions here.
``` DECLARE @xml as xml DECLARE @path as varchar(max) DECLARE @index int, @count int SET @xml = '<doc> <a>1</a> <b ba="1" bb="2" bc="3" /> <c bd="3"/> </doc>' SELECT @index = 1 SET @count = @xml.query('count(/doc/b/@*)').value('.','int') WHILE @index <= @count BEGIN SELECT @xml.value('local-name((/doc/b/@*[sql:variable("@index")])[1])', 'varchar(max)') SET @index = @index + 1 END ``` for element 'b' it returns * ba * bb * bc You can build a loop to get attributes for each element in the xml. BTW The XML in your sample should be closed at closing doc tag.
241,425
<p>I'm also interested in other Symbian SDKs that allow to set their emulator's IMEI.</p>
[ { "answer_id": 243026, "author": "michael aubert", "author_id": 17867, "author_profile": "https://Stackoverflow.com/users/17867", "pm_score": 0, "selected": false, "text": "<p>I have never actually tried that but here's my best guess:</p>\n\n<p>The emulator doesn't have a proper telephony implementation unless:</p>\n\n<ul>\n<li><p>you link it to an actual phone over infrared/usb/serial. In which case the emulator telephony component will need configuration to use AT commands to pilot the phone (even if the phone isn't a Symbian phone). This allows you to make phone calls, send and receive SMS/MMS but certainly not change the IMEI.</p></li>\n<li><p>you use the SIMTSY module. This is a component that uses configuration files to simulate telephony events. It can pretend to send SMS/MMS, pretend you are receiving a phone call...none of that actually creates any kind of network traffic, you understand. I assume the IMEI is in the configuration file but I don't expect you can properly change it without restarting the emulator. I have never seen SIMTSY used outside of Symbian itself so I don't know whether it is available to third-party developer. It should be open-sourced with the rest of the operating system within the next 2 years, though.</p></li>\n</ul>\n\n<p>There is also the possibility that the way the SDK itself was built disabled most of the telephony framework for the emulator, using build-time macro. You should check <a href=\"http://forum.nokia.com\" rel=\"nofollow noreferrer\">http://forum.nokia.com</a></p>\n" }, { "answer_id": 280431, "author": "David Jacobson", "author_id": 28484, "author_profile": "https://Stackoverflow.com/users/28484", "pm_score": 1, "selected": false, "text": "<p>My general approach to these kinds of things is <strong>do it in software</strong>.</p>\n\n<ol>\n<li>Put the IMEI fetching code into one globally-accessible function, and only use this function for IMEI fetching.</li>\n<li><strong><code>#ifdef __WINS__</code></strong> can be used in C++ code to selectively compile in the hard-coded IMEI you want to return in the emulator. In Java, you can probably tell you are in the emulator by other means (eg if the IMEI returned is a fixed weird value in the emulator), and act accordingly.</li>\n<li>You can go one step further and have a dynamic IMEI. Once you do that, you will find that testing your code with different IMEIs becomes much easier.</li>\n</ol>\n" }, { "answer_id": 915150, "author": "JOM", "author_id": 113079, "author_profile": "https://Stackoverflow.com/users/113079", "pm_score": 2, "selected": true, "text": "<p>Emulator has hardcoded IMEI of '000000000000000'. Replace what with whatever you want to use and continue running your code.</p>\n\n<p>Symbian C++:</p>\n\n<pre><code> TPlpVariantMachineId imei;\n PlpVariant::GetMachineIdL(imei); \n imei.Copy(_L(\"123456789012345\"));\n</code></pre>\n\n<p>Python for S60 (PyS60):</p>\n\n<pre><code> import sysinfo\n my_imei = sysinfo.imei()\n my_imei = u\"123456789012345\"\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15647/" ]
I'm also interested in other Symbian SDKs that allow to set their emulator's IMEI.
Emulator has hardcoded IMEI of '000000000000000'. Replace what with whatever you want to use and continue running your code. Symbian C++: ``` TPlpVariantMachineId imei; PlpVariant::GetMachineIdL(imei); imei.Copy(_L("123456789012345")); ``` Python for S60 (PyS60): ``` import sysinfo my_imei = sysinfo.imei() my_imei = u"123456789012345" ```
241,453
<p>I'm experimenting with JavaFX making a small game. </p> <p>I want to add sound. How?</p> <p>I tried <code>MediaPlayer</code> with <code>media</code> defined with relative <code>source</code> attribute like:</p> <pre><code>attribute media = Media{ source: "{__FILE__}/sound/hormpipe.mp3" } attribute player = MediaPlayer{ autoPlay:true media:media } </code></pre> <p>It doesn't play. I get </p> <blockquote> <p><code>FX Media Object caught Exception com.sun.media.jmc.MediaUnavailableException: Media unavailable: file: ... Sound.class/sound/hormpipe.mp3</code></p> </blockquote>
[ { "answer_id": 247606, "author": "GuyWithDogs", "author_id": 9520, "author_profile": "https://Stackoverflow.com/users/9520", "pm_score": 1, "selected": false, "text": "<p>Just a guess, but is that file \"hornpipe.mp3\" and not \"hormpipe.mp3\" (with an m)?</p>\n" }, { "answer_id": 368256, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>var player = javafx.scene.media.MediaPlayer {\n repeatCount: javafx.scene.media.MediaPlayer.REPEAT_FOREVER\n media: Media { source: &quot;{\\_\\_DIR\\_\\_}clip.wav&quot;\n };\n};\nplayer.play();\n</code></pre>\n<p>You have to incluye the audio file in the build/compiled directory so Netbeans can pack it into the jar file.</p>\n" }, { "answer_id": 2957187, "author": "lindelof", "author_id": 1428, "author_profile": "https://Stackoverflow.com/users/1428", "pm_score": 0, "selected": false, "text": "<p>Just a guess, but I think your <code>{__FILE__}</code> will expand to the name of your file. Try replacing it with <code>{__DIR__}</code>.</p>\n" }, { "answer_id": 3076042, "author": "MKA", "author_id": 371074, "author_profile": "https://Stackoverflow.com/users/371074", "pm_score": 0, "selected": false, "text": "<p>Also note that <code>{__DIR__}</code> includes the trailing /, so try this instead:</p>\n\n<pre><code>attribute media = Media{\nsource: \"{__DIR__}sound/hormpipe.mp3\"}\n</code></pre>\n\n<p>EDIT: I did some digging, and apparently, the source of a Media object has to be either a remote URL, or an absolute file path, since media files aren't allowed in JARs (something I hope gets changed with future releases, since I really like JavaFX and want to be able to make desktop apps with it). See: <a href=\"http://javafx.com/faq/#5.3\" rel=\"nofollow noreferrer\">JavaFX FAQs</a>.</p>\n" }, { "answer_id": 20890384, "author": "daevon", "author_id": 2624587, "author_profile": "https://Stackoverflow.com/users/2624587", "pm_score": 0, "selected": false, "text": "<p>This worked for me:</p>\n\n<pre><code>MediaPlayer audio = new MediaPlayer(\n new Media(\n new File(\"file.mp3\").toURI().toString()));\n</code></pre>\n\n<p>Source file should be in project's root directory (not src, not dist).</p>\n" }, { "answer_id": 39737525, "author": "ivanivan", "author_id": 6867430, "author_profile": "https://Stackoverflow.com/users/6867430", "pm_score": 0, "selected": false, "text": "<p>OK, having used this question to get MP3 audio working (kinda), I've learned the following (not much).</p>\n\n<p>1) Audio for compressed formats is very platform dependent. My continually upgraded Mint 17.1->18 machine plays mp3 fine using Media and MediaPlayer. Fresh installs of Mint 18 won't (with the dev tools).</p>\n\n<p>So use .wav files.</p>\n\n<pre><code>Media sound=new Media(new File(\"noises/roll.wav\").toURI().toString());\nMediaPlayer mediaPlayer=new MediaPlayer(sound);\nmediaPlayer.play();\n</code></pre>\n\n<p>2) One of the things you need to be aware of with Media/MediaPlayer is that in order to play multiple times (repeatedly or all at once ie, on a button press/whatever in a game) you have to spawn N number of MediaPlayer objects, and each one will play once and then stop. </p>\n\n<p>So use javafx.scene.media.AudioClip </p>\n\n<pre><code>AudioClip soundMyNoise = new AudioClip(new File(\"noises/roll.wav\").toURI().toString());\nsoundMyNoise.play();\n</code></pre>\n\n<p>AudioClip also has its issues, which include storing the raw audio data in RAM all at once instead of buffering. So there is the possibility of excessive memory use. </p>\n\n<p>No matter which method you end up going with, one thing to be critically aware of was mentioned by <strong>daevon</strong> earlier - the path issue. With NetBeans, you have NetBeansProjects/yourproject/src/yourproject/foo.java. The sounds in the example above go in NetBeansProjects/yourproject/noises/roll.wav</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514822/" ]
I'm experimenting with JavaFX making a small game. I want to add sound. How? I tried `MediaPlayer` with `media` defined with relative `source` attribute like: ``` attribute media = Media{ source: "{__FILE__}/sound/hormpipe.mp3" } attribute player = MediaPlayer{ autoPlay:true media:media } ``` It doesn't play. I get > > `FX Media Object caught Exception com.sun.media.jmc.MediaUnavailableException: Media unavailable: file: ... Sound.class/sound/hormpipe.mp3` > > >
Just a guess, but is that file "hornpipe.mp3" and not "hormpipe.mp3" (with an m)?
241,470
<p>I am designing a simple internal framework for handling time series data. Given that LINQ is my current toy hammer, I want to hit everything with it.</p> <p>I want to implement methods in class TimeSeries (Select(), Where() and so on) so that I can use LINQ syntax to handle time series data</p> <p>Some things are straight forward, e.g. (from x in A select x+10), giving a new time series.</p> <p>What is the best syntax design for combining two or more time series? (from a in A from b in B select a+b) is not great, since it expresses a nested loop. Maybe some join? This should correspond to join on the implicit time variable. (What I have in mind corresponds to the lisp 'zip' function)</p> <hr> <p><strong>EDIT:</strong> <em>Some clarification is necessary.</em></p> <p>A time series is a kind of function depending on time, e.g. stock quotes. A combination of time series could be the difference between two stock prices, as a function of time.</p> <pre><code>Stock1.MyJoin(Stock2, (a,b)=&gt;a-b) </code></pre> <p>is possible, but can this be expressed neatly using some LINQ syntax? I am expecting to implement LINQ methods in <code>class MyTimeSeries</code> myself.</p>
[ { "answer_id": 241478, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p><code>Union</code> sounds like the right way to go - no query expression support, but I think it expresses what you mean.</p>\n\n<p>You might be interested in looking at the Range-based classes in <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"nofollow noreferrer\">MiscUtil</a> which can be nicely used for times. Combined with a bit of extension method fun, you can do:</p>\n\n<pre><code>foreach (DateTime day in 19.June(1976).To(DateTime.Today).Step(1.Day()))\n{\n Console.WriteLine(\"I'm alive!\");\n}\n</code></pre>\n\n<p>I'm not suggesting this should replace whatever you're doing, just that you might be able to take some ideas to make it even neater. Feel free to contribute back, too :)</p>\n" }, { "answer_id": 241563, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 1, "selected": true, "text": "<p>If I'm understanding the question correctly, you want to join multiple sequences based on their position within the sequence?</p>\n\n<p>There isn't anything in the <code>System.Linq.Enumerable</code> class to do this as both the <code>Join</code> and <code>GroupJoin</code> methods are based on join keys. However, by coincidence I wrote a <code>PositionalJoin</code> method for just this purpose a few days back, used as in your example:</p>\n\n<pre><code>sequenceA.PositionalJoin(sequenceB, (a, b) =&gt; new { a, b });\n</code></pre>\n\n<p>The semantics of the method shown below is that it does not require the sequences to be of equal length, but it would be trivial to modify it to require this. I also commented out where the argument checking should be as it was using our internal helper classes.</p>\n\n<pre><code>public static IEnumerable&lt;TResult&gt; PositionalJoin&lt;T1, T2, TResult&gt;(\n this IEnumerable&lt;T1&gt; source1, \n IEnumerable&lt;T2&gt; source2, \n Func&lt;T1, T2, int, TResult&gt; selector)\n{\n // argument checking here\n return PositionalJoinIterator(source1, source2, selector);\n}\n\nprivate static IEnumerable&lt;TResult&gt; PositionalJoinIterator&lt;T1, T2, TResult&gt;(\n IEnumerable&lt;T1&gt; source1, \n IEnumerable&lt;T2&gt; source2, \n Func&lt;T1, T2, TResult&gt; selector)\n{\n using (var enumerator1 = source1.GetEnumerator())\n using (var enumerator2 = source2.GetEnumerator())\n {\n bool gotItem;\n do\n {\n gotItem = false;\n\n T1 item1;\n if (enumerator1.MoveNext())\n {\n item1 = enumerator1.Current;\n gotItem = true;\n }\n else\n {\n item1 = default(T1);\n }\n\n T2 item2;\n if (enumerator2.MoveNext())\n {\n item2 = enumerator2.Current;\n gotItem = true;\n }\n else\n {\n item2 = default(T2);\n }\n\n if (gotItem)\n {\n yield return selector(item1, item2);\n }\n }\n while (gotItem);\n }\n}\n</code></pre>\n\n<p>Not sure if this is exactly what you're looking for, but hopefully of some help.</p>\n" }, { "answer_id": 241590, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 1, "selected": false, "text": "<p>From my <a href=\"http://www.codeplex.com/nextension\" rel=\"nofollow noreferrer\">NExtension</a> project:</p>\n\n<pre><code>public static IEnumerable&lt;TResult&gt; Zip&lt;T1, T2, TResult&gt;(\n this IEnumerable&lt;T1&gt; source1, \n IEnumerable&lt;T2&gt; source2, \n Func&lt;T1, T2, TResult&gt; combine)\n{\n if (source1 == null)\n throw new ArgumentNullException(\"source1\");\n if (source2 == null)\n throw new ArgumentNullException(\"source2\");\n if (combine == null)\n throw new ArgumentNullException(\"combine\");\n\n IEnumerator&lt;T1&gt; data1 = source1.GetEnumerator();\n IEnumerator&lt;T2&gt; data2 = source2.GetEnumerator();\n while (data1.MoveNext() &amp;&amp; data2.MoveNext())\n {\n yield return combine(data1.Current, data2.Current);\n }\n}\n</code></pre>\n\n<p>Syntax is:</p>\n\n<pre><code>Stock1.Zip(Stock2, (a,b)=&gt;a-b)\n</code></pre>\n" }, { "answer_id": 241600, "author": "endian", "author_id": 25462, "author_profile": "https://Stackoverflow.com/users/25462", "pm_score": 1, "selected": false, "text": "<p>Bjarke, take a look at NEsper, it's an open source Complex Event Processing app that amongst other things does SQL-like time series queries. You can either learn how they've done it, or perhaps even leverage their code to achieve your goal. link here <a href=\"http://esper.codehaus.org/about/nesper/nesper.html\" rel=\"nofollow noreferrer\">http://esper.codehaus.org/about/nesper/nesper.html</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31890/" ]
I am designing a simple internal framework for handling time series data. Given that LINQ is my current toy hammer, I want to hit everything with it. I want to implement methods in class TimeSeries (Select(), Where() and so on) so that I can use LINQ syntax to handle time series data Some things are straight forward, e.g. (from x in A select x+10), giving a new time series. What is the best syntax design for combining two or more time series? (from a in A from b in B select a+b) is not great, since it expresses a nested loop. Maybe some join? This should correspond to join on the implicit time variable. (What I have in mind corresponds to the lisp 'zip' function) --- **EDIT:** *Some clarification is necessary.* A time series is a kind of function depending on time, e.g. stock quotes. A combination of time series could be the difference between two stock prices, as a function of time. ``` Stock1.MyJoin(Stock2, (a,b)=>a-b) ``` is possible, but can this be expressed neatly using some LINQ syntax? I am expecting to implement LINQ methods in `class MyTimeSeries` myself.
If I'm understanding the question correctly, you want to join multiple sequences based on their position within the sequence? There isn't anything in the `System.Linq.Enumerable` class to do this as both the `Join` and `GroupJoin` methods are based on join keys. However, by coincidence I wrote a `PositionalJoin` method for just this purpose a few days back, used as in your example: ``` sequenceA.PositionalJoin(sequenceB, (a, b) => new { a, b }); ``` The semantics of the method shown below is that it does not require the sequences to be of equal length, but it would be trivial to modify it to require this. I also commented out where the argument checking should be as it was using our internal helper classes. ``` public static IEnumerable<TResult> PositionalJoin<T1, T2, TResult>( this IEnumerable<T1> source1, IEnumerable<T2> source2, Func<T1, T2, int, TResult> selector) { // argument checking here return PositionalJoinIterator(source1, source2, selector); } private static IEnumerable<TResult> PositionalJoinIterator<T1, T2, TResult>( IEnumerable<T1> source1, IEnumerable<T2> source2, Func<T1, T2, TResult> selector) { using (var enumerator1 = source1.GetEnumerator()) using (var enumerator2 = source2.GetEnumerator()) { bool gotItem; do { gotItem = false; T1 item1; if (enumerator1.MoveNext()) { item1 = enumerator1.Current; gotItem = true; } else { item1 = default(T1); } T2 item2; if (enumerator2.MoveNext()) { item2 = enumerator2.Current; gotItem = true; } else { item2 = default(T2); } if (gotItem) { yield return selector(item1, item2); } } while (gotItem); } } ``` Not sure if this is exactly what you're looking for, but hopefully of some help.
241,512
<p>My HTML is as follows:</p> <pre><code>&lt;ul id="nav"&gt; &lt;li&gt;&lt;a href="./"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/About"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/Contact"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And my css:</p> <pre><code>#nav { display: inline; } </code></pre> <p>However the whitespace between the li's shows up. I can remove the whitespace by collapsing them like so:</p> <pre><code>&lt;ul id="nav"&gt; &lt;li&gt;&lt;a href="./"&gt;Home&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="/About"&gt;About&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="/Contact"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>But this is being maintained largely by hand and I was wondering if there was a cleaner way of doing it.</p>
[ { "answer_id": 241523, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 6, "selected": true, "text": "<p>Several options here, first I'll give you my normal practice when creating inline lists:</p>\n\n<pre><code>&lt;ul id=\"navigation\"&gt;\n &lt;li&gt;&lt;a href=\"#\" title=\"\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\" title=\"\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\" title=\"\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>Then the CSS to make it function as you intend:</p>\n\n<pre><code>#navigation li \n {\n display: inline;\n list-style: none;\n }\n#navigation li a, #navigation li a:link, #navigation li a:visited\n {\n display: block;\n padding: 2px 5px 2px 5px;\n float: left;\n margin: 0 5px 0 0;\n }\n</code></pre>\n\n<p>Obviously I left out the hover and active sets, but this creates a nice block level navigation, and is a very common method for doing this while still keeping with standards. /* remember to tweak to your liking, add color to the background, et cetera */</p>\n\n<p>If you would like to keep it just with text and just inline, no block elements I believe you'd want to add:</p>\n\n<pre><code> margin: 0 5px 0 0; /* that's, top 0, right 5px, bottom 0, left 0 */\n</code></pre>\n\n<p>Realizing you would like to REMOVE the whitespace, just adjust the margins/padding accordingly.</p>\n" }, { "answer_id": 3143465, "author": "J. Holmes", "author_id": 373378, "author_profile": "https://Stackoverflow.com/users/373378", "pm_score": 4, "selected": false, "text": "<p>What you really want is the CSS3 <a href=\"http://www.w3.org/TR/css3-text/#white-space-collapse\" rel=\"noreferrer\">white-space-collapse: discard</a>. But I'm not sure if any browsers actually support that property.</p>\n\n<p>A couple alternative solutions is to let the tailing end of a tag consume the whitespace. For example:</p>\n\n<pre><code>&lt;ul id=\"nav\"\n &gt;&lt;li&gt;&lt;a href=\"./\"&gt;Home&lt;/a&gt;&lt;/li\n &gt;&lt;li&gt;&lt;a href=\"/About\"&gt;About&lt;/a&gt;&lt;/li\n &gt;&lt;li&gt;&lt;a href=\"/Contact\"&gt;Contact&lt;/a&gt;&lt;/li\n&gt;&lt;/ul&gt;\n</code></pre>\n\n<p>Another thing I've seen done is to use HTML comments to consume whitespace</p>\n\n<pre><code>&lt;ul id=\"nav\"&gt;&lt;!--\n --&gt;&lt;li&gt;&lt;a href=\"./\"&gt;Home&lt;/a&gt;&lt;/li&gt;&lt;!--\n --&gt;&lt;li&gt;&lt;a href=\"/About\"&gt;About&lt;/a&gt;&lt;/li&gt;&lt;!--\n --&gt;&lt;li&gt;&lt;a href=\"/Contact\"&gt;Contact&lt;/a&gt;&lt;/li&gt;&lt;!--\n--&gt;&lt;/ul&gt;\n</code></pre>\n\n<p>See thismat's solution if you are okay using floats, and depending on the requirements you might need to add a trailing <code>&lt;li&gt;</code> that is set to <code>clear: both;</code>.</p>\n\n<p>But the CSS3 property is probably the <em>best</em> theoretical way.</p>\n" }, { "answer_id": 3617275, "author": "Marius Schulz", "author_id": 362634, "author_profile": "https://Stackoverflow.com/users/362634", "pm_score": 5, "selected": false, "text": "<p>Another useful way to eliminate the whitespace is to set the list's <code>font-size</code> property to <code>0</code> and the list elements' one back to the required size.</p>\n" }, { "answer_id": 4849282, "author": "guimihanui", "author_id": 596609, "author_profile": "https://Stackoverflow.com/users/596609", "pm_score": 3, "selected": false, "text": "<p>Adopt non-XML-based HTML and omit <code>&lt;/li&gt;</code>.</p>\n\n<pre><code>&lt;ul id=\"nav\"&gt;\n &lt;li&gt;&lt;a href=\"./\"&gt;Home&lt;/a&gt;\n &lt;li&gt;&lt;a href=\"/About\"&gt;About&lt;/a&gt;\n &lt;li&gt;&lt;a href=\"/Contact\"&gt;Contact&lt;/a&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>Then set the display property of the items to inline-block instead of inline.</p>\n\n<pre><code>#nav li {\n display: inline-block;\n /display: inline; /* for IE 6 and IE 7 */\n /zoom: 1; /* for IE 6 and IE 7 */\n}\n</code></pre>\n" }, { "answer_id": 6958307, "author": "Louisa", "author_id": 880805, "author_profile": "https://Stackoverflow.com/users/880805", "pm_score": 3, "selected": false, "text": "<p>A better solution for list items is to use:</p>\n\n<pre><code>#nav li{float:left; width:auto;}\n</code></pre>\n\n<p>Has exactly the same visual effect without the headache.</p>\n" }, { "answer_id": 14598125, "author": "user2024227", "author_id": 2024227, "author_profile": "https://Stackoverflow.com/users/2024227", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;style&gt;\nul li, ul li:before,ul li:after{display:inline; content:' '; }\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;li&gt;three&lt;/li&gt;&lt;/ul&gt;\n&lt;ul&gt;\n &lt;li&gt;one&lt;/li&gt;\n &lt;li&gt;two&lt;/li&gt;\n &lt;li&gt;three&lt;/li&gt;\n&lt;/ul&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 16908678, "author": "user764728", "author_id": 764728, "author_profile": "https://Stackoverflow.com/users/764728", "pm_score": 3, "selected": false, "text": "<p>The problem is the font size in the UL. Set it to 0 and it will disappear, but you don't want you actual text to be set so small, so then set your LI font size to whatever you want it to be.</p>\n\n<pre><code>&lt;ul style=\"font-size:0px;\"&gt;\n&lt;li style=\"font-size:12px;\"&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 26307400, "author": "micha", "author_id": 1725482, "author_profile": "https://Stackoverflow.com/users/1725482", "pm_score": 1, "selected": false, "text": "<p>I had the same Problem and none of the above solutions could fix it. But I found out this works for me:</p>\n\n<p>Instead of this:</p>\n\n<pre><code>&lt;ul id=\"nav\"&gt;\n &lt;li&gt;&lt;a href=\"./\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/About\"&gt;About&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/Contact\"&gt;Contact&lt;/a&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>build your html code like this (whitespace before and after the link text): </p>\n\n<pre><code>&lt;ul id=\"nav\"&gt;\n &lt;li&gt;&lt;a href=\"./\"&gt; Home &lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/About\"&gt; About &lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/Contact\"&gt; Contact &lt;/a&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My HTML is as follows: ``` <ul id="nav"> <li><a href="./">Home</a></li> <li><a href="/About">About</a></li> <li><a href="/Contact">Contact</a></li> </ul> ``` And my css: ``` #nav { display: inline; } ``` However the whitespace between the li's shows up. I can remove the whitespace by collapsing them like so: ``` <ul id="nav"> <li><a href="./">Home</a></li><li><a href="/About">About</a></li><li><a href="/Contact">Contact</a></li> </ul> ``` But this is being maintained largely by hand and I was wondering if there was a cleaner way of doing it.
Several options here, first I'll give you my normal practice when creating inline lists: ``` <ul id="navigation"> <li><a href="#" title="">Home</a></li> <li><a href="#" title="">Home</a></li> <li><a href="#" title="">Home</a></li> </ul> ``` Then the CSS to make it function as you intend: ``` #navigation li { display: inline; list-style: none; } #navigation li a, #navigation li a:link, #navigation li a:visited { display: block; padding: 2px 5px 2px 5px; float: left; margin: 0 5px 0 0; } ``` Obviously I left out the hover and active sets, but this creates a nice block level navigation, and is a very common method for doing this while still keeping with standards. /\* remember to tweak to your liking, add color to the background, et cetera \*/ If you would like to keep it just with text and just inline, no block elements I believe you'd want to add: ``` margin: 0 5px 0 0; /* that's, top 0, right 5px, bottom 0, left 0 */ ``` Realizing you would like to REMOVE the whitespace, just adjust the margins/padding accordingly.
241,526
<p>I've been tasked with build an accessible RSS feed for my company's job listings. I already have an RSS feed from our recruiting partner; so I'm transforming their RSS XML to our own proxy RSS feed to add additional data as well limit the number of items in the feed so we list on the latest jobs.</p> <p>The RSS validates via feedvalidator.org (with warnings); but the problem is this. Unfortunately, no matter how many times I tell them not to; my company's HR team directly copies and pastes their Word documents into our Recruiting partners CMS when inserting new job listings, leaving WordML in my feed. I believe this WordML is causing issues with Feedburner's BrowserFriendly feature; which we want to show up to make it easier for people to subscribe. Therefore, I need to remove the WordML markup in the feed.</p> <p>Anybody have experience doing this? Can anyone point me to a good solution to this problem?</p> <p>Preferably; I'd like to be pointed to a solution in .Net (VB or C# is fine) and/or XSL.</p> <p>Any advice on this is greatly appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 241562, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I would do something like this:</p>\n\n<pre><code>char[] charToRemove = { (char)8217, (char)8216, (char)8220, (char)8221, (char)8211 };\nchar[] charToAdd = { (char)39, (char)39, (char)34, (char)34, '-' };\nstring cleanedStr = \"Your WordML filled Feed Text.\";\n\nfor (int i = 0; i &lt; charToRemove.Length; i++)\n{\n cleanedStr = cleanedStr.Replace(charToRemove.GetValue(i).ToString(), charToAdd.GetValue(i).ToString());\n}\n</code></pre>\n\n<p>This would look for the characters in reference, (Which are the Word special characters that mess up everything and replaces them with their ASCII equivelents.</p>\n" }, { "answer_id": 242708, "author": "d4nt", "author_id": 1039, "author_profile": "https://Stackoverflow.com/users/1039", "pm_score": 0, "selected": false, "text": "<p>Jeff Attwood blogged about how to do this a while ago. His post contains some c# code that will clean the WordML.</p>\n\n<p><a href=\"http://www.codinghorror.com/blog/archives/000485.html\" rel=\"nofollow noreferrer\">http://www.codinghorror.com/blog/archives/000485.html</a></p>\n" }, { "answer_id": 243423, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 2, "selected": true, "text": "<p>I haven't yet worked with WordML, but assuming that its elements are in a different namespace from RSS, it should be quite simple to do with XSLT.</p>\n\n<p>Start with a basic identity transform (a stylesheet that add all nodes from the input doc \"as is\" to the output tree). You need these two templates:</p>\n\n<pre><code> &lt;!-- Copy all elements, and recur on their child nodes. --&gt;\n &lt;xsl:template match=\"*\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"@*\"/&gt;\n &lt;xsl:apply-templates/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n &lt;!-- Copy all non-element nodes. --&gt;\n &lt;xsl:template match=\"@*|text()|comment()|processing-instruction()\"&gt;\n &lt;xsl:copy/&gt;\n &lt;/xsl:template&gt;\n</code></pre>\n\n<p>A transformation using a stylesheet containing just the above two templates would exactly reproduce its input document on output, modulo those things that standards-compliant XML processors are permitted to change, such as entity replacement.</p>\n\n<p>Now, add in a template that matches any element in the WordML namespace. Let's give it the namespace prefix 'wml' for the purposes of this example:</p>\n\n<pre><code> &lt;!-- Do not copy WordML elements or their attributes to the \n output tree; just recur on child nodes. --&gt;\n &lt;xsl:template match=\"wml:*\"&gt;\n &lt;xsl:apply-templates/&gt;\n &lt;/xsl:template&gt;\n</code></pre>\n\n<p>The beginning and end of the stylesheet are left as an exercise for the coder.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10922/" ]
I've been tasked with build an accessible RSS feed for my company's job listings. I already have an RSS feed from our recruiting partner; so I'm transforming their RSS XML to our own proxy RSS feed to add additional data as well limit the number of items in the feed so we list on the latest jobs. The RSS validates via feedvalidator.org (with warnings); but the problem is this. Unfortunately, no matter how many times I tell them not to; my company's HR team directly copies and pastes their Word documents into our Recruiting partners CMS when inserting new job listings, leaving WordML in my feed. I believe this WordML is causing issues with Feedburner's BrowserFriendly feature; which we want to show up to make it easier for people to subscribe. Therefore, I need to remove the WordML markup in the feed. Anybody have experience doing this? Can anyone point me to a good solution to this problem? Preferably; I'd like to be pointed to a solution in .Net (VB or C# is fine) and/or XSL. Any advice on this is greatly appreciated. Thanks.
I haven't yet worked with WordML, but assuming that its elements are in a different namespace from RSS, it should be quite simple to do with XSLT. Start with a basic identity transform (a stylesheet that add all nodes from the input doc "as is" to the output tree). You need these two templates: ``` <!-- Copy all elements, and recur on their child nodes. --> <xsl:template match="*"> <xsl:copy> <xsl:apply-templates select="@*"/> <xsl:apply-templates/> </xsl:copy> </xsl:template> <!-- Copy all non-element nodes. --> <xsl:template match="@*|text()|comment()|processing-instruction()"> <xsl:copy/> </xsl:template> ``` A transformation using a stylesheet containing just the above two templates would exactly reproduce its input document on output, modulo those things that standards-compliant XML processors are permitted to change, such as entity replacement. Now, add in a template that matches any element in the WordML namespace. Let's give it the namespace prefix 'wml' for the purposes of this example: ``` <!-- Do not copy WordML elements or their attributes to the output tree; just recur on child nodes. --> <xsl:template match="wml:*"> <xsl:apply-templates/> </xsl:template> ``` The beginning and end of the stylesheet are left as an exercise for the coder.
241,533
<p>I want to write a program that would print every combination of a set of variables to a text file, creating a word list. Each answer should be written on a separate line and write all of the results for 1 digit, 2 digits, and 3 digits to a single text file.</p> <p>Is there a simple way I can write a python program that can accomplish this? Here is an example of the output I am expecting when printing all the binary number combinations possible for 1, 2, and 3 digits:</p> <pre><code>Output: 0 1 00 01 10 11 000 001 010 011 100 101 110 111 </code></pre>
[ { "answer_id": 241542, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 2, "selected": false, "text": "<p>It shouldn't be too hard in most languages. Does the following pseudo-code help?</p>\n\n<pre><code>for(int i=0; i &lt; 2^digits; i++)\n{\n WriteLine(ToBinaryString(i));\n}\n</code></pre>\n" }, { "answer_id": 241557, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 2, "selected": false, "text": "<pre><code># Given two lists of strings, return a list of all ways to concatenate\n# one from each.\ndef combos(xs, ys):\n return [x + y for x in xs for y in ys]\n\ndigits = ['0', '1']\nfor c in combos(digits, combos(digits, digits)):\n print c\n\n#. 000\n#. 001\n#. 010\n#. 011\n#. 100\n#. 101\n#. 110\n#. 111\n</code></pre>\n" }, { "answer_id": 241577, "author": "Andrew Walker", "author_id": 2246, "author_profile": "https://Stackoverflow.com/users/2246", "pm_score": 2, "selected": false, "text": "<p>A basic function to produce all the permutations of a list is given below. In this approach, permutations are created lazily by using generators.</p>\n\n<pre><code>def perms(seq):\n if seq == []:\n yield []\n else:\n res = []\n for index,item in enumerate(seq):\n rest = seq[:index] + seq[index+1:]\n for restperm in perms(rest):\n yield [item] + restperm\n\nalist = [1,1,0]\nfor permuation in perms(alist):\n print permuation\n</code></pre>\n" }, { "answer_id": 242141, "author": "zvoase", "author_id": 31600, "author_profile": "https://Stackoverflow.com/users/31600", "pm_score": 3, "selected": true, "text": "<p>A naïve solution which solves the problem and is general enough for any application you might have is this:</p>\n\n<pre><code>def combinations(words, length):\n if length == 0:\n return []\n result = [[word] for word in words]\n while length &gt; 1:\n new_result = []\n for combo in result:\n new_result.extend(combo + [word] for word in words)\n result = new_result[:]\n length -= 1\n return result\n</code></pre>\n\n<p>Basically, this gradually builds up a tree in memory of all the combinations, and then returns them. It is memory-intensive, however, and so is impractical for large-scale combinations.</p>\n\n<p>Another solution for the problem is, indeed, to use counting, but then to transform the numbers generated into a list of words from the wordlist. To do so, we first need a function (called <code>number_to_list()</code>):</p>\n\n<pre><code>def number_to_list(number, words):\n list_out = []\n while number:\n list_out = [number % len(words)] + list_out\n number = number // len(words)\n return [words[n] for n in list_out]\n</code></pre>\n\n<p>This is, in fact, a system for converting decimal numbers to other bases. We then write the counting function; this is relatively simple, and will make up the core of the application:</p>\n\n<pre><code>def combinations(words, length):\n numbers = xrange(len(words)**length)\n for number in numbers:\n combo = number_to_list(number, words)\n if len(combo) &lt; length:\n combo = [words[0]] * (length - len(combo)) + combo\n yield combo\n</code></pre>\n\n<p>This is a Python generator; making it a generator allows it to use up less RAM. There is a little work to be done after turning the number into a list of words; this is because these lists will need padding so that they are at the requested length. It would be used like this:</p>\n\n<pre><code>&gt;&gt;&gt; list(combinations('01', 3))\n[['0', '0', '0'], ['0', '0', '1'],\n['0', '1', '0'], ['0', '1', '1'],\n['1', '0', '0'], ['1', '0', '1'],\n['1', '1', '0'], ['1', '1', '1']]\n</code></pre>\n\n<p>As you can see, you get back a list of lists. Each of these sub-lists contains a sequence of the original words; you might then do something like <code>map(''.join, list(combinations('01', 3)))</code> to retrieve the following result:</p>\n\n<pre><code>['000', '001', '010', '011', '100', '101', '110', '111']\n</code></pre>\n\n<p>You could then write this to disk; a better idea, however, would be to use the built-in optimizations that generators have and do something like this:</p>\n\n<pre><code>fileout = open('filename.txt', 'w')\nfileout.writelines(\n ''.join(combo) for combo in combinations('01', 3))\nfileout.close()\n</code></pre>\n\n<p>This will only use as much RAM as necessary (enough to store one combination). I hope this helps.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to write a program that would print every combination of a set of variables to a text file, creating a word list. Each answer should be written on a separate line and write all of the results for 1 digit, 2 digits, and 3 digits to a single text file. Is there a simple way I can write a python program that can accomplish this? Here is an example of the output I am expecting when printing all the binary number combinations possible for 1, 2, and 3 digits: ``` Output: 0 1 00 01 10 11 000 001 010 011 100 101 110 111 ```
A naïve solution which solves the problem and is general enough for any application you might have is this: ``` def combinations(words, length): if length == 0: return [] result = [[word] for word in words] while length > 1: new_result = [] for combo in result: new_result.extend(combo + [word] for word in words) result = new_result[:] length -= 1 return result ``` Basically, this gradually builds up a tree in memory of all the combinations, and then returns them. It is memory-intensive, however, and so is impractical for large-scale combinations. Another solution for the problem is, indeed, to use counting, but then to transform the numbers generated into a list of words from the wordlist. To do so, we first need a function (called `number_to_list()`): ``` def number_to_list(number, words): list_out = [] while number: list_out = [number % len(words)] + list_out number = number // len(words) return [words[n] for n in list_out] ``` This is, in fact, a system for converting decimal numbers to other bases. We then write the counting function; this is relatively simple, and will make up the core of the application: ``` def combinations(words, length): numbers = xrange(len(words)**length) for number in numbers: combo = number_to_list(number, words) if len(combo) < length: combo = [words[0]] * (length - len(combo)) + combo yield combo ``` This is a Python generator; making it a generator allows it to use up less RAM. There is a little work to be done after turning the number into a list of words; this is because these lists will need padding so that they are at the requested length. It would be used like this: ``` >>> list(combinations('01', 3)) [['0', '0', '0'], ['0', '0', '1'], ['0', '1', '0'], ['0', '1', '1'], ['1', '0', '0'], ['1', '0', '1'], ['1', '1', '0'], ['1', '1', '1']] ``` As you can see, you get back a list of lists. Each of these sub-lists contains a sequence of the original words; you might then do something like `map(''.join, list(combinations('01', 3)))` to retrieve the following result: ``` ['000', '001', '010', '011', '100', '101', '110', '111'] ``` You could then write this to disk; a better idea, however, would be to use the built-in optimizations that generators have and do something like this: ``` fileout = open('filename.txt', 'w') fileout.writelines( ''.join(combo) for combo in combinations('01', 3)) fileout.close() ``` This will only use as much RAM as necessary (enough to store one combination). I hope this helps.
241,539
<p>I am extending a class defined in a library which I cannot change:</p> <pre><code>public class Parent { public void init(Map properties) { ... } } </code></pre> <p>If I am defining a class 'Child' that extends Parent and I am using Java 6 with generics, what is the best way to override the init method without getting unchecked warnings?</p> <pre><code>public class Child extends Parent { // warning: Map is a raw type. References to generic type Map&lt;K,V&gt; should be parameterized public void init(Map properties) { } } </code></pre> <p>If I add generic parameters, I get:</p> <pre><code> // error: The method init(Map&lt;Object,Object&gt;) of type Child has the same erasure as init(Map) of type Parent but does not override it public void init(Map&lt;Object,Object&gt;) { ... } // same error public void init(Map&lt;? extends Object,? extends Object&gt;) { ... } // same error public void init(Map&lt;?,?&gt;) { ... } </code></pre> <p>This error occurs regardless of whether I use a specific type, a bounded wildcard, or an unbounded wildcard. Is there a correct or idiomatic way to override a non-generic method without warnings, and without using @SuppressWarnings("unchecked")?</p>
[ { "answer_id": 241921, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 2, "selected": false, "text": "<p>Short answer: no way to do that.</p>\n\n<p>Unsatisfying answer: disable the (specific) warnings in your IDE/build.xml.</p>\n\n<p>If you cannot change the library, alas, you have to stick with non-generic methods.</p>\n\n<p>The problem is that, despite after type erasure both init() have the same signature, they may in fact be different methods -- or the same(*). Compiler cannot tell should it do override or overload, so it's prohibited.</p>\n\n<p>(*)\nSuppose the library developer meant init(Map&lt;String,Integer&gt;). Now you are implementing init(Map&lt;String,String&gt;). This is overloading, and two methods should exist in the vtable of Child class.</p>\n\n<p>But what if the library developer meant init(Map&lt;String,String&gt;)? Then it's overriding, and your method should <strong>replace</strong> original init in Child class, and there would be only one method in the vtable of Child.</p>\n\n<p>P.S. I hate how Generics implemented in Java :-(</p>\n" }, { "answer_id": 241933, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 5, "selected": true, "text": "<p>Yes, you have to declare the overriding method with the same signature as in the parent class, without adding any generics info.</p>\n\n<p>I think your best bet is to add the <code>@SuppressWarnings(\"unchecked\")</code> annotation to the raw-type parameter, not the method, so you won't squelch other generics warnings you might have in your own code.</p>\n" }, { "answer_id": 244199, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 0, "selected": false, "text": "<p>You have to declare the method with the same signature as the parent, and therefore you will get warnings when you compile. You can suppress them with @SuppressWarnings(\"unchecked\")</p>\n\n<p>The reason why there is no way to get rid of this is that the warnings are there to let you know that it's possible to create Collections with invalid types in them. The warnings should only go away when all code that might allow that has been removed. Since you are inheriting from a non-generic class it will always be possible to create a Collection with invalid contents. </p>\n" }, { "answer_id": 5822686, "author": "Zemian", "author_id": 269637, "author_profile": "https://Stackoverflow.com/users/269637", "pm_score": 2, "selected": false, "text": "<p>I think above answer meant to say @SuppressWarnings(\"rawtypes\") instead.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16399/" ]
I am extending a class defined in a library which I cannot change: ``` public class Parent { public void init(Map properties) { ... } } ``` If I am defining a class 'Child' that extends Parent and I am using Java 6 with generics, what is the best way to override the init method without getting unchecked warnings? ``` public class Child extends Parent { // warning: Map is a raw type. References to generic type Map<K,V> should be parameterized public void init(Map properties) { } } ``` If I add generic parameters, I get: ``` // error: The method init(Map<Object,Object>) of type Child has the same erasure as init(Map) of type Parent but does not override it public void init(Map<Object,Object>) { ... } // same error public void init(Map<? extends Object,? extends Object>) { ... } // same error public void init(Map<?,?>) { ... } ``` This error occurs regardless of whether I use a specific type, a bounded wildcard, or an unbounded wildcard. Is there a correct or idiomatic way to override a non-generic method without warnings, and without using @SuppressWarnings("unchecked")?
Yes, you have to declare the overriding method with the same signature as in the parent class, without adding any generics info. I think your best bet is to add the `@SuppressWarnings("unchecked")` annotation to the raw-type parameter, not the method, so you won't squelch other generics warnings you might have in your own code.
241,550
<p>What are some good jQuery Resources along with some gotchas when using it with ASP.Net?</p>
[ { "answer_id": 241588, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 3, "selected": false, "text": "<p>ASP.Net's autogenerated id's make using jQuery's selector syntax somewhat difficult.</p>\n\n<p>Two easy ways around this problem:</p>\n\n<ul>\n<li>Search for objects using css class instead of id</li>\n<li>You can weed out the uniqueid garbage with: <code>$('[id$=myid]')</code></li>\n</ul>\n" }, { "answer_id": 241623, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.west-wind.com/Weblog/\" rel=\"nofollow noreferrer\">Rick Strahl's Blog</a> is a good place to start. He has quite a few jQuery posts.</p>\n" }, { "answer_id": 241658, "author": "tsimon", "author_id": 1685, "author_profile": "https://Stackoverflow.com/users/1685", "pm_score": 3, "selected": true, "text": "<p>One thing to note is that if you use WebMethods for Ajax, the response values will be returned wrapped in an object named 'd' for security reasons. You will have to unwrap that value, which is usually not a problem, unless you are using a component (such as the jqGrid plugin) that relies upon jquery ajax. To get around that, I just changed the code in the grid that called ajax and inserted a bit of code to unwrap. I do plan on sending in some code to the jquery crew to see if it can be accepted for future versions.</p>\n\n<p>The next thing, as was mentioned previously, is the ids. If you have the time and inclination, I actually subclassed all of the HTML controls to make participating in the NamingContainer optional, like this:</p>\n\n<pre><code>protected override void RenderAttributes(HtmlTextWriter writer) {\n HtmlControlImpl.RenderAttributes(this, writer);\n}\n</code></pre>\n\n<p>And then the helper object (to prevent writing the same code in each object) looks like this:</p>\n\n<pre><code>public static void RenderAttributes(IFormControl cntrl, HtmlTextWriter writer) {\n if (cntrl.ID != null) {\n cntrl.Attributes.Remove(\"id\");\n cntrl.Attributes.Remove(\"name\");\n writer.WriteAttribute(\"id\", cntrl.RenderedId);\n writer.WriteAttribute(\"name\", cntrl.RenderedName);\n }\n cntrl.Attributes.Render(writer);\n HtmlContainerControl containerCntrl = cntrl as HtmlContainerControl;\n if (containerCntrl == null)\n writer.Write(\" /\");\n}\n\npublic static string GetRenderedId(IFormControl cntrl) {\n return cntrl.UseNamingContainer ? cntrl.ClientID : cntrl.ID;\n}\n\npublic static string GetRenderedName(IFormControl cntrl) {\n return cntrl.UseNamingContainer ? cntrl.UniqueID : cntrl.ID;\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26931/" ]
What are some good jQuery Resources along with some gotchas when using it with ASP.Net?
One thing to note is that if you use WebMethods for Ajax, the response values will be returned wrapped in an object named 'd' for security reasons. You will have to unwrap that value, which is usually not a problem, unless you are using a component (such as the jqGrid plugin) that relies upon jquery ajax. To get around that, I just changed the code in the grid that called ajax and inserted a bit of code to unwrap. I do plan on sending in some code to the jquery crew to see if it can be accepted for future versions. The next thing, as was mentioned previously, is the ids. If you have the time and inclination, I actually subclassed all of the HTML controls to make participating in the NamingContainer optional, like this: ``` protected override void RenderAttributes(HtmlTextWriter writer) { HtmlControlImpl.RenderAttributes(this, writer); } ``` And then the helper object (to prevent writing the same code in each object) looks like this: ``` public static void RenderAttributes(IFormControl cntrl, HtmlTextWriter writer) { if (cntrl.ID != null) { cntrl.Attributes.Remove("id"); cntrl.Attributes.Remove("name"); writer.WriteAttribute("id", cntrl.RenderedId); writer.WriteAttribute("name", cntrl.RenderedName); } cntrl.Attributes.Render(writer); HtmlContainerControl containerCntrl = cntrl as HtmlContainerControl; if (containerCntrl == null) writer.Write(" /"); } public static string GetRenderedId(IFormControl cntrl) { return cntrl.UseNamingContainer ? cntrl.ClientID : cntrl.ID; } public static string GetRenderedName(IFormControl cntrl) { return cntrl.UseNamingContainer ? cntrl.UniqueID : cntrl.ID; } ```
241,576
<p>Reporting Services 2000 Standard Edition (currently RTM but hope to have SP2 soon).</p> <p>I have a report which takes in a parameter - PlantID</p> <p>I'd like to email a pdf of this report every month to the 80 different plant managers</p> <p>So I have a table:</p> <pre><code>PlantID ManagerEmail 1 [email protected] 2 [email protected] 3 [email protected] </code></pre> <p>I can currently setup a subscription to email a report to multiple users each month (which uses the SQL agent).</p> <p>However I want to specify the input parameter of the report (PlantID) to the recipient of the email (ManagerEmail).</p> <p>Ideas on how to do this? My current thought is to build a C# app which calls the URL of the RS with the correct input parameter in it. Then gets the pdf back, then emails from C#.</p> <p>Many thanks</p>
[ { "answer_id": 241729, "author": "Jared", "author_id": 3442, "author_profile": "https://Stackoverflow.com/users/3442", "pm_score": 0, "selected": false, "text": "<p>That would be my first thought on how to do it also.</p>\n\n<p>You might also be able to set up a scheduled stored proc to execute it for you, but that's more of a guess than an experienced suggestion.</p>\n" }, { "answer_id": 243208, "author": "Erick B", "author_id": 1373, "author_profile": "https://Stackoverflow.com/users/1373", "pm_score": 2, "selected": true, "text": "<p>A Data-Driven Subscription would be the ideal answer, but I see that Data-Driven Subscriptions are not available in RS 2000 Standard.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/database/DataDrivenSubscriptions.aspx\" rel=\"nofollow noreferrer\">This Article</a> discusses how to use a stored procedure to tweak a Reporting Services subscription and insert your own values into the respective fields.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26086/" ]
Reporting Services 2000 Standard Edition (currently RTM but hope to have SP2 soon). I have a report which takes in a parameter - PlantID I'd like to email a pdf of this report every month to the 80 different plant managers So I have a table: ``` PlantID ManagerEmail 1 [email protected] 2 [email protected] 3 [email protected] ``` I can currently setup a subscription to email a report to multiple users each month (which uses the SQL agent). However I want to specify the input parameter of the report (PlantID) to the recipient of the email (ManagerEmail). Ideas on how to do this? My current thought is to build a C# app which calls the URL of the RS with the correct input parameter in it. Then gets the pdf back, then emails from C#. Many thanks
A Data-Driven Subscription would be the ideal answer, but I see that Data-Driven Subscriptions are not available in RS 2000 Standard. [This Article](http://www.codeproject.com/KB/database/DataDrivenSubscriptions.aspx) discusses how to use a stored procedure to tweak a Reporting Services subscription and insert your own values into the respective fields.
241,579
<p>If I import a library to use a method, would it be worth it? Does importing take up a lot of memory?</p>
[ { "answer_id": 241583, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "<p>Importing such a module is not likely to cost that much memory that you should refrain from it, though in this case probably a simple hash would be just as good. Something like</p>\n\n<pre><code>my %number_for = (\n jan =&gt; 1,\n feb =&gt; 2,\n#etc...\n);\n#...\ndo_something_with($number_for{$month})\n</code></pre>\n" }, { "answer_id": 241589, "author": "Oskar", "author_id": 5472, "author_profile": "https://Stackoverflow.com/users/5472", "pm_score": 6, "selected": true, "text": "<p>borrowed from <a href=\"http://www.perlmonks.org/?node_id=95456\" rel=\"noreferrer\">here</a></p>\n\n<pre><code>%mon2num = qw(\n jan 1 feb 2 mar 3 apr 4 may 5 jun 6\n jul 7 aug 8 sep 9 oct 10 nov 11 dec 12\n);\n</code></pre>\n\n<p>and to retrieve</p>\n\n<pre><code>$mon2num{\"jan\"}\n</code></pre>\n" }, { "answer_id": 241841, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 2, "selected": false, "text": "<pre><code>my %month_num = do { my $i = 1; map {; $_ =&gt; $i++ } (\n qw( jan feb mar apr may jun jul aug sep oct nov dec )\n) };\n</code></pre>\n\n<p>Or maybe:</p>\n\n<pre><code>my %month_num;\n$month_num{ $_ } = 1 + keys %month_num for (\n qw( jan feb mar apr may jun jul aug sep oct nov dec )\n);\n</code></pre>\n\n<p>Or using <a href=\"/questions/38345/elegant-zip-in-perl-5#71895\">a zip function</a>:</p>\n\n<pre><code>my %month_num = do {\n my @month = qw( jan feb mar apr may jun jul aug sep oct nov dec );\n zip2( 1 .. 1+$#month, @month );\n};\n</code></pre>\n" }, { "answer_id": 242025, "author": "Robert Krimen", "author_id": 25171, "author_profile": "https://Stackoverflow.com/users/25171", "pm_score": 4, "selected": false, "text": "<p>Here is yet another way to do it:</p>\n\n<pre><code>my %month; @month{qw/jan feb mar apr may jun\n jul aug sep oct nov dec/} = (1 .. 12);\n</code></pre>\n" }, { "answer_id": 242217, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 1, "selected": false, "text": "<p>It depends on how much date manipulation you're intending to do. At first you're probably better off with hand-rolling it, e.g.</p>\n\n<pre><code>my @months = qw(Jan Feb Mar Apr May Jun\n Jul Aug Sep Oct Nov Dec);\nmy %monthnum = map { $_ =&gt; $months[ $_ - 1 ] } 1..12;\n</code></pre>\n\n<p>(I prefer this approach because it's comparatively obvious what you're doing - you have a list of months, then you map them from 1..12 (the numbers that make sense to a human) to 0..11 (the numbers that make sense to a computer). The performance bottlenecks in your code aren't going to be in this sort of code, they'll be in network, database or disc-accessing code, so concentrate on making your code readable.)</p>\n\n<p>As you start adding to your code, you may find that a lot of this stuff is done already by existing modules, and it might be easier to do some of the simple stuff with e.g. Date::Calc. Or you may find a date/time module more suited to your needs; that's beyond the scope of this question.</p>\n\n<p>Bear in mind also that some modules use autosplit, where only those parts of the module that are needed are loaded. Also, the main performance impact of using a large module isn't necessarily RAM, it's probably more likely to be the time/CPU overhead of loading and compiling it before any of your code has ever run.</p>\n" }, { "answer_id": 243133, "author": "Guillaume Gervais", "author_id": 10687, "author_profile": "https://Stackoverflow.com/users/10687", "pm_score": 0, "selected": false, "text": "<p>Definitely a hash, as suggested by others.</p>\n" }, { "answer_id": 244198, "author": "EvdB", "author_id": 5349, "author_profile": "https://Stackoverflow.com/users/5349", "pm_score": 2, "selected": false, "text": "<p>Hmm - there seem to be plenty of overly complicated ways to do this. For something this simple clarity is key:</p>\n\n<pre><code># create a lookup table of month abbreviations to month numbers\nmy %month_abbr_to_number_lkup = (\n jan =&gt; 1,\n feb =&gt; 2,\n mar =&gt; 3,\n apr =&gt; 4,\n may =&gt; 5,\n jun =&gt; 6,\n jul =&gt; 7,\n aug =&gt; 8,\n sep =&gt; 9,\n oct =&gt; 10,\n nov =&gt; 11,\n dec =&gt; 12,\n);\n\n# get the number for a month\nmy $number = $month_abbr_to_number_lkup{$abbr}\n || die \"Could not convert month abbreviation '$abbr' to a number.\";\n</code></pre>\n" }, { "answer_id": 244873, "author": "F5.", "author_id": 13769, "author_profile": "https://Stackoverflow.com/users/13769", "pm_score": 2, "selected": false, "text": "<p>Note also that hash keys are case sensitive; depending on where your abbreviations are coming from you may want to down-case them first to match the hash keys.</p>\n\n<pre><code>%mon_2_num = (jan =&gt; 1,\n feb =&gt; 2,\n ...);\n\n$month_number = $mon_2_num{lc($month_name_abbrev)};\n</code></pre>\n" }, { "answer_id": 248829, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "<p>Another way to do this using a hash slice:</p>\n\n<pre><code>@month{qw(jan feb mar apr may jun jul aug sep oct nov dec)} = 1..12;\n</code></pre>\n" }, { "answer_id": 63093790, "author": "BitDreamer", "author_id": 4921154, "author_profile": "https://Stackoverflow.com/users/4921154", "pm_score": 0, "selected": false, "text": "<p>I love the chance to do TMTOWTDI on a 12 year old question!</p>\n<p>As somebody else mentioned, the hash values will be case sensitive. So let's use regular expressions instead!</p>\n<pre><code>my $months = '1=January 2=February 3=March 4=April 5=May 6=June 7=July 8=August 9=September 10=October 11=November 12=December';\n\nmy $month = 'jan'; # anything that looks like a month name\nmy $monthnumber = $1 if $months =~ m&quot;(\\d+)=$month&quot;i;\nmy $monthname = $1 if $months =~ m&quot;$monthnumber=(\\S+)&quot;;\nmy $monthabbreviation = $1 if $months =~ m&quot;$monthnumber=(...)&quot;;\n</code></pre>\n<p>Here's an example that shows how flexible this is:</p>\n<pre><code>foreach my $month ('jan', 'Feb','MAR','Ap','May','Jun','july','Aug','sep','oct','NOVEM','DECEMBER') {\n my $monthnumber = $1 if $months =~ m&quot;(\\d+)=$month&quot;i;\n my $monthname = $1 if $months =~ m&quot;$monthnumber=(\\S+)&quot;;\n my $monthabbreviation = $1 if $months =~ m&quot;$monthnumber=(...)&quot;;\n printf &quot; %-9s %2d %3s %s\\n&quot;,$month,$monthnumber,$monthabbreviation,$monthname;\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>jan 1 Jan January\nFeb 2 Feb February\nMAR 3 Mar March\nAp 4 Apr April\nMay 5 May May\nJun 6 Jun June\njuly 7 Jul July\nAug 8 Aug August\nsep 9 Sep September\noct 10 Oct October\nNOVEM 11 Nov November\nDECEMBER 12 Dec December\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31301/" ]
If I import a library to use a method, would it be worth it? Does importing take up a lot of memory?
borrowed from [here](http://www.perlmonks.org/?node_id=95456) ``` %mon2num = qw( jan 1 feb 2 mar 3 apr 4 may 5 jun 6 jul 7 aug 8 sep 9 oct 10 nov 11 dec 12 ); ``` and to retrieve ``` $mon2num{"jan"} ```
241,581
<p>I have no trouble building 1.35.0, as well as 1.36.0 on the timesys arm-gcc toolchain, both statically (link-static) as well as dynamically (.so, default option).</p> <p>However, when I try to link a simple sample filesystem app:</p> <pre><code>#include &lt;boost/filesystem.hpp> #include &lt;iostream> namespace fs = boost::filesystem; int main(int argc, char *argv[]) { const char* fileName = argv[1]; std::cout &lt;&lt; "file: " &lt;&lt; fileName &lt;&lt; " => " &lt;&lt; fs::exists(fileName) &lt;&lt; std::endl; return 0; } </code></pre> <p>I get the following linker error:</p> <pre><code> developer@eldp01:~/boost/test$ /opt/timesys/at91sam9263_ek/toolchain/bin/armv5l-timesys-linux-gnueabi-gcc exists.cpp -o exists.exe -I ../boost_1_35_0/ -lboost_filesystem -lboost_system -lstdc++ -L . /tmp/ccex3NGb.o: In function `boost::detail::atomic_decrement(int*)': exists.cpp:(.text._ZN5boost6detail16atomic_decrementEPi[boost::detail::atomic_decrement(int*)]+0x1c): undefined reference to `__sync_fetch_and_add_4' /tmp/ccex3NGb.o: In function `boost::detail::atomic_increment(int*)': exists.cpp:(.text._ZN5boost6detail16atomic_incrementEPi[boost::detail::atomic_increment(int*)]+0x1c): undefined reference to `__sync_fetch_and_add_4' collect2: ld returned 1 exit status </code></pre> <p>Does anyone know how I can get Boost to build for the gcc-arm toolchain?</p>
[ { "answer_id": 241583, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "<p>Importing such a module is not likely to cost that much memory that you should refrain from it, though in this case probably a simple hash would be just as good. Something like</p>\n\n<pre><code>my %number_for = (\n jan =&gt; 1,\n feb =&gt; 2,\n#etc...\n);\n#...\ndo_something_with($number_for{$month})\n</code></pre>\n" }, { "answer_id": 241589, "author": "Oskar", "author_id": 5472, "author_profile": "https://Stackoverflow.com/users/5472", "pm_score": 6, "selected": true, "text": "<p>borrowed from <a href=\"http://www.perlmonks.org/?node_id=95456\" rel=\"noreferrer\">here</a></p>\n\n<pre><code>%mon2num = qw(\n jan 1 feb 2 mar 3 apr 4 may 5 jun 6\n jul 7 aug 8 sep 9 oct 10 nov 11 dec 12\n);\n</code></pre>\n\n<p>and to retrieve</p>\n\n<pre><code>$mon2num{\"jan\"}\n</code></pre>\n" }, { "answer_id": 241841, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 2, "selected": false, "text": "<pre><code>my %month_num = do { my $i = 1; map {; $_ =&gt; $i++ } (\n qw( jan feb mar apr may jun jul aug sep oct nov dec )\n) };\n</code></pre>\n\n<p>Or maybe:</p>\n\n<pre><code>my %month_num;\n$month_num{ $_ } = 1 + keys %month_num for (\n qw( jan feb mar apr may jun jul aug sep oct nov dec )\n);\n</code></pre>\n\n<p>Or using <a href=\"/questions/38345/elegant-zip-in-perl-5#71895\">a zip function</a>:</p>\n\n<pre><code>my %month_num = do {\n my @month = qw( jan feb mar apr may jun jul aug sep oct nov dec );\n zip2( 1 .. 1+$#month, @month );\n};\n</code></pre>\n" }, { "answer_id": 242025, "author": "Robert Krimen", "author_id": 25171, "author_profile": "https://Stackoverflow.com/users/25171", "pm_score": 4, "selected": false, "text": "<p>Here is yet another way to do it:</p>\n\n<pre><code>my %month; @month{qw/jan feb mar apr may jun\n jul aug sep oct nov dec/} = (1 .. 12);\n</code></pre>\n" }, { "answer_id": 242217, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 1, "selected": false, "text": "<p>It depends on how much date manipulation you're intending to do. At first you're probably better off with hand-rolling it, e.g.</p>\n\n<pre><code>my @months = qw(Jan Feb Mar Apr May Jun\n Jul Aug Sep Oct Nov Dec);\nmy %monthnum = map { $_ =&gt; $months[ $_ - 1 ] } 1..12;\n</code></pre>\n\n<p>(I prefer this approach because it's comparatively obvious what you're doing - you have a list of months, then you map them from 1..12 (the numbers that make sense to a human) to 0..11 (the numbers that make sense to a computer). The performance bottlenecks in your code aren't going to be in this sort of code, they'll be in network, database or disc-accessing code, so concentrate on making your code readable.)</p>\n\n<p>As you start adding to your code, you may find that a lot of this stuff is done already by existing modules, and it might be easier to do some of the simple stuff with e.g. Date::Calc. Or you may find a date/time module more suited to your needs; that's beyond the scope of this question.</p>\n\n<p>Bear in mind also that some modules use autosplit, where only those parts of the module that are needed are loaded. Also, the main performance impact of using a large module isn't necessarily RAM, it's probably more likely to be the time/CPU overhead of loading and compiling it before any of your code has ever run.</p>\n" }, { "answer_id": 243133, "author": "Guillaume Gervais", "author_id": 10687, "author_profile": "https://Stackoverflow.com/users/10687", "pm_score": 0, "selected": false, "text": "<p>Definitely a hash, as suggested by others.</p>\n" }, { "answer_id": 244198, "author": "EvdB", "author_id": 5349, "author_profile": "https://Stackoverflow.com/users/5349", "pm_score": 2, "selected": false, "text": "<p>Hmm - there seem to be plenty of overly complicated ways to do this. For something this simple clarity is key:</p>\n\n<pre><code># create a lookup table of month abbreviations to month numbers\nmy %month_abbr_to_number_lkup = (\n jan =&gt; 1,\n feb =&gt; 2,\n mar =&gt; 3,\n apr =&gt; 4,\n may =&gt; 5,\n jun =&gt; 6,\n jul =&gt; 7,\n aug =&gt; 8,\n sep =&gt; 9,\n oct =&gt; 10,\n nov =&gt; 11,\n dec =&gt; 12,\n);\n\n# get the number for a month\nmy $number = $month_abbr_to_number_lkup{$abbr}\n || die \"Could not convert month abbreviation '$abbr' to a number.\";\n</code></pre>\n" }, { "answer_id": 244873, "author": "F5.", "author_id": 13769, "author_profile": "https://Stackoverflow.com/users/13769", "pm_score": 2, "selected": false, "text": "<p>Note also that hash keys are case sensitive; depending on where your abbreviations are coming from you may want to down-case them first to match the hash keys.</p>\n\n<pre><code>%mon_2_num = (jan =&gt; 1,\n feb =&gt; 2,\n ...);\n\n$month_number = $mon_2_num{lc($month_name_abbrev)};\n</code></pre>\n" }, { "answer_id": 248829, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "<p>Another way to do this using a hash slice:</p>\n\n<pre><code>@month{qw(jan feb mar apr may jun jul aug sep oct nov dec)} = 1..12;\n</code></pre>\n" }, { "answer_id": 63093790, "author": "BitDreamer", "author_id": 4921154, "author_profile": "https://Stackoverflow.com/users/4921154", "pm_score": 0, "selected": false, "text": "<p>I love the chance to do TMTOWTDI on a 12 year old question!</p>\n<p>As somebody else mentioned, the hash values will be case sensitive. So let's use regular expressions instead!</p>\n<pre><code>my $months = '1=January 2=February 3=March 4=April 5=May 6=June 7=July 8=August 9=September 10=October 11=November 12=December';\n\nmy $month = 'jan'; # anything that looks like a month name\nmy $monthnumber = $1 if $months =~ m&quot;(\\d+)=$month&quot;i;\nmy $monthname = $1 if $months =~ m&quot;$monthnumber=(\\S+)&quot;;\nmy $monthabbreviation = $1 if $months =~ m&quot;$monthnumber=(...)&quot;;\n</code></pre>\n<p>Here's an example that shows how flexible this is:</p>\n<pre><code>foreach my $month ('jan', 'Feb','MAR','Ap','May','Jun','july','Aug','sep','oct','NOVEM','DECEMBER') {\n my $monthnumber = $1 if $months =~ m&quot;(\\d+)=$month&quot;i;\n my $monthname = $1 if $months =~ m&quot;$monthnumber=(\\S+)&quot;;\n my $monthabbreviation = $1 if $months =~ m&quot;$monthnumber=(...)&quot;;\n printf &quot; %-9s %2d %3s %s\\n&quot;,$month,$monthnumber,$monthabbreviation,$monthname;\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>jan 1 Jan January\nFeb 2 Feb February\nMAR 3 Mar March\nAp 4 Apr April\nMay 5 May May\nJun 6 Jun June\njuly 7 Jul July\nAug 8 Aug August\nsep 9 Sep September\noct 10 Oct October\nNOVEM 11 Nov November\nDECEMBER 12 Dec December\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
I have no trouble building 1.35.0, as well as 1.36.0 on the timesys arm-gcc toolchain, both statically (link-static) as well as dynamically (.so, default option). However, when I try to link a simple sample filesystem app: ``` #include <boost/filesystem.hpp> #include <iostream> namespace fs = boost::filesystem; int main(int argc, char *argv[]) { const char* fileName = argv[1]; std::cout << "file: " << fileName << " => " << fs::exists(fileName) << std::endl; return 0; } ``` I get the following linker error: ``` developer@eldp01:~/boost/test$ /opt/timesys/at91sam9263_ek/toolchain/bin/armv5l-timesys-linux-gnueabi-gcc exists.cpp -o exists.exe -I ../boost_1_35_0/ -lboost_filesystem -lboost_system -lstdc++ -L . /tmp/ccex3NGb.o: In function `boost::detail::atomic_decrement(int*)': exists.cpp:(.text._ZN5boost6detail16atomic_decrementEPi[boost::detail::atomic_decrement(int*)]+0x1c): undefined reference to `__sync_fetch_and_add_4' /tmp/ccex3NGb.o: In function `boost::detail::atomic_increment(int*)': exists.cpp:(.text._ZN5boost6detail16atomic_incrementEPi[boost::detail::atomic_increment(int*)]+0x1c): undefined reference to `__sync_fetch_and_add_4' collect2: ld returned 1 exit status ``` Does anyone know how I can get Boost to build for the gcc-arm toolchain?
borrowed from [here](http://www.perlmonks.org/?node_id=95456) ``` %mon2num = qw( jan 1 feb 2 mar 3 apr 4 may 5 jun 6 jul 7 aug 8 sep 9 oct 10 nov 11 dec 12 ); ``` and to retrieve ``` $mon2num{"jan"} ```
241,605
<p>I am working with a device that requires me to generate a 16 bit CRC.</p> <p>The datasheet for the device says it needs the following CRC Definition:</p> <pre> CRC Type Length Polynomial Direction Preset Residue CRC-CCITT 16 bits x16 + x12 + x5 + 1 Forward FFFF (16) 1D0F (16) </pre> <p>where preset=FFFF (16 bit) and Residue=1D0F (16 bit)</p> <p>I searched for a CRC algorithm and found this link: <a href="http://www.lammertbies.nl/comm/info/crc-calculation.html" rel="nofollow noreferrer">http://www.lammertbies.nl/comm/info/crc-calculation.html</a></p> <p>It has both on it. CRC-CCITT (0xFFFF) CRC-CCITT (0x1D0F)</p> <p>What's the difference between the preset and the residue?</p>
[ { "answer_id": 241874, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 0, "selected": false, "text": "<p>The difference is in what the algorithm does with the two values. I just looked at a CRC algorithm myself and it looks pretty simple.</p>\n\n<p>Preset is the value it starts with and residue is XOR'd with the value at the end.</p>\n\n<p>Now, the <b>reason</b> for choosing particular values for preset and residue, that I don't know.</p>\n" }, { "answer_id": 241890, "author": "XPav", "author_id": 27550, "author_profile": "https://Stackoverflow.com/users/27550", "pm_score": 0, "selected": false, "text": "<p>Something's not right here. </p>\n\n<p>You're looking for a 16-bit CRC, but you've specified a 24-bit Preset and Residue. Post a link to the datasheet for the device you're looking at.</p>\n\n<p>The best source for CRC information is, by the way, is <a href=\"http://www.ross.net/crc/download/crc_v3.txt\" rel=\"nofollow noreferrer\">Ross Williams' guide to CRC.</a></p>\n\n<p>edit: Ah-hah, I see the \"24-bit\" preset was just the formatting of the table. </p>\n" }, { "answer_id": 242164, "author": "Harry Tsai", "author_id": 31954, "author_profile": "https://Stackoverflow.com/users/31954", "pm_score": 3, "selected": false, "text": "<p>You initialize the CRC register with the <strong><em>preset</em></strong> before feeding in your message.</p>\n\n<p>The <strong><em>residue</em></strong> is what should be left in the CRC register after feeding through a message, plus its correct CRC.</p>\n\n<p>If you just want to send a message, you won't see the residue value. But when the device runs your message+CRC through the CRC algorithm again, it'll see a final value of 0x1D0F if there were no transmission errors.</p>\n\n<hr>\n\n<p>You can also demonstrate this to yourself without getting the device involved. This can help you confirm that your algorithm is doing something that, at least, resembles a CRC.</p>\n\n<ul>\n<li>First, calculate the CRC for your message.</li>\n<li>Append your message and that CRC, then pass the whole thing through a new CRC calculation (remember to reset to the preset value first.)</li>\n<li>If all went well, your CRC register should contain the residue value.</li>\n</ul>\n\n<hr>\n\n<p>The best CRC explanation I've ever found is here:</p>\n\n<p><a href=\"https://archive.org/stream/PainlessCRC/crc_v3.txt\" rel=\"nofollow noreferrer\">https://archive.org/stream/PainlessCRC/crc_v3.txt</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am working with a device that requires me to generate a 16 bit CRC. The datasheet for the device says it needs the following CRC Definition: ``` CRC Type Length Polynomial Direction Preset Residue CRC-CCITT 16 bits x16 + x12 + x5 + 1 Forward FFFF (16) 1D0F (16) ``` where preset=FFFF (16 bit) and Residue=1D0F (16 bit) I searched for a CRC algorithm and found this link: <http://www.lammertbies.nl/comm/info/crc-calculation.html> It has both on it. CRC-CCITT (0xFFFF) CRC-CCITT (0x1D0F) What's the difference between the preset and the residue?
You initialize the CRC register with the ***preset*** before feeding in your message. The ***residue*** is what should be left in the CRC register after feeding through a message, plus its correct CRC. If you just want to send a message, you won't see the residue value. But when the device runs your message+CRC through the CRC algorithm again, it'll see a final value of 0x1D0F if there were no transmission errors. --- You can also demonstrate this to yourself without getting the device involved. This can help you confirm that your algorithm is doing something that, at least, resembles a CRC. * First, calculate the CRC for your message. * Append your message and that CRC, then pass the whole thing through a new CRC calculation (remember to reset to the preset value first.) * If all went well, your CRC register should contain the residue value. --- The best CRC explanation I've ever found is here: <https://archive.org/stream/PainlessCRC/crc_v3.txt>
241,622
<p>I am not as familiar with Oracle as I would like to be. I have some 250k records, and I want to display them 100 per page. Currently I have one stored procedure which retrieves all quarter of a million records to a dataset using a data adapter, and dataset, and the dataadapter.Fill(dataset) method on the results from the stored proc. If I have "Page Number" and "Number of records per page" as integer values I can pass as parameters, what would be the best way to get back just that particular section. Say, if I pass 10 as a page number, and 120 as number of pages, from the select statement it would give me the 1880th through 1200th, or something like that, my math in my head might be off. </p> <p>I'm doing this in .NET with C#, thought that's not important, if I can get it right on the sql side, then I should be cool. </p> <p>Update: I was able to use Brian's suggestion, and it is working great. I'd like to work on some optimization, but the pages are coming up in 4 to 5 seconds rather than a minute, and my paging control was able to integrate in very well with my new stored procs. </p>
[ { "answer_id": 241643, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 8, "selected": true, "text": "<p>Something like this should work: <a href=\"http://weblogs.asp.net/fbouma/archive/2007/05/21/api-s-and-production-code-shouldn-t-be-designed-by-scientists.aspx\" rel=\"noreferrer\">From Frans Bouma's Blog</a> </p>\n\n<pre><code>SELECT * FROM\n(\n SELECT a.*, rownum r__\n FROM\n (\n SELECT * FROM ORDERS WHERE CustomerID LIKE 'A%'\n ORDER BY OrderDate DESC, ShippingDate DESC\n ) a\n WHERE rownum &lt; ((pageNumber * pageSize) + 1 )\n)\nWHERE r__ &gt;= (((pageNumber-1) * pageSize) + 1)\n</code></pre>\n" }, { "answer_id": 241657, "author": "Chobicus", "author_id": 1514822, "author_profile": "https://Stackoverflow.com/users/1514822", "pm_score": 7, "selected": false, "text": "<p><a href=\"https://blogs.oracle.com/oraclemagazine/post/on-top-n-and-pagination-queries\" rel=\"nofollow noreferrer\">Ask Tom</a> on pagination and very, very useful analytic functions.</p>\n<p>This is excerpt from that page:</p>\n<pre><code>select * from (\n select /*+ first_rows(25) */\n object_id,object_name,\n row_number() over\n (order by object_id) rn\n from all_objects\n)\nwhere rn between :n and :m\norder by rn;\n</code></pre>\n" }, { "answer_id": 20617033, "author": "Furetto", "author_id": 532392, "author_profile": "https://Stackoverflow.com/users/532392", "pm_score": 3, "selected": false, "text": "<p>Try the following:</p>\n\n<pre><code>SELECT *\nFROM\n (SELECT FIELDA,\n FIELDB,\n FIELDC,\n ROW_NUMBER() OVER (ORDER BY FIELDC) R\n FROM TABLE_NAME\n WHERE FIELDA = 10\n )\nWHERE R &gt;= 10\nAND R &lt;= 15;\n</code></pre>\n\n<p>via<a href=\"http://mbfu.it/r/ta\" rel=\"noreferrer\"> [tecnicume]</a></p>\n" }, { "answer_id": 29927794, "author": "JoelC", "author_id": 2019162, "author_profile": "https://Stackoverflow.com/users/2019162", "pm_score": 7, "selected": false, "text": "<p>In the interest of completeness, for people looking for a more modern solution, in <strong>Oracle 12c</strong> there are some new features including better paging and top handling.</p>\n\n<p><strong>Paging</strong></p>\n\n<p>The paging looks like this:</p>\n\n<pre><code>SELECT *\nFROM user\nORDER BY first_name\nOFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY;\n</code></pre>\n\n<p><strong>Top N Records</strong></p>\n\n<p>Getting the top records looks like this:</p>\n\n<pre><code>SELECT *\nFROM user\nORDER BY first_name\nFETCH FIRST 5 ROWS ONLY\n</code></pre>\n\n<p>Notice how both the above query examples have <code>ORDER BY</code> clauses. The new commands respect these and are run on the sorted data.</p>\n\n<p>I couldn't find a good Oracle reference page for <code>FETCH</code> or <code>OFFSET</code> but <a href=\"http://oracle-base.com/articles/12c/row-limiting-clause-for-top-n-queries-12cr1.php\" rel=\"noreferrer\">this page</a> has a great overview of these new features.</p>\n\n<p><strong>Performance</strong></p>\n\n<p>As @wweicker points out in the comments below, performance is an issue with the new syntax in 12c. I didn't have a copy of 18c to test if Oracle has since improved it.</p>\n\n<p>Interestingly enough, my actual results were returned slightly quicker the first time I ran the queries on my table (113 million+ rows) for the new method:</p>\n\n<ul>\n<li>New method: 0.013 seconds.</li>\n<li>Old method: 0.107 seconds.</li>\n</ul>\n\n<p>However, as @wweicker mentioned, the explain plan looks much worse for the new method:</p>\n\n<ul>\n<li>New method cost: 300,110</li>\n<li>Old method cost: 30</li>\n</ul>\n\n<p>The new syntax caused a full scan of the index on my column, which was the entire cost. Chances are, things get much worse when limiting on unindexed data. </p>\n\n<p>Let's have a look when including a single unindexed column on the previous dataset:</p>\n\n<ul>\n<li>New method time/cost: 189.55 seconds/998,908</li>\n<li>Old method time/cost: 1.973 seconds/256</li>\n</ul>\n\n<p>Summary: use with caution until Oracle improves this handling. If you have an index to work with, perhaps you can get away with using the new method. </p>\n\n<p>Hopefully I'll have a copy of 18c to play with soon and can update</p>\n" }, { "answer_id": 33498058, "author": "Vadim Kirilchuk", "author_id": 2728956, "author_profile": "https://Stackoverflow.com/users/2728956", "pm_score": 4, "selected": false, "text": "<p>Just want to summarize the answers and comments. There are a number of ways doing a pagination.</p>\n\n<p>Prior to oracle 12c there were no OFFSET/FETCH functionality, so take a look at <a href=\"http://www.inf.unideb.hu/~gabora/pagination/article/Gabor_Andras_pagination_article.pdf\" rel=\"noreferrer\">whitepaper</a> as the @jasonk suggested. It's the most complete article I found about different methods with detailed explanation of advantages and disadvantages. It would take a significant amount of time to copy-paste them here, so I won't do it.</p>\n\n<p>There is also a good article from jooq creators explaining some common caveats with oracle and other databases pagination. <a href=\"http://blog.jooq.org/2014/06/09/stop-trying-to-emulate-sql-offset-pagination-with-your-in-house-db-framework/\" rel=\"noreferrer\">jooq's blogpost</a></p>\n\n<p>Good news, since oracle 12c we have a new OFFSET/FETCH functionality. <a href=\"http://www.oracle.com/technetwork/issue-archive/2013/13-sep/o53asktom-1999186.html\" rel=\"noreferrer\">OracleMagazine 12c new features</a>. Please refer to \"Top-N Queries and Pagination\"</p>\n\n<p>You may check your oracle version by issuing the following statement </p>\n\n<pre><code>SELECT * FROM V$VERSION\n</code></pre>\n" }, { "answer_id": 61062846, "author": "Ferdous Wahid", "author_id": 2828176, "author_profile": "https://Stackoverflow.com/users/2828176", "pm_score": 0, "selected": false, "text": "<p>In my project I used <strong>Oracle 12c and java</strong>. The paging code looks like this:</p>\n\n<pre><code> public public List&lt;Map&lt;String, Object&gt;&gt; getAllProductOfferWithPagination(int pageNo, int pageElementSize, Long productOfferId, String productOfferName) {\n try {\n\n if(pageNo==1){\n //do nothing\n } else{\n pageNo=(pageNo-1)*pageElementSize+1;\n }\n System.out.println(\"algo pageNo: \" + pageNo +\" pageElementSize: \"+ pageElementSize+\" productOfferId: \"+ productOfferId+\" productOfferName: \"+ productOfferName);\n\n String sql = \"SELECT * FROM ( SELECT * FROM product_offer po WHERE po.deleted=0 AND (po.product_offer_id=? OR po.product_offer_name LIKE ? )\" +\n \" ORDER BY po.PRODUCT_OFFER_ID asc) foo OFFSET ? ROWS FETCH NEXT ? ROWS ONLY \";\n\n return jdbcTemplate.queryForList(sql,new Object[] {productOfferId,\"%\"+productOfferName+\"%\",pageNo-1, pageElementSize});\n\n } catch (Exception e) {\n System.out.println(e);\n e.printStackTrace();\n return null;\n }\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893/" ]
I am not as familiar with Oracle as I would like to be. I have some 250k records, and I want to display them 100 per page. Currently I have one stored procedure which retrieves all quarter of a million records to a dataset using a data adapter, and dataset, and the dataadapter.Fill(dataset) method on the results from the stored proc. If I have "Page Number" and "Number of records per page" as integer values I can pass as parameters, what would be the best way to get back just that particular section. Say, if I pass 10 as a page number, and 120 as number of pages, from the select statement it would give me the 1880th through 1200th, or something like that, my math in my head might be off. I'm doing this in .NET with C#, thought that's not important, if I can get it right on the sql side, then I should be cool. Update: I was able to use Brian's suggestion, and it is working great. I'd like to work on some optimization, but the pages are coming up in 4 to 5 seconds rather than a minute, and my paging control was able to integrate in very well with my new stored procs.
Something like this should work: [From Frans Bouma's Blog](http://weblogs.asp.net/fbouma/archive/2007/05/21/api-s-and-production-code-shouldn-t-be-designed-by-scientists.aspx) ``` SELECT * FROM ( SELECT a.*, rownum r__ FROM ( SELECT * FROM ORDERS WHERE CustomerID LIKE 'A%' ORDER BY OrderDate DESC, ShippingDate DESC ) a WHERE rownum < ((pageNumber * pageSize) + 1 ) ) WHERE r__ >= (((pageNumber-1) * pageSize) + 1) ```
241,631
<p>I'm writing a web application that <em>dynamically</em> creates URL's based off of some input, to be consumed by a client at another time. For discussion sake these URL's can contain certain characters, like a <strong>forward slash (i.e. '/')</strong>, which should not be interpreted as part of the actual URL, but just as an argument. For example:</p> <pre>http://mycompany.com/PartOfUrl1/PartOfUrl2/ArgumentTo/Url/GoesHere</pre> <p>As you can see, the <strong>ArgumentTo/Url/GoesHere</strong> does indeed have forward slashes but these should be <em>ignored or escaped</em>.</p> <p>This may be a bad example but the question in hand is more general and applies to other <em>special characters</em>.</p> <h3>So, if there are pieces of a URL that are just <em>argument</em>s and should not be used to resolve the actual web request, what's a good way of handling this?</h3> <h1>Update:</h1> <p>Given some of the answers I realized that I failed to point out a few pieces that hopefully will help clarify.</p> <p>I would like to keep this fairly language agnostic as it would be great if the client could just make a request. For example, if the client knew that it wanted to pass <strong>ArgumentTo/Url/GoesHere</strong>, it would be great if that could be <em>encoded</em> into a <em>unique</em> string in which the server could turn around and <em>decode</em> it to use.</p> <p>Can we assume that similar functions like HttpUtility.HtmlEncode/HtmlDecode in the .NET Framework are available on other systems/platforms? The URL does not have to be <em>pretty</em> by any means so having <em>real words</em> in the path does not really matter.</p> <h3>Would something like a base64 encoding of the argument work?</h3> <p>It seems that base64 encoding/decoding is fairly readily available on any platform/language.</p>
[ { "answer_id": 241639, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": false, "text": "<p>You didn't say which language you're using, but PHP has the useful <code>urlencode</code> function and C# has <code>HttpUtility.URLEncode</code> and <code>Server.UrlEncode</code> which should encode parts of your URL nicely.</p>\n<p>In case you need another way <a href=\"http://www.december.com/html/spec/esccodes.html\" rel=\"nofollow noreferrer\">this page</a> has a list of encoded values. E.g.: <code>/ == %2f</code>.</p>\n<h3>update</h3>\n<p>From what you've updated I'd say use Voyagerfan's idea of URLRewriting to make something like:</p>\n<pre><code>http://www.example.com/([A-Za-z0-9/]+) http://www.example.com/?page=$1\n</code></pre>\n<p>And then use the applications GET parser to filter it out.</p>\n" }, { "answer_id": 241641, "author": "codewright", "author_id": 28919, "author_profile": "https://Stackoverflow.com/users/28919", "pm_score": 0, "selected": false, "text": "<p>I believe what you're looking for, if using .net, is the HttpUtility.EncodeUrl() method, as it has many overrides. Look here: <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx</a></p>\n" }, { "answer_id": 241642, "author": "Adron", "author_id": 29345, "author_profile": "https://Stackoverflow.com/users/29345", "pm_score": 0, "selected": false, "text": "<p>Use the HtmlEncode and Decode methods on the server object. I believe that will remove most characters that should not be and takes care of other things such as spaces, etc.</p>\n\n<p>Here's the MSDN Article: <a href=\"http://msdn.microsoft.com/en-us/library/ms525347.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms525347.aspx</a></p>\n" }, { "answer_id": 241648, "author": "dgw", "author_id": 5991, "author_profile": "https://Stackoverflow.com/users/5991", "pm_score": 2, "selected": false, "text": "<p>You could use <a href=\"http://httpd.apache.org/docs/2.0/misc/rewriteguide.html\" rel=\"nofollow noreferrer\">Apache rewrites</a> to rewrite <code>http:// mycompany.com/PartOfUrl1/PartOfUrl2</code> to <code>http:// mycompany.com/path/to/program.php</code> and then pass in <code>ArgumentTo/Url/GoesHere</code> as a standard GET parameter. So what the server actually sends back is the response for <code>http:// mycompany.com/path/to/program.php?arg=ArgumentTo/Url/GoesHere</code></p>\n\n<p>Rewriting is a good way to guard against technology changes (so switching from PHP to ASP, for example, won't change your URLs) and provide friendly URLs to your users at the same time.</p>\n\n<h2>Update</h2>\n\n<p>Using your example URLs and building on what I said before, I'd say to use this code in your httpd.conf or .htaccess:</p>\n\n<p><code>RewriteEngine On</code></p>\n\n<p><code>RewriteRule http:// mycompany.com/PartOfUrl1/PartOfUrl2/([A-Za-z0-9]) http://mycompany.com/path/to/program.php?arg=$1</code></p>\n\n<p>(BTW, remove the space after the first <code>http://</code> in the <code>RewriteRule</code>, plus that line needs to contain <em>no</em> line breaks.)</p>\n\n<p>Changing the paths, the filenames, name of the arg, etc. is fine; the critical parts here are the regex (<code>([A-Za-z0-9])</code>) and the <code>$1</code>.</p>\n" }, { "answer_id": 241709, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 1, "selected": false, "text": "<p>Yes, Base64 encoding your argument will work for you, however you'll need to make sure your entire URL is under the size limit of your target browser (2083 characters for IE 4 - 7, <a href=\"http://support.microsoft.com/kb/208427\" rel=\"nofollow noreferrer\">according to this page</a>).</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916/" ]
I'm writing a web application that *dynamically* creates URL's based off of some input, to be consumed by a client at another time. For discussion sake these URL's can contain certain characters, like a **forward slash (i.e. '/')**, which should not be interpreted as part of the actual URL, but just as an argument. For example: ``` http://mycompany.com/PartOfUrl1/PartOfUrl2/ArgumentTo/Url/GoesHere ``` As you can see, the **ArgumentTo/Url/GoesHere** does indeed have forward slashes but these should be *ignored or escaped*. This may be a bad example but the question in hand is more general and applies to other *special characters*. ### So, if there are pieces of a URL that are just *argument*s and should not be used to resolve the actual web request, what's a good way of handling this? Update: ======= Given some of the answers I realized that I failed to point out a few pieces that hopefully will help clarify. I would like to keep this fairly language agnostic as it would be great if the client could just make a request. For example, if the client knew that it wanted to pass **ArgumentTo/Url/GoesHere**, it would be great if that could be *encoded* into a *unique* string in which the server could turn around and *decode* it to use. Can we assume that similar functions like HttpUtility.HtmlEncode/HtmlDecode in the .NET Framework are available on other systems/platforms? The URL does not have to be *pretty* by any means so having *real words* in the path does not really matter. ### Would something like a base64 encoding of the argument work? It seems that base64 encoding/decoding is fairly readily available on any platform/language.
You didn't say which language you're using, but PHP has the useful `urlencode` function and C# has `HttpUtility.URLEncode` and `Server.UrlEncode` which should encode parts of your URL nicely. In case you need another way [this page](http://www.december.com/html/spec/esccodes.html) has a list of encoded values. E.g.: `/ == %2f`. ### update From what you've updated I'd say use Voyagerfan's idea of URLRewriting to make something like: ``` http://www.example.com/([A-Za-z0-9/]+) http://www.example.com/?page=$1 ``` And then use the applications GET parser to filter it out.
241,634
<p>In Cygwin a space in a path has to be escaped with a backslash Not true in Windows, put the whole path in a quote</p> <p>Is there a way to convert to this automatically in Ruby?</p> <p>Otherwise, how in Ruby do I detect if I am running with Windows or Cygwin?</p>
[ { "answer_id": 241653, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 1, "selected": false, "text": "<p>Quoting paths in Cygwin ought to work fine.</p>\n" }, { "answer_id": 243465, "author": "theschmitzer", "author_id": 2167252, "author_profile": "https://Stackoverflow.com/users/2167252", "pm_score": 0, "selected": false, "text": "<p>I found how to detect the platform at least - the RUBY_PLATFORM constant defines that.</p>\n" }, { "answer_id": 1582028, "author": "knoopx", "author_id": 62368, "author_profile": "https://Stackoverflow.com/users/62368", "pm_score": 2, "selected": true, "text": "<p><a href=\"http://rant.rubyforge.org/\" rel=\"nofollow noreferrer\">http://rant.rubyforge.org/</a></p>\n\n<pre><code>sys.escape(\"foo bar\")\n# gives on Windows: '\"foo bar\"'\n# other systems: 'foo\\ bar'\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2167252/" ]
In Cygwin a space in a path has to be escaped with a backslash Not true in Windows, put the whole path in a quote Is there a way to convert to this automatically in Ruby? Otherwise, how in Ruby do I detect if I am running with Windows or Cygwin?
<http://rant.rubyforge.org/> ``` sys.escape("foo bar") # gives on Windows: '"foo bar"' # other systems: 'foo\ bar' ```
241,645
<p>I have the Profile, CCK, and Views2 modules installed on a Drupal 6 site. I added a string field to the user profile. I can filter easily on preset values, thru the Views GUI builder, really nicely. However, I'd like the filter criteria to be dynamically set based on other environment variables (namely the <code>$_SERVER['SERVER_NAME']</code>).</p> <p>Is there a basic 'How-to-write-a-custom-drupal-views-filter' somewhere out there? I've been looking thru the documentation, but it's not obvious to my simple mind on how to do it.</p>
[ { "answer_id": 288544, "author": "alastairs", "author_id": 5296, "author_profile": "https://Stackoverflow.com/users/5296", "pm_score": 0, "selected": false, "text": "<p>There is the possibility, having looked at the sort of filters installed for my own site, that filters have to be based on some database field, in which case what you're trying to achieve is not possible. It appears that the filters provide the WHERE clause to the generated SQL query. </p>\n\n<p>Having said all that, if you want to pursue it further, your best bet is to start with a module that already provides filters for Views. There are filters provided with Views for the Node module; alternatively, you could look at the <a href=\"http://drupal.org/project/audio\" rel=\"nofollow noreferrer\">audio module</a> which also provides some filters. Additionally, posting to the Drupal forums or support list may turn up another module that will allow you to achieve what you're attempting.</p>\n" }, { "answer_id": 613810, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>yes you can do it. Try using the module \"views filter block\". Once you enable the block .. extract the html of the block from \"view source\" when viewing the page. Now disable the \"views filter block\" ... create your own custom block .. add the code to it with whatever css you like to make it look pretty . Within this code use php to dynamically specify what you want for the filter initial selection to be. Make sure you actually choose the field the filter is based on .. then within the custom php block use php code to write IF condition to check for the server_name value and accordingly assign the filter variable the right value.\" </p>\n\n<p>There maybe other (possibly even better) ways to do it to actually write a module to use the filter . So this is but one suggestion. Also give \"Views PHP Filter\" a try. I have not used it yet but sounds like its worth a shot.</p>\n\n<ul>\n<li>by drupal user (drupal username: drupdrips)</li>\n</ul>\n" }, { "answer_id": 835510, "author": "AbhiG", "author_id": 59182, "author_profile": "https://Stackoverflow.com/users/59182", "pm_score": 2, "selected": false, "text": "<p>You can create your own function like following to add your own filters.</p>\n\n<pre><code>&lt;?php custom_views_embed_view($view_name, $display_id) {\n$view = views_get_view($view_name);\n$view-&gt;set_display($display_id);\n$id = $view-&gt;add_item($display_id, 'filter', 'node', 'created',\n array( 'value' =&gt; array('type' =&gt; 'date', 'value' =&gt; date('c')), 'operator' =&gt; '&lt;='));\nreturn $view-&gt;execute_display($display_id);\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 8225383, "author": "yrk", "author_id": 1059019, "author_profile": "https://Stackoverflow.com/users/1059019", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"http://drupal.org/project/viewsphpfilter\" rel=\"nofollow\"><code>viewsphpfilter</code></a> module which allows filter views by <code>node id.</code> however there is a patch if you need to extend this for <code>user views</code></p>\n" }, { "answer_id": 14578211, "author": "mjimcua", "author_id": 1827690, "author_profile": "https://Stackoverflow.com/users/1827690", "pm_score": 1, "selected": false, "text": "<p>I have a similar problem and this article has been very helpful in resolving the problem.</p>\n\n<p><a href=\"http://www.metaltoad.com/blog/drupal-7-tutorial-creating-custom-filters-views\" rel=\"nofollow\">http://www.metaltoad.com/blog/drupal-7-tutorial-creating-custom-filters-views</a></p>\n\n<p>And hook_views_data oficial documentation</p>\n\n<p><a href=\"http://api.drupal.org/api/views/docs%21docs.php/function/hook_views_data/6\" rel=\"nofollow\">http://api.drupal.org/api/views/docs%21docs.php/function/hook_views_data/6</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6824/" ]
I have the Profile, CCK, and Views2 modules installed on a Drupal 6 site. I added a string field to the user profile. I can filter easily on preset values, thru the Views GUI builder, really nicely. However, I'd like the filter criteria to be dynamically set based on other environment variables (namely the `$_SERVER['SERVER_NAME']`). Is there a basic 'How-to-write-a-custom-drupal-views-filter' somewhere out there? I've been looking thru the documentation, but it's not obvious to my simple mind on how to do it.
You can create your own function like following to add your own filters. ``` <?php custom_views_embed_view($view_name, $display_id) { $view = views_get_view($view_name); $view->set_display($display_id); $id = $view->add_item($display_id, 'filter', 'node', 'created', array( 'value' => array('type' => 'date', 'value' => date('c')), 'operator' => '<=')); return $view->execute_display($display_id); } ?> ```
241,663
<pre><code>$fp_src=fopen('file','r'); $filter = stream_filter_prepend($fp_src, 'convert.iconv.ISO-8859-1/UTF-8'); while(fread($fp_src,4096)){ ++$count; if($count%1000==0) print ftell($fp_src)."\n"; } </code></pre> <p>When I run this the script ends up consuming ~ 200 MB of RAM after going through just 35MB of the file. </p> <p>Running it without the stream_filter zips right through with a constant memory footprint of ~10 MB.</p> <p>What gives?</p>
[ { "answer_id": 241701, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "<p>From what I'm reading <a href=\"http://us3.php.net/manual/en/function.stream-filter-register.php\" rel=\"nofollow noreferrer\">here</a>, you are not implementing <code>stream_filter_prepend()</code> correctly, although there could be something I misunderstand about the process.</p>\n\n<p>Als, I'm not totally sure, but I'm willing to bet that this has more to do with the fact that iconv is an expensive process, and less to do with the fact that you're using it as stream filter.</p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 241714, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You only need to register custom filters. iconv is built in. It's not the particular operation, using a stream filter for rot13 exhibits similar behavior.</p>\n" }, { "answer_id": 242233, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 0, "selected": false, "text": "<p>Any particular reason you want to use stream_filter_prepend()? If it's causing memory problems, then I'd find another way to do what it does.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` $fp_src=fopen('file','r'); $filter = stream_filter_prepend($fp_src, 'convert.iconv.ISO-8859-1/UTF-8'); while(fread($fp_src,4096)){ ++$count; if($count%1000==0) print ftell($fp_src)."\n"; } ``` When I run this the script ends up consuming ~ 200 MB of RAM after going through just 35MB of the file. Running it without the stream\_filter zips right through with a constant memory footprint of ~10 MB. What gives?
You only need to register custom filters. iconv is built in. It's not the particular operation, using a stream filter for rot13 exhibits similar behavior.
241,673
<pre><code>if(!eregi("^([0-9a-z_\[\]\*\- ])+$", $subuser)) $form-&gt;setError($field, "* Username not alphanumeric"); </code></pre> <p>Can anybody tell me why it is not allowing characters such as <code>-</code> and <code>*</code>?</p> <pre><code>if(!eregi("^([0-9a-z])+$", $subuser)) $form-&gt;setError($field, "* Username not alphanumeric"); </code></pre> <p>That is the original piece of code. A friend changed it to the top piece and it will allow a-z and 0-9 but it wont allow the other characters I need it to. Can anyone help me?</p> <p>Thanks in advance.</p>
[ { "answer_id": 241680, "author": "Henning", "author_id": 29549, "author_profile": "https://Stackoverflow.com/users/29549", "pm_score": 3, "selected": false, "text": "<p>Your regex uses PCRE syntax, so you have to use preg_match() instead of eregi().</p>\n\n<p>Try this code instead:</p>\n\n<pre><code>else if (!preg_match(\"/^([0-9a-z_\\[\\]* -])+$/i\", $subuser)) {\n$form-&gt;setError($field, \"* Username not alphanumeric\");\n}\n</code></pre>\n" }, { "answer_id": 241682, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>even using preg_* functions the pattern needs to be wrapped in nonalphanum delimiters:</p>\n\n<p>\"~^([0-9a-z_[]*- ])+$~\"</p>\n" }, { "answer_id": 241684, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 2, "selected": false, "text": "<p>Don't use the ereg family of functions - they are slower and, if I recall correctly, will eventually be deprecated.</p>\n\n<p>This should fix it</p>\n\n<pre><code>if ( preg_match( \"/^[^0-9a-z_\\[\\]* -]$/i\", $subuser )\n{\n $form-&gt;setError( $field, \"* Username not alphanumeric\" );\n}\n</code></pre>\n" }, { "answer_id": 241685, "author": "Trent", "author_id": 31912, "author_profile": "https://Stackoverflow.com/users/31912", "pm_score": 3, "selected": true, "text": "<p>For bracket expressions:</p>\n\n<p>To include a literal <code>]</code> in the list, make it the first character (following a possible <code>^</code>). To include a literal <code>-</code>, make it the first or last character, or the second endpoint of a range. To use a literal <code>-</code> as the first endpoint of a range, enclose it in <code>[.</code> and <code>.]</code> to make it a collating element (see below). With the exception of these and some combinations using <code>[</code> (see next paragraphs), all other special characters, including <code>\\</code>, lose their special significance within a bracket expression.</p>\n\n<p>So this should do what you want:</p>\n\n<pre><code>\"^([]0-9a-z_[* -])+$\"\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29912/" ]
``` if(!eregi("^([0-9a-z_\[\]\*\- ])+$", $subuser)) $form->setError($field, "* Username not alphanumeric"); ``` Can anybody tell me why it is not allowing characters such as `-` and `*`? ``` if(!eregi("^([0-9a-z])+$", $subuser)) $form->setError($field, "* Username not alphanumeric"); ``` That is the original piece of code. A friend changed it to the top piece and it will allow a-z and 0-9 but it wont allow the other characters I need it to. Can anyone help me? Thanks in advance.
For bracket expressions: To include a literal `]` in the list, make it the first character (following a possible `^`). To include a literal `-`, make it the first or last character, or the second endpoint of a range. To use a literal `-` as the first endpoint of a range, enclose it in `[.` and `.]` to make it a collating element (see below). With the exception of these and some combinations using `[` (see next paragraphs), all other special characters, including `\`, lose their special significance within a bracket expression. So this should do what you want: ``` "^([]0-9a-z_[* -])+$" ```
241,691
<p>Rather than scraping a Ruby version of this algorithm off the net I wanted to create my own based on its description <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="noreferrer">here</a>. However I cannot figure out two things</p> <pre><code>def primeSieve(n) primes = Array.new for i in 0..n-2 primes[i] = i+2 end index = 0 while Math.sqrt(primes.last).ceil &gt; primes[index] (primes[index] ** 2).step(primes.length - 1, primes[index]) {|x| x % primes[index] == 0 ? primes.delete(x) : ""} index += 1 end primes end </code></pre> <ol> <li>Why it doesn't iterate to the end of the array?</li> <li>According to the description in the link above the loop should be broken out of when the squareroot of the last element in the array is greater than the current prime - mine does this one before. </li> </ol> <p>I'm fairly sure it has something to do with the delete operation modifying the length of the array. For example my function currently yields 2,3,5,7,9,10 when I enter n=10 which is obviously not correct. Any suggestions on how I can go about alterating this to make it work like it's supposed to?</p>
[ { "answer_id": 241752, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 4, "selected": true, "text": "<p>The following seems to work. I took out the floating point arithmetic and squared instead of square rooting. I also replaced the deletion loop with a \"select\" call.</p>\n\n<pre><code>while primes[index]**2 &lt;= primes.last\n prime = primes[index]\n primes = primes.select { |x| x == prime || x%prime != 0 }\n index += 1\nend\n</code></pre>\n\n<p>Edit: I think I figured out how you're trying to do this. The following seems to work, and seems to be more in line with your original approach.</p>\n\n<pre><code>while Math.sqrt(primes.last).ceil &gt;= primes[index]\n (primes[index] * 2).step(primes.last, primes[index]) do\n |x|\n primes.delete(x)\n end\n index += 1\nend\n</code></pre>\n" }, { "answer_id": 432889, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 4, "selected": false, "text": "<p>There's a faster implementation at <a href=\"http://www.scriptol.org/sieve.php#ruby\" rel=\"noreferrer\">www.scriptol.org</a>:</p>\n\n<pre><code>def sieve_upto(top)\n sieve = []\n for i in 2 .. top\n sieve[i] = i\n end\n for i in 2 .. Math.sqrt(top)\n next unless sieve[i]\n (i*i).step(top, i) do |j|\n sieve[j] = nil\n end\n end\n sieve.compact\nend\n</code></pre>\n\n<p>I think it can be improved on slightly thus:</p>\n\n<pre><code>def better_sieve_upto(n)\n s = (0..n).to_a\n s[0] = s[1] = nil\n s.each do |p|\n next unless p\n break if p * p &gt; n\n (p*p).step(n, p) { |m| s[m] = nil }\n end\n s.compact\nend\n</code></pre>\n\n<p>...largely because of the faster array initialisation, I think, but it's marginal. (I added <code>#compact</code> to both to eliminate the unwanted <code>nil</code>s)</p>\n" }, { "answer_id": 9564096, "author": "nes1983", "author_id": 52573, "author_profile": "https://Stackoverflow.com/users/52573", "pm_score": 2, "selected": false, "text": "<p>This is a pretty straightforward implementation of the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Wikipedia article pseudocode</a>, using a <a href=\"https://github.com/ingramj/bitarray\" rel=\"nofollow\">bit array.</a></p>\n\n<pre><code>#!/usr/bin/env ruby -w\n\nrequire 'rubygems'\nrequire 'bitarray'\n\ndef eratosthenes(n)\n\n a = BitArray.new(n+1)\n\n (4..n).step(2) { |i|\n a[i] = 1\n }\n\n (3..(Math.sqrt(n))).each { |i|\n if(a[i] == 0)\n ((i*i)..n).step(2*i) { |j|\n a[j] = 1\n }\n end\n }\n a\n end\n\ndef primes(n)\n primes = Array.new\n eratosthenes(n).each_with_index { |isPrime, idx|\n primes &lt;&lt; idx if isPrime == 0\n }\n primes[2..-1]\nend\n</code></pre>\n" }, { "answer_id": 19416525, "author": "pjammer", "author_id": 156561, "author_profile": "https://Stackoverflow.com/users/156561", "pm_score": 0, "selected": false, "text": "<p>or </p>\n\n<pre><code>x = []\nPrime.each(123) do |p|\n x &lt;&lt; p\nend\n</code></pre>\n\n<p>There may be a way to use inject here but the inception thing hurts my head today.</p>\n" }, { "answer_id": 23588178, "author": "shin", "author_id": 119198, "author_profile": "https://Stackoverflow.com/users/119198", "pm_score": 1, "selected": false, "text": "<p>This is a reference for those who are interested. The code is from <a href=\"https://github.com/morizyun/aoj-ruby-python/blob/master/ruby/0009.rb\" rel=\"nofollow\">this site</a>.</p>\n\n<p>This code uses Sieve of Eratosthenes as well.</p>\n\n<pre><code>n = 1000000\nns = (n**0.5).to_i + 1\nis_prime = [false, false] + [true]*(n-1)\n2.upto(ns) do |i|\n next if !is_prime[i]\n (i*i).step(n, i) do |j|\n is_prime[j] = false\n end\nend\n\ncount = 0\nlist = (0..n).map do |i|\n count += 1 if is_prime[i]\n count\nend\n\nwhile gets\n puts list[$_.to_i]\nend\n</code></pre>\n\n<p>And here is <a href=\"http://rosettacode.org/wiki/Sieve_of_Eratosthenes#Ruby\" rel=\"nofollow\">another one</a>.</p>\n\n<pre><code>def eratosthenes(n)\n nums = [nil, nil, *2..n]\n (2..Math.sqrt(n)).each do |i|\n (i**2..n).step(i){|m| nums[m] = nil} if nums[i]\n end\n nums.compact\nend\n\np eratosthenes(100)\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2294/" ]
Rather than scraping a Ruby version of this algorithm off the net I wanted to create my own based on its description [here](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). However I cannot figure out two things ``` def primeSieve(n) primes = Array.new for i in 0..n-2 primes[i] = i+2 end index = 0 while Math.sqrt(primes.last).ceil > primes[index] (primes[index] ** 2).step(primes.length - 1, primes[index]) {|x| x % primes[index] == 0 ? primes.delete(x) : ""} index += 1 end primes end ``` 1. Why it doesn't iterate to the end of the array? 2. According to the description in the link above the loop should be broken out of when the squareroot of the last element in the array is greater than the current prime - mine does this one before. I'm fairly sure it has something to do with the delete operation modifying the length of the array. For example my function currently yields 2,3,5,7,9,10 when I enter n=10 which is obviously not correct. Any suggestions on how I can go about alterating this to make it work like it's supposed to?
The following seems to work. I took out the floating point arithmetic and squared instead of square rooting. I also replaced the deletion loop with a "select" call. ``` while primes[index]**2 <= primes.last prime = primes[index] primes = primes.select { |x| x == prime || x%prime != 0 } index += 1 end ``` Edit: I think I figured out how you're trying to do this. The following seems to work, and seems to be more in line with your original approach. ``` while Math.sqrt(primes.last).ceil >= primes[index] (primes[index] * 2).step(primes.last, primes[index]) do |x| primes.delete(x) end index += 1 end ```
241,715
<p>I am writing PHP code where I want to pass the session id myself using POST. I don't want a cookie to store the session, as it should get lost when the user gets out of the POST cycle.</p> <p>PHP automatically sets the cookie where available. I learned it is possible to change this behaviour by setting <code>session.use_cookies</code> to 0 in <code>php.ini</code>. Unfortunately, I don't have access to that file and I also wouldn't want to break the behaviour of other scripts running on the same server.</p> <p>Is there a way to disable or void the session cookie inside the PHP script?</p> <p><strong>EDIT:</strong> As the proposed solutions don't work for me, I used $_SESSION = array() at positions in the code where I found the session should be invalidated.</p>
[ { "answer_id": 241719, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 5, "selected": false, "text": "<p>Use <a href=\"http://php.net/ini_set\" rel=\"noreferrer\">ini_set()</a>:</p>\n\n<pre><code>ini_set('session.use_cookies', '0');\n</code></pre>\n\n<p>Or in your php.ini file:</p>\n\n<pre><code>session.use_cookies = 0\n</code></pre>\n" }, { "answer_id": 241726, "author": "lock", "author_id": 24744, "author_profile": "https://Stackoverflow.com/users/24744", "pm_score": 4, "selected": true, "text": "<p>err its possible to override the default settings of your host by creating your own .htaccess file and here's a great tutorial if you havent touched that yet\n<a href=\"http://www.askapache.com/htaccess/apache-htaccess.html\" rel=\"noreferrer\">http://www.askapache.com/htaccess/apache-htaccess.html</a></p>\n\n<p>or if you're too lazy to learn\njust create a \".htaccess\" file (yes that's the filename) on your sites directory and place the following code<br/></p>\n\n<pre><code>SetEnv session.use_cookies='0';\n</code></pre>\n" }, { "answer_id": 241730, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 2, "selected": false, "text": "<p>You can also put that setting in .htaccess so it applies to all scripts, otherwise you need to ensure that code is called on each request.</p>\n\n<p>Eg.</p>\n\n<p>php_value session.use_cookies 0</p>\n" }, { "answer_id": 241934, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": -1, "selected": false, "text": "<p>The way to do it is to setup sessions yourself.</p>\n\n<p>In the central include file that all your other files are including (you do have one of those, right?), you need to do a few things as early as is practical. </p>\n\n<pre><code>if( !array_key_exists('sessionid', $_POST) ) {\n // recreate the sessionid\n $sessionid = md5(rand().' '.microtime()); // Or something\n} else {\n $sessionid = $_POST['sessionid'];\n\nsession_id($sessionid);\nsession_start();\n</code></pre>\n\n<p>Now you have to remember that as soon as you start the form, you need to include:</p>\n\n<pre><code>&lt;input type='hidden' name='sessionid'&gt;&lt;?= session_id() ?&gt;&lt;/input&gt;\n</code></pre>\n" }, { "answer_id": 244610, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 2, "selected": false, "text": "<p>If you just need to be able to zap a session at a given time, use session_destroy(). If you want to completely end the session, here's a snippet copy/pasted straight out of the documentation:</p>\n\n<pre><code>// Initialize the session.\n// If you are using session_name(\"something\"), don't forget it now!\nsession_start();\n\n// Unset all of the session variables.\n$_SESSION = array();\n\n// If it's desired to kill the session, also delete the session cookie.\n// Note: This will destroy the session, and not just the session data!\nif (isset($_COOKIE[session_name()])) {\n setcookie(session_name(), '', time()-42000, '/');\n}\n\n// Finally, destroy the session.\nsession_destroy();\n</code></pre>\n" }, { "answer_id": 8778645, "author": "Michael Shebanow", "author_id": 1079359, "author_profile": "https://Stackoverflow.com/users/1079359", "pm_score": 2, "selected": false, "text": "<p>I was having trouble with PHP's documented approach to destroying a session w/ cookies.</p>\n\n<pre><code>// If it's desired to kill the session, also delete the session cookie.\n// Note: This will destroy the session, and not just the session data!\nif (ini_get(\"session.use_cookies\")) {\n $params = session_get_cookie_params();\n setcookie(session_name(), '', time() - 42000,\n $params[\"path\"], $params[\"domain\"],\n $params[\"secure\"], $params[\"httponly\"]\n );\n}\n</code></pre>\n\n<p>This was resulting in my seeing the cookie set twice:</p>\n\n<pre><code>Set-Cookie: SESSION_NAME=deleted; expires=Sat, 08-Jan-2011 14:09:10 GMT; path=/; secure\nSet-Cookie: SESSION_NAME=1_4f09a3871d483; path=/\n</code></pre>\n\n<p>As documented in the PHP comments, setting the cookie value to something other than empty ('') gets rid of the \"deleted\" value, but the second cookie set remained.</p>\n\n<p>To get rid of that, I had to add the code suggested above:</p>\n\n<pre><code>ini_set('session.use_cookies', '0');\n</code></pre>\n\n<p>I haven't looked at the source for sessions handling, but my guess is that setcookie(...) is bypassing the sessions module, so sessions doesn't know I called it. So, it is setting a default cookie after I set up a deleted cookie. </p>\n\n<p>I was testing on a mac: PHP 5.3.6 with Suhosin-Patch (cli) (built: Sep 8 2011 19:34:00)</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21974/" ]
I am writing PHP code where I want to pass the session id myself using POST. I don't want a cookie to store the session, as it should get lost when the user gets out of the POST cycle. PHP automatically sets the cookie where available. I learned it is possible to change this behaviour by setting `session.use_cookies` to 0 in `php.ini`. Unfortunately, I don't have access to that file and I also wouldn't want to break the behaviour of other scripts running on the same server. Is there a way to disable or void the session cookie inside the PHP script? **EDIT:** As the proposed solutions don't work for me, I used $\_SESSION = array() at positions in the code where I found the session should be invalidated.
err its possible to override the default settings of your host by creating your own .htaccess file and here's a great tutorial if you havent touched that yet <http://www.askapache.com/htaccess/apache-htaccess.html> or if you're too lazy to learn just create a ".htaccess" file (yes that's the filename) on your sites directory and place the following code ``` SetEnv session.use_cookies='0'; ```
241,725
<p>I'm trying to call a web service in an Excel Macro:</p> <pre><code>Set objHTTP = New MSXML.XMLHTTPRequest objHTTP.Open "post", "https://www.server.com/EIDEServer/EIDEService.asmx" objHTTP.setRequestHeader "Content-Type", "text/xml" objHTTP.setRequestHeader "SOAPAction", "PutSchedule" objHTTP.send strXML </code></pre> <p>And I get back the following response:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;soap:Body&gt; &lt;soap:Fault&gt; &lt;faultcode&gt;soap:Client&lt;/faultcode&gt; &lt;faultstring&gt;Server did not recognize the value of HTTP Header SOAPAction: PutSchedule.&lt;/faultstring&gt; &lt;detail /&gt; &lt;/soap:Fault&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>Anybody out there done something like this before?</p>
[ { "answer_id": 241956, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 3, "selected": true, "text": "<p>You SOAP action should also include namespace of the method\ne.g.</p>\n\n<pre><code>\"http://tempri.org/PutSchedule\"\n</code></pre>\n\n<p>Find out what the namespace of your Service and add it in front of the method name PutSchedule.</p>\n" }, { "answer_id": 261670, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>looks more like you're using xml-rpc instead of soap.\ninteract with the webservice using the soap type library at : <a href=\"http://msdn.microsoft.com/en-us/library/aa192537(office.11).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa192537(office.11).aspx</a>, or the one that corresponds with your ms office version</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1766771/" ]
I'm trying to call a web service in an Excel Macro: ``` Set objHTTP = New MSXML.XMLHTTPRequest objHTTP.Open "post", "https://www.server.com/EIDEServer/EIDEService.asmx" objHTTP.setRequestHeader "Content-Type", "text/xml" objHTTP.setRequestHeader "SOAPAction", "PutSchedule" objHTTP.send strXML ``` And I get back the following response: ``` <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <soap:Fault> <faultcode>soap:Client</faultcode> <faultstring>Server did not recognize the value of HTTP Header SOAPAction: PutSchedule.</faultstring> <detail /> </soap:Fault> </soap:Body> </soap:Envelope> ``` Anybody out there done something like this before?
You SOAP action should also include namespace of the method e.g. ``` "http://tempri.org/PutSchedule" ``` Find out what the namespace of your Service and add it in front of the method name PutSchedule.
241,727
<p>If I had the following select, and did not know the value to use to select an item in advance like in this <a href="https://stackoverflow.com/questions/196684/jquery-get-select-option-text">question</a> or the index of the item I wanted selected, how could I select one of the options with jQuery if I did know the text value like Option C?</p> <pre><code>&lt;select id='list'&gt; &lt;option value='45'&gt;Option A&lt;/option&gt; &lt;option value='23'&gt;Option B&lt;/option&gt; &lt;option value='17'&gt;Option C&lt;/option&gt; &lt;/select&gt; </code></pre>
[ { "answer_id": 241743, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 5, "selected": true, "text": "<pre><code>var option;\n$('#list option').each(function() {\n if($(this).text() == 'Option C') {\n option = this;\n return false;\n }\n});\n</code></pre>\n" }, { "answer_id": 241751, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": false, "text": "<p>This should do the trick:</p>\n\n<pre><code>// option text to search for\nvar optText = \"Option B\";\n// find option value that corresponds\nvar optVal = $(\"#list option:contains('\"+optText+\"')\").attr('value');\n// select the option value \n$(\"#list\").val( optVal )\n</code></pre>\n\n<p>As eyelidlessness points out, this will behave unpredictably when the text being searched for can be found in more than one option.</p>\n" }, { "answer_id": 1364498, "author": "RhinoDevX64", "author_id": 166845, "author_profile": "https://Stackoverflow.com/users/166845", "pm_score": 2, "selected": false, "text": "<pre><code>function SelectItemInDropDownList(itemToFind){ \n var option;\n $('#list option').each(function(){\n if($(this).text() == itemToFind) {\n option = this;\n option.selected = true;\n return false; \n }\n }); }\n</code></pre>\n\n<p>I only modified the previous code because it only located the option in the select list, some may want a literal demonstration.</p>\n" }, { "answer_id": 4653913, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 3, "selected": false, "text": "<pre><code>$(\"#list option\").each(function() {\n this.selected = $(this).text() == \"Option C\";\n});\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25335/" ]
If I had the following select, and did not know the value to use to select an item in advance like in this [question](https://stackoverflow.com/questions/196684/jquery-get-select-option-text) or the index of the item I wanted selected, how could I select one of the options with jQuery if I did know the text value like Option C? ``` <select id='list'> <option value='45'>Option A</option> <option value='23'>Option B</option> <option value='17'>Option C</option> </select> ```
``` var option; $('#list option').each(function() { if($(this).text() == 'Option C') { option = this; return false; } }); ```
241,746
<p>In a database prototype, I have a set of fields (like name, description, status) that are required in multiple, functionally different tables.</p> <p>These fields always have the same end user functionality for labeling, display, search, filtering etc. They are not part of a foreign key constraint. How should this be modeled?</p> <p>I can think of the following variants:</p> <ul> <li><p>Each table gets all these attributes. In this case, how would you name them? The same, in each table, or with a table name prefix (like usrName, prodName)</p></li> <li><p>Move them into a table Attributes, add a foreign key to the "core" tables, referencing Attributes.PK</p></li> <li><p>As above, but instead of a foreign key, use the Attributes.PK as PK in the respective core table as well.</p></li> </ul>
[ { "answer_id": 241764, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": 1, "selected": false, "text": "<p>Normalisation is often best practice in any relational database (within reason). </p>\n\n<p>If you have fields like state (meaning the state within a country), then a reference table like \"State\" with (id, short_name, long_name etc...) might be the way to go, then each record that references a state only need a state_id column which, as you did mention, is a reference to a record in the State table.</p>\n\n<p>However, in some instances normalisation of all data is not necessarily required as it just complicates things, but it should be obvious where to do it and where not to do it.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 241832, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 2, "selected": false, "text": "<p>Unless you use the same name or description <em>values</em> across tables, you shouldn't normalize that data. Status types tend to be reused, so, normalize those. For example:</p>\n\n<pre><code>order_status_types\n- id\n- name\n- description\n\nshipping_accounts\n- id\n- name\n- description\n\norders\n- order_status_type_id\n- shipping_account_id\n\npreferences\n- shipping_account_id\n</code></pre>\n" }, { "answer_id": 241836, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "<p>it sounds like you might be taking the idea of normalization a bit too far. remember, it's the idea that you're reducing redundancy in your <strong>data</strong>. your example seems to indicate you're worried about \"redundancy\" in the meta information of your database design.</p>\n\n<p>ultimately though, <code>user.name</code> and <code>user.description</code> are functionality different from <code>product.name</code> and <code>product.description</code>, and should be treated as such. for <code>status</code>, it depends what you mean by that. is <code>status</code> just an indicator of a product/user's record being active or not? if so, then it could make sense to split that to a different table.</p>\n\n<p>using the info you provided, if \"active/expired/deleted\" is merely an indication of state within the database, then i'd definitely agree with a table structure like so:</p>\n\n<pre><code>users products status\n id id id\n name name name\n description description\n status_id status_id\n</code></pre>\n\n<p>however, if <code>status</code> could conceivably be altered to represent something semantically different (ie, for users, perhaps \"active/retired/fired\", i'd suggest splitting that up to future proof the design:</p>\n\n<pre><code>user_status product_status\n id id\n name name\n</code></pre>\n\n<p>in short, normalize your data, not your database design.</p>\n" }, { "answer_id": 241837, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "<p>I would give each table its own set of columns, even if they have the same names and are logically similar. </p>\n\n<p>If you ever need to change one of the tables by adding or deleting some of these columns, or changing their data type, then you can do it only in the table where it pertains, instead of figuring out how to complicate your shared-attribute table.</p>\n\n<p>Giving each table control of its own attributes promotes <a href=\"http://c2.com/cgi/wiki?CouplingAndCohesion\" rel=\"nofollow noreferrer\">Cohesion</a>, which is a good thing. It also avoids your question about which direction the foreign keys go.</p>\n\n<p>As for column naming, it's not necessary or advisable to put prefixes on column names. If you ever do a join that results in columns of the same name coming from two tables, use aliases to distinguish them.</p>\n" }, { "answer_id": 1610285, "author": "Michael Dillon", "author_id": 189361, "author_profile": "https://Stackoverflow.com/users/189361", "pm_score": 1, "selected": false, "text": "<p>I've always given each table a 3 letter code which I then use in all field names. That way in the product table I have prdname, prddescription, prdstatus, and in the vendor file I have venname, vendescription, venstatus. When things get joined, there is no need to worry about same named fields.</p>\n\n<p>Of course, the tables all have a field named plain old <strong>id</strong> and the product table would have a field named venid that refers to the id field in the vendor table. In this case I don't put the prd prefix on it because venid makes perfect sense and is nonambiguous.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31317/" ]
In a database prototype, I have a set of fields (like name, description, status) that are required in multiple, functionally different tables. These fields always have the same end user functionality for labeling, display, search, filtering etc. They are not part of a foreign key constraint. How should this be modeled? I can think of the following variants: * Each table gets all these attributes. In this case, how would you name them? The same, in each table, or with a table name prefix (like usrName, prodName) * Move them into a table Attributes, add a foreign key to the "core" tables, referencing Attributes.PK * As above, but instead of a foreign key, use the Attributes.PK as PK in the respective core table as well.
it sounds like you might be taking the idea of normalization a bit too far. remember, it's the idea that you're reducing redundancy in your **data**. your example seems to indicate you're worried about "redundancy" in the meta information of your database design. ultimately though, `user.name` and `user.description` are functionality different from `product.name` and `product.description`, and should be treated as such. for `status`, it depends what you mean by that. is `status` just an indicator of a product/user's record being active or not? if so, then it could make sense to split that to a different table. using the info you provided, if "active/expired/deleted" is merely an indication of state within the database, then i'd definitely agree with a table structure like so: ``` users products status id id id name name name description description status_id status_id ``` however, if `status` could conceivably be altered to represent something semantically different (ie, for users, perhaps "active/retired/fired", i'd suggest splitting that up to future proof the design: ``` user_status product_status id id name name ``` in short, normalize your data, not your database design.
241,758
<p>In VB6 you can do this:</p> <pre><code>Dim a As Variant a = Array(1, 2, 3)</code></pre> <p>Can you do a similar thing in VB.NET with specific types, like so?:</p> <pre><code>Dim a() As Integer a = <strong>Array</strong>(1, 2, 3)</code></pre>
[ { "answer_id": 241762, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 5, "selected": true, "text": "<pre><code>Dim a() As Integer = New Integer() {1, 2, 3}\n</code></pre>\n" }, { "answer_id": 241787, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 0, "selected": false, "text": "<p>If you are new to .NET you will want to learn about the List collection and the flexibility it will give you in <a href=\"http://msdn.microsoft.com/en-us/library/41107z8a(VS.80).aspx\" rel=\"nofollow noreferrer\">respect to sorting, filtering, and iteration</a>.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1670/" ]
In VB6 you can do this: ``` Dim a As Variant a = Array(1, 2, 3) ``` Can you do a similar thing in VB.NET with specific types, like so?: ``` Dim a() As Integer a = **Array**(1, 2, 3) ```
``` Dim a() As Integer = New Integer() {1, 2, 3} ```
241,783
<p>I'm interfacing with a payment gateway and not having any luck with Net::SSLeay and its post_https subroutine. The payment gateway has issued me a client certificate that must be used for authentication. The Net::SSLeay perldoc has the following example:</p> <pre><code>($page, $response, %reply_headers) = post_https('www.bacus.pt', 443, '/foo.cgi', # 3b make_headers('Authorization' =&gt; 'Basic ' . MIME::Base64::encode("$user:$pass",'')), make_form(OK =&gt; '1', name =&gt; 'Sampo'), $mime_type6, $path_to_crt7, $path_to_key8); </code></pre> <p>My own version is below and returns the error <strong>Too many arguments for Net::SSLeay::post_https</strong>:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use Net::SSLeay qw(post_https); my %post = ( #snip ); my ($page, $response, %reply_headers) = post_https( 'www.example.com', 443, '/submit', '', make_form(%post), 'text/xml', '/path/to/cert', '/path/to/key', ); </code></pre> <p>Why is this error occurring?</p>
[ { "answer_id": 241800, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 1, "selected": false, "text": "<p>The documentation is incorrect. In my copy (Net::SSLeay 1.04) post_https is shown in the documentation with the example that you cite, but is declared to take a maximum of 6 arguments:</p>\n\n<pre><code>sub post_https ($$$;***) { do_httpx2(POST =&gt; 1, @_) }\n</code></pre>\n\n<p>I'm not yet sure how to make it work.</p>\n\n<p>Edit: Try calling post_https the old fashioned way, as a subroutine using &amp;post_https(...).</p>\n" }, { "answer_id": 241802, "author": "The Dark", "author_id": 31925, "author_profile": "https://Stackoverflow.com/users/31925", "pm_score": -1, "selected": false, "text": "<p>You have an extra comma after '/path/to/key'</p>\n" }, { "answer_id": 241844, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": true, "text": "<p>New versions of Net::SSLeay don't have the prototype that old versions have. Reading the source of old and new version I'd say the prototype was a bug (the code it calls can handle more variables than advertised).</p>\n\n<p>The solution I recommend is upgrading to a newer version of Net::SSLeay. If that is not possible, calling it like &amp;post_https can be a quick but ugly fix.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6406/" ]
I'm interfacing with a payment gateway and not having any luck with Net::SSLeay and its post\_https subroutine. The payment gateway has issued me a client certificate that must be used for authentication. The Net::SSLeay perldoc has the following example: ``` ($page, $response, %reply_headers) = post_https('www.bacus.pt', 443, '/foo.cgi', # 3b make_headers('Authorization' => 'Basic ' . MIME::Base64::encode("$user:$pass",'')), make_form(OK => '1', name => 'Sampo'), $mime_type6, $path_to_crt7, $path_to_key8); ``` My own version is below and returns the error **Too many arguments for Net::SSLeay::post\_https**: ``` #!/usr/bin/perl use strict; use warnings; use Net::SSLeay qw(post_https); my %post = ( #snip ); my ($page, $response, %reply_headers) = post_https( 'www.example.com', 443, '/submit', '', make_form(%post), 'text/xml', '/path/to/cert', '/path/to/key', ); ``` Why is this error occurring?
New versions of Net::SSLeay don't have the prototype that old versions have. Reading the source of old and new version I'd say the prototype was a bug (the code it calls can handle more variables than advertised). The solution I recommend is upgrading to a newer version of Net::SSLeay. If that is not possible, calling it like &post\_https can be a quick but ugly fix.
241,789
<p>I'm trying to parse an international datetime string similar to:</p> <pre><code>24-okt-08 21:09:06 CEST </code></pre> <p>So far I've got something like:</p> <pre><code>CultureInfo culture = CultureInfo.CreateSpecificCulture("nl-BE"); DateTime dt = DateTime.ParseExact("24-okt-08 21:09:06 CEST", "dd-MMM-yy HH:mm:ss ...", culture); </code></pre> <p>The problem is what should I use for the '...' in the format string? Looking at the <a href="http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx" rel="noreferrer">Custom Date and Time Format String</a> MSDN page doesn't seem to list a format string for parsing timezones in PST/CEST/GMT/UTC form.</p>
[ { "answer_id": 241885, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 6, "selected": true, "text": "<p>AFAIK the time zone abbreviations are not recognized. However if you replace the abbreviation with the time zone offset, it will be OK. E.g.:</p>\n\n<pre><code>DateTime dt1 = DateTime.ParseExact(\"24-okt-08 21:09:06 CEST\".Replace(\"CEST\", \"+2\"), \"dd-MMM-yy HH:mm:ss z\", culture);\nDateTime dt2 = DateTime.ParseExact(\"24-okt-08 21:09:06 CEST\".Replace(\"CEST\", \"+02\"), \"dd-MMM-yy HH:mm:ss zz\", culture);\nDateTime dt3 = DateTime.ParseExact(\"24-okt-08 21:09:06 CEST\".Replace(\"CEST\", \"+02:00\"), \"dd-MMM-yy HH:mm:ss zzz\", culture);\n</code></pre>\n" }, { "answer_id": 242136, "author": "makstaks", "author_id": 1100768, "author_profile": "https://Stackoverflow.com/users/1100768", "pm_score": 2, "selected": false, "text": "<p>I have two answers because I'm not exactly sure what you are asking.</p>\n\n<p>1) I see you are using CultureInfo, so if you just want to <strong>format</strong>\nthe date and time to be culture specific, I would separate the date/time and timezone, apply culture method on the date/time and append the timezone. If \"CEST\" is different for different cultures, you will have to change it by listing all the options (maybe in a case statement). </p>\n\n<p>2) If you want date/time to be converted to another timezone, you can't use CultureInfo, </p>\n\n<p>I suggest reading:\n<a href=\"http://msdn.microsoft.com/en-us/library/ms973825.aspx\" rel=\"nofollow noreferrer\"><strong>http://msdn.microsoft.com/en-us/library/ms973825.aspx</strong></a></p>\n\n<p>You can also use the .net framework 3.5 class TimeZoneInfo (different from TimeZone) to make your life easier.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx</a></p>\n" }, { "answer_id": 7662252, "author": "Deep Kumar", "author_id": 790860, "author_profile": "https://Stackoverflow.com/users/790860", "pm_score": -1, "selected": false, "text": "<p>Here's what I had to do. </p>\n\n<p>I receive the datetime from javascript and then pass it on to ASP.NET to store in Oracle database. Here is my C# code for Eastern and Central times. </p>\n\n<pre><code>string datetimevalue = hidfileDateTime.Value; \n\ndatetimevalue= datetimevalue.Replace(\"EDT\", \"EST\"); \ndatetimevalue = datetimevalue.Replace(\"CDT\", \"CST\");\nif (datetimevalue.Contains(\"CST\"))\n{\n filedt = DateTime.ParseExact(datetimevalue, \"ddd MMM d HH:mm:ss CST yyyy\", provider).ToUniversalTime().AddHours(1).ToLocalTime();\n}\nelse\n{\n filedt = DateTime.ParseExact(datetimevalue, \"ddd MMM d HH:mm:ss EST yyyy\", provider);\n}\n</code></pre>\n" }, { "answer_id": 22868721, "author": "Jodrell", "author_id": 659190, "author_profile": "https://Stackoverflow.com/users/659190", "pm_score": 5, "selected": false, "text": "<p>The quick answer is, you can't do it.</p>\n\n<hr>\n\n<p>Here is why,</p>\n\n<p>There is a definitive database of world timezones, you can get it from the <a href=\"http://www.iana.org/time-zones\" rel=\"noreferrer\">IANA here</a>.</p>\n\n<p>The problem is, the 3 or 4 letter abbreviations have a many-to-one association with the IANA timezones. For instance <a href=\"http://www.timeanddate.com/library/abbreviations/timezones/\" rel=\"noreferrer\"><code>\"AMT\"</code></a> means different things, depending on your culture, what part of the world you are in and the context of your application.</p>\n\n<pre><code>AMT \"Armenia Time\" Asia UTC + 4 hours \nAMT \"Amazon Time\" South America UTC - 4 hours \n</code></pre>\n\n<p>If you really want to tackle this, I suggest using <a href=\"http://nodatime.org/\" rel=\"noreferrer\">Noda Time</a> to represent your <code>Instance</code>s. You'll have to write some code to convert the abbreviations to a standard IANA timezone.</p>\n\n<p><strong>We can't do this for you, it depends on the context of your application.</strong></p>\n\n<hr>\n\n<p>Another good example is <a href=\"http://www.timeanddate.com/library/abbreviations/timezones/\" rel=\"noreferrer\"><code>\"CST\"</code></a>.</p>\n\n<pre><code>CST \"China Standard Time\" Asia UTC + 8 hours \nCST \"Central Standard Time\" Central America UTC - 6 hours \nCST \"Cuba Standard Time\" Caribbean UTC - 5 hours \nCST \"Central Standard Time\" North America UTC - 6 hours \n</code></pre>\n" }, { "answer_id": 30303587, "author": "Jussi Palo", "author_id": 1441451, "author_profile": "https://Stackoverflow.com/users/1441451", "pm_score": 4, "selected": false, "text": "<p>Dictionary of abbreviations if you decide to go the search&amp;replace route (I did).</p>\n\n<pre><code>Dictionary&lt;string, string&gt; _timeZones = new Dictionary&lt;string, string&gt;() {\n {\"ACDT\", \"+1030\"},\n {\"ACST\", \"+0930\"},\n {\"ADT\", \"-0300\"},\n {\"AEDT\", \"+1100\"},\n {\"AEST\", \"+1000\"},\n {\"AHDT\", \"-0900\"},\n {\"AHST\", \"-1000\"},\n {\"AST\", \"-0400\"},\n {\"AT\", \"-0200\"},\n {\"AWDT\", \"+0900\"},\n {\"AWST\", \"+0800\"},\n {\"BAT\", \"+0300\"},\n {\"BDST\", \"+0200\"},\n {\"BET\", \"-1100\"},\n {\"BST\", \"-0300\"},\n {\"BT\", \"+0300\"},\n {\"BZT2\", \"-0300\"},\n {\"CADT\", \"+1030\"},\n {\"CAST\", \"+0930\"},\n {\"CAT\", \"-1000\"},\n {\"CCT\", \"+0800\"},\n {\"CDT\", \"-0500\"},\n {\"CED\", \"+0200\"},\n {\"CET\", \"+0100\"},\n {\"CEST\", \"+0200\"},\n {\"CST\", \"-0600\"},\n {\"EAST\", \"+1000\"},\n {\"EDT\", \"-0400\"},\n {\"EED\", \"+0300\"},\n {\"EET\", \"+0200\"},\n {\"EEST\", \"+0300\"},\n {\"EST\", \"-0500\"},\n {\"FST\", \"+0200\"},\n {\"FWT\", \"+0100\"},\n {\"GMT\", \"GMT\"},\n {\"GST\", \"+1000\"},\n {\"HDT\", \"-0900\"},\n {\"HST\", \"-1000\"},\n {\"IDLE\", \"+1200\"},\n {\"IDLW\", \"-1200\"},\n {\"IST\", \"+0530\"},\n {\"IT\", \"+0330\"},\n {\"JST\", \"+0900\"},\n {\"JT\", \"+0700\"},\n {\"MDT\", \"-0600\"},\n {\"MED\", \"+0200\"},\n {\"MET\", \"+0100\"},\n {\"MEST\", \"+0200\"},\n {\"MEWT\", \"+0100\"},\n {\"MST\", \"-0700\"},\n {\"MT\", \"+0800\"},\n {\"NDT\", \"-0230\"},\n {\"NFT\", \"-0330\"},\n {\"NT\", \"-1100\"},\n {\"NST\", \"+0630\"},\n {\"NZ\", \"+1100\"},\n {\"NZST\", \"+1200\"},\n {\"NZDT\", \"+1300\"},\n {\"NZT\", \"+1200\"},\n {\"PDT\", \"-0700\"},\n {\"PST\", \"-0800\"},\n {\"ROK\", \"+0900\"},\n {\"SAD\", \"+1000\"},\n {\"SAST\", \"+0900\"},\n {\"SAT\", \"+0900\"},\n {\"SDT\", \"+1000\"},\n {\"SST\", \"+0200\"},\n {\"SWT\", \"+0100\"},\n {\"USZ3\", \"+0400\"},\n {\"USZ4\", \"+0500\"},\n {\"USZ5\", \"+0600\"},\n {\"USZ6\", \"+0700\"},\n {\"UT\", \"-0000\"},\n {\"UTC\", \"-0000\"},\n {\"UZ10\", \"+1100\"},\n {\"WAT\", \"-0100\"},\n {\"WET\", \"-0000\"},\n {\"WST\", \"+0800\"},\n {\"YDT\", \"-0800\"},\n {\"YST\", \"-0900\"},\n {\"ZP4\", \"+0400\"},\n {\"ZP5\", \"+0500\"},\n {\"ZP6\", \"+0600\"}\n };\n</code></pre>\n" }, { "answer_id": 49252458, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 1, "selected": false, "text": "<p>This is how:</p>\n\n<ol>\n<li>Get the string (precondition: format: ddd, dd MMM yyyy HH:mm:ss zzz)</li>\n<li>Get the last whitespace</li>\n<li>Remove zzz from string, but save value of zzz</li>\n<li>Lookup offset for zzz</li>\n<li>Add offset to string</li>\n</ol>\n\n<blockquote>\n<pre><code>string dateString = reader.ReadContentAsString();\nint timeZonePos = dateString.LastIndexOf(' ') + 1;\nstring tz = dateString.Substring(timeZonePos);\ndateString = dateString.Substring(0, dateString.Length - tz.Length );\ndateString += s_timeZoneOffsets[tz];\n\n// https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx\n//string es = reader.ReadElementString(\"pubDate\");\nthis.m_value = System.DateTime.ParseExact(dateString, \"ddd, dd MMM yyyy HH:mm zzz\", System.Globalization.CultureInfo.InvariantCulture);\n</code></pre>\n</blockquote>\n\n<p>with </p>\n\n<pre><code>private static System.Collections.Generic.Dictionary&lt;string, string&gt; s_timeZoneOffsets =\n new System.Collections.Generic.Dictionary&lt;string, string&gt;() {\n {\"ACDT\", \"+10:30\"},\n {\"ACST\", \"+09:30\"},\n {\"ADT\", \"-03:00\"},\n {\"AEDT\", \"+11:00\"},\n {\"AEST\", \"+10:00\"},\n {\"AHDT\", \"-09:00\"},\n {\"AHST\", \"-10:00\"},\n {\"AST\", \"-04:00\"},\n {\"AT\", \"-02:00\"},\n {\"AWDT\", \"+09:00\"},\n {\"AWST\", \"+08:00\"},\n {\"BAT\", \"+03:00\"},\n {\"BDST\", \"+02:00\"},\n {\"BET\", \"-11:00\"},\n {\"BST\", \"-03:00\"},\n {\"BT\", \"+03:00\"},\n {\"BZT2\", \"-03:00\"},\n {\"CADT\", \"+10:30\"},\n {\"CAST\", \"+09:30\"},\n {\"CAT\", \"-10:00\"},\n {\"CCT\", \"+08:00\"},\n {\"CDT\", \"-05:00\"},\n {\"CED\", \"+02:00\"},\n {\"CET\", \"+01:00\"},\n {\"CEST\", \"+02:00\"},\n {\"CST\", \"-06:00\"},\n {\"EAST\", \"+10:00\"},\n {\"EDT\", \"-04:00\"},\n {\"EED\", \"+03:00\"},\n {\"EET\", \"+02:00\"},\n {\"EEST\", \"+03:00\"},\n {\"EST\", \"-05:00\"},\n {\"FST\", \"+02:00\"},\n {\"FWT\", \"+01:00\"},\n {\"GMT\", \"+00:00\"},\n {\"GST\", \"+10:00\"},\n {\"HDT\", \"-09:00\"},\n {\"HST\", \"-10:00\"},\n {\"IDLE\", \"+12:00\"},\n {\"IDLW\", \"-12:00\"},\n {\"IST\", \"+05:30\"},\n {\"IT\", \"+03:30\"},\n {\"JST\", \"+09:00\"},\n {\"JT\", \"+07:00\"},\n {\"MDT\", \"-06:00\"},\n {\"MED\", \"+02:00\"},\n {\"MET\", \"+01:00\"},\n {\"MEST\", \"+02:00\"},\n {\"MEWT\", \"+01:00\"},\n {\"MST\", \"-07:00\"},\n {\"MT\", \"+08:00\"},\n {\"NDT\", \"-02:30\"},\n {\"NFT\", \"-03:30\"},\n {\"NT\", \"-11:00\"},\n {\"NST\", \"+06:30\"},\n {\"NZ\", \"+11:00\"},\n {\"NZST\", \"+12:00\"},\n {\"NZDT\", \"+13:00\"},\n {\"NZT\", \"+12:00\"},\n {\"PDT\", \"-07:00\"},\n {\"PST\", \"-08:00\"},\n {\"ROK\", \"+09:00\"},\n {\"SAD\", \"+10:00\"},\n {\"SAST\", \"+09:00\"},\n {\"SAT\", \"+09:00\"},\n {\"SDT\", \"+10:00\"},\n {\"SST\", \"+02:00\"},\n {\"SWT\", \"+01:00\"},\n {\"USZ3\", \"+04:00\"},\n {\"USZ4\", \"+05:00\"},\n {\"USZ5\", \"+06:00\"},\n {\"USZ6\", \"+07:00\"},\n {\"UT\", \"-00:00\"},\n {\"UTC\", \"-00:00\"},\n {\"UZ10\", \"+11:00\"},\n {\"WAT\", \"-01:00\"},\n {\"WET\", \"-00:00\"},\n {\"WST\", \"+08:00\"},\n {\"YDT\", \"-08:00\"},\n {\"YST\", \"-09:00\"},\n {\"ZP4\", \"+04:00\"},\n {\"ZP5\", \"+05:00\"},\n {\"ZP6\", \"+06:00\"}\n};\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/163/" ]
I'm trying to parse an international datetime string similar to: ``` 24-okt-08 21:09:06 CEST ``` So far I've got something like: ``` CultureInfo culture = CultureInfo.CreateSpecificCulture("nl-BE"); DateTime dt = DateTime.ParseExact("24-okt-08 21:09:06 CEST", "dd-MMM-yy HH:mm:ss ...", culture); ``` The problem is what should I use for the '...' in the format string? Looking at the [Custom Date and Time Format String](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx) MSDN page doesn't seem to list a format string for parsing timezones in PST/CEST/GMT/UTC form.
AFAIK the time zone abbreviations are not recognized. However if you replace the abbreviation with the time zone offset, it will be OK. E.g.: ``` DateTime dt1 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+2"), "dd-MMM-yy HH:mm:ss z", culture); DateTime dt2 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02"), "dd-MMM-yy HH:mm:ss zz", culture); DateTime dt3 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02:00"), "dd-MMM-yy HH:mm:ss zzz", culture); ```
241,790
<p>There have been a couple of questions that sort of dealt with this but not covering my exact question so here we go.</p> <p>For site settings, if these are stored in a database do you:</p> <ol> <li>retrieve them from the db every time someone makes a request</li> <li>store them in a session variable on login</li> <li>???????</li> </ol> <p>For user specific settings do I do the same as site settings??</p> <p>Any guidance/best practice would be greatly appreciated.</p> <p>Cheers</p>
[ { "answer_id": 241820, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 0, "selected": false, "text": "<p>Generally I would put site settings in the web.config file, unless you are building an application that has multiple sites and gets changed by the application itself frequently, it usually wouldn't make sense to put it in the database at first.</p>\n\n<p>For user specific settings I would look into starting with the default asp.net Profile Provider which will store the settings in the database and manage the retrival of the user settings once per Request and save the updates to the end to minimize the number of DB calls. Once you start to hit performance problems you can consider extending the profile provider for caching and/or your specific needs.</p>\n" }, { "answer_id": 241823, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 1, "selected": false, "text": "<p>I suggest creating a module for retrieving preferences that could be implemented either way, and then for your first implementation hit the database every time since that's easier. If you have performance problems, add caching to the module to reduce the database traffic.</p>\n" }, { "answer_id": 241946, "author": "Jeff Fritz", "author_id": 29156, "author_profile": "https://Stackoverflow.com/users/29156", "pm_score": 2, "selected": true, "text": "<p>I prefer an approach like Glomek proposes... Caching the settings in the WebCache will greatly enhance speed of access. Consider the following:</p>\n\n<pre><code> #region Data Access\n\nprivate string GetSettingsFromDb(string settingName)\n{\n return \"\";\n}\nprivate Dictionary&lt;string,string&gt; GetSettingsFromDb()\n{\n return new Dictionary&lt;string, string&gt;();\n}\n\n#endregion\n\nprivate const string KEY_SETTING1 = \"Setting1\";\npublic string Setting1\n{\n get\n {\n if (Cache.Get(KEY_SETTING1) != null)\n return Cache.Get(KEY_SETTING1).ToString();\n\n Setting1 = GetSettingsFromDb(KEY_SETTING1);\n\n return Setting1;\n\n } \n set\n {\n Cache.Remove(KEY_SETTING1);\n Cache.Insert(KEY_SETTING1, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(2));\n }\n}\n\nprivate Cache Cache { get { return HttpContext.Current.Cache; } }\n</code></pre>\n\n<p>You'll get the dynamic loading goodness, memory conservation of tossing items out of Cache after 2 hours of non-use, and the flush and reload you need when the settings are modified.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29376/" ]
There have been a couple of questions that sort of dealt with this but not covering my exact question so here we go. For site settings, if these are stored in a database do you: 1. retrieve them from the db every time someone makes a request 2. store them in a session variable on login 3. ??????? For user specific settings do I do the same as site settings?? Any guidance/best practice would be greatly appreciated. Cheers
I prefer an approach like Glomek proposes... Caching the settings in the WebCache will greatly enhance speed of access. Consider the following: ``` #region Data Access private string GetSettingsFromDb(string settingName) { return ""; } private Dictionary<string,string> GetSettingsFromDb() { return new Dictionary<string, string>(); } #endregion private const string KEY_SETTING1 = "Setting1"; public string Setting1 { get { if (Cache.Get(KEY_SETTING1) != null) return Cache.Get(KEY_SETTING1).ToString(); Setting1 = GetSettingsFromDb(KEY_SETTING1); return Setting1; } set { Cache.Remove(KEY_SETTING1); Cache.Insert(KEY_SETTING1, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(2)); } } private Cache Cache { get { return HttpContext.Current.Cache; } } ``` You'll get the dynamic loading goodness, memory conservation of tossing items out of Cache after 2 hours of non-use, and the flush and reload you need when the settings are modified.
241,819
<p>What's the difference between the two and when should I use each:</p> <pre><code>&lt;person&gt; &lt;firstname&gt;Joe&lt;/firstname&gt; &lt;lastname&gt;Plumber&lt;/lastname&gt; &lt;/person&gt; </code></pre> <p>versus</p> <pre><code>&lt;person firstname="Joe" lastname="Plumber" /&gt; </code></pre> <p>Thanks</p>
[ { "answer_id": 241828, "author": "LeopardSkinPillBoxHat", "author_id": 22489, "author_profile": "https://Stackoverflow.com/users/22489", "pm_score": 2, "selected": false, "text": "<p>In my company, we would favour the 2nd approach.</p>\n\n<p>The way we think about it is that \"firstname\" and \"lastname\" are <em>attributes</em> of the \"person\" node, rather than <em>sub-fields</em> of the \"person\" node. It's a subtle difference. </p>\n\n<p>In my opinion the 2nd approach is more concise, and readability/maintainability is significantly improved, which is very important.</p>\n\n<p>Of course it would depend on your application. I don't think there is a blanket rule that covers all scenarios.</p>\n" }, { "answer_id": 241829, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "<p>Attributes are not order sensitive. This may be an advantage or a disadvantage depending on your situation.</p>\n\n<p>Attributes cannot be duplicated. If \"Joe\" has two first names, then nodes are the only way to go.</p>\n" }, { "answer_id": 241834, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>Sometime in the future when you add an <code>&lt;address&gt;</code> property, you won't want to make it an XML attribute. This is because an <code>&lt;address&gt;</code> might be a more complex element made up of street address, city, country, etc.</p>\n\n<p>For this reason, you may want to choose the first subelement form unless you're really sure that the attribute won't need to go much deeper. The first form allows for greater extensibility in the future.</p>\n\n<p>If you're at all concerned about space, compress your XML.</p>\n" }, { "answer_id": 241847, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 7, "selected": true, "text": "<p>There are element centric and attribute centric XML, in your example, the first one is element centric, the second is\nattribute centric.</p>\n<p>Most of the time, these two patterns are equivalent, however there are some exceptions.</p>\n<p><strong>Attribute centric</strong></p>\n<ul>\n<li>Smaller size than element centric.</li>\n<li>Not very interoperable, since most XML parsers will think the user data is presented by the element, Attributes are used to describe the element.</li>\n<li>There is no way to present nullable value for some data type. e.g. nullable int</li>\n<li>Can not express complex type.</li>\n</ul>\n<p><strong>Element centric</strong></p>\n<ul>\n<li>Complex type can be only presented as an element node.</li>\n<li>Very interoperable</li>\n<li>Bigger size than attribute centric. (Compression can be used to reduce the size significantly.)</li>\n<li>Nullable data can be expressed with attribute xsi:nil=&quot;true&quot;</li>\n<li>Faster to parse since the parser only looks to elements for user data.</li>\n</ul>\n<p><strong>Practical</strong></p>\n<p>If you really care about the size of your XML, use an attribute whenever you can, if it is appropriate. Use elements where you need something nullable, a complex type, or to hold a large text value. If you don't care about the size of XML or you have compression enabled during transportation, stick with elements as they are more extensible.</p>\n<p><strong>Background</strong></p>\n<p>In DOT NET, XmlSerializer can serialize properties of objects into either attributes or elements.\nIn the recent WCF framework, DataContract serializer can only serialize properties into elements and it is faster than XmlSerializer; the reason is obvious, it just needs to look for user data from elements while deserializing.</p>\n<p>Here an article that explains it as well\n<a href=\"http://www.ibm.com/developerworks/xml/library/x-eleatt.html\" rel=\"nofollow noreferrer\">Element vs attribute</a></p>\n" }, { "answer_id": 30951951, "author": "JavaHopper", "author_id": 3059893, "author_profile": "https://Stackoverflow.com/users/3059893", "pm_score": 2, "selected": false, "text": "<p>I found following information very helpful in explaining the choice of attributes vs elements in a short fashion</p>\n\n<p>Some of the problems with using attributes are:</p>\n\n<p>attributes cannot contain multiple values (elements can)<br>\nattributes cannot contain tree structures (elements can)<br>\nattributes are not easily expandable (for future changes)<br></p>\n\n<p>Attributes are difficult to read and maintain. Use elements for data. Use attributes for information that is not relevant to the data.</p>\n\n<p>source : <a href=\"http://www.w3schools.com/xml/xml_attributes.asp\" rel=\"nofollow\">http://www.w3schools.com/xml/xml_attributes.asp</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24059/" ]
What's the difference between the two and when should I use each: ``` <person> <firstname>Joe</firstname> <lastname>Plumber</lastname> </person> ``` versus ``` <person firstname="Joe" lastname="Plumber" /> ``` Thanks
There are element centric and attribute centric XML, in your example, the first one is element centric, the second is attribute centric. Most of the time, these two patterns are equivalent, however there are some exceptions. **Attribute centric** * Smaller size than element centric. * Not very interoperable, since most XML parsers will think the user data is presented by the element, Attributes are used to describe the element. * There is no way to present nullable value for some data type. e.g. nullable int * Can not express complex type. **Element centric** * Complex type can be only presented as an element node. * Very interoperable * Bigger size than attribute centric. (Compression can be used to reduce the size significantly.) * Nullable data can be expressed with attribute xsi:nil="true" * Faster to parse since the parser only looks to elements for user data. **Practical** If you really care about the size of your XML, use an attribute whenever you can, if it is appropriate. Use elements where you need something nullable, a complex type, or to hold a large text value. If you don't care about the size of XML or you have compression enabled during transportation, stick with elements as they are more extensible. **Background** In DOT NET, XmlSerializer can serialize properties of objects into either attributes or elements. In the recent WCF framework, DataContract serializer can only serialize properties into elements and it is faster than XmlSerializer; the reason is obvious, it just needs to look for user data from elements while deserializing. Here an article that explains it as well [Element vs attribute](http://www.ibm.com/developerworks/xml/library/x-eleatt.html)
241,857
<p>I'm trying to use XPath to parse an XML document. One of my NSXMLElement's looks like the following, hypothetically speaking:</p> <pre><code>&lt;foo bar="yummy"&gt; </code></pre> <p>I'm trying to get the value for the attribute bar, however any interpretation of code I use, gives me back bar="woo", which means I need to do further string processing in order to obtain access to woo and woo alone.</p> <p>Essentially I'm doing something like</p> <pre><code>NSArray *nodes = [xmlDoc nodesForXPath:@"foo/@bar" error:&amp;error]; xmlElement = [nodes objectAtIndex:0]; </code></pre> <p>Is there anyway to write the code above to just give me yummy, versus bar="yummy" so I can relieve myself of parsing the string?</p> <p>Thanks.</p> <hr> <p>Assuming TouchXML is being used, is there still anyway to obtain similar results? As in grabbing just the value for the attribute, without the attribute="value"? That results in then further having to parse the string to get the value out.</p>
[ { "answer_id": 241888, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "<p>If you're trying to use the NSXMLDocument class on an iPhone, you're going to be sorely disappointed, because this class (and related NSXMLNode, NSXMLElement, etc classes) are not available on the phone (they ARE available in the Simulator, which can be confusing). </p>\n\n<p>Take a look at libxml2 to do XML parsing on the phone. There are several free frameworks (I believe TouchXML is a good one) for doing this.</p>\n\n<p>That being said, if you want to run this code on a Mac, you can use the NSXMLElement method <code>-attributeForName:</code> to pull out just the attribute you want.</p>\n" }, { "answer_id": 242013, "author": "Noah Witherspoon", "author_id": 30618, "author_profile": "https://Stackoverflow.com/users/30618", "pm_score": 2, "selected": false, "text": "<p>Ben's right - while iPhone-SDK code will build with NSXMLDocument and run in the simulator, it won't work at all on the device. The docs probably mention it somewhere, but it's fairly obscure. TouchXML is part of TouchCode; you can find more information about it <a href=\"http://code.google.com/p/touchcode/wiki/TouchXML\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 242218, "author": "Brian Gianforcaro", "author_id": 3415, "author_profile": "https://Stackoverflow.com/users/3415", "pm_score": 3, "selected": true, "text": "<p>The TouchXML API is supposed to be an exact duplicate of Apple's NSXML implementation, so it should be the same except you'll replaces all NS-Method's with C-Methods.</p>\n<blockquote>\n<p>The TouxhXML classes map directly to the NSXML classes. <strong>NSXMLNode -&gt; CXMLNode</strong>, <strong>NSXMLDocument -&gt; CXMLDocument</strong>, <strong>NSXMLElement -&gt; CXMLElement</strong>. For obvious reasons you can't mix and match NSXML and TouchXML classes.</p>\n<p>The TouxhXML methods map directly to NSXML methods as well, but only a small subset of methods are supported. Constant and enum names are almost equivalent (CXML... vs NSXML...) but constant values will not be equival</p>\n</blockquote>\n<p><a href=\"http://code.google.com/p/touchcode/wiki/TouchXMLImplementation\" rel=\"nofollow noreferrer\">reference</a></p>\n<p>Using either the regular Apple classes or the TouchXML framework the following code will give you just the string &quot;yummy&quot; for your example.</p>\n<pre><code> NSArray *nodes = [xmlDoc nodesForXPath:@&quot;./foo/@bar&quot; error:&amp;err];\n NSString *value = [[nodes objectAtIndex:0] stringValue];\n</code></pre>\n<p>Good Luck,</p>\n<p><strong>Brian G</strong></p>\n" }, { "answer_id": 303497, "author": "Ryan Townshend", "author_id": 24707, "author_profile": "https://Stackoverflow.com/users/24707", "pm_score": 0, "selected": false, "text": "<p>The iPhone does have access to NSXMLParser which is a nice little sax parser.\nAaron Hillegass has a good article on using NSXMLParser.\nIt doesn't support XPath, but is pretty handy at ripping xml into your data objects.</p>\n\n<p><a href=\"http://weblog.bignerdranch.com/?p=48\" rel=\"nofollow noreferrer\">Parsing XML in Cocoa</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to use XPath to parse an XML document. One of my NSXMLElement's looks like the following, hypothetically speaking: ``` <foo bar="yummy"> ``` I'm trying to get the value for the attribute bar, however any interpretation of code I use, gives me back bar="woo", which means I need to do further string processing in order to obtain access to woo and woo alone. Essentially I'm doing something like ``` NSArray *nodes = [xmlDoc nodesForXPath:@"foo/@bar" error:&error]; xmlElement = [nodes objectAtIndex:0]; ``` Is there anyway to write the code above to just give me yummy, versus bar="yummy" so I can relieve myself of parsing the string? Thanks. --- Assuming TouchXML is being used, is there still anyway to obtain similar results? As in grabbing just the value for the attribute, without the attribute="value"? That results in then further having to parse the string to get the value out.
The TouchXML API is supposed to be an exact duplicate of Apple's NSXML implementation, so it should be the same except you'll replaces all NS-Method's with C-Methods. > > The TouxhXML classes map directly to the NSXML classes. **NSXMLNode -> CXMLNode**, **NSXMLDocument -> CXMLDocument**, **NSXMLElement -> CXMLElement**. For obvious reasons you can't mix and match NSXML and TouchXML classes. > > > The TouxhXML methods map directly to NSXML methods as well, but only a small subset of methods are supported. Constant and enum names are almost equivalent (CXML... vs NSXML...) but constant values will not be equival > > > [reference](http://code.google.com/p/touchcode/wiki/TouchXMLImplementation) Using either the regular Apple classes or the TouchXML framework the following code will give you just the string "yummy" for your example. ``` NSArray *nodes = [xmlDoc nodesForXPath:@"./foo/@bar" error:&err]; NSString *value = [[nodes objectAtIndex:0] stringValue]; ``` Good Luck, **Brian G**
241,860
<p>Say I want to get the HTML of</p> <pre>http://www.google.com</pre> <p>as a String using some built-in classes of the Cocoa Touch framework.</p> <p>What is the least amount of code I need to write?</p> <p>I've gotten this far, but can't figure out how to progress. There must be an easier way.</p> <pre><code>CFHTTPMessageRef req; NSURL *url = [NSURL URLWithString:@"http://www.google.com"]; req = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), (CFURLRef)url, kCFHTTPVersion1_1); </code></pre>
[ { "answer_id": 241875, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 4, "selected": true, "text": "<p>The <i>quickest</i> way is to use NSString's <code>+stringWithContentsOfURL:</code> method. However, this is a modal call, and your application will be non-responsive while it runs. You can either move it to a background thread, or use the NSURLConnection class to make a proper, asynchronous request.</p>\n" }, { "answer_id": 242257, "author": "Brian Gianforcaro", "author_id": 3415, "author_profile": "https://Stackoverflow.com/users/3415", "pm_score": 3, "selected": false, "text": "<p>One way to do this is as follows, however as <strong>Ben Gottlieb</strong> points out, this is a synchronouseRequest and will cause your program's execution to wait on the return of this function call, possibly making your application non-responsive. </p>\n\n<pre><code>NSURL *url = [ NSURL URLWithString: @\"http://www.google.com\"]; \nNSURLRequest *req = [ NSURLRequest requestWithURL:url\n cachePolicy:NSURLRequestReloadIgnoringCacheData\n timeoutInterval:30.0 ];\nNSError *err;\nNSURLResponse *res;\nNSData *d = [ NSURLConnection sendSynchronousRequest:req\n returningResponse:&amp;res\n error:&amp;err ];\n</code></pre>\n\n<p>You can find information on writing the proper delegate methods to handle a Asynchronous Connection <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-170129\" rel=\"noreferrer\">here</a> on the Apple dev-docs.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
Say I want to get the HTML of ``` http://www.google.com ``` as a String using some built-in classes of the Cocoa Touch framework. What is the least amount of code I need to write? I've gotten this far, but can't figure out how to progress. There must be an easier way. ``` CFHTTPMessageRef req; NSURL *url = [NSURL URLWithString:@"http://www.google.com"]; req = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), (CFURLRef)url, kCFHTTPVersion1_1); ```
The *quickest* way is to use NSString's `+stringWithContentsOfURL:` method. However, this is a modal call, and your application will be non-responsive while it runs. You can either move it to a background thread, or use the NSURLConnection class to make a proper, asynchronous request.
241,868
<p>My client has an old MS SQL 2000 database that uses varchar(50) fields to store names. He tried to use this database to capture some data (via a web form). Some of the form-fillers are from other countries, and the varchar fields went nutty when some of these folks entered their names. Is it possible to recover the data somehow? Maybe by guessing what the character should be based on what it resolved to in ASCII/varchar and the country the person is from? Some of the data:</p> <p>Name / Country / First or Last Name?<br> Jiří / CZE / F<br> Torbjörn / FIN / F<br> Huszár / HUN / L<br> Jürgen / DEU / F<br> Müller / CHE / L<br> Bumbálková / CZE / L<br> Doležal / CZE / L<br> Loïc / DEU / L </p> <p>By the way, the web form specified this content-type:</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; </code></pre>
[ { "answer_id": 241944, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 0, "selected": false, "text": "<p>You basically need to poke it through libiconv, converting it to UTF8. </p>\n\n<p>A full list of appropriate character sets is going to depend on your application, but you can make some guesses based on the country code. Start with <a href=\"http://en.wikipedia.org/wiki/8859\" rel=\"nofollow noreferrer\">this page on WikiPedia</a>. </p>\n\n<p>Warning: <strong>You will need a human to verify <em>each</em> conversion.</strong></p>\n" }, { "answer_id": 241951, "author": "Richard A", "author_id": 24355, "author_profile": "https://Stackoverflow.com/users/24355", "pm_score": 4, "selected": true, "text": "<p>Working from the 5th example.</p>\n\n<p>à is ascii #195 (C3). \n¼ is ascii #188 (BC).</p>\n\n<p>I'd guess that Müller is meant to be Müller. </p>\n\n<p>If this is UTF-8, based upon\n<a href=\"http://en.wikipedia.org/wiki/UTF-8#Description\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/UTF-8#Description</a></p>\n\n<p>We've got \nC3 BC = 1100 0011 1011 1100</p>\n\n<p>Applying the UTF-8 mapping:</p>\n\n<p>(110) 00011 (10) 11 1100</p>\n\n<p>0000 0000 1111 1100</p>\n\n<p>00FC which is Unicode ü</p>\n\n<p>U+00FC (see <a href=\"http://en.wikipedia.org/wiki/Latin_characters_in_Unicode\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Latin_characters_in_Unicode</a>)</p>\n\n<p>Seems to me that you could work through this programmatically.</p>\n\n<p>Now solving the first example:</p>\n\n<p>Jiå™ã was actually Jiří (The final character not shown).</p>\n\n<p>Ignoring the Ji, which is correct,</p>\n\n<p>C5 99 c3 AD</p>\n\n<p>(110)0 0101 (10)01 1001 (110)0 0011 (10)10 1101</p>\n\n<p>0159 00ED</p>\n\n<p>ří</p>\n\n<p>So the name is: Jiří. Wikipedia says that special r is Czech and so is the i. Furthermore if I google Jiří (<a href=\"http://www.google.com/search?q=Ji%C5%99%C3%AD&amp;ie=utf-8&amp;oe=utf-8\" rel=\"nofollow noreferrer\">http://www.google.com/search?q=Ji%C5%99%C3%AD&amp;ie=utf-8&amp;oe=utf-8</a>) I get plenty of hits. We're on a winner here.</p>\n\n<p>The second example, Torbjörn, maps nicely to Torbjörn which sounds convincing.</p>\n\n<p>IMHO there's no great need for human checking of these, they seem to just work.</p>\n" }, { "answer_id": 241966, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 1, "selected": false, "text": "<p>The Russian post office did it. Did anyone save the image before it disappeared?</p>\n\n<p><a href=\"http://forums.thedailywtf.com/forums/p/7156/133456.aspx\" rel=\"nofollow noreferrer\">http://forums.thedailywtf.com/forums/p/7156/133456.aspx</a></p>\n" }, { "answer_id": 242183, "author": "Frentos", "author_id": 23978, "author_profile": "https://Stackoverflow.com/users/23978", "pm_score": 0, "selected": false, "text": "<p>Further to Richard's comments: if the web page containing the form specifies a character set (e.g. iso-8859-1 == unicode) &amp; encoding (e.g. utf-8) then a standards-compliant browser should submit form data using that character set and encoding. If your web pages specified unicode, then you should't have to cope with random Microsoft codepages in the data - it should all be unicode.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13700/" ]
My client has an old MS SQL 2000 database that uses varchar(50) fields to store names. He tried to use this database to capture some data (via a web form). Some of the form-fillers are from other countries, and the varchar fields went nutty when some of these folks entered their names. Is it possible to recover the data somehow? Maybe by guessing what the character should be based on what it resolved to in ASCII/varchar and the country the person is from? Some of the data: Name / Country / First or Last Name? Jiří / CZE / F Torbjörn / FIN / F Huszár / HUN / L Jürgen / DEU / F Müller / CHE / L Bumbálková / CZE / L Doležal / CZE / L Loïc / DEU / L By the way, the web form specified this content-type: ``` <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ```
Working from the 5th example. à is ascii #195 (C3). ¼ is ascii #188 (BC). I'd guess that Müller is meant to be Müller. If this is UTF-8, based upon <http://en.wikipedia.org/wiki/UTF-8#Description> We've got C3 BC = 1100 0011 1011 1100 Applying the UTF-8 mapping: (110) 00011 (10) 11 1100 0000 0000 1111 1100 00FC which is Unicode ü U+00FC (see <http://en.wikipedia.org/wiki/Latin_characters_in_Unicode>) Seems to me that you could work through this programmatically. Now solving the first example: Jiå™ã was actually Jiří (The final character not shown). Ignoring the Ji, which is correct, C5 99 c3 AD (110)0 0101 (10)01 1001 (110)0 0011 (10)10 1101 0159 00ED ří So the name is: Jiří. Wikipedia says that special r is Czech and so is the i. Furthermore if I google Jiří (<http://www.google.com/search?q=Ji%C5%99%C3%AD&ie=utf-8&oe=utf-8>) I get plenty of hits. We're on a winner here. The second example, Torbjörn, maps nicely to Torbjörn which sounds convincing. IMHO there's no great need for human checking of these, they seem to just work.
241,873
<p>i need to redirect all of the stdout of a program except the first line into a file. </p> <p>Is there a common unix program that removes lines from stdin and spits the rest out to stdout?</p>
[ { "answer_id": 241878, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "<p>tail -n +2 -f -</p>\n" }, { "answer_id": 241881, "author": "jwa", "author_id": 31933, "author_profile": "https://Stackoverflow.com/users/31933", "pm_score": 0, "selected": false, "text": "<p>sed -e 1d &lt; input > output</p>\n" }, { "answer_id": 241884, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 6, "selected": true, "text": "<p>Others have already mentioned \"tail\". sed will also work:</p>\n\n<pre><code>sed 1d\n</code></pre>\n\n<p>As will Awk:</p>\n\n<pre><code>awk 'NR &gt; 1'\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17076/" ]
i need to redirect all of the stdout of a program except the first line into a file. Is there a common unix program that removes lines from stdin and spits the rest out to stdout?
Others have already mentioned "tail". sed will also work: ``` sed 1d ``` As will Awk: ``` awk 'NR > 1' ```
241,892
<p>I'm investigating SUDS as a SOAP client for python. I want to inspect the methods available from a specified service, and the types required by a specified method.</p> <p>The aim is to generate a user interface, allowing users to select a method, then fill in values in a dynamically generated form.</p> <p>I can get some information on a particular method, but am unsure how to parse it:</p> <pre><code>client = Client(url) method = client.sd.service.methods['MyMethod'] </code></pre> <p>I am unable to <strong>programmaticaly</strong> figure out what object type I need to create to be able to call the service</p> <pre><code>obj = client.factory.create('?') res = client.service.MyMethod(obj, soapheaders=authen) </code></pre> <p>Does anyone have some sample code?</p>
[ { "answer_id": 1842812, "author": "artdanil", "author_id": 214178, "author_profile": "https://Stackoverflow.com/users/214178", "pm_score": 4, "selected": false, "text": "<p>According to <code>suds</code> <a href=\"https://fedorahosted.org/suds/wiki/Documentation#BASICUSAGE\" rel=\"noreferrer\">documentation</a>, you can inspect <code>service</code> object with <code>__str()__</code>. So the following gets a list of methods and complex types:</p>\n\n<pre><code>from suds.client import Client;\n\nurl = 'http://www.webservicex.net/WeatherForecast.asmx?WSDL'\nclient = Client(url)\n\ntemp = str(client);\n</code></pre>\n\n<p>The code above produces following result (contents of <code>temp</code>):</p>\n\n<pre><code>Suds ( https://fedorahosted.org/suds/ ) version: 0.3.4 (beta) build: R418-20081208\n\nService ( WeatherForecast ) tns=\"http://www.webservicex.net\"\n Prefixes (1)\n ns0 = \"http://www.webservicex.net\"\n Ports (2):\n (WeatherForecastSoap)\n Methods (2):\n GetWeatherByPlaceName(xs:string PlaceName, )\n GetWeatherByZipCode(xs:string ZipCode, )\n Types (3):\n ArrayOfWeatherData\n WeatherData\n WeatherForecasts\n (WeatherForecastSoap12)\n Methods (2):\n GetWeatherByPlaceName(xs:string PlaceName, )\n GetWeatherByZipCode(xs:string ZipCode, )\n Types (3):\n ArrayOfWeatherData\n WeatherData\n WeatherForecasts\n</code></pre>\n\n<p>This would be much easier to parse. Also every method is listed with their parameters along with their types. You could, probably, even use just regular expression to extract information you need. </p>\n" }, { "answer_id": 1858144, "author": "sj26", "author_id": 158252, "author_profile": "https://Stackoverflow.com/users/158252", "pm_score": 5, "selected": false, "text": "<p>Okay, so SUDS does quite a bit of magic.</p>\n\n<p>A <code>suds.client.Client</code>, is built from a WSDL file:</p>\n\n<pre><code>client = suds.client.Client(\"http://mssoapinterop.org/asmx/simple.asmx?WSDL\")\n</code></pre>\n\n<p>It downloads the WSDL and creates a definition in <code>client.wsdl</code>. When you call a method using SUDS via <code>client.service.&lt;method&gt;</code> it's actually doing a whole lot of recursive resolve magic behind the scenes against that interpreted WSDL. To discover the parameters and types for methods you'll need to introspect this object.</p>\n\n<p>For example:</p>\n\n<pre><code>for method in client.wsdl.services[0].ports[0].methods.values():\n print '%s(%s)' % (method.name, ', '.join('%s: %s' % (part.type, part.name) for part in method.soap.input.body.parts))\n</code></pre>\n\n<p>This should print something like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>echoInteger((u'int', http://www.w3.org/2001/XMLSchema): inputInteger)\nechoFloatArray((u'ArrayOfFloat', http://soapinterop.org/): inputFloatArray)\nechoVoid()\nechoDecimal((u'decimal', http://www.w3.org/2001/XMLSchema): inputDecimal)\nechoStructArray((u'ArrayOfSOAPStruct', http://soapinterop.org/xsd): inputStructArray)\nechoIntegerArray((u'ArrayOfInt', http://soapinterop.org/): inputIntegerArray)\nechoBase64((u'base64Binary', http://www.w3.org/2001/XMLSchema): inputBase64)\nechoHexBinary((u'hexBinary', http://www.w3.org/2001/XMLSchema): inputHexBinary)\nechoBoolean((u'boolean', http://www.w3.org/2001/XMLSchema): inputBoolean)\nechoStringArray((u'ArrayOfString', http://soapinterop.org/): inputStringArray)\nechoStruct((u'SOAPStruct', http://soapinterop.org/xsd): inputStruct)\nechoDate((u'dateTime', http://www.w3.org/2001/XMLSchema): inputDate)\nechoFloat((u'float', http://www.w3.org/2001/XMLSchema): inputFloat)\nechoString((u'string', http://www.w3.org/2001/XMLSchema): inputString)\n</code></pre>\n\n<p>So the first element of the part's type tuple is probably what you're after:</p>\n\n<pre><code>&gt;&gt;&gt; client.factory.create(u'ArrayOfInt')\n(ArrayOfInt){\n _arrayType = \"\"\n _offset = \"\"\n _id = \"\"\n _href = \"\"\n _arrayType = \"\"\n }\n</code></pre>\n\n<p>Update:</p>\n\n<p>For the Weather service it appears that the \"parameters\" are a part with an <code>element</code> not a <code>type</code>:</p>\n\n<pre><code>&gt;&gt;&gt; client = suds.client.Client('http://www.webservicex.net/WeatherForecast.asmx?WSDL')\n&gt;&gt;&gt; client.wsdl.services[0].ports[0].methods.values()[0].soap.input.body.parts[0].element\n(u'GetWeatherByZipCode', http://www.webservicex.net)\n&gt;&gt;&gt; client.factory.create(u'GetWeatherByZipCode')\n(GetWeatherByZipCode){\n ZipCode = None\n }\n</code></pre>\n\n<p>But this is magic'd into the parameters of the method call (a la <code>client.service.GetWeatherByZipCode(\"12345\")</code>. IIRC this is SOAP RPC binding style? I think there's enough information here to get you started. Hint: the Python command line interface is your friend!</p>\n" }, { "answer_id": 16616472, "author": "gbutler", "author_id": 1535087, "author_profile": "https://Stackoverflow.com/users/1535087", "pm_score": 3, "selected": false, "text": "<p>Here's a quick script I wrote based on the above information to list the input methods suds reports as available on a WSDL. Pass in the WSDL URL. Works for the project I'm currently on, I can't guarantee it for yours.</p>\n\n<pre><code>import suds\n\ndef list_all(url):\n client = suds.client.Client(url)\n for service in client.wsdl.services:\n for port in service.ports:\n methods = port.methods.values()\n for method in methods:\n print(method.name)\n for part in method.soap.input.body.parts:\n part_type = part.type\n if(not part_type):\n part_type = part.element[0]\n print(' ' + str(part.name) + ': ' + str(part_type))\n o = client.factory.create(part_type)\n print(' ' + str(o))\n</code></pre>\n" }, { "answer_id": 17830415, "author": "toudi", "author_id": 1915230, "author_profile": "https://Stackoverflow.com/users/1915230", "pm_score": 2, "selected": false, "text": "<p>You can access suds's ServiceDefinition object. Here's a quick sample:</p>\n\n<pre><code>from suds.client import Client\nc = Client('http://some/wsdl/link')\n\ntypes = c.sd[0].types\n</code></pre>\n\n<p>Now, if you want to know the prefixed name of a type, it's also quite easy:</p>\n\n<pre><code>c.sd[0].xlate(c.sd[0].types[0][0])\n</code></pre>\n\n<p>This double bracket notation is because the types are a list (hence a first [0]) and then in each item on this list there may be two items. However, suds's internal implementation of <code>__unicode__</code> does exactly that (i.e. takes only the first item on the list):</p>\n\n<pre><code>s.append('Types (%d):' % len(self.types))\n for t in self.types:\n s.append(indent(4))\n s.append(self.xlate(t[0]))\n</code></pre>\n\n<p>Happy coding ;)</p>\n" }, { "answer_id": 34442878, "author": "fomars", "author_id": 3316574, "author_profile": "https://Stackoverflow.com/users/3316574", "pm_score": 1, "selected": false, "text": "<p>Once you created WSDL method object you can get information about it from it's <code>__metadata__</code>, including list of it's arguments' names.</p>\n\n<p>Given the argument's name, you can access it's actual instance in the method created. That instance also contains it's information in <code>__metadata__</code>, there you can get it's type name</p>\n\n<pre><code># creating method object\nmethod = client.factory.create('YourMethod')\n# getting list of arguments' names\narg_names = method.__metadata__.ordering\n# getting types of those arguments\ntypes = [method.__getitem__(arg).__metadata__.sxtype.name for arg in arg_names]\n</code></pre>\n\n<p>Disclaimer: this only works with complex WSDL types. Simple types, like strings and numbers, are defaulted to None</p>\n" }, { "answer_id": 40762187, "author": "SAMI UL HUDA", "author_id": 3214350, "author_profile": "https://Stackoverflow.com/users/3214350", "pm_score": 1, "selected": false, "text": "<pre><code>from suds.client import Client\nurl = 'http://localhost:1234/sami/2009/08/reporting?wsdl'\nclient = Client(url)\nfunctions = [m for m in client.wsdl.services[0].ports[0].methods]\ncount = 0\nfor function_name in functions:\n print (function_name)\n count+=1\nprint (\"\\nNumber of services exposed : \" ,count)\n</code></pre>\n" }, { "answer_id": 61767522, "author": "alex", "author_id": 4444742, "author_profile": "https://Stackoverflow.com/users/4444742", "pm_score": 0, "selected": false, "text": "<p>i needed an example of using suds with objects.\nbeside the answers found here, i found a very good <a href=\"https://webkul.com/blog/python-suds-client/\" rel=\"nofollow noreferrer\">article</a> \nthat answered my question even further.</p>\n\n<p>here is a short summary:</p>\n\n<p>first, print the client to see an overview of it's content.</p>\n\n<pre><code>from suds.client import Client client =\nClient(\"https://wsvc.cdiscount.com/MarketplaceAPIService.svc?wsdl\")\nprint client\n</code></pre>\n\n<p>second, create an instance of a type (using it's name including it's prefix ns*.), and print it, to see it's member data.</p>\n\n<pre><code>HeaderMessage = client.factory.create('ns0:HeaderMessage')\nprint HeaderMessage\n</code></pre>\n\n<p>to fill your object's data members, either assign them a scalar value for scalar members, or a dict, to object members.</p>\n\n<pre><code>HeaderMessage.Context = {\n \"CatalogID\": \"XXXXX\"\n \"CustomerID\": 'XXXXX'\n \"SiteID\": 123\n }\n</code></pre>\n\n<p>members whose type name start with ArrayOf expect a list of objects of the type mentioned in the rest of the type name.</p>\n\n<pre><code>ArrayOfDomainRights = client.factory.create('ns0:ArrayOfDomainRights')\nArrayOfDomainRights.DomainRights = [XXXXXXXXXXXXX, XXXXXXXXXXXX]\n</code></pre>\n" }, { "answer_id": 61842870, "author": "alex", "author_id": 4444742, "author_profile": "https://Stackoverflow.com/users/4444742", "pm_score": 0, "selected": false, "text": "<p>i needed an example of using suds with objects.\nbeside the answers found here, i found a very good <a href=\"https://webkul.com/blog/python-suds-client/\" rel=\"nofollow noreferrer\">article</a> \nthat answered my question even further.</p>\n\n<p>here is a short summary:</p>\n\n<p>first, print the client to see an overview of it's content.</p>\n\n<pre><code>from suds.client import Client client =\nClient(\"https://wsvc.cdiscount.com/MarketplaceAPIService.svc?wsdl\")\nprint client\n</code></pre>\n\n<p>second, create an instance of a type (using it's name including it's prefix ns*.), and print it, to see it's member data.</p>\n\n<pre><code>HeaderMessage = client.factory.create('ns0:HeaderMessage')\nprint HeaderMessage\n</code></pre>\n\n<p>to fill your object's data members, either assign them a scalar value for scalar members, or a dict, to object members.</p>\n\n<pre><code>HeaderMessage.Context = {\n \"CatalogID\": \"XXXXX\"\n \"CustomerID\": 'XXXXX'\n \"SiteID\": 123\n }\n</code></pre>\n\n<p>members whose type name start with ArrayOf expect a list of objects of the type mentioned in the rest of the type name.</p>\n\n<pre><code>ArrayOfDomainRights = client.factory.create('ns0:ArrayOfDomainRights')\nArrayOfDomainRights.DomainRights = [XXXXXXXXXXXXX, XXXXXXXXXXXX]\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18138/" ]
I'm investigating SUDS as a SOAP client for python. I want to inspect the methods available from a specified service, and the types required by a specified method. The aim is to generate a user interface, allowing users to select a method, then fill in values in a dynamically generated form. I can get some information on a particular method, but am unsure how to parse it: ``` client = Client(url) method = client.sd.service.methods['MyMethod'] ``` I am unable to **programmaticaly** figure out what object type I need to create to be able to call the service ``` obj = client.factory.create('?') res = client.service.MyMethod(obj, soapheaders=authen) ``` Does anyone have some sample code?
Okay, so SUDS does quite a bit of magic. A `suds.client.Client`, is built from a WSDL file: ``` client = suds.client.Client("http://mssoapinterop.org/asmx/simple.asmx?WSDL") ``` It downloads the WSDL and creates a definition in `client.wsdl`. When you call a method using SUDS via `client.service.<method>` it's actually doing a whole lot of recursive resolve magic behind the scenes against that interpreted WSDL. To discover the parameters and types for methods you'll need to introspect this object. For example: ``` for method in client.wsdl.services[0].ports[0].methods.values(): print '%s(%s)' % (method.name, ', '.join('%s: %s' % (part.type, part.name) for part in method.soap.input.body.parts)) ``` This should print something like: ```py echoInteger((u'int', http://www.w3.org/2001/XMLSchema): inputInteger) echoFloatArray((u'ArrayOfFloat', http://soapinterop.org/): inputFloatArray) echoVoid() echoDecimal((u'decimal', http://www.w3.org/2001/XMLSchema): inputDecimal) echoStructArray((u'ArrayOfSOAPStruct', http://soapinterop.org/xsd): inputStructArray) echoIntegerArray((u'ArrayOfInt', http://soapinterop.org/): inputIntegerArray) echoBase64((u'base64Binary', http://www.w3.org/2001/XMLSchema): inputBase64) echoHexBinary((u'hexBinary', http://www.w3.org/2001/XMLSchema): inputHexBinary) echoBoolean((u'boolean', http://www.w3.org/2001/XMLSchema): inputBoolean) echoStringArray((u'ArrayOfString', http://soapinterop.org/): inputStringArray) echoStruct((u'SOAPStruct', http://soapinterop.org/xsd): inputStruct) echoDate((u'dateTime', http://www.w3.org/2001/XMLSchema): inputDate) echoFloat((u'float', http://www.w3.org/2001/XMLSchema): inputFloat) echoString((u'string', http://www.w3.org/2001/XMLSchema): inputString) ``` So the first element of the part's type tuple is probably what you're after: ``` >>> client.factory.create(u'ArrayOfInt') (ArrayOfInt){ _arrayType = "" _offset = "" _id = "" _href = "" _arrayType = "" } ``` Update: For the Weather service it appears that the "parameters" are a part with an `element` not a `type`: ``` >>> client = suds.client.Client('http://www.webservicex.net/WeatherForecast.asmx?WSDL') >>> client.wsdl.services[0].ports[0].methods.values()[0].soap.input.body.parts[0].element (u'GetWeatherByZipCode', http://www.webservicex.net) >>> client.factory.create(u'GetWeatherByZipCode') (GetWeatherByZipCode){ ZipCode = None } ``` But this is magic'd into the parameters of the method call (a la `client.service.GetWeatherByZipCode("12345")`. IIRC this is SOAP RPC binding style? I think there's enough information here to get you started. Hint: the Python command line interface is your friend!
241,897
<p>How do I alternate HTML table row colors using JSP?</p> <p>My CSS looks something like:</p> <pre><code>tr.odd {background-color: #EEDDEE} tr.even {background-color: #EEEEDD} </code></pre> <p>I want to use <code>&lt;c:forEach&gt;</code> to iterate over a collection. </p> <pre><code>&lt;c:forEach items="${element}" var="myCollection"&gt; &lt;tr&gt; &lt;td&gt;&lt;c:out value="${element.field}"/&gt;&lt;/td&gt; ... &lt;/tr&gt; &lt;/c:forEach&gt; </code></pre> <p>I need an int count variable or boolean odd/even variable to track the row. Then my <code>&lt;tr&gt;</code> tag would look something like:</p> <pre><code>&lt;tr class="odd or even depending on the row"&gt; </code></pre>
[ { "answer_id": 241917, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<p>I don't use JSP, so I can't give you an answer in your language, but here's what I do (using pseudo code)</p>\n\n<pre><code>counter = 0\nforeach (elements)\n counter = counter + 1\n output: &lt;tr class=\"row{counter % 2}\"&gt;...&lt;/tr&gt;\n</code></pre>\n\n<p>Personally, I name the classes \"row0\" and \"row1\", which lets you alternate between them with a simple modulus calculation, also, if you decide to have rows alternating in triples or quads (instead of pairs), you can easily extend it to <code>row2</code>, <code>row3</code> and change your output code to be <code>counter % 4</code>, etc.</p>\n" }, { "answer_id": 241927, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I've used a tertiary operator in cases like this. It would look something like:</p>\n\n<pre><code>String oddEven=\"\";\n&lt;c:forEach items=\"${element}\" var=\"myCollection\"&gt;\n oddEven = (oddEven == \"even\") ? \"odd\" : \"even\";\n &lt;tr class='\"'+oddEven+'\"'&gt;\n &lt;td&gt;&lt;c:out value=\"${element.field}\"/&gt;&lt;/td&gt;\n ...\n &lt;/tr&gt;\n&lt;/c:forEach&gt;\n</code></pre>\n" }, { "answer_id": 241939, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 7, "selected": true, "text": "<p>Use the <code>varStatus</code> attribute on your <code>forEach</code> tag and JSTL will manage an instance of a <a href=\"http://java.sun.com/products/jsp/jstl/1.1/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html\" rel=\"noreferrer\"><code>javax.servlet.jsp.jstl.core.LoopTagStatus</code></a> for you in the variable name you specify. </p>\n\n<p>You can then use a ternary operator to easily output the appropriate class name:</p>\n\n<pre><code>&lt;c:forEach items=\"${element}\" var=\"myCollection\" varStatus=\"loopStatus\"&gt;\n &lt;tr class=\"${loopStatus.index % 2 == 0 ? 'even' : 'odd'}\"&gt;\n ...\n &lt;/tr&gt;\n&lt;/c:forEach&gt;\n</code></pre>\n\n<p>This <a href=\"http://www.ibm.com/developerworks/java/library/j-jstl0318/\" rel=\"noreferrer\">JSTL primer</a> from IBM has more information about the <code>core</code> tag library and what it gives you.</p>\n" }, { "answer_id": 241978, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 2, "selected": false, "text": "<p>If you are willing to make this happen on the client side, you can do Zebra Striping with JQuery.</p>\n\n<p>It would be done with just a couple lines of code, but you would have to include the jquery library in your file.</p>\n\n<p><a href=\"http://docs.jquery.com/Tutorials:Zebra_Striping_Made_Easy\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Tutorials:Zebra_Striping_Made_Easy</a></p>\n\n<p><a href=\"http://docs.jquery.com/Selectors/odd\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Selectors/odd</a></p>\n\n<p><a href=\"http://docs.jquery.com/Selectors/even\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Selectors/even</a></p>\n" }, { "answer_id": 242002, "author": "Andy Ford", "author_id": 17252, "author_profile": "https://Stackoverflow.com/users/17252", "pm_score": 2, "selected": false, "text": "<p>(this answer only pertains to the CSS side of things...)</p>\n\n<p>As a matter of course, I always target the child TD's like so:</p>\n\n<pre><code>tr.odd td {}\ntr.even td {}\n</code></pre>\n\n<p>The reason being is that IE actually applies TR background-color by removing the value set on the TR and applying it to each individual TD within that TR. Sometimes you might have a css reset or other css rules that overrides IE's strange way of doing TR background-color, so this is a way to make sure you avoid that.</p>\n\n<p>Also, you might want to consider setting just</p>\n\n<pre><code>tr td {background-color: #EEDDEE}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>tr.odd td {background-color: #EEEEDD}\n</code></pre>\n\n<p>so your code is slightly less verbose</p>\n" }, { "answer_id": 7594526, "author": "Cifi", "author_id": 915369, "author_profile": "https://Stackoverflow.com/users/915369", "pm_score": 2, "selected": false, "text": "<p>Just do like this and is going to work:</p>\n\n<pre><code>table tr:nth-child(odd) { background-color: #ccc; }\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24396/" ]
How do I alternate HTML table row colors using JSP? My CSS looks something like: ``` tr.odd {background-color: #EEDDEE} tr.even {background-color: #EEEEDD} ``` I want to use `<c:forEach>` to iterate over a collection. ``` <c:forEach items="${element}" var="myCollection"> <tr> <td><c:out value="${element.field}"/></td> ... </tr> </c:forEach> ``` I need an int count variable or boolean odd/even variable to track the row. Then my `<tr>` tag would look something like: ``` <tr class="odd or even depending on the row"> ```
Use the `varStatus` attribute on your `forEach` tag and JSTL will manage an instance of a [`javax.servlet.jsp.jstl.core.LoopTagStatus`](http://java.sun.com/products/jsp/jstl/1.1/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html) for you in the variable name you specify. You can then use a ternary operator to easily output the appropriate class name: ``` <c:forEach items="${element}" var="myCollection" varStatus="loopStatus"> <tr class="${loopStatus.index % 2 == 0 ? 'even' : 'odd'}"> ... </tr> </c:forEach> ``` This [JSTL primer](http://www.ibm.com/developerworks/java/library/j-jstl0318/) from IBM has more information about the `core` tag library and what it gives you.
241,925
<p>I have a number of generated .sql files that I want to run in succession. I'd like to run them from a SQL statement in a query (i.e. Query Analyzer/Server Management Studio).<br> Is it possible to do something like this and if so what is the syntax for doing this?</p> <p>I'm hoping for something like:</p> <pre><code>exec 'c:\temp\file01.sql' exec 'c:\temp\file02.sql' </code></pre> <p>I am using SQL Server 2005 and running queries in management studio.</p>
[ { "answer_id": 241940, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 7, "selected": true, "text": "<p>use <a href=\"http://msdn.microsoft.com/en-us/library/aa260689(SQL.80).aspx\" rel=\"noreferrer\">xp_cmdshell</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms166559.aspx\" rel=\"noreferrer\">sqlcmd</a></p>\n\n<pre><code>EXEC xp_cmdshell 'sqlcmd -S ' + @DBServerName + ' -d ' + @DBName + ' -i ' + @FilePathName\n</code></pre>\n" }, { "answer_id": 241941, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "<p>I wouldn't recommended doing this, but if you really have to then the extended stored procedure <a href=\"http://msdn.microsoft.com/en-us/library/aa260689(SQL.80).aspx\" rel=\"noreferrer\"><code>xp_cmdshell</code></a> is what you want. You will have to first read the contents of the file into a variable and then use something like this:</p>\n\n<pre><code>DECLARE @cmd sysname, @var sysname\nSET @var = 'Hello world'\nSET @cmd = 'echo ' + @var + ' &gt; var_out.txt'\nEXEC master..xp_cmdshell @cmd\n</code></pre>\n\n<p>Note: xp_cmdshell runs commands in the background, because of this, it must not be used to run programs that require user input. </p>\n" }, { "answer_id": 241985, "author": "John Dyer", "author_id": 2862, "author_profile": "https://Stackoverflow.com/users/2862", "pm_score": 2, "selected": false, "text": "<p>Take a look at OSQL. This utility lets you run SQL from the command prompt. It's easy to get installed on a system, I think it comes with the free SQL Server Express.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa213090(SQL.80).aspx\" rel=\"nofollow noreferrer\">Using the osql Utility\n</a></p>\n\n<p>A qick search of \"OSQL\" on stack overflow shows a lot of stuff is available.</p>\n\n<p>The main thing to handle properly is the user and password account parameters that get passed in on the command line. I have seen batch files that use NT file access permissions to control the file with the password and then using this file's contents to get the script started. You could also write a quick C# or VB program to run it using the Process class.</p>\n" }, { "answer_id": 6614716, "author": "Bruce Thompson", "author_id": 834057, "author_profile": "https://Stackoverflow.com/users/834057", "pm_score": 3, "selected": false, "text": "<p>This is what I use. Works well and is simple to reuse. It can be changed to read all files in the directory, but this way I get to control which ones to execute.</p>\n\n<pre><code>/* \nexecute a list of .sql files against the server and DB specified \n*/ \nSET NOCOUNT ON \n\nSET XACT_ABORT ON \nBEGIN TRAN \n\nDECLARE @DBServerName VARCHAR(100) = 'servername' \nDECLARE @DBName VARCHAR(100) = 'db name' \nDECLARE @FilePath VARCHAR(200) = 'path to scrips\\' \n/*\n\ncreate a holder for all filenames to be executed \n\n*/ \nDECLARE @FileList TABLE (Files NVARCHAR(MAX)) \n\nINSERT INTO @FileList VALUES ('script 1.sql') \nINSERT INTO @FileList VALUES ('script 2.sql') \nINSERT INTO @FileList VALUES ('script X.sql') \n\nWHILE (SELECT COUNT(Files) FROM @FileList) &gt; 0 \nBEGIN \n /* \n execute each file one at a time \n */ \n DECLARE @FileName NVARCHAR(MAX) = (SELECT TOP(1) Files FROM @FileList) \n DECLARE @command VARCHAR(500) = 'sqlcmd -S ' + @DBServerName + ' -d ' + @DBName + ' -i \"' + @FilePath + @Filename +'\"' \n EXEC xp_cmdshell @command \n\n PRINT 'EXECUTED: ' + @FileName \n DELETE FROM @FileList WHERE Files = @FileName \nEND \nCOMMIT TRAN \n</code></pre>\n" }, { "answer_id": 11775904, "author": "Archi Moore", "author_id": 597425, "author_profile": "https://Stackoverflow.com/users/597425", "pm_score": 4, "selected": false, "text": "<p>Very helpful thanks, see also this link:\n<a href=\"https://stackoverflow.com/questions/3523365/execute-sql-server-scripts?rq=1\">Execute SQL Server scripts</a>\nfor a similar example.\nTo turn <code>xp_cmdshell</code> on and off see below:</p>\n\n<p>On</p>\n\n<pre><code>SET NOCOUNT ON \nEXEC master.dbo.sp_configure 'show advanced options', 1 \nRECONFIGURE \nEXEC master.dbo.sp_configure 'xp_cmdshell', 1 \nRECONFIGURE \n</code></pre>\n\n<p>Off</p>\n\n<pre><code>EXEC master.dbo.sp_configure 'xp_cmdshell', 0 \nRECONFIGURE \nEXEC master.dbo.sp_configure 'show advanced options', 0 \nRECONFIGURE \nSET NOCOUNT OFF \n</code></pre>\n" }, { "answer_id": 40998657, "author": "Pesche Helfer", "author_id": 298494, "author_profile": "https://Stackoverflow.com/users/298494", "pm_score": 3, "selected": false, "text": "<p>Or just use openrowset to read your script into a variable and execute it (sorry for reviving an 8 years old topic):</p>\n\n<pre><code>DECLARE @SQL varchar(MAX)\nSELECT @SQL = BulkColumn\nFROM OPENROWSET\n ( BULK 'MeinPfad\\MeinSkript.sql'\n , SINGLE_BLOB ) AS MYTABLE\n\n--PRINT @sql\nEXEC (@sql)\n</code></pre>\n" }, { "answer_id": 52988397, "author": "Alper Ebicoglu", "author_id": 1767482, "author_profile": "https://Stackoverflow.com/users/1767482", "pm_score": 2, "selected": false, "text": "<p>Open windows command line (CMD)</p>\n\n<pre><code>sqlcmd -S localhost -d NorthWind -i \"C:\\MyScript.sql\"\n</code></pre>\n" }, { "answer_id": 57572931, "author": "Adam Henderson", "author_id": 1339507, "author_profile": "https://Stackoverflow.com/users/1339507", "pm_score": 2, "selected": false, "text": "<p>For anybody stumbling onto this question like I did and might find this useful, I liked <a href=\"https://stackoverflow.com/a/6614716/1339507\">Bruce Thompson's answer</a> (which ran SQL from files in a loop), but I preferred <a href=\"https://stackoverflow.com/a/40998657/1339507\">Pesche Helfer's approach to file execution</a> (as it avoided using xp_cmdshell). </p>\n\n<p>So I combined the two (and tweaked it slightly so it runs everything from a folder instead of a manually created list):</p>\n\n<pre><code>DECLARE @Dir NVARCHAR(512) = 'd:\\SQLScriptsDirectory'\n\nDECLARE @FileList TABLE (\n subdirectory NVARCHAR(512),\n depth int,\n [file] bit\n)\n\nINSERT @FileList\nEXEC Master.dbo.xp_DirTree @Dir,1,1\n\nWHILE (SELECT COUNT(*) FROM @FileList) &gt; 0 \nBEGIN \n DECLARE @FileName NVARCHAR(MAX) = (SELECT TOP(1) subdirectory FROM @FileList) \n DECLARE @FullPath NVARCHAR(MAX) = @Dir + '\\' + @FileName\n\n DECLARE @SQL NVARCHAR(MAX)\n DECLARE @SQL_TO_EXEC NVARCHAR(MAX)\n SELECT @SQL_TO_EXEC = 'select @SQL = BulkColumn\n FROM OPENROWSET\n ( BULK ''' + @FullPath + '''\n , SINGLE_BLOB ) AS MYTABLE'\n\n DECLARE @parmsdeclare NVARCHAR(4000) = '@SQL varchar(max) OUTPUT' \n\n EXEC sp_executesql @stmt = @SQL_TO_EXEC\n , @params = @parmsdeclare\n , @SQL = @SQL OUTPUT \n\n EXEC (@sql)\n DELETE FROM @FileList WHERE subdirectory = @FileName \n\n PRINT 'EXECUTED: ' + @FileName \nEND\n</code></pre>\n" }, { "answer_id": 57794320, "author": "live-love", "author_id": 436341, "author_profile": "https://Stackoverflow.com/users/436341", "pm_score": 2, "selected": false, "text": "<p>For Windows Authentication, if you are running as another user:\nOpen Command Prompt as your Windows user (Right click on it, Open File Location, Shift + Right Click, Run as a different user)</p>\n\n<pre><code> sqlcmd -S localhost\\SQLEXPRESS -d DatabaseName-i \"c:\\temp\\script.sql\"\n</code></pre>\n\n<p>Or if you are using Sql Server user:</p>\n\n<pre><code>sqlcmd -S localhost\\SQLEXPRESS -d DatabaseName-i \"c:\\temp\\script.sql\" -U UserName -P Password\n</code></pre>\n\n<p>Replace localhost\\SQLEXPRESS with you server name if not local server.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25719/" ]
I have a number of generated .sql files that I want to run in succession. I'd like to run them from a SQL statement in a query (i.e. Query Analyzer/Server Management Studio). Is it possible to do something like this and if so what is the syntax for doing this? I'm hoping for something like: ``` exec 'c:\temp\file01.sql' exec 'c:\temp\file02.sql' ``` I am using SQL Server 2005 and running queries in management studio.
use [xp\_cmdshell](http://msdn.microsoft.com/en-us/library/aa260689(SQL.80).aspx) and [sqlcmd](http://msdn.microsoft.com/en-us/library/ms166559.aspx) ``` EXEC xp_cmdshell 'sqlcmd -S ' + @DBServerName + ' -d ' + @DBName + ' -i ' + @FilePathName ```
241,936
<p>The deceptively simple foundation of dynamic code generation within a C/C++ framework has already been covered in <a href="https://stackoverflow.com/questions/45408/">another question</a>. Are there any gentle introductions into topic with code examples? </p> <p>My eyes are starting to bleed staring at highly intricate open source JIT compilers when my needs are much more modest.</p> <p>Are there good texts on the subject that don't assume a doctorate in computer science? I'm looking for well worn patterns, things to watch out for, performance considerations, etc. Electronic or tree-based resources can be equally valuable. You can assume a working knowledge of (not just x86) assembly language.</p>
[ { "answer_id": 241963, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "<p>I'm not aware of any sources specifically related to JITs, but I imagine that it's pretty much like a normal compiler, only simpler if you aren't worried about performance.</p>\n\n<p>The easiest way is to start with a VM interpreter. Then, for each VM instruction, generate the assembly code that the interpreter would have executed.</p>\n\n<p>To go beyond that, I imagine that you would parse the VM byte codes and convert them into some sort of suitable intermediate form (three address code? SSA?) and then optimize and generate code as in any other compiler.</p>\n\n<p>For a stack based VM, it may help to to keep track of the \"current\" stack depth as you translate the byte codes into intermediate form, and treat each stack location as a variable. For example, if you think that the current stack depth is 4, and you see a \"push\" instruction, you might generate an assignment to \"stack_variable_5\" and increment a compile time stack counter, or something like that. An \"add\" when the stack depth is 5 might generate the code \"stack_variable_4 = stack_variable_4+stack_variable_5\" and decrement the compile time stack counter.</p>\n\n<p>It is also possible to translate stack based code into syntax trees. Maintain a compile-time stack. Every \"push\" instruction causes a representation of the thing being pushed to be stored on the stack. Operators create syntax tree nodes that include their operands. For example, \"X Y +\" might cause the stack to contain \"var(X)\", then \"var(X) var(Y)\" and then the plus pops both var references off and pushes \"plus(var(X), var(Y))\".</p>\n" }, { "answer_id": 241997, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 3, "selected": true, "text": "<p>Well a pattern I've used in emulators goes something like this:</p>\n\n<pre><code>typedef void (*code_ptr)();\nunsigned long instruction_pointer = entry_point;\nstd::map&lt;unsigned long, code_ptr&gt; code_map;\n\n\nvoid execute_block() {\n code_ptr f;\n std::map&lt;unsigned long, void *&gt;::iterator it = code_map.find(instruction_pointer);\n if(it != code_map.end()) {\n f = it-&gt;second\n } else {\n f = generate_code_block();\n code_map[instruction_pointer] = f;\n }\n f();\n instruction_pointer = update_instruction_pointer();\n}\n\nvoid execute() {\n while(true) {\n execute_block();\n }\n}\n</code></pre>\n\n<p>This is a simplification, but the idea is there. Basically, every time the engine is asked to execute a \"basic block\" (usually a everything up to next flow control op or whole function in possible), it will look it up to see if it has already been created. If so, execute it, else create it, add it and then execute.</p>\n\n<p>rinse repeat :)</p>\n\n<p>As for the code generation, that gets a little complicated, but the idea is to emit a proper \"function\" which does the work of your basic block in the context of your VM.</p>\n\n<p>EDIT: note that I haven't demonstrated any optimizations either, but you asked for a \"gentle introduction\"</p>\n\n<p>EDIT 2: I forgot to mention one of the most immediately productive speed ups you can implement with this pattern. Basically, if you <em>never</em> remove a block from your tree (you can work around it if you do but it is way simpler if you never do), then you can \"chain\" blocks together to avoid lookups. Here's the concept. Whenever you return from f() and are about to do the \"update_instruction_pointer\", if the block you just executed ended in either a call, unconditional jump, or didn't end in flow control at all, then you can \"fixup\" its ret instruction with a direct jmp to the next block it'll execute (cause it'll always be the same one) <em>if</em> you have already emited it. This makes it so you are executing more and more often in the VM and less and less in the \"execute_block\" function.</p>\n" }, { "answer_id": 242188, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 0, "selected": false, "text": "<p>Get yourself a copy of Joel Pobar's book on Rotor (when it's out), and delve through the source to the <a href=\"http://research.microsoft.com/sscli/\" rel=\"nofollow noreferrer\">SSCLI</a>. Beware, insanity lies within :)</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892/" ]
The deceptively simple foundation of dynamic code generation within a C/C++ framework has already been covered in [another question](https://stackoverflow.com/questions/45408/). Are there any gentle introductions into topic with code examples? My eyes are starting to bleed staring at highly intricate open source JIT compilers when my needs are much more modest. Are there good texts on the subject that don't assume a doctorate in computer science? I'm looking for well worn patterns, things to watch out for, performance considerations, etc. Electronic or tree-based resources can be equally valuable. You can assume a working knowledge of (not just x86) assembly language.
Well a pattern I've used in emulators goes something like this: ``` typedef void (*code_ptr)(); unsigned long instruction_pointer = entry_point; std::map<unsigned long, code_ptr> code_map; void execute_block() { code_ptr f; std::map<unsigned long, void *>::iterator it = code_map.find(instruction_pointer); if(it != code_map.end()) { f = it->second } else { f = generate_code_block(); code_map[instruction_pointer] = f; } f(); instruction_pointer = update_instruction_pointer(); } void execute() { while(true) { execute_block(); } } ``` This is a simplification, but the idea is there. Basically, every time the engine is asked to execute a "basic block" (usually a everything up to next flow control op or whole function in possible), it will look it up to see if it has already been created. If so, execute it, else create it, add it and then execute. rinse repeat :) As for the code generation, that gets a little complicated, but the idea is to emit a proper "function" which does the work of your basic block in the context of your VM. EDIT: note that I haven't demonstrated any optimizations either, but you asked for a "gentle introduction" EDIT 2: I forgot to mention one of the most immediately productive speed ups you can implement with this pattern. Basically, if you *never* remove a block from your tree (you can work around it if you do but it is way simpler if you never do), then you can "chain" blocks together to avoid lookups. Here's the concept. Whenever you return from f() and are about to do the "update\_instruction\_pointer", if the block you just executed ended in either a call, unconditional jump, or didn't end in flow control at all, then you can "fixup" its ret instruction with a direct jmp to the next block it'll execute (cause it'll always be the same one) *if* you have already emited it. This makes it so you are executing more and more often in the VM and less and less in the "execute\_block" function.
241,955
<p>I find myself writing code that looks like this a lot:</p> <pre><code>set&lt;int&gt; affected_items; while (string code = GetKeyCodeFromSomewhere()) { if (code == "some constant" || code == "some other constant") { affected_items.insert(some_constant_id); } else if (code == "yet another constant" || code == "the constant I didn't mention yet") { affected_items.insert(some_other_constant_id); } // else if etc... } for (set&lt;int&gt;::iterator it = affected_items.begin(); it != affected_items.end(); it++) { switch(*it) { case some_constant_id: RunSomeFunction(with, these, params); break; case some_other_constant_id: RunSomeOtherFunction(with, these, other, params); break; // etc... } } </code></pre> <p>The reason I end up writing this code is that I need to only run the functions in the second loop once even if I've received multiple key codes that might cause them to run.</p> <p>This just doesn't seem like the best way to do it. Is there a neater way?</p>
[ { "answer_id": 241972, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 2, "selected": true, "text": "<p>Since you don't seem to care about the actual values in the set you could replace it with setting bits in an int. You can also replace the linear time search logic with log time search logic. Here's the final code:</p>\n\n<pre><code>// Ahead of time you build a static map from your strings to bit values.\nstd::map&lt; std::string, int &gt; codesToValues;\ncodesToValues[ \"some constant\" ] = 1;\ncodesToValues[ \"some other constant\" ] = 1;\ncodesToValues[ \"yet another constant\" ] = 2;\ncodesToValues[ \"the constant I didn't mention yet\" ] = 2;\n\n// When you want to do your work\nint affected_items = 0;\nwhile (string code = GetKeyCodeFromSomewhere())\n affected_items |= codesToValues[ code ];\n\nif( affected_items &amp; 1 )\n RunSomeFunction(with, these, params);\nif( affected_items &amp; 2 )\n RunSomeOtherFunction(with, these, other, params);\n// etc...\n</code></pre>\n" }, { "answer_id": 241974, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": false, "text": "<p>Its certainly not neater, but you could maintain a set of flags that say whether you've called that specific function or not. That way you avoid having to save things off in a set, you just have the flags.</p>\n\n<p>Since there is (presumably from the way it is written), a fixed at compile time number of different if/else blocks, you can do this pretty easily with a bitset.</p>\n" }, { "answer_id": 241996, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "<p>One approach is to maintain a map from strings to booleans. The main logic can start with something like:</p>\n\n<pre><code>if(done[code])\n continue;\ndone[code] = true;\n</code></pre>\n\n<p>Then you can perform the appropriate action as soon as you identify the code.</p>\n\n<p>Another approach is to store something executable (object, function pointer, whatever) into a sort of \"to do list.\" For example:</p>\n\n<pre><code>while (string code = GetKeyCodeFromSomewhere())\n{\n todo[code] = codefor[code];\n}\n</code></pre>\n\n<p>Initialize codefor to contain the appropriate function pointer, or object subclassed from a common base class, for each code value. If the same code shows up more than once, the appropriate entry in todo will just get overwritten with the same value that it already had. At the end, iterate over todo and run all of its members.</p>\n" }, { "answer_id": 242179, "author": "mbyrne215", "author_id": 5241, "author_profile": "https://Stackoverflow.com/users/5241", "pm_score": 0, "selected": false, "text": "<p>Obviously, it will depend on the specific circumstances, but it might be better to have the functions that you call keep track of whether they've already been run and exit early if required. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20889/" ]
I find myself writing code that looks like this a lot: ``` set<int> affected_items; while (string code = GetKeyCodeFromSomewhere()) { if (code == "some constant" || code == "some other constant") { affected_items.insert(some_constant_id); } else if (code == "yet another constant" || code == "the constant I didn't mention yet") { affected_items.insert(some_other_constant_id); } // else if etc... } for (set<int>::iterator it = affected_items.begin(); it != affected_items.end(); it++) { switch(*it) { case some_constant_id: RunSomeFunction(with, these, params); break; case some_other_constant_id: RunSomeOtherFunction(with, these, other, params); break; // etc... } } ``` The reason I end up writing this code is that I need to only run the functions in the second loop once even if I've received multiple key codes that might cause them to run. This just doesn't seem like the best way to do it. Is there a neater way?
Since you don't seem to care about the actual values in the set you could replace it with setting bits in an int. You can also replace the linear time search logic with log time search logic. Here's the final code: ``` // Ahead of time you build a static map from your strings to bit values. std::map< std::string, int > codesToValues; codesToValues[ "some constant" ] = 1; codesToValues[ "some other constant" ] = 1; codesToValues[ "yet another constant" ] = 2; codesToValues[ "the constant I didn't mention yet" ] = 2; // When you want to do your work int affected_items = 0; while (string code = GetKeyCodeFromSomewhere()) affected_items |= codesToValues[ code ]; if( affected_items & 1 ) RunSomeFunction(with, these, params); if( affected_items & 2 ) RunSomeOtherFunction(with, these, other, params); // etc... ```
241,960
<p>How do I drop a Groovlet into a Grails app? Say, for example, in web-app/groovlet.groovy</p> <pre> import java.util.Date if (session == null) { session = request.getSession(true); } if (session.counter == null) { session.counter = 1 } println """ &lt;html> &lt;head> &lt;title>Groovy Servlet&lt;/title> &lt;/head> &lt;body> Hello, ${request.remoteHost}: Counter: ${session.counter}! Date: ${new Date()} &lt;br> """ </pre>
[ { "answer_id": 242030, "author": "kolrie", "author_id": 14540, "author_profile": "https://Stackoverflow.com/users/14540", "pm_score": 0, "selected": false, "text": "<p>The way I understand it, groovlets are used when you have a Servlet container with Groovy scripting support, </p>\n\n<p>I think in Grails you would need to move your business logic code to a <a href=\"http://grails.org/Controllers\" rel=\"nofollow noreferrer\">controller</a> and leave the view part to an HTML or a <a href=\"http://grails.org/doc/1.0.x/guide/6.%20The%20Web%20Layer.html#6.2\" rel=\"nofollow noreferrer\">GSP file</a>.</p>\n\n<p>Something along those lines (meta-code from the top of my head, not tested):</p>\n\n<p>grails-app/controllers/SampleController.groovy</p>\n\n<pre><code>class DateController {\n def index = {\n if (session == null) {\n session = request.getSession(true);\n }\n\n if (session.counter == null) {\n session.counter = 1\n }\n }\n}\n</code></pre>\n\n<p>web-app/sample/index.gsp</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;Groovy Servlet&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\nHello, ${request.remoteHost}: Counter: ${session.counter}! Date: ${new Date()}\n&lt;br&gt;\n</code></pre>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 242041, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 4, "selected": true, "text": "<ol>\n<li><code>grails install-templates</code></li>\n<li>Edit <code>src/templates/web/web.xml</code> to include your groovlet</li>\n<li><code>grails war</code></li>\n<li>deploy</li>\n</ol>\n\n<p>I've not personally done this to incorporate a groovlet, but this is the documented way to modify the deployed Grails <code>web.xml</code></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I drop a Groovlet into a Grails app? Say, for example, in web-app/groovlet.groovy ``` import java.util.Date if (session == null) { session = request.getSession(true); } if (session.counter == null) { session.counter = 1 } println """ <html> <head> <title>Groovy Servlet</title> </head> <body> Hello, ${request.remoteHost}: Counter: ${session.counter}! Date: ${new Date()} <br> """ ```
1. `grails install-templates` 2. Edit `src/templates/web/web.xml` to include your groovlet 3. `grails war` 4. deploy I've not personally done this to incorporate a groovlet, but this is the documented way to modify the deployed Grails `web.xml`
241,967
<p>I am playing with the new stuff of C#3.0 and I have this code (mostly taken from <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx" rel="noreferrer">MSDN</a>) but I can only get true,false,true... and not the real value :</p> <pre><code> int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var oddNumbers = numbers.Select(n =&gt; n % 2 == 1); Console.WriteLine("Numbers &lt; 5:"); foreach (var x in oddNumbers) { Console.WriteLine(x); } </code></pre> <p>How can I fix that to show the list of integer?</p>
[ { "answer_id": 241975, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 6, "selected": true, "text": "<p>Change your \"Select\" to a \"Where\"</p>\n\n<pre><code> int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };\n\n var oddNumbers = numbers.Where(n =&gt; n % 2 == 1);\n\n Console.WriteLine(\"Odd Number:\");\n foreach (var x in oddNumbers)\n {\n Console.WriteLine(x);\n }\n</code></pre>\n\n<p>The \"Select\" method is creating a new list of the lambda result for each element (true/false). The \"Where\" method is filtering based on the lambda.</p>\n\n<p>In C#, you could also use this syntax, which you may find clearer:</p>\n\n<pre><code> var oddNumbers = from n in numbers\n where n % 2 == 1\n select n;\n</code></pre>\n\n<p>which the compiler translates to:</p>\n\n<pre><code>var oddNumbers = numbers.Where(n =&gt; n % 2 == 1).Select(n =&gt; n);\n</code></pre>\n" }, { "answer_id": 241981, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "<blockquote>\n<pre><code>numbers.Select(n =&gt; n % 2 == 1);\n</code></pre>\n</blockquote>\n\n<p>Change this to</p>\n\n<pre><code>numbers.Where(n =&gt; n % 2 == 1);\n</code></pre>\n\n<p>What select does is \"convert\" one thing to another. So in this case, it's \"Converting\" n to \"n % 2 == 1\" (which is a boolean) - hence you get all the true and falses.</p>\n\n<p>It's usually used for getting properties on things. For example if you had a list of <code>Person</code> objects, and you wanted to get their names, you'd do</p>\n\n<pre><code>var listOfNames = listOfPeople.Select( p =&gt; p.Name );\n</code></pre>\n\n<p>You can think of this like so:</p>\n\n<ul>\n<li>Convert the list of people into a list of strings, using the following method: ( p => p.Name)</li>\n</ul>\n\n<p>To \"select\" (in the \"filtering\" sense of the word) a subset of a collection, you need to use Where.</p>\n\n<p>Thanks Microsoft for the terrible naming</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
I am playing with the new stuff of C#3.0 and I have this code (mostly taken from [MSDN](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx)) but I can only get true,false,true... and not the real value : ``` int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var oddNumbers = numbers.Select(n => n % 2 == 1); Console.WriteLine("Numbers < 5:"); foreach (var x in oddNumbers) { Console.WriteLine(x); } ``` How can I fix that to show the list of integer?
Change your "Select" to a "Where" ``` int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var oddNumbers = numbers.Where(n => n % 2 == 1); Console.WriteLine("Odd Number:"); foreach (var x in oddNumbers) { Console.WriteLine(x); } ``` The "Select" method is creating a new list of the lambda result for each element (true/false). The "Where" method is filtering based on the lambda. In C#, you could also use this syntax, which you may find clearer: ``` var oddNumbers = from n in numbers where n % 2 == 1 select n; ``` which the compiler translates to: ``` var oddNumbers = numbers.Where(n => n % 2 == 1).Select(n => n); ```
241,989
<p>When I restart my apache2 and reload a page, the log file shows</p> <pre><code>boogie.tontut.fi - - [28/Oct/2008:03:27:49 +0200] "GET /test HTTP/1.1" 404 457 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3" </code></pre> <p>...as supposed to, as it's <code>03:27:49</code> now. However, when I click the refresh button again, the new log entry is:</p> <pre><code>boogie.tontut.fi - - [27/Oct/2008:21:27:52 -0400] "GET /test HTTP/1.1" 404 457 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3" </code></pre> <p>Offset has changed from <code>+0200 to -0400</code> and I have no clue where this comes from.</p> <p>How can I start troubleshooting this problem?</p>
[ { "answer_id": 242011, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 0, "selected": false, "text": "<p>Try and set your timezone explicitly in the <code>httpd.conf</code>:</p>\n\n<pre><code>SetEnv TZ GMT+2\n</code></pre>\n" }, { "answer_id": 242138, "author": "Martin Redmond", "author_id": 30541, "author_profile": "https://Stackoverflow.com/users/30541", "pm_score": 0, "selected": false, "text": "<p>Maybe looking at the system call would help; on Unix its <code>gettimeofday</code> and on Windows its <code>GetSystemTime</code>. </p>\n" }, { "answer_id": 242185, "author": "che", "author_id": 7806, "author_profile": "https://Stackoverflow.com/users/7806", "pm_score": 0, "selected": false, "text": "<p>Isn't it possible that something that runs in apache is changing locale settings in its environment?</p>\n\n<p>Something like:</p>\n\n<ol>\n<li>First reload: log message <code>GMT+2</code></li>\n<li>Apache runs /weird_script.php that calls some kind of <code>setlocale()</code></li>\n<li>Second reload, new enviroment setting in effect, results in log message <code>GMT-4</code></li>\n</ol>\n" }, { "answer_id": 25302309, "author": "Sanjeeb Mohanta", "author_id": 3936089, "author_profile": "https://Stackoverflow.com/users/3936089", "pm_score": 1, "selected": false, "text": "<p>sudo vim /etc/php5/apache2/php.ini</p>\n<h1>Add time zone</h1>\n<p>date.timezone=&quot;Europe/London&quot;</p>\n<p>restart apache2\n/etc/init.d/apache2 restart</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30141/" ]
When I restart my apache2 and reload a page, the log file shows ``` boogie.tontut.fi - - [28/Oct/2008:03:27:49 +0200] "GET /test HTTP/1.1" 404 457 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3" ``` ...as supposed to, as it's `03:27:49` now. However, when I click the refresh button again, the new log entry is: ``` boogie.tontut.fi - - [27/Oct/2008:21:27:52 -0400] "GET /test HTTP/1.1" 404 457 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3" ``` Offset has changed from `+0200 to -0400` and I have no clue where this comes from. How can I start troubleshooting this problem?
sudo vim /etc/php5/apache2/php.ini Add time zone ============= date.timezone="Europe/London" restart apache2 /etc/init.d/apache2 restart
241,994
<p>This is something that I have always wondered about, but never bothered to profile.</p> <p>Is it more efficient to assign a value to a temp variable, than to keep using that value. An Example may be clearer:</p> <pre><code>string s = reader.GetItem[0].ToString(); someClass.SomeField = s; someOtherClass.someField = s; </code></pre> <p>OR</p> <pre><code>someClass.SomeField = reader.GetItem[0].ToString(); someOtherClass.someField = reader.GetItem[0].ToString(); </code></pre> <p>My initial thought would the top example would be more efficient as it doesn't have to access the Item collection or call ToString.</p> <p>Would be interested to hear other peoples ideas, or definitive answer either way.</p>
[ { "answer_id": 242004, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 5, "selected": true, "text": "<p>The compiler cannot know if the expression on the right-hand-side has side-effects, so it must re-evaluate it if you code it twice. Hence the first is more efficient in the sense that it will not re-do the GetItem &amp; ToString calls.</p>\n\n<p>So if you the programmer know that these calls are pure/idempotent, then you should write the code the first way.</p>\n" }, { "answer_id": 242007, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 0, "selected": false, "text": "<p>Well assuming that the <code>ToString</code> function not just hands out a reference to some pre-made internal object, it must be pretty clear that the first version, where only one call to it is being made, will be the fastest. However, if this is a performance issue you should care about or not is a completely different story.</p>\n\n<p>One issue to <strong>do</strong> think bout, however, is that the second example might render different results in the first and second line if the item is accessed/changed simultaneously from another thread. </p>\n" }, { "answer_id": 242009, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 3, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/questions/241994/which-is-more-efficient-way-to-assign-values-to-variables-in-net#242004\">Brian</a> said, the first way will be more efficient, though whether it makes much difference in the real world depends on how expensive the duplicated functions are, and how frequently this piece of code as a whole is called.</p>\n\n<p>However, as well as being more efficient, the first way better indicates intention - that you mean to assign the same value to the two things. It also aids maintainability because if it needs to change, you only need to change it in one place. For me, both of these are typically more important than efficiency.</p>\n" }, { "answer_id": 242083, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>I just have habit of storing a value in a local variable if I'm going to be using it more than once. Usually, though, it's because I prefer the compactness of the code rather than being too concerned about efficiency -- although, I'd definitely do it if using it repeatedly in a loop.</p>\n\n<p>Sometimes, I'm inconsistent and will just retype, especially if just using an accessor and not calling a method that requires computation.</p>\n" }, { "answer_id": 242137, "author": "Tim Stewart", "author_id": 26002, "author_profile": "https://Stackoverflow.com/users/26002", "pm_score": 0, "selected": false, "text": "<p>Here's my rule of thumb. When in doubt, <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=A362781C-3870-43BE-8926-862B40AA0CD0&amp;displaylang=en\" rel=\"nofollow noreferrer\">profile your code</a>. An optimizing compiler can remove a lot of code thus making your code run faster.</p>\n\n<p>Two facts must also be considered:</p>\n\n<ul>\n<li>.NET allocates memory very quickly.</li>\n<li>Excessive garbage can slow down your application due to additional page faults, poor locality of reference, excessive garbage collection.</li>\n</ul>\n\n<p>This implies that under a cursory observation, your code can be very fast, but if you're generating a lot of garbage, your program's performance will suffer as it runs for a while.</p>\n" }, { "answer_id": 242148, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 0, "selected": false, "text": "<p>Readability matters.\nWhat is the use of \"s\" named variable?</p>\n\n<p>Also, instead of using [0], a field name will make more sense.</p>\n" }, { "answer_id": 242416, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>There is another option - composite assignment:</p>\n\n<pre><code>someOtherClass.someField = someClass.SomeField = reader.GetItem[0].ToString();\n</code></pre>\n\n<p>With this usage the compiler will evaluate <code>reader.GetItem[0].ToString()</code> <em>once</em>, and use it to assign to both members (it does <em>not</em> use the <code>get</code>of <code>someClass</code>). It does this by duplicating the value on the stack (which doesn't need an explicit local).</p>\n\n<p>Very efficient, but to be honest I wouldn't get too excited about the original with a variable.</p>\n" }, { "answer_id": 1449758, "author": "grantwparks", "author_id": 117773, "author_profile": "https://Stackoverflow.com/users/117773", "pm_score": 0, "selected": false, "text": "<p>There are other issues to consider. If the use of <code>s</code>, to assign to other variables, is separated from where <code>s</code> is initialized by more than a couple lines of code, you open the possibility that someone else will come along and add code later that alters the value of <code>s</code> between its uses, or somehow branches around the original assignment to <code>s</code>.</p>\n\n<p>One thing I see a lot of is the assignment of a function return to a variable even when that value is only being used in one place, and I hate that, because (and it doesn't matter what that variable is named) that inevitably leads to having to go find where that variable was assigned to know what it really represents. Assigning the return value of the function directly to what is going to use it, explicitly indicates what's going on.</p>\n\n<p>There is a faction in programming that believes in \"variable-less programming\" (in the flavor of the famous \"goto-less programming\" paper decades ago). For example, XSL, while it does have \"variables\", they are not mutable after their initial assignment within a single scope. This, some say, is what helps guarantee no unintended side-effects.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
This is something that I have always wondered about, but never bothered to profile. Is it more efficient to assign a value to a temp variable, than to keep using that value. An Example may be clearer: ``` string s = reader.GetItem[0].ToString(); someClass.SomeField = s; someOtherClass.someField = s; ``` OR ``` someClass.SomeField = reader.GetItem[0].ToString(); someOtherClass.someField = reader.GetItem[0].ToString(); ``` My initial thought would the top example would be more efficient as it doesn't have to access the Item collection or call ToString. Would be interested to hear other peoples ideas, or definitive answer either way.
The compiler cannot know if the expression on the right-hand-side has side-effects, so it must re-evaluate it if you code it twice. Hence the first is more efficient in the sense that it will not re-do the GetItem & ToString calls. So if you the programmer know that these calls are pure/idempotent, then you should write the code the first way.
241,995
<p>I would like to be able to drop to the python REPL from the debugger -- if this is not possible is there an easier way to evaluate python expressions in the context of the current breakpoint other than manually adding them all as watch expressions?</p>
[ { "answer_id": 242774, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 3, "selected": true, "text": "<p>I don't use <em>pydev</em>, but to drop to python's interactive REPL from code:</p>\n\n<pre><code>import code\ncode.interact(local=locals())\n</code></pre>\n\n<p>To drop to python's debugger from code:</p>\n\n<pre><code>import pdb\npdb.set_trace()\n</code></pre>\n\n<p>Finally, to run a interactive REPL after running some code, you can use python's <code>-i</code> switch:</p>\n\n<pre><code>python -i script.py\n</code></pre>\n\n<p>That will give you a python prompt after the code, even if it throws an exception.</p>\n\n<p>You may be able to hook some of those solutions into <em>pydev</em>, I think.</p>\n" }, { "answer_id": 516482, "author": "Dag Høidahl", "author_id": 22146, "author_profile": "https://Stackoverflow.com/users/22146", "pm_score": 3, "selected": false, "text": "<p>There is a dedicated Pydev Console available by clicking on the \"New console\" dropdown in the console view.</p>\n\n<p>See <a href=\"http://pydev.sourceforge.net/console.html\" rel=\"noreferrer\">http://pydev.sourceforge.net/console.html</a></p>\n" }, { "answer_id": 8726587, "author": "Giacomo Lacava", "author_id": 1129851, "author_profile": "https://Stackoverflow.com/users/1129851", "pm_score": 2, "selected": false, "text": "<p>As Dag Høidahl said, the PyDev Console is actually the best option (at least on Eclipse Indigo), no need to hack around. </p>\n\n<p>Just go to Open Console:\n<img src=\"https://i.stack.imgur.com/nXYND.png\" alt=\"Open Console\"></p>\n\n<p>Then select PyDev Console:</p>\n\n<p><img src=\"https://i.stack.imgur.com/nx9M1.png\" alt=\"PyDev Console\"></p>\n\n<p>If you need to add specific parameters (for example, Jython tends to miss the python.os VM property), you can change them under Window -> Properties -> PyDev -> Interactive Console.\n<img src=\"https://i.stack.imgur.com/ysj5d.png\" alt=\"enter image description here\"></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/241995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2168/" ]
I would like to be able to drop to the python REPL from the debugger -- if this is not possible is there an easier way to evaluate python expressions in the context of the current breakpoint other than manually adding them all as watch expressions?
I don't use *pydev*, but to drop to python's interactive REPL from code: ``` import code code.interact(local=locals()) ``` To drop to python's debugger from code: ``` import pdb pdb.set_trace() ``` Finally, to run a interactive REPL after running some code, you can use python's `-i` switch: ``` python -i script.py ``` That will give you a python prompt after the code, even if it throws an exception. You may be able to hook some of those solutions into *pydev*, I think.
242,012
<p>After looking on MSDN, it's still unclear to me how I should form a proper predicate to use the Find() method in List using a member variable of T (where T is a class)</p> <p>For example:</p> <pre><code>public class Car { public string Make; public string Model; public int Year; } { // somewhere in my code List&lt;Car&gt; carList = new List&lt;Car&gt;(); // ... code to add Cars ... Car myCar = new Car(); // Find the first of each car made between 1980 and 2000 for (int x = 1980; x &lt; 2000; x++) { myCar = carList.Find(byYear(x)); Console.Writeline(myCar.Make + myCar.Model); } } </code></pre> <p>What should my "byYear" predicate look like? </p> <p>(The MSDN example only talks about a List of dinosaurs and only searches for an unchanging value "saurus" -- It doesn't show how to pass a value into the predicate...)</p> <p>EDIT: I'm using VS2005/.NET2.0, so I don't think Lambda notation is available to me...</p> <p>EDIT2: Removed "1999" in the example because I may want to "Find" programatically based on different values. Example changed to range of cars from 1980 to 2000 using for-do loop.</p>
[ { "answer_id": 242020, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "<p>Hmm. Thinking more about it, you could use currying to return a predicate.</p>\n\n<pre><code>Func&lt;int, Predicate&lt;Car&gt;&gt; byYear = i =&gt; (c =&gt; c.Year == i);\n</code></pre>\n\n<p>Now you can pass the result of this function (which is a predicate) to your Find method:</p>\n\n<pre><code>my99Car = cars.Find(byYear(1999));\nmy65Car = cars.Find(byYear(1965));\n</code></pre>\n" }, { "answer_id": 242024, "author": "Dan Finucane", "author_id": 30026, "author_profile": "https://Stackoverflow.com/users/30026", "pm_score": 5, "selected": false, "text": "<p>You can use a lambda expression as follows:</p>\n\n<pre><code>myCar = carList.Find(car =&gt; car.Year == 1999);\n</code></pre>\n" }, { "answer_id": 242033, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": true, "text": "<p>Ok, in .NET 2.0 you can use delegates, like so:</p>\n\n<pre><code>static Predicate&lt;Car&gt; ByYear(int year)\n{\n return delegate(Car car)\n {\n return car.Year == year;\n };\n}\n\nstatic void Main(string[] args)\n{\n // yeah, this bit is C# 3.0, but ignore it - it's just setting up the list.\n List&lt;Car&gt; list = new List&lt;Car&gt;\n {\n new Car { Year = 1940 },\n new Car { Year = 1965 },\n new Car { Year = 1973 },\n new Car { Year = 1999 }\n };\n var car99 = list.Find(ByYear(1999));\n var car65 = list.Find(ByYear(1965));\n\n Console.WriteLine(car99.Year);\n Console.WriteLine(car65.Year);\n}\n</code></pre>\n" }, { "answer_id": 242058, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 4, "selected": false, "text": "<p>Or you can use an anonymous delegate:</p>\n\n<pre><code>Car myCar = cars.Find(delegate(Car c) { return c.Year == x; });\n\n// If not found myCar will be null\nif (myCar != null)\n{\n Console.Writeline(myCar.Make + myCar.Model);\n}\n</code></pre>\n" }, { "answer_id": 242281, "author": "Ajaxx", "author_id": 25228, "author_profile": "https://Stackoverflow.com/users/25228", "pm_score": 3, "selected": false, "text": "<p>Since you can't use lambda you can just replace it with an anonymous delegate.</p>\n\n<pre><code>myCar = carList.Find(delegate(Car car) { return car.Year == i; });\n</code></pre>\n" }, { "answer_id": 23519671, "author": "phclummia", "author_id": 3611320, "author_profile": "https://Stackoverflow.com/users/3611320", "pm_score": 1, "selected": false, "text": "<p>You can use this too:</p>\n\n<pre><code>var existData =\n cars.Find(\n c =&gt; c.Year== 1999);\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21244/" ]
After looking on MSDN, it's still unclear to me how I should form a proper predicate to use the Find() method in List using a member variable of T (where T is a class) For example: ``` public class Car { public string Make; public string Model; public int Year; } { // somewhere in my code List<Car> carList = new List<Car>(); // ... code to add Cars ... Car myCar = new Car(); // Find the first of each car made between 1980 and 2000 for (int x = 1980; x < 2000; x++) { myCar = carList.Find(byYear(x)); Console.Writeline(myCar.Make + myCar.Model); } } ``` What should my "byYear" predicate look like? (The MSDN example only talks about a List of dinosaurs and only searches for an unchanging value "saurus" -- It doesn't show how to pass a value into the predicate...) EDIT: I'm using VS2005/.NET2.0, so I don't think Lambda notation is available to me... EDIT2: Removed "1999" in the example because I may want to "Find" programatically based on different values. Example changed to range of cars from 1980 to 2000 using for-do loop.
Ok, in .NET 2.0 you can use delegates, like so: ``` static Predicate<Car> ByYear(int year) { return delegate(Car car) { return car.Year == year; }; } static void Main(string[] args) { // yeah, this bit is C# 3.0, but ignore it - it's just setting up the list. List<Car> list = new List<Car> { new Car { Year = 1940 }, new Car { Year = 1965 }, new Car { Year = 1973 }, new Car { Year = 1999 } }; var car99 = list.Find(ByYear(1999)); var car65 = list.Find(ByYear(1965)); Console.WriteLine(car99.Year); Console.WriteLine(car65.Year); } ```
242,032
<p>Is there a way to get the directory of a project in Eclipse? We are writing a plugin that will allow the user to select files, and then run some processes on those files. I would ideally like to be able to get all the files with a certain extension, but that is not necessary.</p>
[ { "answer_id": 242075, "author": "AdamC", "author_id": 16476, "author_profile": "https://Stackoverflow.com/users/16476", "pm_score": 4, "selected": true, "text": "<p>sure:</p>\n\n<pre><code>ResourcesPlugin.getWorkspace().getRoot().getProjects()\n</code></pre>\n\n<p>will get you a list of all the projects in the workspace. you can easily iterate to find the one you want. At that point, you can look for certain files by extensions, etc.</p>\n" }, { "answer_id": 243030, "author": "Denis R.", "author_id": 32015, "author_profile": "https://Stackoverflow.com/users/32015", "pm_score": 1, "selected": false, "text": "<p>If you want to enable your users to select files inside eclipse workspace with a certain extension, you can look at the class <strong>org.eclipse.ui.dialogs.ElementTreeSelectionDialog</strong> (org.eclipse.ui.dialogs plugin)as a start.</p>\n\n<p>Then, to have an example on how to make it filter extensions, you can look at the class <strong>org.eclipse.jdt.internal.ui.viewsupport.FilteredElementTreeSelectionDialog</strong> (org.eclipse.jdt.ui plugin) to see how they do it and then reimplement the stuff.</p>\n\n<p>This should give you a higher level of action than going threw files inside projects by hand and reimplement dialogs.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17712/" ]
Is there a way to get the directory of a project in Eclipse? We are writing a plugin that will allow the user to select files, and then run some processes on those files. I would ideally like to be able to get all the files with a certain extension, but that is not necessary.
sure: ``` ResourcesPlugin.getWorkspace().getRoot().getProjects() ``` will get you a list of all the projects in the workspace. you can easily iterate to find the one you want. At that point, you can look for certain files by extensions, etc.
242,066
<p>I am currently validating a client's HTML Source and I am getting a lot of validation errors for images and input files which do not have the Omittag. I would do it manually but this client literally has thousands of files, with a lot of instances where the is not .</p> <p>This client has validated some img tags (for whatever reason).</p> <p>Just wondering if there is a unix command I could run to check to see if the does not have a Omittag to add it.</p> <p>I have done simple search and replaces with the following command:</p> <pre><code>find . \! -path '*.svn*' -type f -exec sed -i -n '1h;1!H;${;g;s/&lt;b&gt;/&lt;strong&gt;/g;p}' {} \; </code></pre> <p>But never something this large. Any help would be appreciated.</p>
[ { "answer_id": 242374, "author": "Anirvan", "author_id": 31100, "author_profile": "https://Stackoverflow.com/users/31100", "pm_score": 2, "selected": false, "text": "<p>Try this. It'll go through your files, make a <code>.orig</code> backup of each file (perl's <code>-i</code> operator), and replace <code>&lt;img&gt;</code> and <code>&lt;input&gt;</code> tags with <code>&lt;img /&gt;</code> and <code>&lt;input &gt;</code>.</p>\n\n<pre><code>find . \\! -path '*.svn*' -type f -exec perl -pi.orig -e 's{ ( &lt;(?:img|input)\\b ([^&gt;]*?) ) \\ ?/?&gt; }{$1\\ /&gt;}sgxi' {} \\;\n</code></pre>\n\n<p>Given input:</p>\n\n<pre><code>&lt;img&gt; &lt;img/&gt; &lt;img src=\"..\"&gt; &lt;img src=\"\" &gt;\n&lt;input&gt; &lt;input/&gt; &lt;input id=\"..\"&gt; &lt;input id=\"\" &gt;\n</code></pre>\n\n<p>It changes the file to:</p>\n\n<pre><code>&lt;img /&gt; &lt;img /&gt; &lt;img src=\"..\" /&gt; &lt;img src=\"\" /&gt;\n&lt;input /&gt; &lt;input /&gt; &lt;input id=\"..\" /&gt; &lt;input id=\"\" /&gt;\n</code></pre>\n\n<p>Here's what the regexp is doing:</p>\n\n<pre><code>s{(&lt;(?:img|input)\\b ([^&gt;]*?)) # capture \"&lt;img\" or \"&lt;input\" followed by non-\"&gt;\" chars\n \\ ?/?&gt;} # optional space, optional slash, followed by \"&gt;\"\n{$1\\ /&gt;}sgxi # replace with: captured text, plus \" /&gt;\"\n</code></pre>\n" }, { "answer_id": 242377, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 1, "selected": true, "text": "<p>See questions I asked in comment at top.</p>\n\n<p>Assuming you're using GNU sed, and that you're trying to <strong>add</strong> the trailing <code>/</code> to your tags to make XML-compliant <code>&lt;img /&gt;</code> and <code>&lt;input /&gt;</code>, then replace the sed expression in your command with this one, and it should do the trick: <code>'1h;1!H;${;g;s/\\(img\\|input\\)\\( [^&gt;]*[^/]\\)&gt;/\\1\\2\\/&gt;/g;p;}'</code></p>\n\n<p>Here it is on a simple test file (SO's colorizer doing wacky things):</p>\n\n<pre><code>$ cat test.html\nThis is an &lt;img tag&gt; without closing slash.\nHere is an &lt;img tag /&gt; with closing slash.\nThis is an &lt;input tag &gt; without closing slash.\nAnd here one &lt;input attrib=\"1\" \n &gt; that spans multiple lines.\nFinally one &lt;input\n attrib=\"1\" /&gt; with closing slash.\n\n$ sed -n '1h;1!H;${;g;s/\\(img\\|input\\)\\( [^&gt;]*[^/]\\)&gt;/\\1\\2\\/&gt;/g;p;}' test.html\nThis is an &lt;img tag/&gt; without closing slash.\nHere is an &lt;img tag /&gt; with closing slash.\nThis is an &lt;input tag /&gt; without closing slash.\nAnd here one &lt;input attrib=\"1\" \n /&gt; that spans multiple lines.\nFinally one &lt;input\n attrib=\"1\" /&gt; with closing slash.\n</code></pre>\n\n<p>Here's <a href=\"http://www.gnu.org/software/sed/manual/sed.html#Regular-Expressions\" rel=\"nofollow noreferrer\">GNU sed regex syntax</a> and <a href=\"http://www.ilfilosofo.com/blog/2008/04/26/sed-multi-line-search-and-replace/\" rel=\"nofollow noreferrer\">how the buffering works to do multiline search/replace</a>.</p>\n\n<p>Alternately you could use something like <a href=\"http://tidy.sourceforge.net/\" rel=\"nofollow noreferrer\">Tidy</a> that's designed for sanitizing bad HTML -- that's what I'd do if I were doing anything more complicated than a couple of simple search/replaces. Tidy's options get complicated fast, so it's usually better to write a script in your scripting language of choice (Python, Perl) that calls <code>libtidy</code> and sets whatever options you need.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am currently validating a client's HTML Source and I am getting a lot of validation errors for images and input files which do not have the Omittag. I would do it manually but this client literally has thousands of files, with a lot of instances where the is not . This client has validated some img tags (for whatever reason). Just wondering if there is a unix command I could run to check to see if the does not have a Omittag to add it. I have done simple search and replaces with the following command: ``` find . \! -path '*.svn*' -type f -exec sed -i -n '1h;1!H;${;g;s/<b>/<strong>/g;p}' {} \; ``` But never something this large. Any help would be appreciated.
See questions I asked in comment at top. Assuming you're using GNU sed, and that you're trying to **add** the trailing `/` to your tags to make XML-compliant `<img />` and `<input />`, then replace the sed expression in your command with this one, and it should do the trick: `'1h;1!H;${;g;s/\(img\|input\)\( [^>]*[^/]\)>/\1\2\/>/g;p;}'` Here it is on a simple test file (SO's colorizer doing wacky things): ``` $ cat test.html This is an <img tag> without closing slash. Here is an <img tag /> with closing slash. This is an <input tag > without closing slash. And here one <input attrib="1" > that spans multiple lines. Finally one <input attrib="1" /> with closing slash. $ sed -n '1h;1!H;${;g;s/\(img\|input\)\( [^>]*[^/]\)>/\1\2\/>/g;p;}' test.html This is an <img tag/> without closing slash. Here is an <img tag /> with closing slash. This is an <input tag /> without closing slash. And here one <input attrib="1" /> that spans multiple lines. Finally one <input attrib="1" /> with closing slash. ``` Here's [GNU sed regex syntax](http://www.gnu.org/software/sed/manual/sed.html#Regular-Expressions) and [how the buffering works to do multiline search/replace](http://www.ilfilosofo.com/blog/2008/04/26/sed-multi-line-search-and-replace/). Alternately you could use something like [Tidy](http://tidy.sourceforge.net/) that's designed for sanitizing bad HTML -- that's what I'd do if I were doing anything more complicated than a couple of simple search/replaces. Tidy's options get complicated fast, so it's usually better to write a script in your scripting language of choice (Python, Perl) that calls `libtidy` and sets whatever options you need.
242,073
<p>This is similar to <a href="https://stackoverflow.com/questions/18932/sql-how-can-i-remove-duplicate-rows">this question</a>, but it seems like some of the answers there aren't quite compatible with MySQL (or I'm not doing it right), and I'm having a heck of a time figuring out the changes I need. Apparently my SQL is rustier than I thought it was. I'm also looking to change a column value rather than delete, but I think at least <b>that</b> part is simple...</p> <p>I have a table like:</p> <pre>rowid SERIAL fingerprint TEXT duplicate BOOLEAN contents TEXT created_date DATETIME</pre> <p>I want to set duplicate=true for all but the first (by created_date) of each group by fingerprint. It's easy to mark <em>all</em> of the rows with duplicate fingerprints as dupes. The part I'm getting stuck on is keeping the first.</p> <p>One of the apps that populates the table does bulk loads of data, with multiple workers loading data from different sources, and the workers' data isn't necessarily partitioned by date, so it's a pain to try to mark these all as they come in (the first one inserted isn't necessarily the first one by date). Also, I already have a bunch of data in there I'll need to clean up either way. So I'd rather just have a relatively efficient query I can run after a bulk load to clean up than try to build it into that app.</p> <p>Thanks!</p>
[ { "answer_id": 242102, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 0, "selected": false, "text": "<p>How about a two-step approach, assuming you can go offline during a data load:</p>\n\n<ul>\n<li>Mark every item as duplicate.</li>\n<li>Select the earliest row from each group, and clear the duplicate flag.</li>\n</ul>\n\n<p>Not elegant, but gets the job done.</p>\n" }, { "answer_id": 242336, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "<p>Here's a funny way to do it:</p>\n\n<pre><code>SET @rowid := 0;\n\nUPDATE mytable\nSET duplicate = (rowid = @rowid), \n rowid = (@rowid:=rowid)\nORDER BY rowid, created_date;\n</code></pre>\n\n<ul>\n<li>First set a user variable to zero, assuming this is less than any rowid in your table.</li>\n<li>Then use the MySQL <code>UPDATE...ORDER BY</code> feature to ensure that the rows are updated in order by <code>rowid</code>, then by <code>created_date</code>. </li>\n<li>For each row, if the current <code>rowid</code> is not equal to the user variable <code>@rowid</code>, set <code>duplicate</code> to 0 (false). This will be true only on the first row encountered with a given value for <code>rowid</code>.</li>\n<li>Then add a dummy set of <code>rowid</code> to its own value, setting <code>@rowid</code> to that value as a side effect. </li>\n<li>As you <code>UPDATE</code> the next row, if it's a duplicate of the previous row, <code>rowid</code> will be equal to the user variable <code>@rowid</code>, and therefore <code>duplicate</code> will be set to 1 (true).</li>\n</ul>\n\n<p><strong>Edit:</strong> Now I have tested this, and I corrected a mistake in the line that sets <code>duplicate</code>.</p>\n" }, { "answer_id": 245950, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 0, "selected": false, "text": "<p>I don't know the MySQL syntax, but in PLSQL you just do:</p>\n\n<pre><code>UPDATE t1\nSET duplicate = 1\nFROM MyTable t1\nWHERE rowid != (\n SELECT TOP 1 rowid FROM MyTable t2\n WHERE t2.fingerprint = t1.fingerprint ORDER BY created_date DESC\n)\n</code></pre>\n\n<p>That may have some syntax errors, as I'm just typing off the cuff/not able to test it, but that's the gist of it.</p>\n\n<hr>\n\n<p>MySQL version (not tested):</p>\n\n<pre><code>UPDATE t1\n SET duplicate = 1\nFROM MyTable t1\nWHERE rowid != (\n SELECT rowid FROM MyTable t2\n WHERE t2.fingerprint = t1.fingerprint\n ORDER BY created_date DESC\n LIMIT 1\n)\n</code></pre>\n" }, { "answer_id": 254436, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "<p>Here's another way to do it, using MySQL's multi-table <code>UPDATE</code> syntax:</p>\n\n<pre><code>UPDATE mytable m1\n JOIN mytable m2 ON (m1.rowid = m2.rowid AND m1.created_date &lt; m2.created_date)\nSET m2.duplicate = 1;\n</code></pre>\n" }, { "answer_id": 667923, "author": "Dipin", "author_id": 67976, "author_profile": "https://Stackoverflow.com/users/67976", "pm_score": 2, "selected": false, "text": "<p>MySQL needs to be explicitly told if the data you are grouping by is larger than 1024 bytes (see <a href=\"http://dev.mysql.com/doc/refman/5.1/en/blob.html\" rel=\"nofollow noreferrer\">this link</a> for details). So if your data in the fingerprint column is larger than 1024 bytes you should use set the <code>max_sort_length</code> variable (see <a href=\"http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_max_sort_length\" rel=\"nofollow noreferrer\">this link</a> for details about values allowed, and <a href=\"http://dev.mysql.com/doc/refman/5.0/en/set-option.html\" rel=\"nofollow noreferrer\">this link</a> about how to set it) to a larger number so that the group by wont silently use only part of your data for grouping.</p>\n\n<p>Once you're certain that MySQL will group your data properly, the following query will set the duplicate flag so that the first fingerprint record has duplicate set to FALSE/0 and any subsequent fingerprint records have duplicate set to TRUE/1:</p>\n\n<pre><code> UPDATE mytable m1\nINNER JOIN (SELECT fingerprint\n , MIN(rowid) AS minrow \n FROM mytable m2 \n GROUP BY fingerprint) m3 \n ON m1.fingerprint = m3.fingerprint\n SET m1.duplicate = m3.minrow != m1.rowid;\n</code></pre>\n\n<p>Please keep in mind that this solution does not take NULLs into account and if it is possible for the fingerprint field to be NULL then you would need additional logic to handle that case.</p>\n" }, { "answer_id": 842445, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>Untested...</p>\n\n<pre><code>UPDATE TheAnonymousTable\n SET duplicate = TRUE\n WHERE rowid NOT IN\n (SELECT rowid\n FROM (SELECT MIN(created_date) AS created_date, fingerprint\n FROM TheAnonymousTable\n GROUP BY fingerprint\n ) AS M,\n TheAnonymousTable AS T\n WHERE M.created_date = T.created_date\n AND M.fingerprint = T.fingerprint\n );\n</code></pre>\n\n<p>The logic is that the innermost query returns the earliest <code>created_date</code> for each distinct fingerprint as table alias M. The middle query determines the rowid value for each of those rows; it is a nuisance to have to do this (but necessary), and the code assumes that you won't get two records for the same fingerprint and timestamp. This gives you the rowid for the earlist record for each separate fingerprint. Then the outer query (the UPDATE) sets the 'duplicate' flag on all those rows where the rowid is not one of the earliest rows.</p>\n\n<p>Some DBMS may be unhappy about doing (nested) sub-queries on the table being updated.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is similar to [this question](https://stackoverflow.com/questions/18932/sql-how-can-i-remove-duplicate-rows), but it seems like some of the answers there aren't quite compatible with MySQL (or I'm not doing it right), and I'm having a heck of a time figuring out the changes I need. Apparently my SQL is rustier than I thought it was. I'm also looking to change a column value rather than delete, but I think at least **that** part is simple... I have a table like: ``` rowid SERIAL fingerprint TEXT duplicate BOOLEAN contents TEXT created_date DATETIME ``` I want to set duplicate=true for all but the first (by created\_date) of each group by fingerprint. It's easy to mark *all* of the rows with duplicate fingerprints as dupes. The part I'm getting stuck on is keeping the first. One of the apps that populates the table does bulk loads of data, with multiple workers loading data from different sources, and the workers' data isn't necessarily partitioned by date, so it's a pain to try to mark these all as they come in (the first one inserted isn't necessarily the first one by date). Also, I already have a bunch of data in there I'll need to clean up either way. So I'd rather just have a relatively efficient query I can run after a bulk load to clean up than try to build it into that app. Thanks!
MySQL needs to be explicitly told if the data you are grouping by is larger than 1024 bytes (see [this link](http://dev.mysql.com/doc/refman/5.1/en/blob.html) for details). So if your data in the fingerprint column is larger than 1024 bytes you should use set the `max_sort_length` variable (see [this link](http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_max_sort_length) for details about values allowed, and [this link](http://dev.mysql.com/doc/refman/5.0/en/set-option.html) about how to set it) to a larger number so that the group by wont silently use only part of your data for grouping. Once you're certain that MySQL will group your data properly, the following query will set the duplicate flag so that the first fingerprint record has duplicate set to FALSE/0 and any subsequent fingerprint records have duplicate set to TRUE/1: ``` UPDATE mytable m1 INNER JOIN (SELECT fingerprint , MIN(rowid) AS minrow FROM mytable m2 GROUP BY fingerprint) m3 ON m1.fingerprint = m3.fingerprint SET m1.duplicate = m3.minrow != m1.rowid; ``` Please keep in mind that this solution does not take NULLs into account and if it is possible for the fingerprint field to be NULL then you would need additional logic to handle that case.
242,079
<p>In Java, we can always use an array to store object reference. Then we have an ArrayList or HashTable which is automatically expandable to store objects. But does anyone know a native way to have an auto-expandable array of object references?</p> <p>Edit: What I mean is I want to know if the Java API has some class with the ability to store references to objects (but not storing the actual object like XXXList or HashTable do) AND the ability of auto-expansion.</p>
[ { "answer_id": 242084, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 0, "selected": false, "text": "<p>There's no first-class language construct that does that that I'm aware of, if that's what you're looking for.</p>\n" }, { "answer_id": 242089, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": -1, "selected": false, "text": "<p>if you can write your code in javascript, yes, you can do that. javascript arrays are sparse arrays. it will expand whichever way you want.</p>\n\n<p>you can write</p>\n\n<p>a[0] = 4;<br>\na[1000] = 434;<br>\na[888] = \"a string\";</p>\n" }, { "answer_id": 242093, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 4, "selected": true, "text": "<p>Java arrays are, by their definition, fixed size. If you need auto-growth, you use XXXList classes.</p>\n\n<p>EDIT - question has been clarified a bit</p>\n\n<p>When I was first starting to learn Java (coming from a C and C++ background), this was probably one of the first things that tripped me up. Hopefully I can shed some light.</p>\n\n<p>Unlike C++, Object arrays in Java do <em>not</em> store objects. They store object references.</p>\n\n<p>In C++, if you declared something similar to:</p>\n\n<pre><code>String myStrings[10];\n</code></pre>\n\n<p>You would get 10 String objects. At this point, it would be perfectly legal to do something like println(myStrings[5].length); - you'd get '0' - the default constructor for String creates an empty string with length 0.</p>\n\n<p>In Java, when you construct a new array, you get an empty container that can hold 10 String references. So the call:</p>\n\n<pre><code>String[] myStrings = new String[10];\nprintln(myStringsp[5].length);\n</code></pre>\n\n<p>would throw a null pointer exception, because you haven't actually placed a String reference into the array yet.</p>\n\n<p>If you are coming from a C++ background, think of new String[10] as being equivalent to new (String *)[10] from C++.</p>\n\n<p>So, with that in mind, it should be fairly clear why ArrayList <em>is</em> the solution for an auto expanding array of objects (and in fact, ArrayList is implemented using simple arrays, with a growth algorithm built in that allocates new expanded arrays as needed and copies the content from the old to the new).</p>\n\n<p>In practice, there are actually relatively few situations where we use arrays. If you are writing a container (something akin to ArrayList, or a BTree), then they are useful, or if you are doing a lot of low level byte manipulation - but at the level that most development occurs, using one of the Collections classes is by far the preferred technique.</p>\n" }, { "answer_id": 242101, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "<p>What do you mean by \"native\" way? If you want an expandable list f objects then you can use the ArrayList. With List collections you have the get(index) method that allows you to access objects in the list by index which gives you similar functionality to an array. Internally the ArrayList is implemented with an array and the ArrayList handles expanding it automatically for you.</p>\n" }, { "answer_id": 242117, "author": "Brandon DuRette", "author_id": 17834, "author_profile": "https://Stackoverflow.com/users/17834", "pm_score": 0, "selected": false, "text": "<p>It's not very efficient, but if you're just appending to an array, you can use <a href=\"http://tinyurl.com/5jvhod\" rel=\"nofollow noreferrer\">Apache Commons ArrayUtils.add()</a>. It returns a copy of the original array with the additional element in it.</p>\n" }, { "answer_id": 242125, "author": "101010110101", "author_id": 14013, "author_profile": "https://Stackoverflow.com/users/14013", "pm_score": 1, "selected": false, "text": "<p>Straight from the <a href=\"http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html\" rel=\"nofollow noreferrer\">Array Java Tutorials</a> on the sun webpage:</p>\n\n<p>-> An array is a container object that holds a <strong><em>fixed</em></strong> number of values of a single type. </p>\n\n<p>Because the size of the array is declared when it is created, there is actually no way to expand it afterwards. The whole purpose of declaring an array of a certain size is to only allocate as much memory as will likely be used when the program is executed. What you <em>could</em> do is declare a second array that is a function based on the size of the original, copy all of the original elements into it, and then add the necessary new elements (although this isn't very 'automatic' :) ). Otherwise, as you and a few others have mentioned, the List Collections is the most efficient way to go.</p>\n" }, { "answer_id": 242457, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>All the classes implementing Collection are expandable and store only references: you don't store objects, you create them in some data space and only manipulate references to them, until they go out of scope without reference on them.</p>\n\n<p>You can put a reference to an object in two or more Collections. That's how you can have sorted hash tables and such...</p>\n" }, { "answer_id": 242844, "author": "mtruesdell", "author_id": 6479, "author_profile": "https://Stackoverflow.com/users/6479", "pm_score": 1, "selected": false, "text": "<p>In Java, all object variables are references. So</p>\n\n<pre><code>Foo myFoo = new Foo();\nFoo anotherFoo = myFoo;\n</code></pre>\n\n<p>means that both variables are referring to the same object, not to two separate copies. Likewise, when you put an object in a <code>Collection</code>, you are only storing a reference to the object. Therefore using <code>ArrayList</code> or similar is the correct way to have an automatically expanding piece of storage.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8203/" ]
In Java, we can always use an array to store object reference. Then we have an ArrayList or HashTable which is automatically expandable to store objects. But does anyone know a native way to have an auto-expandable array of object references? Edit: What I mean is I want to know if the Java API has some class with the ability to store references to objects (but not storing the actual object like XXXList or HashTable do) AND the ability of auto-expansion.
Java arrays are, by their definition, fixed size. If you need auto-growth, you use XXXList classes. EDIT - question has been clarified a bit When I was first starting to learn Java (coming from a C and C++ background), this was probably one of the first things that tripped me up. Hopefully I can shed some light. Unlike C++, Object arrays in Java do *not* store objects. They store object references. In C++, if you declared something similar to: ``` String myStrings[10]; ``` You would get 10 String objects. At this point, it would be perfectly legal to do something like println(myStrings[5].length); - you'd get '0' - the default constructor for String creates an empty string with length 0. In Java, when you construct a new array, you get an empty container that can hold 10 String references. So the call: ``` String[] myStrings = new String[10]; println(myStringsp[5].length); ``` would throw a null pointer exception, because you haven't actually placed a String reference into the array yet. If you are coming from a C++ background, think of new String[10] as being equivalent to new (String \*)[10] from C++. So, with that in mind, it should be fairly clear why ArrayList *is* the solution for an auto expanding array of objects (and in fact, ArrayList is implemented using simple arrays, with a growth algorithm built in that allocates new expanded arrays as needed and copies the content from the old to the new). In practice, there are actually relatively few situations where we use arrays. If you are writing a container (something akin to ArrayList, or a BTree), then they are useful, or if you are doing a lot of low level byte manipulation - but at the level that most development occurs, using one of the Collections classes is by far the preferred technique.
242,097
<p>What's a more elegant way of having the code below where i want to return a derived class based on the type of another class.</p> <pre><code> if (option_ is Rectangle) { modelInputs = new Foo(); } else if (option_ is Circle) { modelInputs = new Bar(); } else if (option_ is Triangle) { modelInputs = new Bar2(); } </code></pre>
[ { "answer_id": 242103, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 0, "selected": false, "text": "<p>You could associate a type with \"option_\", if it allows, and then just create an instance of it.</p>\n" }, { "answer_id": 242109, "author": "mmiika", "author_id": 6846, "author_profile": "https://Stackoverflow.com/users/6846", "pm_score": 4, "selected": true, "text": "<p>Have Rectangle, Circle and Triangle implement IHasModelInput:</p>\n\n<pre><code>interface IHasModelInput\n{\n IModelInput GetModelInput();\n}\n</code></pre>\n\n<p>then you can do</p>\n\n<pre><code>IModelInput modelInputs = option_.GetModelInput();\n</code></pre>\n" }, { "answer_id": 242198, "author": "Andrew Stapleton", "author_id": 28506, "author_profile": "https://Stackoverflow.com/users/28506", "pm_score": 2, "selected": false, "text": "<p>My opinion: your \"inelegant\" way is fine. It's simple, readable and does the job.</p>\n\n<p>Having the Rectangle, Circle and Triangle implement the necessary factory function via <i>IHasModelInput</i> would work, but it has a design cost: you've now coupled this set of classes with the IModelInput set of classes (Foo, Bar and Bar2). They could be in two completely different libraries, and maybe they shouldn't know about one another.</p>\n\n<p>A more complicated method is below. It gives you the advantage of being able to configure your factory logic at runtime. </p>\n\n<pre><code> public static class FactoryMethod&lt;T&gt; where T : IModelInput, new()\n {\n public static IModelInput Create()\n {\n return new T();\n }\n }\n\n delegate IModelInput ModelInputCreateFunction();\n\n IModelInput CreateIModelInput(object item)\n {\n\n Dictionary&lt;Type, ModelInputCreateFunction&gt; factory = new Dictionary&lt;Type, ModelInputCreateFunction&gt;();\n\n\n factory.Add(typeof(Rectangle), FactoryMethod&lt;Foo&gt;.Create);\n factory.Add(typeof(Circle), FactoryMethod&lt;Bar&gt;.Create);\n // Add more type mappings here\n\n\n\n\n IModelInput modelInput;\n foreach (Type t in factory.Keys)\n {\n if ( item.GetType().IsSubclassOf(t) || item.GetType().Equals(t))\n {\n modelInput = factory[t].Invoke();\n break;\n }\n }\n return modelInput;\n }\n</code></pre>\n\n<p>But then ask the question: which one would you rather read?</p>\n" }, { "answer_id": 242222, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 1, "selected": false, "text": "<p>You could put the inputs and outputs in a Hashtable, or store the types which create each class inside each one of the classes you create and then use Activator.CreateInstance to do the factoryin':</p>\n\n<pre><code>Hashtable ht = new Hashtable();\nht.Add(typeof(Rectangle), typeof(Bar));\nht.Add(typeof(Square), typeof(Bar2));\n\nmodelInputs = Activator.CreateInstance(ht[option.GetType()]);\n</code></pre>\n\n<p>Either way, Activator.CreateInstance is a pretty cool way of making factories work in .NET. Enjoy, and use the power I have given you wisely, son.</p>\n" }, { "answer_id": 242232, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>I usually use a factory method like this when I want to convert a string to a type at runtime, I use a Dictionary that maps a string to a Type.</p>\n\n<p>Like this from a recent project:</p>\n\n<pre><code>public class TaskFactory\n{\n private Dictionary&lt;String, Type&gt; _taskTypes = new Dictionary&lt;String, Type&gt;();\n\n public TaskFactory()\n {\n // Preload the Task Types into a dictionary so we can look them up later\n foreach (Type type in typeof(TaskFactory).Assembly.GetTypes())\n {\n if (type.IsSubclassOf(typeof(CCTask)))\n {\n _taskTypes[type.Name.ToLower()] = type;\n }\n }\n }\n\n public CCTask CreateTask(XmlElement task)\n {\n if (task != null)\n {\n string taskName = task.Name;\n taskName = taskName.ToLower() + \"task\";\n\n // If the Type information is in our Dictionary, instantiate a new instance of that task\n Type taskType;\n if (_taskTypes.TryGetValue(taskName, out taskType))\n {\n return (CCTask)Activator.CreateInstance(taskType, task);\n }\n else\n {\n throw new ArgumentException(\"Unrecognized Task:\" + task.Name);\n } \n }\n else\n {\n return null;\n }\n }\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
What's a more elegant way of having the code below where i want to return a derived class based on the type of another class. ``` if (option_ is Rectangle) { modelInputs = new Foo(); } else if (option_ is Circle) { modelInputs = new Bar(); } else if (option_ is Triangle) { modelInputs = new Bar2(); } ```
Have Rectangle, Circle and Triangle implement IHasModelInput: ``` interface IHasModelInput { IModelInput GetModelInput(); } ``` then you can do ``` IModelInput modelInputs = option_.GetModelInput(); ```
242,118
<p>Assuming a Perl script that allows users to specify several text filter expressions in a config file, is there a safe way to let them enter regular expressions as well, without the possibility of unintended side effects or code execution? Without actually parsing the regexes and checking them for problematic constructs, that is. There won't be any substitution, only matching.</p> <p>As an aside, is there a way to test if the specified regex is valid before actually using it? I'd like to issue warnings if something like <code>/foo (bar/</code> was entered.</p> <p>Thanks, Z.</p> <p><hr> EDIT:<br> Thanks for the very interesting answers. I've since found out that the following dangerous constructs will only be evaluated in regexes if the <code>use re 'eval'</code> pragma is used:</p> <pre><code>(?{code}) (??{code}) ${code} @{code} </code></pre> <p>The default is <code>no re 'eval'</code>; so unless I'm missing something, it should be safe to read regular expressions from a file, with the only check being the eval/catch posted by Axeman. At least I haven't been able to hide anything evil in them in my tests.</p> <p>Thanks again. Z.</p>
[ { "answer_id": 242122, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>You will probably have to do some level of sanitisation. For example, the <a href=\"http://perldoc.perl.org/perlre.html\" rel=\"nofollow noreferrer\">perlre</a> man page describes the following construct:</p>\n\n<pre><code>(?{ code })\n</code></pre>\n\n<p>which allows executable code inside a pattern match.</p>\n" }, { "answer_id": 242132, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 4, "selected": false, "text": "<p>This</p>\n\n<pre><code>eval { \n qr/$re/;\n};\nif ( $@ ) { \n # do something\n}\n</code></pre>\n\n<p>compiles an expression, and lets you recover from an error. </p>\n\n<p>You can watch for malicious expression, since you're only going to do matching, by looking for these patterns, which would allow arbitrary code to be run:</p>\n\n<pre><code>(?: \\( \\?{1,2} \\{ # '(' followed by '?' or '??', and then '{'\n| \\@ \\{ \\s* \\[ # a dereference of a literal array, which may be arbitrary code.\n)\n</code></pre>\n\n<p>Make sure you compile this with the <code>x</code> flag. </p>\n" }, { "answer_id": 242272, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 4, "selected": false, "text": "<p>Depending on what you're matching against, and the version of Perl you're running, there might be some regexes that act as an effective denial of service attack by using excessive lookaheads, lookbehinds, and other assertions.</p>\n\n<p>You're best off allowing only a small, well-known subset of regex patterns, and expanding it cautiously as you and your users learn how to use the system. In the same way that many blog commenting systems allow only a small subset of HTML tags.</p>\n\n<p>Eventually Parse::RecDescent might become useful, if you need to do complex analysis of regexes.</p>\n" }, { "answer_id": 242560, "author": "tsee", "author_id": 13164, "author_profile": "https://Stackoverflow.com/users/13164", "pm_score": 3, "selected": false, "text": "<p>I would suggest not trusting any regular expressions from users. If you are actually determined to do so, please run perl in taint (-T) mode. In that case, you'll need some form of validation. Instead of using Parse::RecDescent for writing your own regular expression parser as another answer suggests, you should use the existing <a href=\"http://search.cpan.org/dist/YAPE-Regex\" rel=\"nofollow noreferrer\">YAPE::Regex</a> regexp parser which is probably faster, was written by an expert and works like a charm.</p>\n\n<p>Finally, since perl 5.10.0, you can plug different regular expression engines into perl (lexically!). You could check whether there's a less powerful regular expression engine available whose syntax is more easily verifiable. If you want to go down that route, read <a href=\"http://search.cpan.org/perldoc?perlreapi\" rel=\"nofollow noreferrer\">the API description</a>, <a href=\"http://search.cpan.org/perldoc?re::engine::Plugin\" rel=\"nofollow noreferrer\">Avar's re::engine::Plugin</a>, or in general check out any of <a href=\"http://search.cpan.org/~avar\" rel=\"nofollow noreferrer\">Avar's plugin engines</a>.</p>\n" }, { "answer_id": 244218, "author": "Danny", "author_id": 26630, "author_profile": "https://Stackoverflow.com/users/26630", "pm_score": 0, "selected": false, "text": "<p>Would the <a href=\"http://perldoc.perl.org/Safe.html\" rel=\"nofollow noreferrer\" title=\"Safe\">Safe</a> module be of any use with regard to compiling/executing untrusted regular expressions?</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31682/" ]
Assuming a Perl script that allows users to specify several text filter expressions in a config file, is there a safe way to let them enter regular expressions as well, without the possibility of unintended side effects or code execution? Without actually parsing the regexes and checking them for problematic constructs, that is. There won't be any substitution, only matching. As an aside, is there a way to test if the specified regex is valid before actually using it? I'd like to issue warnings if something like `/foo (bar/` was entered. Thanks, Z. --- EDIT: Thanks for the very interesting answers. I've since found out that the following dangerous constructs will only be evaluated in regexes if the `use re 'eval'` pragma is used: ``` (?{code}) (??{code}) ${code} @{code} ``` The default is `no re 'eval'`; so unless I'm missing something, it should be safe to read regular expressions from a file, with the only check being the eval/catch posted by Axeman. At least I haven't been able to hide anything evil in them in my tests. Thanks again. Z.
This ``` eval { qr/$re/; }; if ( $@ ) { # do something } ``` compiles an expression, and lets you recover from an error. You can watch for malicious expression, since you're only going to do matching, by looking for these patterns, which would allow arbitrary code to be run: ``` (?: \( \?{1,2} \{ # '(' followed by '?' or '??', and then '{' | \@ \{ \s* \[ # a dereference of a literal array, which may be arbitrary code. ) ``` Make sure you compile this with the `x` flag.
242,143
<p>I am using WCF to upload data to a server.</p> <p>If the communication fails, is there any way to resume the upload?</p>
[ { "answer_id": 242122, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>You will probably have to do some level of sanitisation. For example, the <a href=\"http://perldoc.perl.org/perlre.html\" rel=\"nofollow noreferrer\">perlre</a> man page describes the following construct:</p>\n\n<pre><code>(?{ code })\n</code></pre>\n\n<p>which allows executable code inside a pattern match.</p>\n" }, { "answer_id": 242132, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 4, "selected": false, "text": "<p>This</p>\n\n<pre><code>eval { \n qr/$re/;\n};\nif ( $@ ) { \n # do something\n}\n</code></pre>\n\n<p>compiles an expression, and lets you recover from an error. </p>\n\n<p>You can watch for malicious expression, since you're only going to do matching, by looking for these patterns, which would allow arbitrary code to be run:</p>\n\n<pre><code>(?: \\( \\?{1,2} \\{ # '(' followed by '?' or '??', and then '{'\n| \\@ \\{ \\s* \\[ # a dereference of a literal array, which may be arbitrary code.\n)\n</code></pre>\n\n<p>Make sure you compile this with the <code>x</code> flag. </p>\n" }, { "answer_id": 242272, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 4, "selected": false, "text": "<p>Depending on what you're matching against, and the version of Perl you're running, there might be some regexes that act as an effective denial of service attack by using excessive lookaheads, lookbehinds, and other assertions.</p>\n\n<p>You're best off allowing only a small, well-known subset of regex patterns, and expanding it cautiously as you and your users learn how to use the system. In the same way that many blog commenting systems allow only a small subset of HTML tags.</p>\n\n<p>Eventually Parse::RecDescent might become useful, if you need to do complex analysis of regexes.</p>\n" }, { "answer_id": 242560, "author": "tsee", "author_id": 13164, "author_profile": "https://Stackoverflow.com/users/13164", "pm_score": 3, "selected": false, "text": "<p>I would suggest not trusting any regular expressions from users. If you are actually determined to do so, please run perl in taint (-T) mode. In that case, you'll need some form of validation. Instead of using Parse::RecDescent for writing your own regular expression parser as another answer suggests, you should use the existing <a href=\"http://search.cpan.org/dist/YAPE-Regex\" rel=\"nofollow noreferrer\">YAPE::Regex</a> regexp parser which is probably faster, was written by an expert and works like a charm.</p>\n\n<p>Finally, since perl 5.10.0, you can plug different regular expression engines into perl (lexically!). You could check whether there's a less powerful regular expression engine available whose syntax is more easily verifiable. If you want to go down that route, read <a href=\"http://search.cpan.org/perldoc?perlreapi\" rel=\"nofollow noreferrer\">the API description</a>, <a href=\"http://search.cpan.org/perldoc?re::engine::Plugin\" rel=\"nofollow noreferrer\">Avar's re::engine::Plugin</a>, or in general check out any of <a href=\"http://search.cpan.org/~avar\" rel=\"nofollow noreferrer\">Avar's plugin engines</a>.</p>\n" }, { "answer_id": 244218, "author": "Danny", "author_id": 26630, "author_profile": "https://Stackoverflow.com/users/26630", "pm_score": 0, "selected": false, "text": "<p>Would the <a href=\"http://perldoc.perl.org/Safe.html\" rel=\"nofollow noreferrer\" title=\"Safe\">Safe</a> module be of any use with regard to compiling/executing untrusted regular expressions?</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I am using WCF to upload data to a server. If the communication fails, is there any way to resume the upload?
This ``` eval { qr/$re/; }; if ( $@ ) { # do something } ``` compiles an expression, and lets you recover from an error. You can watch for malicious expression, since you're only going to do matching, by looking for these patterns, which would allow arbitrary code to be run: ``` (?: \( \?{1,2} \{ # '(' followed by '?' or '??', and then '{' | \@ \{ \s* \[ # a dereference of a literal array, which may be arbitrary code. ) ``` Make sure you compile this with the `x` flag.
242,172
<blockquote> <p><strong>Edit:</strong> The code here still has some bugs in it, and it could do better in the performance department, but instead of trying to fix this, for the record I took the problem over to the Intel discussion groups and got lots of great feedback, and if all goes well a polished version of Atomic float will be included in a near future release of Intel's Threading Building Blocks</p> </blockquote> <p>Ok here's a tough one, I want an Atomic float, not for super-fast graphics performance, but to use routinely as data-members of classes. And I don't want to pay the price of using locks on these classes, because it provides no additional benefits for my needs. </p> <p>Now with intel's tbb and other atomic libraries I've seen, integer types are supported, but not floating points. So I went on and implemented one, and it works... but I'm not sure if it REALLY works, or I'm just very lucky that it works.</p> <p>Anyone here knows if this is not some form of threading heresy?</p> <pre><code>typedef unsigned int uint_32; struct AtomicFloat { private: tbb::atomic&lt;uint_32&gt; atomic_value_; public: template&lt;memory_semantics M&gt; float fetch_and_store( float value ) { const uint_32 value_ = atomic_value_.tbb::atomic&lt;uint_32&gt;::fetch_and_store&lt;M&gt;((uint_32&amp;)value); return reinterpret_cast&lt;const float&amp;&gt;(value_); } float fetch_and_store( float value ) { const uint_32 value_ = atomic_value_.tbb::atomic&lt;uint_32&gt;::fetch_and_store((uint_32&amp;)value); return reinterpret_cast&lt;const float&amp;&gt;(value_); } template&lt;memory_semantics M&gt; float compare_and_swap( float value, float comparand ) { const uint_32 value_ = atomic_value_.tbb::atomic&lt;uint_32&gt;::compare_and_swap&lt;M&gt;((uint_32&amp;)value,(uint_32&amp;)compare); return reinterpret_cast&lt;const float&amp;&gt;(value_); } float compare_and_swap(float value, float compare) { const uint_32 value_ = atomic_value_.tbb::atomic&lt;uint_32&gt;::compare_and_swap((uint_32&amp;)value,(uint_32&amp;)compare); return reinterpret_cast&lt;const float&amp;&gt;(value_); } operator float() const volatile // volatile qualifier here for backwards compatibility { const uint_32 value_ = atomic_value_; return reinterpret_cast&lt;const float&amp;&gt;(value_); } float operator=(float value) { const uint_32 value_ = atomic_value_.tbb::atomic&lt;uint_32&gt;::operator =((uint_32&amp;)value); return reinterpret_cast&lt;const float&amp;&gt;(value_); } float operator+=(float value) { volatile float old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;float&amp;&gt;(atomic_value_); new_value_ = old_value_ + value; } while(compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); } float operator*=(float value) { volatile float old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;float&amp;&gt;(atomic_value_); new_value_ = old_value_ * value; } while(compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); } float operator/=(float value) { volatile float old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;float&amp;&gt;(atomic_value_); new_value_ = old_value_ / value; } while(compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); } float operator-=(float value) { return this-&gt;operator+=(-value); } float operator++() { return this-&gt;operator+=(1); } float operator--() { return this-&gt;operator+=(-1); } float fetch_and_add( float addend ) { return this-&gt;operator+=(-addend); } float fetch_and_increment() { return this-&gt;operator+=(1); } float fetch_and_decrement() { return this-&gt;operator+=(-1); } }; </code></pre> <p>Thanks!</p> <p><strong>Edit:</strong> changed size_t to uint32_t as Greg Rogers suggested, that way its more portable</p> <p><strong>Edit:</strong> added listing for the entire thing, with some fixes.</p> <p><strong>More Edits:</strong> Performance wise using a locked float for 5.000.000 += operations with 100 threads on my machine takes 3.6s, while my atomic float even with its silly do-while takes 0.2s to do the same work. So the >30x performance boost means its worth it, (and this is the catch) if its correct.</p> <p><strong>Even More Edits:</strong> As Awgn pointed out my <code>fetch_and_xxxx</code> parts were all wrong. Fixed that and removed parts of the API I'm not sure about (templated memory models). And implemented other operations in terms of operator += to avoid code repetition</p> <p><strong>Added:</strong> Added operator *= and operator /=, since floats wouldn't be floats without them. Thanks to Peterchen's comment that this was noticed</p> <p><strong>Edit:</strong> Latest version of the code follows (I'll leave the old version for reference though)</p> <pre><code> #include &lt;tbb/atomic.h&gt; typedef unsigned int uint_32; typedef __TBB_LONG_LONG uint_64; template&lt;typename FLOATING_POINT,typename MEMORY_BLOCK&gt; struct atomic_float_ { /* CRC Card ----------------------------------------------------- | Class: atmomic float template class | | Responsability: handle integral atomic memory as it were a float, | but partially bypassing FPU, SSE/MMX, so it is | slower than a true float, but faster and smaller | than a locked float. | *Warning* If your float usage is thwarted by | the A-B-A problem this class isn't for you | *Warning* Atomic specification says we return, | values not l-values. So (i = j) = k doesn't work. | | Collaborators: intel's tbb::atomic handles memory atomicity ----------------------------------------------------------------*/ typedef typename atomic_float_&lt;FLOATING_POINT,MEMORY_BLOCK&gt; self_t; tbb::atomic&lt;MEMORY_BLOCK&gt; atomic_value_; template&lt;memory_semantics M&gt; FLOATING_POINT fetch_and_store( FLOATING_POINT value ) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::fetch_and_store&lt;M&gt;((MEMORY_BLOCK&amp;)value); //atomic specification requires returning old value, not new one return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } FLOATING_POINT fetch_and_store( FLOATING_POINT value ) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::fetch_and_store((MEMORY_BLOCK&amp;)value); //atomic specification requires returning old value, not new one return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } template&lt;memory_semantics M&gt; FLOATING_POINT compare_and_swap( FLOATING_POINT value, FLOATING_POINT comparand ) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::compare_and_swap&lt;M&gt;((MEMORY_BLOCK&amp;)value,(MEMORY_BLOCK&amp;)compare); //atomic specification requires returning old value, not new one return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } FLOATING_POINT compare_and_swap(FLOATING_POINT value, FLOATING_POINT compare) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::compare_and_swap((MEMORY_BLOCK&amp;)value,(MEMORY_BLOCK&amp;)compare); //atomic specification requires returning old value, not new one return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } operator FLOATING_POINT() const volatile // volatile qualifier here for backwards compatibility { const MEMORY_BLOCK value_ = atomic_value_; return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } //Note: atomic specification says we return the a copy of the base value not an l-value FLOATING_POINT operator=(FLOATING_POINT rhs) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::operator =((MEMORY_BLOCK&amp;)rhs); return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } //Note: atomic specification says we return an l-value when operating among atomics self_t&amp; operator=(self_t&amp; rhs) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::operator =((MEMORY_BLOCK&amp;)rhs); return *this; } FLOATING_POINT&amp; _internal_reference() const { return reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::_internal_reference()); } FLOATING_POINT operator+=(FLOATING_POINT value) { FLOATING_POINT old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_); new_value_ = old_value_ + value; //floating point binary representation is not an issue because //we are using our self's compare and swap, thus comparing floats and floats } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); //return resulting value } FLOATING_POINT operator*=(FLOATING_POINT value) { FLOATING_POINT old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_); new_value_ = old_value_ * value; //floating point binary representation is not an issue becaus //we are using our self's compare and swap, thus comparing floats and floats } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); //return resulting value } FLOATING_POINT operator/=(FLOATING_POINT value) { FLOATING_POINT old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_); new_value_ = old_value_ / value; //floating point binary representation is not an issue because //we are using our self's compare and swap, thus comparing floats and floats } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); //return resulting value } FLOATING_POINT operator-=(FLOATING_POINT value) { return this-&gt;operator+=(-value); //return resulting value } //Prefix operator FLOATING_POINT operator++() { return this-&gt;operator+=(1); //return resulting value } //Prefix operator FLOATING_POINT operator--() { return this-&gt;operator+=(-1); //return resulting value } //Postfix operator FLOATING_POINT operator++(int) { const FLOATING_POINT temp = this; this-&gt;operator+=(1); return temp//return resulting value } //Postfix operator FLOATING_POINT operator--(int) { const FLOATING_POINT temp = this; this-&gt;operator+=(1); return temp//return resulting value } FLOATING_POINT fetch_and_add( FLOATING_POINT addend ) { const FLOATING_POINT old_value_ = atomic_value_; this-&gt;operator+=(addend); //atomic specification requires returning old value, not new one as in operator x= return old_value_; } FLOATING_POINT fetch_and_increment() { const FLOATING_POINT old_value_ = atomic_value_; this-&gt;operator+=(+1); //atomic specification requires returning old value, not new one as in operator x= return old_value_; } FLOATING_POINT fetch_and_decrement() { const FLOATING_POINT old_value_ = atomic_value_; this-&gt;operator+=(-1); //atomic specification requires returning old value, not new one as in operator x= return old_value_; } }; typedef atomic_float_&lt;float,uint_32&gt; AtomicFloat; typedef atomic_float_&lt;double,uint_64&gt; AtomicDouble; </code></pre>
[ { "answer_id": 242178, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>It looks like your implementation assumes that <code>sizeof(size_t) == sizeof(float)</code>. Will that always be true for your target platforms?</p>\n\n<p>And I wouldn't say <em>threading</em> heresy so much as <em>casting</em> heresy. :)</p>\n" }, { "answer_id": 242210, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 4, "selected": true, "text": "<p>I would seriously advise against public inheritance. I don't know what the atomic implementation is like, but im assuming it has overloaded operators that use it as the integral type, which means that those promotions will be used instead of your float in many (maybe most?) cases.</p>\n\n<p>I don't see any reason why that wouldn't work, but like you I have to way to prove that...</p>\n\n<p>One note: your <code>operator float()</code> routine does not have load-acquire semantics, and shouldn't it be marked const volatile (or definitely at least const)?</p>\n\n<p>EDIT: If you are going to provide operator--() you should provide both prefix/postfix forms.</p>\n" }, { "answer_id": 242220, "author": "Joshua", "author_id": 14768, "author_profile": "https://Stackoverflow.com/users/14768", "pm_score": 0, "selected": false, "text": "<p>From my reading of that code, I would be really mad at such a compiler as to put out assembly for this that wasn't atomic.</p>\n" }, { "answer_id": 242270, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 0, "selected": false, "text": "<p>Have your compiler generate assembly code and take a look at it. If the operation is more than a single assembly-language instruction, then it's <em>not</em> an atomic operation, and requires locks to operate properly in multiprocessor systems.</p>\n\n<p>Unfortunately, I'm not certain that the opposite is also true -- that single-instruction operations <em>are</em> guaranteed to be atomic. I don't know the details of multiprocessor programming down to that level. I could make a case for either result. (If anyone else has some definitive information on that, feel free to chime in.)</p>\n" }, { "answer_id": 242319, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 1, "selected": false, "text": "<p>This is the state of the code as it stands now after talks on the intel boards, but still hasn't been thoroughly verified to work correctly in all scenarios.</p>\n\n<pre><code> #include &lt;tbb/atomic.h&gt;\n typedef unsigned int uint_32;\n typedef __TBB_LONG_LONG uint_64;\n\n template&lt;typename FLOATING_POINT,typename MEMORY_BLOCK&gt;\n struct atomic_float_\n {\n /* CRC Card -----------------------------------------------------\n | Class: atmomic float template class\n |\n | Responsability: handle integral atomic memory as it were a float,\n | but partially bypassing FPU, SSE/MMX, so it is\n | slower than a true float, but faster and smaller\n | than a locked float.\n | *Warning* If your float usage is thwarted by\n | the A-B-A problem this class isn't for you\n | *Warning* Atomic specification says we return,\n | values not l-values. So (i = j) = k doesn't work.\n |\n | Collaborators: intel's tbb::atomic handles memory atomicity\n ----------------------------------------------------------------*/\n typedef typename atomic_float_&lt;FLOATING_POINT,MEMORY_BLOCK&gt; self_t;\n\n tbb::atomic&lt;MEMORY_BLOCK&gt; atomic_value_;\n\n template&lt;memory_semantics M&gt;\n FLOATING_POINT fetch_and_store( FLOATING_POINT value ) \n {\n const MEMORY_BLOCK value_ = \n atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::fetch_and_store&lt;M&gt;((MEMORY_BLOCK&amp;)value);\n //atomic specification requires returning old value, not new one\n return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_);\n }\n\n FLOATING_POINT fetch_and_store( FLOATING_POINT value ) \n {\n const MEMORY_BLOCK value_ = \n atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::fetch_and_store((MEMORY_BLOCK&amp;)value);\n //atomic specification requires returning old value, not new one\n return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_);\n }\n\n template&lt;memory_semantics M&gt;\n FLOATING_POINT compare_and_swap( FLOATING_POINT value, FLOATING_POINT comparand ) \n {\n const MEMORY_BLOCK value_ = \n atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::compare_and_swap&lt;M&gt;((MEMORY_BLOCK&amp;)value,(MEMORY_BLOCK&amp;)compare);\n //atomic specification requires returning old value, not new one\n return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_);\n }\n\n FLOATING_POINT compare_and_swap(FLOATING_POINT value, FLOATING_POINT compare)\n {\n const MEMORY_BLOCK value_ = \n atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::compare_and_swap((MEMORY_BLOCK&amp;)value,(MEMORY_BLOCK&amp;)compare);\n //atomic specification requires returning old value, not new one\n return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_);\n }\n\n operator FLOATING_POINT() const volatile // volatile qualifier here for backwards compatibility \n {\n const MEMORY_BLOCK value_ = atomic_value_;\n return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_);\n }\n\n //Note: atomic specification says we return the a copy of the base value not an l-value\n FLOATING_POINT operator=(FLOATING_POINT rhs) \n {\n const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::operator =((MEMORY_BLOCK&amp;)rhs);\n return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_);\n }\n\n //Note: atomic specification says we return an l-value when operating among atomics\n self_t&amp; operator=(self_t&amp; rhs) \n {\n const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::operator =((MEMORY_BLOCK&amp;)rhs);\n return *this;\n }\n\n FLOATING_POINT&amp; _internal_reference() const\n {\n return reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::_internal_reference());\n }\n\n FLOATING_POINT operator+=(FLOATING_POINT value)\n {\n FLOATING_POINT old_value_, new_value_;\n do\n {\n old_value_ = reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_);\n new_value_ = old_value_ + value;\n //floating point binary representation is not an issue because\n //we are using our self's compare and swap, thus comparing floats and floats\n } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_);\n return (new_value_); //return resulting value\n }\n\n FLOATING_POINT operator*=(FLOATING_POINT value)\n {\n FLOATING_POINT old_value_, new_value_;\n do\n {\n old_value_ = reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_);\n new_value_ = old_value_ * value;\n //floating point binary representation is not an issue becaus\n //we are using our self's compare and swap, thus comparing floats and floats\n } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_);\n return (new_value_); //return resulting value\n }\n\n FLOATING_POINT operator/=(FLOATING_POINT value)\n {\n FLOATING_POINT old_value_, new_value_;\n do\n {\n old_value_ = reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_);\n new_value_ = old_value_ / value;\n //floating point binary representation is not an issue because\n //we are using our self's compare and swap, thus comparing floats and floats\n } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_);\n return (new_value_); //return resulting value\n }\n\n FLOATING_POINT operator-=(FLOATING_POINT value)\n {\n return this-&gt;operator+=(-value); //return resulting value\n }\n\n //Prefix operator\n FLOATING_POINT operator++()\n {\n return this-&gt;operator+=(1); //return resulting value\n }\n\n //Prefix operator\n FLOATING_POINT operator--() \n {\n return this-&gt;operator+=(-1); //return resulting value\n }\n\n //Postfix operator\n FLOATING_POINT operator++(int)\n {\n const FLOATING_POINT temp = this;\n this-&gt;operator+=(1);\n return temp//return resulting value\n }\n\n //Postfix operator\n FLOATING_POINT operator--(int) \n {\n const FLOATING_POINT temp = this;\n this-&gt;operator+=(1);\n return temp//return resulting value\n }\n\n FLOATING_POINT fetch_and_add( FLOATING_POINT addend ) \n {\n const FLOATING_POINT old_value_ = atomic_value_;\n this-&gt;operator+=(addend);\n //atomic specification requires returning old value, not new one as in operator x=\n return old_value_; \n }\n\n FLOATING_POINT fetch_and_increment() \n {\n const FLOATING_POINT old_value_ = atomic_value_;\n this-&gt;operator+=(+1);\n //atomic specification requires returning old value, not new one as in operator x=\n return old_value_; \n }\n\n FLOATING_POINT fetch_and_decrement() \n {\n const FLOATING_POINT old_value_ = atomic_value_;\n this-&gt;operator+=(-1);\n //atomic specification requires returning old value, not new one as in operator x=\n return old_value_; \n }\n };\n\n typedef atomic_float_&lt;float,uint_32&gt; AtomicFloat;\n typedef atomic_float_&lt;double,uint_64&gt; AtomicDouble;\n</code></pre>\n" }, { "answer_id": 242571, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 1, "selected": false, "text": "<p>Although the size of a <em>uint32_t</em> may be equivalent to that of a <em>float</em> on a given arch, by reinterpreting a cast from one into the other you are implicitly assuming that atomic increments, decrements and all the other operations on bits are semantically equivalent on both types, which are not in reality. I doubt it works as expected.</p>\n" }, { "answer_id": 242677, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 1, "selected": false, "text": "<p>I strongly doubt that you get the correct values in fetch_and_add etc, as float addition is different from int addition. </p>\n\n<p>Here's what I get from these arithmetics: </p>\n\n<pre><code>1 + 1 = 1.70141e+038 \n100 + 1 = -1.46937e-037 \n100 + 0.01 = 1.56743e+038 \n23 + 42 = -1.31655e-036 \n</code></pre>\n\n<p>So yeah, threadsafe but not what you expect.</p>\n\n<p>the lock-free algorithms (operator + etc.) should work regarding atomicity (haven't checked for the algorithm itself..)</p>\n\n<hr>\n\n<p>Other solution:\nAs it is all additions and subtractions, you might be able to give every thread its own instance, then add the results from multiple threads.</p>\n" }, { "answer_id": 2563016, "author": "Lutorm", "author_id": 307175, "author_profile": "https://Stackoverflow.com/users/307175", "pm_score": 1, "selected": false, "text": "<p>Just a note about this (I wanted to make a comment but apparently new users aren't allowed to comment): Using reinterpret_cast on references produces incorrect code with gcc 4.1 -O3. This seems to be fixed in 4.4 because there it works. Changing the reinterpret_casts to pointers, while slightly uglier, works in both cases.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
> > **Edit:** The code here still has some bugs in it, and it could do better in the performance department, but instead of trying to fix this, for the record I took the problem over to the Intel discussion groups and got lots of great feedback, and if all goes well a polished version of Atomic float will be included in a near future release of Intel's Threading Building Blocks > > > Ok here's a tough one, I want an Atomic float, not for super-fast graphics performance, but to use routinely as data-members of classes. And I don't want to pay the price of using locks on these classes, because it provides no additional benefits for my needs. Now with intel's tbb and other atomic libraries I've seen, integer types are supported, but not floating points. So I went on and implemented one, and it works... but I'm not sure if it REALLY works, or I'm just very lucky that it works. Anyone here knows if this is not some form of threading heresy? ``` typedef unsigned int uint_32; struct AtomicFloat { private: tbb::atomic<uint_32> atomic_value_; public: template<memory_semantics M> float fetch_and_store( float value ) { const uint_32 value_ = atomic_value_.tbb::atomic<uint_32>::fetch_and_store<M>((uint_32&)value); return reinterpret_cast<const float&>(value_); } float fetch_and_store( float value ) { const uint_32 value_ = atomic_value_.tbb::atomic<uint_32>::fetch_and_store((uint_32&)value); return reinterpret_cast<const float&>(value_); } template<memory_semantics M> float compare_and_swap( float value, float comparand ) { const uint_32 value_ = atomic_value_.tbb::atomic<uint_32>::compare_and_swap<M>((uint_32&)value,(uint_32&)compare); return reinterpret_cast<const float&>(value_); } float compare_and_swap(float value, float compare) { const uint_32 value_ = atomic_value_.tbb::atomic<uint_32>::compare_and_swap((uint_32&)value,(uint_32&)compare); return reinterpret_cast<const float&>(value_); } operator float() const volatile // volatile qualifier here for backwards compatibility { const uint_32 value_ = atomic_value_; return reinterpret_cast<const float&>(value_); } float operator=(float value) { const uint_32 value_ = atomic_value_.tbb::atomic<uint_32>::operator =((uint_32&)value); return reinterpret_cast<const float&>(value_); } float operator+=(float value) { volatile float old_value_, new_value_; do { old_value_ = reinterpret_cast<float&>(atomic_value_); new_value_ = old_value_ + value; } while(compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); } float operator*=(float value) { volatile float old_value_, new_value_; do { old_value_ = reinterpret_cast<float&>(atomic_value_); new_value_ = old_value_ * value; } while(compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); } float operator/=(float value) { volatile float old_value_, new_value_; do { old_value_ = reinterpret_cast<float&>(atomic_value_); new_value_ = old_value_ / value; } while(compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); } float operator-=(float value) { return this->operator+=(-value); } float operator++() { return this->operator+=(1); } float operator--() { return this->operator+=(-1); } float fetch_and_add( float addend ) { return this->operator+=(-addend); } float fetch_and_increment() { return this->operator+=(1); } float fetch_and_decrement() { return this->operator+=(-1); } }; ``` Thanks! **Edit:** changed size\_t to uint32\_t as Greg Rogers suggested, that way its more portable **Edit:** added listing for the entire thing, with some fixes. **More Edits:** Performance wise using a locked float for 5.000.000 += operations with 100 threads on my machine takes 3.6s, while my atomic float even with its silly do-while takes 0.2s to do the same work. So the >30x performance boost means its worth it, (and this is the catch) if its correct. **Even More Edits:** As Awgn pointed out my `fetch_and_xxxx` parts were all wrong. Fixed that and removed parts of the API I'm not sure about (templated memory models). And implemented other operations in terms of operator += to avoid code repetition **Added:** Added operator \*= and operator /=, since floats wouldn't be floats without them. Thanks to Peterchen's comment that this was noticed **Edit:** Latest version of the code follows (I'll leave the old version for reference though) ``` #include <tbb/atomic.h> typedef unsigned int uint_32; typedef __TBB_LONG_LONG uint_64; template<typename FLOATING_POINT,typename MEMORY_BLOCK> struct atomic_float_ { /* CRC Card ----------------------------------------------------- | Class: atmomic float template class | | Responsability: handle integral atomic memory as it were a float, | but partially bypassing FPU, SSE/MMX, so it is | slower than a true float, but faster and smaller | than a locked float. | *Warning* If your float usage is thwarted by | the A-B-A problem this class isn't for you | *Warning* Atomic specification says we return, | values not l-values. So (i = j) = k doesn't work. | | Collaborators: intel's tbb::atomic handles memory atomicity ----------------------------------------------------------------*/ typedef typename atomic_float_<FLOATING_POINT,MEMORY_BLOCK> self_t; tbb::atomic<MEMORY_BLOCK> atomic_value_; template<memory_semantics M> FLOATING_POINT fetch_and_store( FLOATING_POINT value ) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic<MEMORY_BLOCK>::fetch_and_store<M>((MEMORY_BLOCK&)value); //atomic specification requires returning old value, not new one return reinterpret_cast<const FLOATING_POINT&>(value_); } FLOATING_POINT fetch_and_store( FLOATING_POINT value ) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic<MEMORY_BLOCK>::fetch_and_store((MEMORY_BLOCK&)value); //atomic specification requires returning old value, not new one return reinterpret_cast<const FLOATING_POINT&>(value_); } template<memory_semantics M> FLOATING_POINT compare_and_swap( FLOATING_POINT value, FLOATING_POINT comparand ) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic<MEMORY_BLOCK>::compare_and_swap<M>((MEMORY_BLOCK&)value,(MEMORY_BLOCK&)compare); //atomic specification requires returning old value, not new one return reinterpret_cast<const FLOATING_POINT&>(value_); } FLOATING_POINT compare_and_swap(FLOATING_POINT value, FLOATING_POINT compare) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic<MEMORY_BLOCK>::compare_and_swap((MEMORY_BLOCK&)value,(MEMORY_BLOCK&)compare); //atomic specification requires returning old value, not new one return reinterpret_cast<const FLOATING_POINT&>(value_); } operator FLOATING_POINT() const volatile // volatile qualifier here for backwards compatibility { const MEMORY_BLOCK value_ = atomic_value_; return reinterpret_cast<const FLOATING_POINT&>(value_); } //Note: atomic specification says we return the a copy of the base value not an l-value FLOATING_POINT operator=(FLOATING_POINT rhs) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic<MEMORY_BLOCK>::operator =((MEMORY_BLOCK&)rhs); return reinterpret_cast<const FLOATING_POINT&>(value_); } //Note: atomic specification says we return an l-value when operating among atomics self_t& operator=(self_t& rhs) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic<MEMORY_BLOCK>::operator =((MEMORY_BLOCK&)rhs); return *this; } FLOATING_POINT& _internal_reference() const { return reinterpret_cast<FLOATING_POINT&>(atomic_value_.tbb::atomic<MEMORY_BLOCK>::_internal_reference()); } FLOATING_POINT operator+=(FLOATING_POINT value) { FLOATING_POINT old_value_, new_value_; do { old_value_ = reinterpret_cast<FLOATING_POINT&>(atomic_value_); new_value_ = old_value_ + value; //floating point binary representation is not an issue because //we are using our self's compare and swap, thus comparing floats and floats } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); //return resulting value } FLOATING_POINT operator*=(FLOATING_POINT value) { FLOATING_POINT old_value_, new_value_; do { old_value_ = reinterpret_cast<FLOATING_POINT&>(atomic_value_); new_value_ = old_value_ * value; //floating point binary representation is not an issue becaus //we are using our self's compare and swap, thus comparing floats and floats } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); //return resulting value } FLOATING_POINT operator/=(FLOATING_POINT value) { FLOATING_POINT old_value_, new_value_; do { old_value_ = reinterpret_cast<FLOATING_POINT&>(atomic_value_); new_value_ = old_value_ / value; //floating point binary representation is not an issue because //we are using our self's compare and swap, thus comparing floats and floats } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); //return resulting value } FLOATING_POINT operator-=(FLOATING_POINT value) { return this->operator+=(-value); //return resulting value } //Prefix operator FLOATING_POINT operator++() { return this->operator+=(1); //return resulting value } //Prefix operator FLOATING_POINT operator--() { return this->operator+=(-1); //return resulting value } //Postfix operator FLOATING_POINT operator++(int) { const FLOATING_POINT temp = this; this->operator+=(1); return temp//return resulting value } //Postfix operator FLOATING_POINT operator--(int) { const FLOATING_POINT temp = this; this->operator+=(1); return temp//return resulting value } FLOATING_POINT fetch_and_add( FLOATING_POINT addend ) { const FLOATING_POINT old_value_ = atomic_value_; this->operator+=(addend); //atomic specification requires returning old value, not new one as in operator x= return old_value_; } FLOATING_POINT fetch_and_increment() { const FLOATING_POINT old_value_ = atomic_value_; this->operator+=(+1); //atomic specification requires returning old value, not new one as in operator x= return old_value_; } FLOATING_POINT fetch_and_decrement() { const FLOATING_POINT old_value_ = atomic_value_; this->operator+=(-1); //atomic specification requires returning old value, not new one as in operator x= return old_value_; } }; typedef atomic_float_<float,uint_32> AtomicFloat; typedef atomic_float_<double,uint_64> AtomicDouble; ```
I would seriously advise against public inheritance. I don't know what the atomic implementation is like, but im assuming it has overloaded operators that use it as the integral type, which means that those promotions will be used instead of your float in many (maybe most?) cases. I don't see any reason why that wouldn't work, but like you I have to way to prove that... One note: your `operator float()` routine does not have load-acquire semantics, and shouldn't it be marked const volatile (or definitely at least const)? EDIT: If you are going to provide operator--() you should provide both prefix/postfix forms.
242,177
<p>I understand object oriented programming, and have been writing OO programs for a long time. People seem to talk about aspect-oriented programming, but I've never really learned what it is or how to use it. What is the basic paradigm?</p> <p>This question is related, but doesn't quite ask it:</p> <p><a href="https://stackoverflow.com/questions/232884/aspect-oriented-programming-vs-object-oriented-programming">Aspect-Oriented Programming vs. Object Oriented Programming</a></p>
[ { "answer_id": 242194, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 9, "selected": true, "text": "<p>AOP addresses the problem of <em>cross-cutting concerns</em>, which would be any kind of code that is repeated in different methods and can't normally be completely refactored into its own module, like with logging or verification. So, with AOP you can leave that stuff out of the main code and define it vertically like so:</p>\n\n<pre><code>function mainProgram()\n{ \n var x = foo();\n doSomethingWith(x);\n return x;\n}\n\naspect logging\n{ \n before (mainProgram is called):\n { \n log.Write(\"entering mainProgram\");\n }\n\n after (mainProgram is called):\n { \n log.Write( \"exiting mainProgram with return value of \"\n + mainProgram.returnValue);\n }\n } \n\naspect verification\n{ \n before (doSomethingWith is called):\n { \n if (doSomethingWith.arguments[0] == null) \n { \n throw NullArgumentException();\n }\n\n if (!doSomethingWith.caller.isAuthenticated)\n { \n throw Securityexception();\n }\n }\n }\n</code></pre>\n\n<p>And then an <em>aspect-weaver</em> is used to compile the code into this:</p>\n\n<pre><code>function mainProgram()\n{ \n log.Write(\"entering mainProgram\");\n\n var x = foo(); \n\n if (x == null) throw NullArgumentException();\n if (!mainProgramIsAuthenticated()) throw Securityexception();\n doSomethingWith(x); \n\n log.Write(\"exiting mainProgram with return value of \"+ x);\n return x;\n} \n</code></pre>\n" }, { "answer_id": 242205, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 2, "selected": false, "text": "<p>AOP is a way to better modularize your application for functionality that spans across multiple boundaries. AOP is another way to encapsulate these features and follow Single Responsiblity by moving these cross-cutting concerns (logging, error handling, etc.) out of the main components of your application. When used appropriately AOP can lead to higher levels of maintainability and extensibility in your application over time.</p>\n" }, { "answer_id": 242238, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 4, "selected": false, "text": "<p>Unfortunately, it seems to be surprisingly difficult to make AOP really useful in a normal mid-large size organization. (Editor support, sense of control, the fact that you start with the not-so-important things leading to code-rot, people going home to their families, etc.)</p>\n\n<p>I put my hopes to <strong>composite oriented programming</strong>, which is something more and more realistic. It connects to many popular ideas and gives you something really cool.</p>\n\n<p>Look at an up and coming implementation here: <a href=\"http://www.qi4j.org/\" rel=\"noreferrer\">qi4j.org/</a></p>\n\n<p>PS. Actually, I think that one of the beauties with AOP is also its achilles heel: Its non-intrusive, letting people ignore it if they can, so it will be treated as a secondary concern in most organizations.</p>\n" }, { "answer_id": 319742, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>Copied from a duplicate for completeness (Buzzer):</p>\n\n<p>Class and method attributes in .NET are a form of aspect-oriented programming. You decorate your classes/methods with attributes. Behind the scenes this adds code to your class/method that performs the particular functions of the attribute. For example, marking a class serializable allows it to be serialized automatically for storage or transmission to another system. Other attributes might mark certain properties as non-serializable and these would be automatically omitted from the serialized object. Serialization is an aspect, implemented by other code in the system, and applied to your class by the application of a \"configuration\" attribute (decoration) .</p>\n" }, { "answer_id": 319743, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>Copied from a duplicate for completeness (Einstein):</p>\n\n<p>The classic examples are security and logging. Instead of writing code within your application to log occurance of x or check object z for security access control there is a language contraption \"out of band\" of normal code which can systematically inject security or logging into routines that don't nativly have them in such a way that even though your code doesn't supply it -- its taken care of.</p>\n\n<p>A more concrete example is the operating system providing access controls to a file. A software program does not need to check for access restrictions because the underlying system does that work for it.</p>\n\n<p>If you think you need AOP in my experience you actually really need to be investing more time and effort into appropriate meta-data management within your system with a focus on well thought structural / systems design.</p>\n" }, { "answer_id": 32582457, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Copied from Spring in Action</p>\n\n<blockquote>\n <p>AOP is often defined as a technique that promotes separation of\n concerns in a software system. Systems are composed of several\n components, each responsible for a specific piece of functionality.\n But often these components also carry additional responsibilities\n beyond their core functionality. System services such as logging,\n transaction management, and security often find their way into\n components whose core responsibilities is something else. These system\n services are commonly referred to as cross-cutting concerns because\n they tend to cut across multiple components in a system.</p>\n</blockquote>\n" }, { "answer_id": 36825092, "author": "R.F", "author_id": 2888844, "author_profile": "https://Stackoverflow.com/users/2888844", "pm_score": 3, "selected": false, "text": "<p>There is an example of AOP, it used spring AOP as an example. The example is quite easy to understand.</p>\n\n<p>Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.</p>\n\n<p>Reference: <a href=\"http://www.mkyong.com/spring/spring-aop-examples-advice/\" rel=\"noreferrer\">http://www.mkyong.com/spring/spring-aop-examples-advice/</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31952/" ]
I understand object oriented programming, and have been writing OO programs for a long time. People seem to talk about aspect-oriented programming, but I've never really learned what it is or how to use it. What is the basic paradigm? This question is related, but doesn't quite ask it: [Aspect-Oriented Programming vs. Object Oriented Programming](https://stackoverflow.com/questions/232884/aspect-oriented-programming-vs-object-oriented-programming)
AOP addresses the problem of *cross-cutting concerns*, which would be any kind of code that is repeated in different methods and can't normally be completely refactored into its own module, like with logging or verification. So, with AOP you can leave that stuff out of the main code and define it vertically like so: ``` function mainProgram() { var x = foo(); doSomethingWith(x); return x; } aspect logging { before (mainProgram is called): { log.Write("entering mainProgram"); } after (mainProgram is called): { log.Write( "exiting mainProgram with return value of " + mainProgram.returnValue); } } aspect verification { before (doSomethingWith is called): { if (doSomethingWith.arguments[0] == null) { throw NullArgumentException(); } if (!doSomethingWith.caller.isAuthenticated) { throw Securityexception(); } } } ``` And then an *aspect-weaver* is used to compile the code into this: ``` function mainProgram() { log.Write("entering mainProgram"); var x = foo(); if (x == null) throw NullArgumentException(); if (!mainProgramIsAuthenticated()) throw Securityexception(); doSomethingWith(x); log.Write("exiting mainProgram with return value of "+ x); return x; } ```
242,181
<p>I have a form with several checkboxes which values are pulled from a database. I managed to display them in the form, assign an appropriate value to each, but cannot insert their values into other database.</p> <p>Here's the code:</p> <pre><code>&lt;form id=&quot;form1&quot; name=&quot;form1&quot; method=&quot;post&quot; action=&quot;&quot;&gt; &lt;?php $info_id = $_GET['info_id']; $kv_dodatoci = mysql_query(&quot;SELECT * FROM `dodatoci`&quot;) or die('ERROR DISPLAYING: ' . mysql_error()); while ($kol = mysql_fetch_array($kv_dodatoci)){ $id_dodatoci = $kol['id_dodatoci']; $mk = $kol['mk']; echo '&lt;input type=&quot;checkbox&quot; name=&quot;id_dodatoci[]&quot; id=&quot;id_dodatoci&quot; value=&quot;' . $id_dodatoci . '&quot; /&gt;'; echo '&lt;label for=&quot;' . $id_dodatoci.'&quot;&gt;' . $mk . '&lt;/label&gt;&lt;br /&gt;'; } ?&gt; &lt;input type=&quot;hidden&quot; value=&quot;&lt;?=$info_id?&gt;&quot; name=&quot;info_id&quot; /&gt; &lt;input name=&quot;insert_info&quot; type=&quot;submit&quot; value=&quot;Insert Additional info&quot; /&gt; &lt;/form&gt; &lt;?php if (isset($_POST['insert_info']) &amp;&amp; is_array($id_dodatoci)) { echo $id_dodatoci . '&lt;br /&gt;'; echo $mk . '&lt;br /&gt;'; // --- Guess here's the problem ----- // foreach ($_POST['id_dodatoci'] as $dodatok) { $dodatok_kv = mysql_query(&quot;INSERT INTO `dodatoci_hotel` (id_dodatoci, info_id) VALUES ('$dodatok', '$info_id')&quot;) or die('ERROR INSERTING: '.mysql_error()); } } </code></pre> <p>My problem is to loop through all checkboxes, and for each checked, populate a separate record in a database. Actually I don't know how to recognize the which box is checked, and put the appropriate value in db.</p>
[ { "answer_id": 242215, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 2, "selected": false, "text": "<p>You can tell if a checkbox is selected because it will have a value. If it's not selected, it won't appear in the request/get/post in PHP at all.</p>\n\n<p>What you may want to do is check for the value of it and work based on that. The value is the string 'on' by default, but can be changed by the value='' attribute in HTML.</p>\n\n<p>Here are a couple snippets of code that may help (not exactly production quality, but it will help illustrate):</p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code>&lt;input type='checkbox' name='ShowCloseWindowLink' value='1'/&gt; Show the 'Close Window' link at the bottom of the form.\n</code></pre>\n\n<p>PHP:</p>\n\n<pre><code>if (isset($_POST[\"ShowCloseWindowLink\"])) {\n $ShowCloseWindowLink=1;\n} else {\n $ShowCloseWindowLink=0;\n}\n\n .....\n\n\n$sql = \"update table set ShowCloseWindowLink = \".mysql_real_escape_string($ShowCloseWindowLink).\" where ...\"\n</code></pre>\n\n<p>(assuming a table with a ShowCloseWindowLink column that will accept a 1 or 0)</p>\n" }, { "answer_id": 242562, "author": "bastiandoeen", "author_id": 371953, "author_profile": "https://Stackoverflow.com/users/371953", "pm_score": 0, "selected": false, "text": "<p>Well, as Eli wrote, the POST is not set, when a checkbox is not checked.</p>\n<p>I sometimes use an additional hidden field (-array) to make sure, I have a list of all checkboxes on the page.</p>\n<p>Example:</p>\n<pre><code>&lt;input type=&quot;checkbox&quot; name=&quot;my_checkbox[&lt;?=$id_of_checkbox?&gt;]&quot;&gt;\n&lt;input type=&quot;hidden&quot; name=&quot;array_checkboxes[&lt;?=$id_of_checkbox?&gt;]&quot; value=&quot;is_on_page&quot;&gt;\n</code></pre>\n<p>So I get in the $_POST:</p>\n<pre><code>array(2){\n array(1){&quot;my_checkbox&quot; =&gt; array(1){[123]=&gt;&quot;1&quot;}}\n array(1){&quot;array_checkboxes&quot; =&gt; array(1){[123]=&gt;&quot;is_on_page&quot;}}\n}\n</code></pre>\n<p>I even get the second line, when the checkbox is NOT checked and I can loop through all checkboxes with something like this:</p>\n<pre><code>foreach ($_POST[&quot;array_checkboxes&quot;] as $key =&gt; $value)\n{\n if($value==&quot;is_on_page&quot;)\n {\n $value_of_checkbox[$key] = $_POST[&quot;my_checkbox&quot;][$key];\n //Save this value\n }\n}\n</code></pre>\n" }, { "answer_id": 242782, "author": "Ryan McCue", "author_id": 2575, "author_profile": "https://Stackoverflow.com/users/2575", "pm_score": 0, "selected": false, "text": "<p>As an extra note: You're using the wrong HTML syntax for IDs and <code>&lt;label&gt;</code>. <code>&lt;label&gt;</code>'s \"for\" attribute should point to an ID, not a value. You also need unique IDs for each element. The code you have posted would not validate.</p>\n\n<p>Also, you're not validating your code at all. At the very least, do a <code>htmlspecialchars()</code> or <code>htmlentities()</code> on the input before you output it and a <a href=\"http://php.net/mysql_real_escape_string\" rel=\"nofollow noreferrer\"><code>mysql_real_escape_string()</code></a> before you insert data into the DB.</p>\n" }, { "answer_id": 244535, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 0, "selected": false, "text": "<p><strong>2nd Answer:</strong></p>\n\n<p>You might do something like this:</p>\n\n<p>HTML:</p>\n\n<pre><code>echo '&lt;input type=\"checkbox\" name=\"id_dodatoci[]\" value=\"'.$id_dodatoci.'\" /&gt;';\n</code></pre>\n\n<p>PHP:</p>\n\n<pre><code>if ( !empty($_POST[\"id_dodatoci\"]) ) {\n $id_dodatoci = $_POST[\"id_dodatoci\"];\n print_r($id_dodatoci);\n // This should provide an array of all the checkboxes that were checked.\n // Any not checked will not be present.\n} else {\n // None of the id_dodatoci checkboxes were checked.\n}\n</code></pre>\n\n<p>This is because you are using the same name for all of the checkboxes, so their values will be passed to php as an array. If you used different names, then each would have it's own post key/value pair.</p>\n\n<p>This might help too:</p>\n\n<p><a href=\"http://www.php-mysql-tutorial.com/php-tutorial/using-php-forms.php\" rel=\"nofollow noreferrer\">http://www.php-mysql-tutorial.com/php-tutorial/using-php-forms.php</a></p>\n" }, { "answer_id": 244954, "author": "Bertrand Gorge", "author_id": 30955, "author_profile": "https://Stackoverflow.com/users/30955", "pm_score": -1, "selected": false, "text": "<p>Also something that few people use but that is quite nice in HTML, is that you can have:</p>\n\n<pre><code>&lt;input type=\"hidden\" name=\"my_checkbox\" value=\"N\" /&gt;\n&lt;input type=\"checkbox\" name=\"my_checkbox\" value=\"Y\" /&gt;\n</code></pre>\n\n<p>and <em>voila!</em> - default values for checkboxes...!</p>\n" }, { "answer_id": 245552, "author": "dede", "author_id": 432217, "author_profile": "https://Stackoverflow.com/users/432217", "pm_score": 0, "selected": false, "text": "<p>This is the loop that I needed. I realized that I need a loop through each key with the <code>$i</code> variable.</p>\n\n<pre><code>if(isset($_POST['id_dodatoci'])){\n $id_dodatoci=$_POST['id_dodatoci'];\n $arr_num=count($id_dodatoci);\n $i=0;\n while ($i &lt; $arr_num)\n {\n $query=\"INSERT INTO `dodatoci_hotel`(id_dodatoci,info_id) \n VALUES ('$id_dodatoci[$i]','$info_id')\";\n $res=mysql_query($query) or die('ERROR INSERTING: '.mysql_error());\n $i++;\n }\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a form with several checkboxes which values are pulled from a database. I managed to display them in the form, assign an appropriate value to each, but cannot insert their values into other database. Here's the code: ``` <form id="form1" name="form1" method="post" action=""> <?php $info_id = $_GET['info_id']; $kv_dodatoci = mysql_query("SELECT * FROM `dodatoci`") or die('ERROR DISPLAYING: ' . mysql_error()); while ($kol = mysql_fetch_array($kv_dodatoci)){ $id_dodatoci = $kol['id_dodatoci']; $mk = $kol['mk']; echo '<input type="checkbox" name="id_dodatoci[]" id="id_dodatoci" value="' . $id_dodatoci . '" />'; echo '<label for="' . $id_dodatoci.'">' . $mk . '</label><br />'; } ?> <input type="hidden" value="<?=$info_id?>" name="info_id" /> <input name="insert_info" type="submit" value="Insert Additional info" /> </form> <?php if (isset($_POST['insert_info']) && is_array($id_dodatoci)) { echo $id_dodatoci . '<br />'; echo $mk . '<br />'; // --- Guess here's the problem ----- // foreach ($_POST['id_dodatoci'] as $dodatok) { $dodatok_kv = mysql_query("INSERT INTO `dodatoci_hotel` (id_dodatoci, info_id) VALUES ('$dodatok', '$info_id')") or die('ERROR INSERTING: '.mysql_error()); } } ``` My problem is to loop through all checkboxes, and for each checked, populate a separate record in a database. Actually I don't know how to recognize the which box is checked, and put the appropriate value in db.
You can tell if a checkbox is selected because it will have a value. If it's not selected, it won't appear in the request/get/post in PHP at all. What you may want to do is check for the value of it and work based on that. The value is the string 'on' by default, but can be changed by the value='' attribute in HTML. Here are a couple snippets of code that may help (not exactly production quality, but it will help illustrate): **HTML:** ``` <input type='checkbox' name='ShowCloseWindowLink' value='1'/> Show the 'Close Window' link at the bottom of the form. ``` PHP: ``` if (isset($_POST["ShowCloseWindowLink"])) { $ShowCloseWindowLink=1; } else { $ShowCloseWindowLink=0; } ..... $sql = "update table set ShowCloseWindowLink = ".mysql_real_escape_string($ShowCloseWindowLink)." where ..." ``` (assuming a table with a ShowCloseWindowLink column that will accept a 1 or 0)