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
125,094
<p>I have a 2D character array:<br> <code>char nm[MAX1][MAX2] = { "john", "bob", "david" };</code><br> I want to swap two of these elements (without <code>std::swap</code>) by simply writing<br> <code>swapPointers(nm[0], nm[1]);</code><br> where <code>swapPointers</code> looks like this </p> <pre><code>void swapPointers(char *&amp;a, char *&amp;b) { char *temp = a; a = b; b = a; } </code></pre> <p>However, this does not compile (and while adding casts makes it compile, the pointers end up pointing to wrong/weird locations). </p> <p>Can anybody help?<br> Thanks!</p>
[ { "answer_id": 125103, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 0, "selected": false, "text": "<pre><code>void swapPointers(char** ppa, char** ppb)\n{\n char* ptemp = *ppa;\n *ppb = *ppa;\n *ppa = ptemp;\n}\n\nswapPointers(&amp;nm[0], &amp;nm[1]);\n</code></pre>\n" }, { "answer_id": 125183, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 2, "selected": false, "text": "<p>You cannot swap those pointers by reassigning the pointers, because those pointers point into a 2-D character array.</p>\n\n<p>nm[a] and nm[b] are very strongly <code>const</code> because nm is a truly <code>const</code> object. If it wasn't, you could move C variables around in RAM by reassigning their names. </p>\n\n<p>Just think of the havoc! So you can't do that. :-)</p>\n\n<p>To swap what those pointers point to, you need to swap the values in those array locations.</p>\n\n<pre><code>swap(char *a, char *b)\n{\n char temp[MAX1];\n memcpy(temp, a, MAX1);\n memcpy(b, a, MAX1);\n memcpy(a, temp, MAX1);\n}\n</code></pre>\n" }, { "answer_id": 125255, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 2, "selected": false, "text": "<p>Your <code>swapPointers()</code> swaps pointers, whereas you're trying to pass it arrays.</p>\n\n<p>If you change</p>\n\n<pre><code>char nm[MAX1][MAX2]\n</code></pre>\n\n<p>to</p>\n\n<pre><code>char *nm[MAX1]\n</code></pre>\n\n<p>and fix the small bug in <code>swapPointers()</code> (last line should be <code>b = temp;</code>), it works.</p>\n" }, { "answer_id": 125454, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 3, "selected": true, "text": "<p>Zan is close, but his problem is that his 'swap' function can take any pointer to characters. This can cause problems if misused. Here is a safer version:</p>\n\n<pre><code>void swap(char (&amp;x)[MAX2], char (&amp;y)[MAX2])\n{\n char temp[MAX2];\n\n memcpy(temp, x, MAX2);\n memcpy(x, y, MAX2);\n memcpy(y, temp, MAX2);\n}\n</code></pre>\n\n<p>There is also a misunderstanding on the part of the poster: 'nm' is a 2-dimensional array of characters. There are no pointers. nm[0], nm[2], etc... are also not pointers either -- they are still (1-dimensional) arrays. The fact that 1-dimensional arrays are implicitly convertible to pointers causes this type of confusion among many C and C++ programmers.</p>\n\n<p>In order to swap the data in the 2-dimensional array, you have to swap blocks of memory of size MAX2 -- as indicated by both 'swap' functions Zan and I wrote.</p>\n" }, { "answer_id": 125554, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 1, "selected": false, "text": "<p>The real point is, if you are using c++ then you should be using a std::vector of std::string instead:</p>\n\n<pre><code>std::vector&lt;std::string&gt; nm;\nnm.push_back( \"john\" );\nnm.push_back( \"bob\" );\nnm.push_back( \"david\" );\nstd::swap( nm[0], nm[1] );\n</code></pre>\n\n<p>Note: not tested.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21475/" ]
I have a 2D character array: `char nm[MAX1][MAX2] = { "john", "bob", "david" };` I want to swap two of these elements (without `std::swap`) by simply writing `swapPointers(nm[0], nm[1]);` where `swapPointers` looks like this ``` void swapPointers(char *&a, char *&b) { char *temp = a; a = b; b = a; } ``` However, this does not compile (and while adding casts makes it compile, the pointers end up pointing to wrong/weird locations). Can anybody help? Thanks!
Zan is close, but his problem is that his 'swap' function can take any pointer to characters. This can cause problems if misused. Here is a safer version: ``` void swap(char (&x)[MAX2], char (&y)[MAX2]) { char temp[MAX2]; memcpy(temp, x, MAX2); memcpy(x, y, MAX2); memcpy(y, temp, MAX2); } ``` There is also a misunderstanding on the part of the poster: 'nm' is a 2-dimensional array of characters. There are no pointers. nm[0], nm[2], etc... are also not pointers either -- they are still (1-dimensional) arrays. The fact that 1-dimensional arrays are implicitly convertible to pointers causes this type of confusion among many C and C++ programmers. In order to swap the data in the 2-dimensional array, you have to swap blocks of memory of size MAX2 -- as indicated by both 'swap' functions Zan and I wrote.
125,096
<p>I have an app that has impersonation used throughout. But when a user is logged in as an admin, a few operation require them to write to the server itself. Now if these users do not have rights on the actual server (some don't) it will not let them write. </p> <p>What I want to do is turn off impersonation for just a couple commands.</p> <p>Is there a way to do something like this?</p> <pre><code>using(HostingEnvironment.Impersonate.Off()) //I know this isn't a command, but you get the idea? </code></pre> <p>Thank you.</p>
[ { "answer_id": 125219, "author": "jedatu", "author_id": 2582, "author_profile": "https://Stackoverflow.com/users/2582", "pm_score": 2, "selected": false, "text": "<p>I am not sure if this is the preferred approach but when I wanted to do this I new'd up an instance of a <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx\" rel=\"nofollow noreferrer\">WindowsIdentity</a> and called the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx\" rel=\"nofollow noreferrer\">Impersonate</a> method. This allows subsequent code to impersonate a different Windows user. It returns a <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx\" rel=\"nofollow noreferrer\">WindowsImpersonationContext</a> that has an <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.undo.aspx\" rel=\"nofollow noreferrer\">Undo</a> method which reverts the impersonation context back again.</p>\n" }, { "answer_id": 125307, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 0, "selected": false, "text": "<p>You could turn off authentication for the page and then manually impersonate the authenticated user during the remainder of your code.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/306158\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/306158</a></p>\n\n<p>This has a reference to that last part, but basically you impersonate User.Identity</p>\n\n<p>This will mean you will have to impersonate at the beginning of any call to the page, turn it off when you need it off, then turn it back on when you are done, but it should be a workable solution.</p>\n" }, { "answer_id": 125574, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 0, "selected": false, "text": "<p>I just ended up giving the folders write permissions to \"Authenticated Users\"</p>\n" }, { "answer_id": 217452, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 6, "selected": true, "text": "<p>Make sure the Application Pool do have the proper rights that you need.</p>\n\n<p>Then, when you want to revert to the application pool identity... run the following:</p>\n\n<pre><code>private WindowsImpersonationContext context = null;\npublic void RevertToAppPool()\n{\n try\n {\n if (!WindowsIdentity.GetCurrent().IsSystem)\n {\n context = WindowsIdentity.Impersonate(System.IntPtr.Zero);\n }\n }\n catch { }\n}\npublic void UndoImpersonation()\n{\n try\n {\n if (context != null)\n {\n context.Undo();\n }\n }\n catch { }\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
I have an app that has impersonation used throughout. But when a user is logged in as an admin, a few operation require them to write to the server itself. Now if these users do not have rights on the actual server (some don't) it will not let them write. What I want to do is turn off impersonation for just a couple commands. Is there a way to do something like this? ``` using(HostingEnvironment.Impersonate.Off()) //I know this isn't a command, but you get the idea? ``` Thank you.
Make sure the Application Pool do have the proper rights that you need. Then, when you want to revert to the application pool identity... run the following: ``` private WindowsImpersonationContext context = null; public void RevertToAppPool() { try { if (!WindowsIdentity.GetCurrent().IsSystem) { context = WindowsIdentity.Impersonate(System.IntPtr.Zero); } } catch { } } public void UndoImpersonation() { try { if (context != null) { context.Undo(); } } catch { } } ```
125,099
<p>Anyone know the formula used to control the movement of a simple tank-like vehicle?</p> <p>To 'steer' it, you need to alter the force applied the left and right "wheels". Eg. 1 unit of force on both wheels makes it go forward. -1 units of force on both wheels makes it go backwards. Apply more force to one wheel than the other and it turns.</p> <p>How would you calculate the amount of force needed on both wheels to turn the tank a certain number of degrees either way?</p> <p>Or am I thinking about this in the wrong way?</p> <p>edit: As William Keller mentioned I missed out the speed of the tank. Assume 1 unit of force on both wheels moves the tank forward at 1 unit per second.</p> <p>For anyone who's interested, I just found this thread on gamedev.net: <a href="http://66.102.9.104/search?q=cache:wSn5t58ACJwJ:www.gamedev.net/community/forums/topic.asp%3Ftopic_id%3D407491+tank+track+radius+velocity&amp;hl=en&amp;ct=clnk&amp;cd=1&amp;gl=za&amp;client=firefox-a" rel="nofollow noreferrer">http://66.102.9.104/search?q=cache:wSn5t58ACJwJ:www.gamedev.net/community/forums/topic.asp%3Ftopic_id%3D407491+tank+track+radius+velocity&amp;hl=en&amp;ct=clnk&amp;cd=1&amp;gl=za&amp;client=firefox-a</a></p> <p>Another thread: <a href="http://www.physicsforums.com/showthread.php?t=220317" rel="nofollow noreferrer">http://www.physicsforums.com/showthread.php?t=220317</a></p> <p>It turns out the key to finding the formula was just knowing the correct terminology ("skid steer") :P</p>
[ { "answer_id": 125116, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 1, "selected": false, "text": "<p>Well, keep in mind that you're also talking about duration here. You need to find out the forces taking in to account the speed at which the tank turns at (1, -1).</p>\n\n<p>I.E., if the tank takes one second to spin 360˚ at (1, -1), and you want to spin 180˚ in one second, (.5, -.5) would do the trick. If you wanted to spin the same amount in half a second, then (1, -1) would work.</p>\n\n<p>This is all further complicated if you use abs(lrate) != abs(rrate), in which case you'll probably need to break out a pencil!</p>\n" }, { "answer_id": 125126, "author": "Loren Pechtel", "author_id": 10659, "author_profile": "https://Stackoverflow.com/users/10659", "pm_score": 2, "selected": false, "text": "<p>You're thinking about it the wrong way. The thing is, differing amounts of force on the tracks will not turn the tank a certain number of degrees. Rather, differing force will alter the <em>RATE</em> of turn.</p>\n\n<p>The relationship between the force and the turn rate will vary depending on the mechanics of the tank. The wider the tank the slower it turns. The faster the tank the faster it turns.</p>\n\n<p>P.S. Some more thoughts on this: I don't think a physics-based answer is possible without basing it off a real-world tank. Several of the answers address the physics of the turn but there is the implicit assumption in all of them that the system has infinite power. Can the tank really operate at 1, -1? And can it reach that velocity instantly--acceleration applies to turns, also.</p>\n\n<p>Finally, treads have length as well as width. That means you are going to get some sideways slippage of the treads in any turning situation, the faster the turn the more such slippage will be required. That is going to burn up energy in a sharp turn, even if the engine has the power to do a 1, -1 turn it wouldn't turn as fast as that would indicate because of friction losses.</p>\n" }, { "answer_id": 125138, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 0, "selected": false, "text": "<p>It has been a while since I did any physics but I would have thought that the apposing forces of the two tracks moving in opposite directions results in a torque about the center of mass of the tank.</p>\n\n<p>It is this torque that results in the angular momentum of the tank which is just another way of saying the tank starts to rotation.</p>\n" }, { "answer_id": 125149, "author": "user17250", "author_id": 17250, "author_profile": "https://Stackoverflow.com/users/17250", "pm_score": 0, "selected": false, "text": "<p>It's not a matter of force - it depends on the difference in velocity between the 2 sides, and how long that difference holds (also the tank's width, but that's just a constant parameter).</p>\n\n<p>Basically, you should calculate it along these lines:</p>\n\n<ul>\n<li>The velocity ratio between the 2 sides is the same as the radius ratio.</li>\n<li>The tank's width is the actual difference between the 2 rasiuses (sp?).</li>\n<li>Using those 2 numbers, find the actual values for the radius.</li>\n<li>Multiply the velocity of one of the sides by the time it was moving to get the distance it traveled.</li>\n<li>Calculate what part of a full circle it traveled by dividing that into that circle's perimeter.</li>\n</ul>\n" }, { "answer_id": 125152, "author": "Dominic Eidson", "author_id": 5042, "author_profile": "https://Stackoverflow.com/users/5042", "pm_score": 0, "selected": false, "text": "<p>I'd say you're thinking about it in the wrong way.</p>\n\n<p>Increasing the difference in speed between the two treads doesn't cause degrees of turn - they, combined with time (distance at different speed) cause degrees of turn.</p>\n\n<p>The more of a difference in tread speed, the less time needed to achieve X degrees of turn.</p>\n\n<p>So, in order to come up with a formula, you'll have to make a few assumptions. Either turn at a fixed rate, and use time as your variable for turning X degrees, or set a fixed amount of time to complete a turn, and use the track speed difference as your variable.</p>\n" }, { "answer_id": 125154, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 2, "selected": false, "text": "<pre><code>Change in angle (in radians/sec) = (l-r)/(radius between treads)\nVelocity = l+r\n</code></pre>\n\n<p>For the dtheta, imagine you had a wooden pole between your two hands, and you want to calculate how much it rotates depending on how hard and which way your hands are pressing - you want to figure out:</p>\n\n<p>how much surface distance on the pole you cover per sec -> how many rotations/sec that is -> how many radians/sec (i.e. mult by 2pi)</p>\n" }, { "answer_id": 125170, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 1, "selected": false, "text": "<p>Here's how I would attack the tank problem.</p>\n\n<p>The center of the tank will probably be moving by the average speed of the right and left tracks. At the same time, the tank will be rotating clockwise around it's center by ([left track speed] * -[right track speed]) / [width].</p>\n\n<p>This should give you speed and a direction vector.</p>\n\n<p>Disclaimer: I have not tested this...</p>\n" }, { "answer_id": 125209, "author": "julz", "author_id": 16536, "author_profile": "https://Stackoverflow.com/users/16536", "pm_score": 0, "selected": false, "text": "<p>You could look at it by saying : each track describes a circle.\nIn the case where one track is turning (lets say the left) and the other isn't, then the facing will be dependant on how long and how far the left tracks turn for.</p>\n\n<p>This distance will be the speed of the tracks x time. </p>\n\n<p>Now draw a triangle with this distance, and the wheelbase pencilled in, plus some sin and cos equations &amp; approximations, and you might get an approximate equation like : </p>\n\n<p>facing change = distance travelled by tracks / wheelbase</p>\n\n<p>Then you could incorporate some accelleration to be more realistic: More physics...</p>\n\n<p>The speed isn't constant - it accellerates (and decellerates).</p>\n\n<p>ie over a period of time the speed increases from 0, to 0.1 ... 0.2 ... 0.3 up to a limit.</p>\n\n<p>Of course, as the speed changes, the rate of change of the facing changes too - a bit more realistic than the speed (and thus rate of change of the facing) being entirely constant.</p>\n\n<p>In other words, instead of controlling the speed, the player controls the <em>change</em> in speed. This would make the speed go from 0 ... 0.02 ... 0.06 ... 0.1 etc. as the player pushes the controller. Similarly for decelleration, but a bit more rapidly probably.</p>\n\n<p>hope this helps.</p>\n" }, { "answer_id": 125220, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>I think everyone should also take note of the fact that tanks can turn on a Zero-radius circle: by applying the same speed on each track but on opposite directions, tanks <em>can</em> turn on a dime.</p>\n" }, { "answer_id": 39111386, "author": "Paul Carew", "author_id": 1892952, "author_profile": "https://Stackoverflow.com/users/1892952", "pm_score": 3, "selected": true, "text": "<p>For a skid steered vehicle that is required to turn in radius 'r' at a given speed 'Si' of the Inner Wheel/Track, the Outer track must be driven at speed 'So' :</p>\n\n<pre><code>So = Si * ((r+d)/r)\n</code></pre>\n\n<p><strong>Details:</strong></p>\n\n<p>In Skid Steering, a turn is performed by the outer wheels/track traveling further distance than the inner wheels/track.</p>\n\n<p>Furthermore, the extra distance traveled is completed in the same time as the inner track, meaning that the outer wheels/track must run faster.</p>\n\n<p>Circle circumference circumscribed by \"Inner\" track:</p>\n\n<pre><code>c1 = 2*PI*r\n'r' is radius of circle origin to track/wheel\n</code></pre>\n\n<p>Circle circumference circumscribed by \"Outer\" track:</p>\n\n<pre><code>c2 = 2*PI*(r+d)\n'r' is radius of circle origin to inner track/wheel\n'd' is the distance between the Inner and Outer wheels/track.\n</code></pre>\n\n<p>Furthermore, c2 = X * c1, which says that c2 is proportionally bigger than c1</p>\n\n<pre><code>X = c2 / c1\nX = 2*PI*(r+d) / 2*PI*r\nX = (r+d)/r\n</code></pre>\n\n<p>Therefore for a skid steered vehicle that is required to turn in radius 'r' at a given speed 's' of the Inner Wheel/Track, the Outer track must be driven at :</p>\n\n<pre><code>So = Si * ((r+d)/r)\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>'So' = Speed of outer track\n'Si' = Speed of inner track\n'r' = turn radius from inner track\n'd' = distance between vehicle tracks.\n\n\n ********* &lt;---------------- Outer Track\n **** | **** \n ** |&lt;--------**----------- 'd' Distance between tracks\n * *******&lt;-------*---------- Inner Track\n * *** ^ *** * \n * * |&lt;-----*------*-------- 'r' Radius of Turn\n * * | * * \n * * O * * \n * * * * \n * * * * \n * *** *** * \n * ******* * \n ** ** \n **** **** \n ********* \n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
Anyone know the formula used to control the movement of a simple tank-like vehicle? To 'steer' it, you need to alter the force applied the left and right "wheels". Eg. 1 unit of force on both wheels makes it go forward. -1 units of force on both wheels makes it go backwards. Apply more force to one wheel than the other and it turns. How would you calculate the amount of force needed on both wheels to turn the tank a certain number of degrees either way? Or am I thinking about this in the wrong way? edit: As William Keller mentioned I missed out the speed of the tank. Assume 1 unit of force on both wheels moves the tank forward at 1 unit per second. For anyone who's interested, I just found this thread on gamedev.net: <http://66.102.9.104/search?q=cache:wSn5t58ACJwJ:www.gamedev.net/community/forums/topic.asp%3Ftopic_id%3D407491+tank+track+radius+velocity&hl=en&ct=clnk&cd=1&gl=za&client=firefox-a> Another thread: <http://www.physicsforums.com/showthread.php?t=220317> It turns out the key to finding the formula was just knowing the correct terminology ("skid steer") :P
For a skid steered vehicle that is required to turn in radius 'r' at a given speed 'Si' of the Inner Wheel/Track, the Outer track must be driven at speed 'So' : ``` So = Si * ((r+d)/r) ``` **Details:** In Skid Steering, a turn is performed by the outer wheels/track traveling further distance than the inner wheels/track. Furthermore, the extra distance traveled is completed in the same time as the inner track, meaning that the outer wheels/track must run faster. Circle circumference circumscribed by "Inner" track: ``` c1 = 2*PI*r 'r' is radius of circle origin to track/wheel ``` Circle circumference circumscribed by "Outer" track: ``` c2 = 2*PI*(r+d) 'r' is radius of circle origin to inner track/wheel 'd' is the distance between the Inner and Outer wheels/track. ``` Furthermore, c2 = X \* c1, which says that c2 is proportionally bigger than c1 ``` X = c2 / c1 X = 2*PI*(r+d) / 2*PI*r X = (r+d)/r ``` Therefore for a skid steered vehicle that is required to turn in radius 'r' at a given speed 's' of the Inner Wheel/Track, the Outer track must be driven at : ``` So = Si * ((r+d)/r) ``` Where: ``` 'So' = Speed of outer track 'Si' = Speed of inner track 'r' = turn radius from inner track 'd' = distance between vehicle tracks. ********* <---------------- Outer Track **** | **** ** |<--------**----------- 'd' Distance between tracks * *******<-------*---------- Inner Track * *** ^ *** * * * |<-----*------*-------- 'r' Radius of Turn * * | * * * * O * * * * * * * * * * * *** *** * * ******* * ** ** **** **** ********* ```
125,102
<p>Say I have the following string:</p> <pre><code>"I am the most foo h4ck3r ever!!" </code></pre> <p>I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in:</p> <pre><code>"I am the most &lt;span class="special"&gt;foo&gt;&lt;/span&gt; h4ck3r ever!!" </code></pre> <p>BeautifulSoup seemed like the way to go, but I haven't been able to make it work.</p> <p>I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea.</p> <p>Some advice for this would be really useful, especially in python. </p>
[ { "answer_id": 125122, "author": "fuentesjr", "author_id": 10708, "author_profile": "https://Stackoverflow.com/users/10708", "pm_score": 3, "selected": true, "text": "<p>How about this:</p>\n\n<pre><code>Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; def makeSpecial(mystring, special_substr):\n... return mystring.replace(special_substr, '&lt;span class=\"special\"&gt;%s&lt;/span&gt;\n' % special_substr)\n...\n&gt;&gt;&gt; makeSpecial(\"I am the most foo h4ck3r ever!!\", \"foo\")\n'I am the most &lt;span class=\"special\"&gt;foo&lt;/span&gt; h4ck3r ever!!'\n&gt;&gt;&gt;\n</code></pre>\n" }, { "answer_id": 125134, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 1, "selected": false, "text": "<p>As far as I can tell, you're doing a simple string replace. You're replacing \"foo\" with \"bar foo bar.\" So from <a href=\"http://docs.python.org/lib/string-methods.html\" rel=\"nofollow noreferrer\" title=\"string methods\">string</a> you could just use </p>\n\n<pre><code>replace(old, new[, count]) \n</code></pre>\n\n<p>Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. </p>\n\n<p>So for you it would be:</p>\n\n<pre><code>myStr.replace(\"foo\", \"&lt;span&gt;foo&lt;/span&gt;\") \n</code></pre>\n" }, { "answer_id": 125142, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<p>If you wanted to do it with javascript/jQuery, take a look at this question: <a href=\"https://stackoverflow.com/questions/119441/highlight-a-word-with-jquery\">Highlight a word with jQuery</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9106/" ]
Say I have the following string: ``` "I am the most foo h4ck3r ever!!" ``` I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in: ``` "I am the most <span class="special">foo></span> h4ck3r ever!!" ``` BeautifulSoup seemed like the way to go, but I haven't been able to make it work. I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea. Some advice for this would be really useful, especially in python.
How about this: ``` Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def makeSpecial(mystring, special_substr): ... return mystring.replace(special_substr, '<span class="special">%s</span> ' % special_substr) ... >>> makeSpecial("I am the most foo h4ck3r ever!!", "foo") 'I am the most <span class="special">foo</span> h4ck3r ever!!' >>> ```
125,109
<p>I'm trying to bind a <code>List&lt;T&gt;</code> to a DataGridView control, and I'm not having any luck creating custom bindings.</p> <p>I have tried:</p> <pre><code>gvProgramCode.DataBindings.Add(new Binding("Opcode",code,"Opcode")); </code></pre> <p>It throws an exception, saying that nothing was found by that property name.</p> <p>The name of the column in question is "Opcode". The name of the property in the <code>List&lt;T&gt;</code> is Opcode.</p> <p><strong>ANSWER EDIT</strong>: the problem was that I did not have the bindable fields in my class as properties, just public fields...Apparently it doesn't reflect on fields, just properties.</p>
[ { "answer_id": 125132, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 4, "selected": false, "text": "<p>Is the property on the grid you are binding to Opcode as well?.. if you want to bind directly to List you would just DataSource = list. The databindings allows custom binding. are you trying to do something other than the datasource?</p>\n\n<p>You are getting a bunch of empty rows? do the auto generated columns have names? Have you verified data is in the object (not just string.empty) ?</p>\n\n<pre><code> class MyObject\n {\n public string Something { get; set; }\n public string Text { get; set; }\n public string Other { get; set; }\n }\n\n public Form1()\n {\n InitializeComponent();\n\n List&lt;MyObject&gt; myList = new List&lt;MyObject&gt;();\n\n for (int i = 0; i &lt; 200; i++)\n {\n string num = i.ToString();\n myList.Add(new MyObject { Something = \"Something \" + num , Text = \"Some Row \" + num , Other = \"Other \" + num });\n }\n\n dataGridView1.DataSource = myList;\n }\n</code></pre>\n\n<p>this should work fine...</p>\n" }, { "answer_id": 125165, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 3, "selected": false, "text": "<p>I can't really tell what you're trying to do with the example you included, but binding to a generic list of objects is fairly straightforward if you just want to list the objects:</p>\n\n<pre><code> private BindingSource _gridSource;\n\n private BindingSource GridSource\n {\n get\n {\n if (_gridSource == null)\n _gridSource = new BindingSource();\n return _gridSource;\n }\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n List&lt;FluffyBunny&gt; list = new List&lt;FluffyBunny&gt;();\n list.Add(new FluffyBunny { Color = \"White\", EarType = \"Long\", Name = \"Stan\" });\n list.Add(new FluffyBunny { Color = \"Brown\", EarType = \"Medium\", Name = \"Mike\" });\n list.Add(new FluffyBunny { Color = \"Mottled\", EarType = \"Short\", Name = \"Torvald\" });\n\n GridSource.DataSource = list;\n dataGridView1.Columns[\"EarType\"].Visible = false; //Optionally hide a column\n dataGridView1.DataSource = GridSource;\n\n }\n</code></pre>\n\n<p>If you only want to display specific properties of the List's type you should be able to make the unwanted column(s) invisible. </p>\n\n<p>Technically, you don't really need to create the BindingSource, but I find it's a whole lot easier when I'm doing updates or changes if I have it.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 686696, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Had the same issue... I had a struct with public fields obviously. nothing in the grid. provided public getters, worked.</p>\n" }, { "answer_id": 1728974, "author": "Nikola Stjelja", "author_id": 32582, "author_profile": "https://Stackoverflow.com/users/32582", "pm_score": 2, "selected": false, "text": "<p>Another solution I've found is to use the BindingList collection.</p>\n\n<pre><code>\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n BindingList people= new BindingList {\n new Person {Name=\"John\",Age=23},\n new Person {Name=\"Lucy\",Age=16}\n };\n\n dataGridView1.DataSource= people;\n}\n</code></pre>\n\n<p>It works fine for me,</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I'm trying to bind a `List<T>` to a DataGridView control, and I'm not having any luck creating custom bindings. I have tried: ``` gvProgramCode.DataBindings.Add(new Binding("Opcode",code,"Opcode")); ``` It throws an exception, saying that nothing was found by that property name. The name of the column in question is "Opcode". The name of the property in the `List<T>` is Opcode. **ANSWER EDIT**: the problem was that I did not have the bindable fields in my class as properties, just public fields...Apparently it doesn't reflect on fields, just properties.
Is the property on the grid you are binding to Opcode as well?.. if you want to bind directly to List you would just DataSource = list. The databindings allows custom binding. are you trying to do something other than the datasource? You are getting a bunch of empty rows? do the auto generated columns have names? Have you verified data is in the object (not just string.empty) ? ``` class MyObject { public string Something { get; set; } public string Text { get; set; } public string Other { get; set; } } public Form1() { InitializeComponent(); List<MyObject> myList = new List<MyObject>(); for (int i = 0; i < 200; i++) { string num = i.ToString(); myList.Add(new MyObject { Something = "Something " + num , Text = "Some Row " + num , Other = "Other " + num }); } dataGridView1.DataSource = myList; } ``` this should work fine...
125,113
<p>What is the most efficient way to convert a MySQL query to CSV in PHP please?</p> <p>It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required).</p> <p>The CSV should also include one top line of field names.</p>
[ { "answer_id": 125118, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<pre><code>// Export to CSV\nif($_GET['action'] == 'export') {\n\n $rsSearchResults = mysql_query($sql, $db) or die(mysql_error());\n\n $out = '';\n $fields = mysql_list_fields('database','table',$db);\n $columns = mysql_num_fields($fields);\n\n // Put the name of all fields\n for ($i = 0; $i &lt; $columns; $i++) {\n $l=mysql_field_name($fields, $i);\n $out .= '\"'.$l.'\",';\n }\n $out .=\"\\n\";\n\n // Add all values in the table\n while ($l = mysql_fetch_array($rsSearchResults)) {\n for ($i = 0; $i &lt; $columns; $i++) {\n $out .='\"'.$l[\"$i\"].'\",';\n }\n $out .=\"\\n\";\n }\n // Output to browser with appropriate mime type, you choose ;)\n header(\"Content-type: text/x-csv\");\n //header(\"Content-type: text/csv\");\n //header(\"Content-type: application/csv\");\n header(\"Content-Disposition: attachment; filename=search_results.csv\");\n echo $out;\n exit;\n}\n</code></pre>\n" }, { "answer_id": 125120, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": false, "text": "<p>Look at the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html\" rel=\"noreferrer\">documentation</a> regarding the SELECT ... INTO OUTFILE syntax.</p>\n\n<pre><code>SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'\n FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'\n LINES TERMINATED BY '\\n'\n FROM test_table;\n</code></pre>\n" }, { "answer_id": 125125, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 8, "selected": true, "text": "<pre><code>SELECT * INTO OUTFILE \"c:/mydata.csv\"\nFIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'\nLINES TERMINATED BY \"\\n\"\nFROM my_table;\n</code></pre>\n\n<p>(<em>the documentation for this is here: <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/select.html</a></em>)</p>\n\n<p>or:</p>\n\n<pre><code>$select = \"SELECT * FROM table_name\";\n\n$export = mysql_query ( $select ) or die ( \"Sql error : \" . mysql_error( ) );\n\n$fields = mysql_num_fields ( $export );\n\nfor ( $i = 0; $i &lt; $fields; $i++ )\n{\n $header .= mysql_field_name( $export , $i ) . \"\\t\";\n}\n\nwhile( $row = mysql_fetch_row( $export ) )\n{\n $line = '';\n foreach( $row as $value )\n { \n if ( ( !isset( $value ) ) || ( $value == \"\" ) )\n {\n $value = \"\\t\";\n }\n else\n {\n $value = str_replace( '\"' , '\"\"' , $value );\n $value = '\"' . $value . '\"' . \"\\t\";\n }\n $line .= $value;\n }\n $data .= trim( $line ) . \"\\n\";\n}\n$data = str_replace( \"\\r\" , \"\" , $data );\n\nif ( $data == \"\" )\n{\n $data = \"\\n(0) Records Found!\\n\"; \n}\n\nheader(\"Content-type: application/octet-stream\");\nheader(\"Content-Disposition: attachment; filename=your_desired_name.xls\");\nheader(\"Pragma: no-cache\");\nheader(\"Expires: 0\");\nprint \"$header\\n$data\";\n</code></pre>\n" }, { "answer_id": 125578, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 7, "selected": false, "text": "<p>Check out this <a href=\"https://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin#81951\">question / answer</a>. It's more concise than @Geoff's, and also uses the builtin fputcsv function.</p>\n\n<pre><code>$result = $db_con-&gt;query('SELECT * FROM `some_table`');\nif (!$result) die('Couldn\\'t fetch records');\n$num_fields = mysql_num_fields($result);\n$headers = array();\nfor ($i = 0; $i &lt; $num_fields; $i++) {\n $headers[] = mysql_field_name($result , $i);\n}\n$fp = fopen('php://output', 'w');\nif ($fp &amp;&amp; $result) {\n header('Content-Type: text/csv');\n header('Content-Disposition: attachment; filename=\"export.csv\"');\n header('Pragma: no-cache');\n header('Expires: 0');\n fputcsv($fp, $headers);\n while ($row = $result-&gt;fetch_array(MYSQLI_NUM)) {\n fputcsv($fp, array_values($row));\n }\n die;\n}\n</code></pre>\n" }, { "answer_id": 837194, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 3, "selected": false, "text": "<p>If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine) </p>\n\n<p>These functions setup the headers: </p>\n\n<pre><code>function setExcelContentType() {\n if(headers_sent())\n return false;\n\n header('Content-type: application/vnd.ms-excel');\n return true;\n}\n\nfunction setDownloadAsHeader($filename) {\n if(headers_sent())\n return false;\n\n header('Content-disposition: attachment; filename=' . $filename);\n return true;\n}\n</code></pre>\n\n<p>This one sends a CSV to a stream using a mysql result</p>\n\n<pre><code>function csvFromResult($stream, $result, $showColumnHeaders = true) {\n if($showColumnHeaders) {\n $columnHeaders = array();\n $nfields = mysql_num_fields($result);\n for($i = 0; $i &lt; $nfields; $i++) {\n $field = mysql_fetch_field($result, $i);\n $columnHeaders[] = $field-&gt;name;\n }\n fputcsv($stream, $columnHeaders);\n }\n\n $nrows = 0;\n while($row = mysql_fetch_row($result)) {\n fputcsv($stream, $row);\n $nrows++;\n }\n\n return $nrows;\n}\n</code></pre>\n\n<p>This one uses the above function to write a CSV to a file, given by $filename</p>\n\n<pre><code>function csvFileFromResult($filename, $result, $showColumnHeaders = true) {\n $fp = fopen($filename, 'w');\n $rc = csvFromResult($fp, $result, $showColumnHeaders);\n fclose($fp);\n return $rc;\n}\n</code></pre>\n\n<p>And this is where the magic happens ;)</p>\n\n<pre><code>function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {\n setExcelContentType();\n setDownloadAsHeader($asFilename);\n return csvFileFromResult('php://output', $result, $showColumnHeaders);\n}\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>$result = mysql_query(\"SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'\");\ncsvToExcelDownloadFromResult($result);\n</code></pre>\n" }, { "answer_id": 7125198, "author": "John M", "author_id": 127776, "author_profile": "https://Stackoverflow.com/users/127776", "pm_score": 4, "selected": false, "text": "<p>An update to @jrgns (with some slight syntax differences) solution.</p>\n\n<pre><code>$result = mysql_query('SELECT * FROM `some_table`'); \nif (!$result) die('Couldn\\'t fetch records'); \n$num_fields = mysql_num_fields($result); \n$headers = array(); \nfor ($i = 0; $i &lt; $num_fields; $i++) \n{ \n $headers[] = mysql_field_name($result , $i); \n} \n$fp = fopen('php://output', 'w'); \nif ($fp &amp;&amp; $result) \n{ \n header('Content-Type: text/csv');\n header('Content-Disposition: attachment; filename=\"export.csv\"');\n header('Pragma: no-cache'); \n header('Expires: 0');\n fputcsv($fp, $headers); \n while ($row = mysql_fetch_row($result)) \n {\n fputcsv($fp, array_values($row)); \n }\ndie; \n} \n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5165/" ]
What is the most efficient way to convert a MySQL query to CSV in PHP please? It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required). The CSV should also include one top line of field names.
``` SELECT * INTO OUTFILE "c:/mydata.csv" FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY "\n" FROM my_table; ``` (*the documentation for this is here: <http://dev.mysql.com/doc/refman/5.0/en/select.html>*) or: ``` $select = "SELECT * FROM table_name"; $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) ); $fields = mysql_num_fields ( $export ); for ( $i = 0; $i < $fields; $i++ ) { $header .= mysql_field_name( $export , $i ) . "\t"; } while( $row = mysql_fetch_row( $export ) ) { $line = ''; foreach( $row as $value ) { if ( ( !isset( $value ) ) || ( $value == "" ) ) { $value = "\t"; } else { $value = str_replace( '"' , '""' , $value ); $value = '"' . $value . '"' . "\t"; } $line .= $value; } $data .= trim( $line ) . "\n"; } $data = str_replace( "\r" , "" , $data ); if ( $data == "" ) { $data = "\n(0) Records Found!\n"; } header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=your_desired_name.xls"); header("Pragma: no-cache"); header("Expires: 0"); print "$header\n$data"; ```
125,117
<p>I was looking at how some site implemented rounded corners, and the CSS had these odd tags that I've never really seen before.</p> <pre><code>-moz-border-radius-topright: 5px; -webkit-border-top-right-radius: 5px; -moz-border-radius-bottomright: 5px; -webkit-border-bottom-right-radius: 5px; </code></pre> <p>I googled it, and they seem to be Firefox specific tags? </p> <p><b>Update</b></p> <p>The site I was looking at was twitter, it's wierd how a site like that would alienate their IE users.</p>
[ { "answer_id": 125123, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>I suggest browsing the site from IE or some other browser. I bet you get different markup.</p>\n" }, { "answer_id": 125128, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "<p>The <code>-moz-*</code> properties are Gecko-only (Firefox, Mozilla, Camino), the <code>-webkit-*</code> properties are WebKit-only (Chrome, Safari, Epiphany). Vendor-specific prefixes are common for implementing CSS capabilities that have not yet been standardized by the W3C.</p>\n\n<hr>\n\n<p>Twitter's not \"alienating\" their IE users. There's simply adding style for browsers that support it.</p>\n" }, { "answer_id": 125130, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 1, "selected": false, "text": "<p>The -moz ones are firefox specific, the -webkit ones are for safari, chrome and a few other browsers that use that rendering engine.</p>\n\n<p>These are early implementations of attributes that are defined in CSS3 so they will be coming in the future without the prefixes. </p>\n" }, { "answer_id": 125131, "author": "Bill Turner", "author_id": 17773, "author_profile": "https://Stackoverflow.com/users/17773", "pm_score": 0, "selected": false, "text": "<p>Those are for Firefox (the ones labeled -moz-border) and for Safari (-webkit-border).</p>\n" }, { "answer_id": 125133, "author": "NGittlen", "author_id": 10047, "author_profile": "https://Stackoverflow.com/users/10047", "pm_score": 0, "selected": false, "text": "<p>Yes, anything with a -moz in front of it will only work in Firefox.</p>\n\n<p>The -webkit ones will only work in webkit-based browsers like Safari, Chrome or Webkit.</p>\n\n<p>See <a href=\"http://www.google.com/search?hl=un&amp;q=CSS+rounded+corners\" rel=\"nofollow noreferrer\">here</a> for many ways to make rounded corners with just normal css tags.</p>\n\n<p>Edit: I don't think that not having rounded corners is exactly alienating, just a slightly different look for IE. </p>\n\n<p>Complete lists of all <a href=\"http://developer.mozilla.org/En/Mozilla_CSS_Extensions\" rel=\"nofollow noreferrer\">-moz</a> and <a href=\"http://qooxdoo.org/documentation/general/webkit_css_styles\" rel=\"nofollow noreferrer\">-webkit</a> css styles if anyone wants to know</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I was looking at how some site implemented rounded corners, and the CSS had these odd tags that I've never really seen before. ``` -moz-border-radius-topright: 5px; -webkit-border-top-right-radius: 5px; -moz-border-radius-bottomright: 5px; -webkit-border-bottom-right-radius: 5px; ``` I googled it, and they seem to be Firefox specific tags? **Update** The site I was looking at was twitter, it's wierd how a site like that would alienate their IE users.
The `-moz-*` properties are Gecko-only (Firefox, Mozilla, Camino), the `-webkit-*` properties are WebKit-only (Chrome, Safari, Epiphany). Vendor-specific prefixes are common for implementing CSS capabilities that have not yet been standardized by the W3C. --- Twitter's not "alienating" their IE users. There's simply adding style for browsers that support it.
125,124
<p>How do you pass options to an executable? Is there an easier way than making the options boolean arguments?</p> <p>EDIT: The last two answers have suggested using arguments. I know I can code a workable solution like that, but I'd rather have them be options.</p> <p>EDIT2: Per requests for clarification, I'll use this simple example: It's fairly easy to handle arguments because they automatically get parsed into an array.</p> <pre><code>./printfile file.txt 1000 </code></pre> <p>If I want to know what the name of the file the user wants to print, I access it via argv[1].</p> <p>Now about how this situation:</p> <pre><code>./printfile file.txt 1000 --nolinebreaks </code></pre> <p>The user wants to print the file with no line breaks. This is not required for the program to be able to run (as the filename and number of lines to print are), but the user has the option of using if if s/he would like. Now I could do this using:</p> <pre><code>./printfile file.txt 1000 true </code></pre> <p>The usage prompt would inform the user that the third argument is used to determine whether to print the file with line breaks or not. However, this seems rather clumsy. </p>
[ { "answer_id": 125139, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>I use two methods for passing information:</p>\n\n<p>1/ The use of command line arguments, which are made easier to handle with specific libraries such as getargs.</p>\n\n<p>2/ As environment variables, using getenv.</p>\n" }, { "answer_id": 125141, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 4, "selected": false, "text": "<p>Command-line arguments is the way to go. You may want to consider using Boost.ProgramOptions to simplify this task.</p>\n" }, { "answer_id": 125156, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 0, "selected": false, "text": "<p>The question isn't blazingly clear as to the context and just what you are trying to do - you mean running an executable from within a C++ program? There are several standard C library functions with names like execl(), execv(), execve(), ... that take the options as strings or pointer to an array of strings. There's also system() which takes a string containing whatever you'd be typing at a bash prompt, options and all.</p>\n" }, { "answer_id": 125182, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 1, "selected": false, "text": "<p>Pax has the right idea here.</p>\n\n<p>If you need more thorough two-way communication, open the process with pipes and send stuff to stdin/listen on stdout.</p>\n" }, { "answer_id": 125186, "author": "PiNoYBoY82", "author_id": 13646, "author_profile": "https://Stackoverflow.com/users/13646", "pm_score": -1, "selected": false, "text": "<p>You can put options in a .ini file and use the <a href=\"http://msdn.microsoft.com/en-us/library/ms724353(VS.85).aspx\" rel=\"nofollow noreferrer\">GetPrivateProfileXXX API's</a> to create a class that can read the type of program options you're looking for from the .ini.</p>\n\n<p>You can also create an interactive shell for your app to change certain settings real-time.</p>\n\n<p>EDIT:\nFrom your edits, can't you just parse each option looking for special keywords associated with that option that are \"optional\"?</p>\n" }, { "answer_id": 125204, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "<p>You can also use Window's PostMessage() function. This is very handy if the executable you want to send the options to is already running. I can post some example code if you are interested in this technique.</p>\n" }, { "answer_id": 125225, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 3, "selected": true, "text": "<p>You seem to think that there is some fundamental difference between \"options\" that start with \"<code>--</code>\" and \"arguments\" that don't. The only difference is in how you parse them.</p>\n\n<p>It might be worth your time to look at GNU's <code>getopt()</code>/<code>getopt_long()</code> option parser. It supports passing arguments with options such as <code>--number-of-line-breaks 47</code>.</p>\n" }, { "answer_id": 125387, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 0, "selected": false, "text": "<p>I like the popt library. It is C, but works fine from C++ as well. </p>\n\n<p>It doesn't appear to be cross-platform though. I found that out when I had to hack out my own API-compatible version of it for a Windows port of some Linux software.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7545/" ]
How do you pass options to an executable? Is there an easier way than making the options boolean arguments? EDIT: The last two answers have suggested using arguments. I know I can code a workable solution like that, but I'd rather have them be options. EDIT2: Per requests for clarification, I'll use this simple example: It's fairly easy to handle arguments because they automatically get parsed into an array. ``` ./printfile file.txt 1000 ``` If I want to know what the name of the file the user wants to print, I access it via argv[1]. Now about how this situation: ``` ./printfile file.txt 1000 --nolinebreaks ``` The user wants to print the file with no line breaks. This is not required for the program to be able to run (as the filename and number of lines to print are), but the user has the option of using if if s/he would like. Now I could do this using: ``` ./printfile file.txt 1000 true ``` The usage prompt would inform the user that the third argument is used to determine whether to print the file with line breaks or not. However, this seems rather clumsy.
You seem to think that there is some fundamental difference between "options" that start with "`--`" and "arguments" that don't. The only difference is in how you parse them. It might be worth your time to look at GNU's `getopt()`/`getopt_long()` option parser. It supports passing arguments with options such as `--number-of-line-breaks 47`.
125,157
<p>Is it possible to specify a relative path reference in connectionstring, attachDbFileName property in a web.config?</p> <p>For example, In my database is located in the App_data folder, I can easily specify the AttachDBFilename as|DataDirectory|\mydb.mdf and the |Datadirectory| will automatically resolve to the correct path.</p> <p>Now, suppose that web.config file is located in A folder, but the database is located in B\App_data folder, where A and B folder is located in the same folder. Is there anyway to use relative path reference to resolve to the correct path?</p>
[ { "answer_id": 125236, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 3, "selected": false, "text": "<p>It depends on where your '|DataDirectory|' is located. If the resolved value of '|DataDirectory|' is in folder A (where the web.config is), then no - you can't specify a relative path that is not a subfolder of the resolved value of '|DataDirectory|'.</p>\n\n<p>What you <em>can</em> do is set the value of '|DataDirectory|' to be wherever you would like, by calling the <strong>AppDomain.SetData</strong> method.</p>\n\n<p>From the MSDN online documentation:</p>\n\n<blockquote>\n <p>When DataDirectory is used, the resulting file path cannot be higher in the directory structure than the directory pointed to by the substitution string. For example, if the fully expanded DataDirectory is C:\\AppDirectory\\app_data, then the sample connection string shown above works because it is below c:\\AppDirectory. However, attempting to specify DataDirectory as |DataDirectory|..\\data will result in an error because \\data is not a subdirectory of \\AppDirectory.</p>\n</blockquote>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 125250, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 0, "selected": false, "text": "<p>In IIS you could also create a virtual directory that points at wherever the the real database is kept. Then your connection string just references the virtual directory.</p>\n" }, { "answer_id": 2522135, "author": "jbandi", "author_id": 32749, "author_profile": "https://Stackoverflow.com/users/32749", "pm_score": 4, "selected": false, "text": "<p>I had the same problem with the following scenario: I wanted to use the same database as the application from my integration tests.</p>\n\n<p>I went with the following workaround:</p>\n\n<p>In the App.config of my test-project I have:</p>\n\n<pre><code>&lt;appSettings&gt;\n &lt;add key=\"DataDirectory\" value=\"..\\..\\..\\BookShop\\App_Data\\\"/&gt;\n&lt;/appSettings&gt;\n</code></pre>\n\n<p>In the test-setup I execute the following code:</p>\n\n<pre><code> var dataDirectory = ConfigurationManager.AppSettings[\"DataDirectory\"]; \n var absoluteDataDirectory = Path.GetFullPath(dataDirectory); \n AppDomain.CurrentDomain.SetData(\"DataDirectory\", absoluteDataDirectory); \n</code></pre>\n" }, { "answer_id": 5627794, "author": "JohnSpin", "author_id": 702988, "author_profile": "https://Stackoverflow.com/users/702988", "pm_score": 1, "selected": false, "text": "<p>Add the following attributes to the test method:</p>\n\n<pre><code>[DeploymentItem(\"..\\\\TestSolutionDir\\\\TestProjedtDir\\\\TestDataFolder\\\\TestAutomationSpreadsheet.xlsx\")]\n[DataSource(\"System.Data.Odbc\", \"Dsn=Excel Files;dbq=|DataDirectory|\\\\TestAutomationSpreadsheet.xlsx\", \"SpreadsheetTabName$\", DataAccessMethod.Sequential)]\n</code></pre>\n\n<p>The <code>|DataDirctory|</code> variable is defined by the system when it runs the test. The DeploymentItem copies the spreadsheet there. You point to the spreadsheet and to the tab within the spreadsheet that the data is coming from. Right-click on the tab to rename it to something easy to remember.</p>\n" }, { "answer_id": 60204426, "author": "Unni Krishnan SJ Nair", "author_id": 11082833, "author_profile": "https://Stackoverflow.com/users/11082833", "pm_score": 0, "selected": false, "text": "<p><strong>Web.config</strong></p>\n\n<pre><code> &lt;appSettings&gt;\n &lt;add key=\"FilePath\" value=\"App_Data\\SavedFiles\\\"/&gt;\n &lt;/appSettings&gt;\n</code></pre>\n\n<p><strong>Path.cs</strong></p>\n\n<pre><code>string filePath = AppDomain.CurrentDomain.BaseDirectory + (ConfigurationManager.AppSettings[\"FilePath\"]);\n</code></pre>\n\n<p>Works for me..!!</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
Is it possible to specify a relative path reference in connectionstring, attachDbFileName property in a web.config? For example, In my database is located in the App\_data folder, I can easily specify the AttachDBFilename as|DataDirectory|\mydb.mdf and the |Datadirectory| will automatically resolve to the correct path. Now, suppose that web.config file is located in A folder, but the database is located in B\App\_data folder, where A and B folder is located in the same folder. Is there anyway to use relative path reference to resolve to the correct path?
I had the same problem with the following scenario: I wanted to use the same database as the application from my integration tests. I went with the following workaround: In the App.config of my test-project I have: ``` <appSettings> <add key="DataDirectory" value="..\..\..\BookShop\App_Data\"/> </appSettings> ``` In the test-setup I execute the following code: ``` var dataDirectory = ConfigurationManager.AppSettings["DataDirectory"]; var absoluteDataDirectory = Path.GetFullPath(dataDirectory); AppDomain.CurrentDomain.SetData("DataDirectory", absoluteDataDirectory); ```
125,171
<p>I need to pass a regex substitution as a variable:</p> <pre><code>sub proc { my $pattern = shift; my $txt = &quot;foo baz&quot;; $txt =~ $pattern; } my $pattern = 's/foo/bar/'; proc($pattern); </code></pre> <p>This, of course, doesn't work. I tried eval'ing the substitution:</p> <pre><code>eval(&quot;$txt =~ $pattern;&quot;); </code></pre> <p>but that didn't work either. What horribly obvious thing am I missing here?</p>
[ { "answer_id": 125212, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 3, "selected": false, "text": "<p>Well, you can precompile the regular expression using the <em>qr//</em> operator. But you can't pass an operator (s///).</p>\n<pre><code>$pattern = qr/foo/;\n\nprint &quot;match!\\n&quot; if $text =~ $pattern;\n</code></pre>\n<p>But if you have to pass the substitution operator, you are down to passing either code or strings:</p>\n<pre><code>proc('$text =~ s/foo/bar');\n\nsub proc {\n my $code = shift;\n\n ...\n\n eval $code;\n}\n</code></pre>\n<p>or, code:</p>\n<pre><code>proc(sub {my $text = shift; $text =~ s/foo/bar});\n\nsub proc {\n my $code = shift;\n\n ...\n\n $code-&gt;(&quot;some text&quot;);\n}\n</code></pre>\n" }, { "answer_id": 125240, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<pre><code>sub proc {\n my($match, $subst) = @_;\n my $txt = \"foo baz\";\n $txt =~ s/$match/$subst/;\n print \"$txt\\n\";\n}\n\nmy $matcher = qr/foo/;\nmy $sub_str = \"bar\";\n\nproc($matcher, $sub_str);\n</code></pre>\n\n<p>This rather directly answers your question. You can do more - but when I used a qr// term instead of the $sub_str as a simple literal, then the expanded regex was substituted.</p>\n\n<p>I recently needed to create a parser (test parser) for statements with some peculiar (dialect of) SQL types, recognizing lines such as this, splitting it into three type names:</p>\n\n<pre><code>input: datetime year to second,decimal(16,6), integer\n</code></pre>\n\n<p>The script I used to demo this used quoted regexes.</p>\n\n<pre><code>#!/bin/perl -w\nuse strict;\nwhile (&lt;&gt;)\n{\n chomp;\n print \"Read: &lt;$_&gt;\\n\";\n my($r1) = qr%^input\\s*:\\s*%i;\n if ($_ =~ $r1)\n {\n print \"Found input:\\n\";\n s%$r1%%;\n print \"Residue: &lt;$_&gt;\\n\";\n my($r3) = qr%(?:year|month|day|hour|minute|second|fraction(?:\\([1-5]\\))?)%;\n my($r2) = qr%\n (?:\\s*,?\\s*)? # Commas and spaces\n (\n (?:money|numeric|decimal)(?:\\(\\d+(?:,\\d+)?\\))? |\n int(?:eger)? |\n smallint |\n datetime\\s+$r3\\s+to\\s+$r3\n )\n %ix;\n while ($_ =~ m/$r2/)\n {\n print \"Got type: &lt;$1&gt;\\n\";\n s/$r2//;\n }\n print \"Residue 2: &lt;$_&gt;\\n\";\n }\n else\n {\n print \"No match:\\n\";\n }\n print \"Next?\\n\";\n}\n</code></pre>\n\n<p>We can argue about the use of names like $r1, etc. But it did the job...it was not, and is not, production code.</p>\n" }, { "answer_id": 125266, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 6, "selected": true, "text": "<blockquote>\n <p>I need to pass a regex substitution as a variable</p>\n</blockquote>\n\n<p>Do you? Why not pass a code reference? Example:</p>\n\n<pre><code>sub modify\n{\n my($text, $code) = @_;\n $code-&gt;($text);\n return $text;\n}\n\nmy $new_text = modify('foo baz', sub { $_[0] =~ s/foo/bar/ });\n</code></pre>\n\n<p>In general, when you want to pass \"something that does something\" to a subroutine (\"a regex substitution\" in the case of your question) the answer is to pass a reference to a piece of code. <a href=\"http://hop.perl.plover.com/\" rel=\"noreferrer\">Higher Order Perl</a> is a good book on the topic.</p>\n" }, { "answer_id": 125329, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "<pre><code>eval &quot;$txt =~ $pattern&quot;;\n</code></pre>\n<p>This becomes</p>\n<pre><code>eval &quot;\\&quot;foo baz\\&quot; =~ s/foo/bar/&quot;\n</code></pre>\n<p>and substitutions don't work on literal strings.</p>\n<p>This would work:</p>\n<pre><code>eval &quot;\\$txt =~ $pattern&quot;\n</code></pre>\n<p>but that's not very pleasing. <em>eval</em> is almost never the right solution.</p>\n<p><a href=\"https://stackoverflow.com/questions/125171/passing-a-regex-substitution-as-a-variable-in-perl/125212#125212\">zigdon's solution</a> can do anything, and <a href=\"https://stackoverflow.com/questions/125171/passing-a-regex-substitution-as-a-variable-in-perl/125240#125240\">Jonathan's solution</a> is quite suitable if the replacement string is static. If you want something more structured than the first and more flexible than the second, I'd suggest a hybrid:</p>\n<pre><code>sub proc {\n my $pattern = shift;\n my $code = shift;\n my $txt = &quot;foo baz&quot;;\n $txt =~ s/$pattern/$code-&gt;()/e;\n print &quot;$txt\\n&quot;;\n}\n\nmy $pattern = qr/foo/;\nproc($pattern, sub { &quot;bar&quot; }); # ==&gt; bar baz\nproc($pattern, sub { &quot;\\U$&amp;&quot; }); # ==&gt; FOO baz\n</code></pre>\n" }, { "answer_id": 126457, "author": "rjray", "author_id": 6421, "author_profile": "https://Stackoverflow.com/users/6421", "pm_score": 2, "selected": false, "text": "<p>Perhaps you might rethink your approach.</p>\n<p>You want to pass in to a function a regex substitution, probably because the function will be deriving the text to be operated upon from some other source (reading from a file, socket, etc.). But you're conflating regular expression with <em>regular expression substitution</em>.</p>\n<p>In the expression, <code>s/foo/bar/</code>, you actually have a regular expression (&quot;/foo/&quot;) and a substitution (&quot;bar&quot;) that should replace what is matched by the expression. In the approaches you've tried thus far, you ran into problems trying to use <code>eval</code>, mainly because of the likelihood of special characters in the expression that either interfere with <code>eval</code> or get interpolated (i.e., gobbled up) in the process of evaluation.</p>\n<p>So instead, try passing your routine two arguments: the expression and the substitution:</p>\n<pre><code>sub apply_regex {\n my $regex = shift;\n my $subst = shift || ''; # No subst string will mean matches are &quot;deleted&quot;\n\n # Some setup and processing happens...\n\n # Time to make use of the regex that was passed in:\n while (defined($_ = &lt;$some_filehandle&gt;)) {\n s/$regex/$subst/g; # You can decide if you want to use /g etc.\n }\n\n # The rest of the processing...\n}\n</code></pre>\n<p>This approach has an added benefit: if your regex pattern <em>doesn't</em> have any special characters in it, you can just pass it in directly:</p>\n<pre><code>apply_regex('foo', 'bar');\n</code></pre>\n<p>Or, if it does, you can use the <code>qr//</code> quoting-operator to create a regex object and pass that as the first parameter:</p>\n<pre><code>apply_regex(qr{(foo|bar)}, 'baz');\napply_regex(qr/[ab]+/, '(one or more of &quot;a&quot; or &quot;b&quot;)');\napply_regex(qr|\\d+|); # Delete any sequences of digits\n</code></pre>\n<p>Most of all, you really don't need <code>eval</code> or the use of code-references/closures for this task. That will only add complexity that may make debugging harder than it needs to be.</p>\n" }, { "answer_id": 128321, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 3, "selected": false, "text": "<p><code>s///</code> is not a regex. Thus, you can't pass it as a regex.</p>\n<p>I don't like <code>eval</code> for this. It's very fragile, with a lot of bordercases.</p>\n<p>I think it's best to take an approach similar to the one JavaScript takes: pass both a regex (in Perl, that is <code>qr//</code>) and a code reference for the substitution. For example, to pass parameters to get the same effect as</p>\n<pre><code>s/(\\w+)/\\u\\L$1/g;\n</code></pre>\n<p>You can call</p>\n<pre><code>replace($string, qr/(\\w+)/, sub { &quot;\\u\\L$1&quot; }, 'g');\n</code></pre>\n<p>Note that the 'g' modifier is not actually a flag for the regex (I think attaching it to the regex is a design mistake in JavaScript), so I chose to pass it in a third parameter.</p>\n<p>Once the API has been decided on, the implementation can be done next:</p>\n<pre><code>sub replace {\n my($string, $find, $replace, $global) = @_;\n unless($global) {\n $string =~ s($find){ $replace-&gt;() }e;\n } else {\n $string =~ s($find){ $replace-&gt;() }ge;\n }\n return $string;\n}\n</code></pre>\n<p>Let's try it:</p>\n<pre><code>print replace('content-TYPE', qr/(\\w+)/, sub { &quot;\\u\\L$1&quot; }, 'g');\n</code></pre>\n<p>Result:</p>\n<blockquote>\n<p>Content-Type</p>\n</blockquote>\n<p>That looks good to me.</p>\n" }, { "answer_id": 4046820, "author": "pevgeniev", "author_id": 408821, "author_profile": "https://Stackoverflow.com/users/408821", "pm_score": -1, "selected": false, "text": "<p>You're right - you were very close:</p>\n\n<pre><code>eval('$txt =~ ' . \"$pattern;\");\n</code></pre>\n" }, { "answer_id": 10691133, "author": "Jeff Burdges", "author_id": 667457, "author_profile": "https://Stackoverflow.com/users/667457", "pm_score": 0, "selected": false, "text": "<p>I have an extremely simple script for mass file renaming that employs this trick:</p>\n<pre><code>#!/opt/local/bin/perl\nsub oops { die &quot;Usage : sednames s/old/new [files ..]\\n&quot;; }\noops if ($#ARGV &lt; 0);\n\n$regex = eval 'sub { $_ = $_[0]; ' . shift(@ARGV) . '; return $_; }';\nsub regex_rename { foreach (&lt;$_[0]&gt;) {\n rename(&quot;$_&quot;, &amp;$regex($_));\n} }\n\nif ($#ARGV &lt; 0) { regex_rename(&quot;*&quot;); }\nelse { regex_rename(@ARGV); }\n</code></pre>\n<p>Any Perl command that modifies <code>$_</code> like <code>s/old/new</code> could be employed to modify the files.</p>\n<p>I decided upon using <code>eval</code> so that the regular expression only needed to be compiled once. There is some wonkiness with <code>eval</code> and <code>$_</code> that prevented me from using simply:</p>\n<pre><code>eval 'sub { ' . shift(@ARGV) . ' }';\n</code></pre>\n<p>Although this <code>&amp;$regex</code> certainly does modify <code>$_</code>, requiring the <code>&quot;$_&quot;</code> to evaluate <code>$_</code> before calling <code>rename</code>. Yes, <code>eval</code> is quite fragile, like everyone else said.</p>\n" }, { "answer_id": 46698295, "author": "Aloso", "author_id": 3393058, "author_profile": "https://Stackoverflow.com/users/3393058", "pm_score": 0, "selected": false, "text": "<p>I found a probably better way to do it:</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>sub proc {\n my ($pattern, $replacement) = @_;\n my $txt = \"foo baz\";\n\n $txt =~ s/$pattern/$replacement/g; # This substitution is global.\n}\n\nmy $pattern = qr/foo/; # qr means the regex is pre-compiled.\nmy $replacement = 'bar';\n\nproc($pattern, $replacement);\n</code></pre>\n\n<p>If the flags of the substitution have to be variable, you can use this:</p>\n\n<pre><code>sub proc {\n my ($pattern, $replacement, $flags) = @_;\n my $txt = \"foo baz\";\n\n eval('$txt =~ s/$pattern/$replacement/' . $flags);\n}\n\nproc(qr/foo/, 'bar', 'g');\n</code></pre>\n\n<p>Please note that you don't need to escape <code>/</code> in the replacement string.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8130/" ]
I need to pass a regex substitution as a variable: ``` sub proc { my $pattern = shift; my $txt = "foo baz"; $txt =~ $pattern; } my $pattern = 's/foo/bar/'; proc($pattern); ``` This, of course, doesn't work. I tried eval'ing the substitution: ``` eval("$txt =~ $pattern;"); ``` but that didn't work either. What horribly obvious thing am I missing here?
> > I need to pass a regex substitution as a variable > > > Do you? Why not pass a code reference? Example: ``` sub modify { my($text, $code) = @_; $code->($text); return $text; } my $new_text = modify('foo baz', sub { $_[0] =~ s/foo/bar/ }); ``` In general, when you want to pass "something that does something" to a subroutine ("a regex substitution" in the case of your question) the answer is to pass a reference to a piece of code. [Higher Order Perl](http://hop.perl.plover.com/) is a good book on the topic.
125,192
<p>A common pattern with STL containers is this:</p> <pre><code>map&lt;Key, Value&gt; map; for(map&lt;Key, Value&gt;::iterator iter = map.begin(); iter != map.end(); ++iter) { ... } </code></pre> <p>So in order to avoid writing the declaration of the template parameters we can do this somewhere:</p> <pre><code>typedef map&lt;Key, Value&gt; TNiceNameForAMap; </code></pre> <p>But if this map is only used in a single function or for a single iteration this is an annoying overhead.</p> <p>Is there any way around this typedef?</p>
[ { "answer_id": 125201, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "<p>Not sure what you mean by \"overhead\". If it simplifies the way you write your code, use it, otherwise stick with the longhand.</p>\n\n<p>If it's only used in a restricted scope, put the typedef in that same scope. Then it doesn't need to be published, or documented, or appear on any UML diagrams. For example (and I don't claim this is the best code ever in other respects):</p>\n\n<pre><code>int totalSize() {\n typedef std::map&lt;Key, Value&gt; DeDuplicator;\n DeDuplicator everything;\n\n // Run around the universe finding everything. If we encounter a key\n // more than once it's only added once.\n\n // now compute the total\n int total = 0;\n for(DeDuplicator::iterator i = everything.begin(); i &lt;= everything.end(); ++i) {\n total += i-&gt;second.size(); // yeah, yeah, overflow. Whatever.\n }\n return total;\n}\n</code></pre>\n\n<p>Combining with Ferruccio's suggestion (if you're using boost), the loop becomes:</p>\n\n<pre><code>BOOST_FOREACH(DeDuplicator::pair p, everything) {\n total += p.second.size();\n}\n</code></pre>\n\n<p>And combining with bk1e's suggestion (if you're using C++0x or have features from it), and assuming that BOOST_FOREACH interacts with auto in the way I think it should based on the fact that it can normally handle implicit casts to compatible types:</p>\n\n<pre><code>std::map&lt;Key, Value&gt; everything;\n// snipped code to run around...\nint total = 0;\nBOOST_FOREACH(auto p, everything) {\n total += p.second.size();\n}\n</code></pre>\n\n<p>Not bad.</p>\n" }, { "answer_id": 125217, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html\" rel=\"nofollow noreferrer\">Boost.Foreach</a></p>\n" }, { "answer_id": 125218, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "<p>Personally I think <strong>MYMAP::iterator</strong> is more readable than <strong>map&lt;int,string&gt;::iterator</strong> or even <strong>std::map&lt;int, std::string&gt;::iterator</strong> so I always do the typedef. The only overhead is one line of code.</p>\n\n<p>Once the code is compiled, there will be no difference in the size or speed of the executable. It's just about readability.</p>\n" }, { "answer_id": 125296, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "<p>A future version of the C++ standard (known as <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x\" rel=\"nofollow noreferrer\">C++0x</a>) will introduce a <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x#Type_determination\" rel=\"nofollow noreferrer\">new use for the <code>auto</code> keyword</a>, allowing you to write something like the following:</p>\n\n<pre><code>map&lt;Key, Value&gt; map;\nfor(auto iter = map.begin(); iter != map.end(); ++iter)\n{\n ...\n}\n</code></pre>\n" }, { "answer_id": 125347, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 0, "selected": false, "text": "<p>If the typedef is local to a single function it doesn't even need to be a <em>nice</em> name. Use X or MAP, just like in a template.</p>\n" }, { "answer_id": 125491, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 0, "selected": false, "text": "<p>C++0x will also offer ranged-based for loop, which is similar to iterative for looping in other languages.</p>\n\n<p>Unfortunately, GCC does not yet implement range-based for (but <em>does</em> implement auto).</p>\n\n<p>Edit: In the meanwhile, also consider typedefing the iterator. It doesn't get around the one-use typedef (unless you put that in a header, which is always an option), but it makes the resulting code shorter by one ::iterator.</p>\n" }, { "answer_id": 125918, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 0, "selected": false, "text": "<p>Over the past few years I've really tried to move away from using manually written loops in preference to using the STL algorithms. Your above code can be changed to:</p>\n\n<pre><code>struct DoLoopBody {\n template &lt;typename ValueType&gt;\n inline void operator()(ValueType v) const {\n // ...\n }\n};\n\nstd::for_each (map.begin(), map.end(), DoLoopBody ());\n</code></pre>\n\n<p>Unfortunately the class DoLoopBody cannot be a local class, which is often highlighted as a disadvantage. However, I see this as an advantage in that the body of the loop can now be unit tested in isolation.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
A common pattern with STL containers is this: ``` map<Key, Value> map; for(map<Key, Value>::iterator iter = map.begin(); iter != map.end(); ++iter) { ... } ``` So in order to avoid writing the declaration of the template parameters we can do this somewhere: ``` typedef map<Key, Value> TNiceNameForAMap; ``` But if this map is only used in a single function or for a single iteration this is an annoying overhead. Is there any way around this typedef?
Not sure what you mean by "overhead". If it simplifies the way you write your code, use it, otherwise stick with the longhand. If it's only used in a restricted scope, put the typedef in that same scope. Then it doesn't need to be published, or documented, or appear on any UML diagrams. For example (and I don't claim this is the best code ever in other respects): ``` int totalSize() { typedef std::map<Key, Value> DeDuplicator; DeDuplicator everything; // Run around the universe finding everything. If we encounter a key // more than once it's only added once. // now compute the total int total = 0; for(DeDuplicator::iterator i = everything.begin(); i <= everything.end(); ++i) { total += i->second.size(); // yeah, yeah, overflow. Whatever. } return total; } ``` Combining with Ferruccio's suggestion (if you're using boost), the loop becomes: ``` BOOST_FOREACH(DeDuplicator::pair p, everything) { total += p.second.size(); } ``` And combining with bk1e's suggestion (if you're using C++0x or have features from it), and assuming that BOOST\_FOREACH interacts with auto in the way I think it should based on the fact that it can normally handle implicit casts to compatible types: ``` std::map<Key, Value> everything; // snipped code to run around... int total = 0; BOOST_FOREACH(auto p, everything) { total += p.second.size(); } ``` Not bad.
125,230
<p>What MySQL query will do a text search and replace in one particular field in a table?</p> <p>I.e. search for <code>foo</code> and replace with <code>bar</code> so a record with a field with the value <code>hello foo</code> becomes <code>hello bar</code>.</p>
[ { "answer_id": 125241, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace\" rel=\"nofollow noreferrer\">Replace</a> string function will do that.</p>\n" }, { "answer_id": 125243, "author": "thesmallprint", "author_id": 12765, "author_profile": "https://Stackoverflow.com/users/12765", "pm_score": 7, "selected": false, "text": "<pre><code>UPDATE table_name \nSET field = replace(field, 'string-to-find', 'string-that-will-replace-it');\n</code></pre>\n" }, { "answer_id": 125249, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 10, "selected": true, "text": "<p>Change <code>table_name</code> and <code>field</code> to match your table name and field in question:</p>\n\n<pre><code>UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') &gt; 0;\n</code></pre>\n\n<ul>\n<li><a href=\"https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace\" rel=\"noreferrer\">REPLACE</a> (string functions)</li>\n<li><a href=\"https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_instr\" rel=\"noreferrer\">INSTR</a> (string functions)</li>\n</ul>\n" }, { "answer_id": 10460455, "author": "basdog22", "author_id": 190898, "author_profile": "https://Stackoverflow.com/users/190898", "pm_score": 3, "selected": false, "text": "<p>And if you want to search and replace based on the value of another field you could do a CONCAT:</p>\n\n<pre><code>update table_name set `field_name` = replace(`field_name`,'YOUR_OLD_STRING',CONCAT('NEW_STRING',`OTHER_FIELD_VALUE`,'AFTER_IF_NEEDED'));\n</code></pre>\n\n<p>Just to have this one here so that others will find it at once.</p>\n" }, { "answer_id": 24629959, "author": "Umesh Patil", "author_id": 1200323, "author_profile": "https://Stackoverflow.com/users/1200323", "pm_score": 4, "selected": false, "text": "<pre><code> UPDATE table SET field = replace(field, text_needs_to_be_replaced, text_required);\n</code></pre>\n\n<p>Like for example, if I want to replace all occurrences of John by Mark I will use below, </p>\n\n<pre><code>UPDATE student SET student_name = replace(student_name, 'John', 'Mark');\n</code></pre>\n" }, { "answer_id": 25456967, "author": "Schwann", "author_id": 3741261, "author_profile": "https://Stackoverflow.com/users/3741261", "pm_score": 0, "selected": false, "text": "<p>I used the above command line as follow:\nupdate TABLE-NAME set FIELD = replace(FIELD, 'And', 'and');\nthe purpose was to replace And with and (\"A\" should be lowercase). The problem is it cannot find the \"And\" in database, but if I use like \"%And%\" then it can find it along with many other ands that are part of a word or even the ones that are already lowercase.</p>\n" }, { "answer_id": 49674425, "author": "Gaspy", "author_id": 498105, "author_profile": "https://Stackoverflow.com/users/498105", "pm_score": 4, "selected": false, "text": "<p>In my experience, the fastest method is</p>\n\n<pre><code>UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE field LIKE '%foo%';\n</code></pre>\n\n<p>The <code>INSTR()</code> way is the second-fastest and omitting the <code>WHERE</code> clause altogether is slowest, even if the column is not indexed.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16536/" ]
What MySQL query will do a text search and replace in one particular field in a table? I.e. search for `foo` and replace with `bar` so a record with a field with the value `hello foo` becomes `hello bar`.
Change `table_name` and `field` to match your table name and field in question: ``` UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0; ``` * [REPLACE](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace) (string functions) * [INSTR](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_instr) (string functions)
125,265
<p>In reading about Perl 6, I see a feature being trumpeted about, where you no longer have to do:</p> <pre><code>return "0 but true"; </code></pre> <p>...but can instead do:</p> <pre><code>return 0 but True; </code></pre> <p>If that's the case, how does truth work in Perl 6? In Perl 5, it was pretty simple: 0, "", and undef are false, everything else is true.</p> <p>What are the rules in Perl 6 when it comes to boolean context?</p>
[ { "answer_id": 125303, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>According to O'Reilly's <em><a href=\"http://books.google.com/books?id=NYgzEwH5tsQC&amp;pg=PA37&amp;lpg=PA36&amp;ots=cjwHsY0ZrS&amp;output=html\" rel=\"nofollow noreferrer\">Perl 6 and Parrot Essentials</a></em>, <strong>false</strong> is 0, undef, the empty string, and values flagged as <em>false</em>. <strong>true</strong> is everything else.</p>\n\n<p>Also, Perl 6 has both a primitive boolean type and by having True and False <strong>roles</strong> that any value can mix in (so you can have a \"0 but True\" value or a \"1 but False\" one for example, or a false list containing elements, or a true list that's empty). </p>\n\n<p>See <a href=\"http://www.mail-archive.com/[email protected]/msg09930.html\" rel=\"nofollow noreferrer\">http://www.mail-archive.com/[email protected]/msg09930.html</a></p>\n" }, { "answer_id": 125318, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 4, "selected": false, "text": "<p>See <a href=\"http://dev.perl.org/perl6/doc/design/syn/S12.html#Roles\" rel=\"noreferrer\">Synopsis 12: Roles</a>.</p>\n\n<p>The rules are the same, but the \"but\" copies the 0 and applies a role to the copy that causes it to be true in boolean context.</p>\n\n<p>You can do the same thing with overload in Perl 5.</p>\n" }, { "answer_id": 125861, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 4, "selected": false, "text": "<p>Perl 6 evaluates truth now by asking the object a question instead of looking at its value. The value is not the object. It's something I've liked about other object languages and will be glad to have in Perl: I get to decide how the object responds and can mutate that. As ysth said, you could do that in Perl 5 with overload, but I always feel like I have to wash my hands after doing it that way. :)</p>\n\n<p>If you don't do anything to change that, Perl 6 behaves in the same way as Perl 5 so you get the least amount of surprise.</p>\n" }, { "answer_id": 125881, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 4, "selected": false, "text": "<p>Truthness test just calls the <code>.true</code> method on an object, so the \"mix in\" operation <code>$stuff but True</code> just (among other things) overrides that method.</p>\n\n<p>This is specified in <a href=\"http://perlcabal.org/syn/S02.html#Context\" rel=\"noreferrer\">S02</a>, generally enum types (of which Bool is one) are described in <a href=\"http://perlcabal.org/syn/S12.html#Enums\" rel=\"noreferrer\">S12</a>.</p>\n" }, { "answer_id": 127522, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": 3, "selected": true, "text": "<p>So to combine what I think to be the best of everyone's answers:</p>\n\n<p>When you evaluate a variable in boolean context, its .true() method gets called. The default .true() method used by an object does a Perl 5-style &lt;0, \"\", undef> check of the object's value, but when you say \"but True\" or \"but False\", this method is overridden with one that doesn't look at the value just returns a constant. </p>\n\n<p>One could conceivable write a true() method which, say, returned true when the value was even and false when it was odd.</p>\n" }, { "answer_id": 23433786, "author": "kovacsbv", "author_id": 1106586, "author_profile": "https://Stackoverflow.com/users/1106586", "pm_score": 1, "selected": false, "text": "<p>One false value that gets neglected nearly everywhere is \"0\". I recently made this painful discovery that \"0\" is <strong>false</strong> in PERL 5. Gee. A non-empty string that's false. I was really hoping that would change in PERL6, but I guess not.</p>\n\n<pre><code>&gt; if ( \"0\" ) { say \"True\" } else { say \"False\" }\nFalse\n</code></pre>\n\n<p>The ||= idiom clobbered some strings I really wasn't expecting:</p>\n\n<pre><code>$ perl -e '$x = \"0\"; $x ||= \"\"; print \"&gt;&gt;$x&lt;&lt;\\n\";'\n&gt;&gt;&lt;&lt;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
In reading about Perl 6, I see a feature being trumpeted about, where you no longer have to do: ``` return "0 but true"; ``` ...but can instead do: ``` return 0 but True; ``` If that's the case, how does truth work in Perl 6? In Perl 5, it was pretty simple: 0, "", and undef are false, everything else is true. What are the rules in Perl 6 when it comes to boolean context?
So to combine what I think to be the best of everyone's answers: When you evaluate a variable in boolean context, its .true() method gets called. The default .true() method used by an object does a Perl 5-style <0, "", undef> check of the object's value, but when you say "but True" or "but False", this method is overridden with one that doesn't look at the value just returns a constant. One could conceivable write a true() method which, say, returned true when the value was even and false when it was odd.
125,268
<p>Is it possible to chain static methods together using a static class? Say I wanted to do something like this:</p> <pre><code>$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result(); </code></pre> <p>. . . and obviously I would want $value to be assigned the number 14. Is this possible?</p> <p><strong>Update</strong>: It doesn't work (you can't return "self" - it's not an instance!), but this is where my thoughts have taken me:</p> <pre><code>class TestClass { public static $currentValue; public static function toValue($value) { self::$currentValue = $value; } public static function add($value) { self::$currentValue = self::$currentValue + $value; return self; } public static function subtract($value) { self::$currentValue = self::$currentValue - $value; return self; } public static function result() { return self::$value; } } </code></pre> <p>After working that out, I think it would just make more sense to simply work with a class instance rather than trying to chain static function calls (which doesn't look possible, unless the above example could be tweaked somehow).</p>
[ { "answer_id": 125291, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 1, "selected": false, "text": "<p>In a nutshell... no. :) The resolution operator (::) would work for the TetsClass::toValue(5) part, but everything after that will just give a syntax error.</p>\n\n<p>Once namespaces are implemented in 5.3, you can have \"chained\" :: operators, but all that'll do is drill down through the namespace tree; it won't be possible to have methods in the middle of things like this.</p>\n" }, { "answer_id": 125299, "author": "jW.", "author_id": 8880, "author_profile": "https://Stackoverflow.com/users/8880", "pm_score": 0, "selected": false, "text": "<p>No, this won't work. The <code>::</code> operator needs to evaluate back to a class, so after the <code>TestClass::toValue(5)</code> evaluates, the <code>::add(3)</code> method would only be able to evaluate on the answer of the last one.</p>\n\n<p>So if <code>toValue(5)</code> returned the integer 5, you would basically be calling <code>int(5)::add(3)</code> which obviously is an error.</p>\n" }, { "answer_id": 125317, "author": "Camilo Díaz Repka", "author_id": 861, "author_profile": "https://Stackoverflow.com/users/861", "pm_score": 4, "selected": false, "text": "<p>If toValue(x) returns an object, you could do like this:</p>\n\n<pre><code>$value = TestClass::toValue(5)-&gt;add(3)-&gt;substract(2)-&gt;add(8);\n</code></pre>\n\n<p>Providing that toValue returns a new instance of the object, and each next method mutates it, returning an instance of $this.</p>\n" }, { "answer_id": 125388, "author": "Mathew Byrne", "author_id": 10942, "author_profile": "https://Stackoverflow.com/users/10942", "pm_score": 7, "selected": true, "text": "<p>I like the solution provided by Camilo above, essentially since all you're doing is altering the value of a static member, and since you do want chaining (even though it's only syntatic sugar), then instantiating TestClass is probably the best way to go.</p>\n\n<p>I'd suggest a Singleton pattern if you want to restrict instantiation of the class:</p>\n\n<pre><code>class TestClass\n{ \n public static $currentValue;\n\n private static $_instance = null;\n\n private function __construct () { }\n\n public static function getInstance ()\n {\n if (self::$_instance === null) {\n self::$_instance = new self;\n }\n\n return self::$_instance;\n }\n\n public function toValue($value) {\n self::$currentValue = $value;\n return $this;\n }\n\n public function add($value) {\n self::$currentValue = self::$currentValue + $value;\n return $this;\n }\n\n public function subtract($value) {\n self::$currentValue = self::$currentValue - $value;\n return $this;\n }\n\n public function result() {\n return self::$currentValue;\n }\n}\n\n// Example Usage:\n$result = TestClass::getInstance ()\n -&gt;toValue(5)\n -&gt;add(3)\n -&gt;subtract(2)\n -&gt;add(8)\n -&gt;result();\n</code></pre>\n" }, { "answer_id": 125433, "author": "Phobis", "author_id": 19854, "author_profile": "https://Stackoverflow.com/users/19854", "pm_score": 2, "selected": false, "text": "<p>You could always use the First method as a static and the remaining as instance methods:</p>\n\n<pre><code>$value = Math::toValue(5)-&gt;add(3)-&gt;subtract(2)-&gt;add(8)-&gt;result();\n</code></pre>\n\n<p>Or better yet:</p>\n\n<pre><code> $value = Math::eval(Math::value(5)-&gt;add(3)-&gt;subtract(2)-&gt;add(8));\n\nclass Math {\n public $operation;\n public $operationValue;\n public $args;\n public $allOperations = array();\n\n public function __construct($aOperation, $aValue, $theArgs)\n {\n $this-&gt;operation = $aOperation;\n $this-&gt;operationValue = $aValue;\n $this-&gt;args = $theArgs;\n }\n\n public static function eval($math) {\n if(strcasecmp(get_class($math), \"Math\") == 0){\n $newValue = $math-&gt;operationValue;\n foreach ($math-&gt;allOperations as $operationKey=&gt;$currentOperation) {\n switch($currentOperation-&gt;operation){\n case \"add\":\n $newvalue = $currentOperation-&gt;operationValue + $currentOperation-&gt;args;\n break;\n case \"subtract\":\n $newvalue = $currentOperation-&gt;operationValue - $currentOperation-&gt;args;\n break;\n }\n }\n return $newValue;\n }\n return null;\n }\n\n public function add($number){\n $math = new Math(\"add\", null, $number);\n $this-&gt;allOperations[count($this-&gt;allOperations)] &amp;= $math;\n return $this;\n }\n\n public function subtract($number){\n $math = new Math(\"subtract\", null, $number);\n $this-&gt;allOperations[count($this-&gt;allOperations)] &amp;= $math;\n return $this;\n }\n\n public static function value($number){\n return new Math(\"value\", $number, null);\n }\n }\n</code></pre>\n\n<p>Just an FYI.. I wrote this off the top of my head (right here on the site). So, it may not run, but that is the idea. I could have also did a recursive method call to eval, but I thought this may be simpler. Please let me know if you would like me to elaborate or provide any other help.</p>\n" }, { "answer_id": 11338446, "author": "sectus", "author_id": 1503018, "author_profile": "https://Stackoverflow.com/users/1503018", "pm_score": 5, "selected": false, "text": "<p>Little crazy code on php5.3... just for fun.</p>\n\n<pre><code>namespace chaining;\nclass chain\n {\n static public function one()\n {return get_called_class();}\n\n static public function two()\n {return get_called_class();}\n }\n\n${${${${chain::one()} = chain::two()}::one()}::two()}::one();\n</code></pre>\n" }, { "answer_id": 11907348, "author": "Ariful Islam", "author_id": 559483, "author_profile": "https://Stackoverflow.com/users/559483", "pm_score": 6, "selected": false, "text": "<pre><code>class oop{\n public static $val;\n\n public static function add($var){\n static::$val+=$var;\n return new static;\n }\n\n public static function sub($var){\n static::$val-=$var;\n return new static;\n }\n\n public static function out(){\n return static::$val;\n }\n\n public static function init($var){\n static::$val=$var;\n return new static; \n }\n}\n\necho oop::init(5)-&gt;add(2)-&gt;out();\n</code></pre>\n" }, { "answer_id": 18343691, "author": "jsdeveloper", "author_id": 1057013, "author_profile": "https://Stackoverflow.com/users/1057013", "pm_score": 1, "selected": false, "text": "<p><strong>The best that can be done</strong></p>\n\n<pre><code>class S\n{\n public static function __callStatic($name,$args)\n {\n echo 'called S::'.$name . '( )&lt;p&gt;';\n return '_t';\n }\n}\n\n$_t='S';\n${${S::X()}::F()}::C();\n</code></pre>\n" }, { "answer_id": 25623368, "author": "George G", "author_id": 3172092, "author_profile": "https://Stackoverflow.com/users/3172092", "pm_score": 3, "selected": false, "text": "<p>This is more accurate, easier, and read-friendly (allows code-completion)</p>\n\n<pre><code>class Calculator\n{ \n public static $value = 0;\n\n protected static $onlyInstance;\n\n protected function __construct () \n {\n // disable creation of public instances \n }\n\n protected static function getself()\n {\n if (static::$onlyInstance === null) \n {\n static::$onlyInstance = new Calculator;\n }\n\n return static::$onlyInstance;\n }\n\n /**\n * add to value\n * @param numeric $num \n * @return \\Calculator\n */\n public static function add($num) \n {\n static::$value += $num;\n return static::getself();\n }\n\n /**\n * substruct\n * @param string $num\n * @return \\Calculator\n */\n public static function subtract($num) \n {\n static::$value -= $num;\n return static::getself();\n }\n\n /**\n * multiple by\n * @param string $num\n * @return \\Calculator\n */\n public static function multiple($num) \n {\n static::$value *= $num;\n return static::getself();\n }\n\n /**\n * devide by\n * @param string $num\n * @return \\Calculator\n */\n public static function devide($num) \n {\n static::$value /= $num;\n return static::getself();\n }\n\n public static function result()\n {\n return static::$value;\n }\n}\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>echo Calculator::add(5)\n -&gt;subtract(2)\n -&gt;multiple(2.1)\n -&gt;devide(10)\n -&gt;result();\n</code></pre>\n\n<p><strong>result: 0.63</strong></p>\n" }, { "answer_id": 32343888, "author": "sectus", "author_id": 1503018, "author_profile": "https://Stackoverflow.com/users/1503018", "pm_score": 5, "selected": false, "text": "<p>With php7 you will be able to use desired syntax because of new <a href=\"https://wiki.php.net/rfc/uniform_variable_syntax\" rel=\"noreferrer\">Uniform Variable Syntax</a></p>\n\n<pre><code>&lt;?php\n\nabstract class TestClass {\n\n public static $currentValue;\n\n public static function toValue($value) {\n self::$currentValue = $value;\n return __CLASS__;\n }\n\n public static function add($value) {\n self::$currentValue = self::$currentValue + $value;\n return __CLASS__;\n }\n\n public static function subtract($value) {\n self::$currentValue = self::$currentValue - $value;\n return __CLASS__;\n }\n\n public static function result() {\n return self::$currentValue;\n }\n\n}\n\n$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();\necho $value;\n</code></pre>\n\n<p><a href=\"https://3v4l.org/XH42Y\" rel=\"noreferrer\">Demo</a></p>\n" }, { "answer_id": 44523323, "author": "Pratik Soni", "author_id": 3357538, "author_profile": "https://Stackoverflow.com/users/3357538", "pm_score": 0, "selected": false, "text": "<p>The most easiest way i have ever found for method chaining from new Instance or Static method of class is as below. I have used Late Static Binding here and i really loved this solution.</p>\n\n<p>I have created a utility to send multiple User Notification on next page using tostr in Laravel.</p>\n\n<pre><code>&lt;?php\n\nnamespace App\\Utils;\n\nuse Session;\n\nuse Illuminate\\Support\\HtmlString;\n\nclass Toaster\n{\n private static $options = [\n\n \"closeButton\" =&gt; false,\n\n \"debug\" =&gt; false,\n\n \"newestOnTop\" =&gt; false,\n\n \"progressBar\" =&gt; false,\n\n \"positionClass\" =&gt; \"toast-top-right\",\n\n \"preventDuplicates\" =&gt; false,\n\n \"onclick\" =&gt; null,\n\n \"showDuration\" =&gt; \"3000\",\n\n \"hideDuration\" =&gt; \"1000\",\n\n \"timeOut\" =&gt; \"5000\",\n\n \"extendedTimeOut\" =&gt; \"1000\",\n\n \"showEasing\" =&gt; \"swing\",\n\n \"hideEasing\" =&gt; \"linear\",\n\n \"showMethod\" =&gt; \"fadeIn\",\n\n \"hideMethod\" =&gt; \"fadeOut\"\n ];\n\n private static $toastType = \"success\";\n\n private static $instance;\n\n private static $title;\n\n private static $message;\n\n private static $toastTypes = [\"success\", \"info\", \"warning\", \"error\"];\n\n public function __construct($options = [])\n {\n self::$options = array_merge(self::$options, $options);\n }\n\n public static function setOptions(array $options = [])\n {\n self::$options = array_merge(self::$options, $options);\n\n return self::getInstance();\n }\n\n public static function setOption($option, $value)\n {\n self::$options[$option] = $value;\n\n return self::getInstance();\n }\n\n private static function getInstance()\n {\n if(empty(self::$instance) || self::$instance === null)\n {\n self::setInstance();\n }\n\n return self::$instance;\n }\n\n private static function setInstance()\n {\n self::$instance = new static();\n }\n\n public static function __callStatic($method, $args)\n {\n if(in_array($method, self::$toastTypes))\n {\n self::$toastType = $method;\n\n return self::getInstance()-&gt;initToast($method, $args);\n }\n\n throw new \\Exception(\"Ohh my god. That toast doesn't exists.\");\n }\n\n public function __call($method, $args)\n {\n return self::__callStatic($method, $args);\n }\n\n private function initToast($method, $params=[])\n {\n if(count($params)==2)\n {\n self::$title = $params[0];\n\n self::$message = $params[1];\n }\n elseif(count($params)==1)\n {\n self::$title = ucfirst($method);\n\n self::$message = $params[0];\n }\n\n $toasters = [];\n\n if(Session::has('toasters'))\n {\n $toasters = Session::get('toasters');\n }\n\n $toast = [\n\n \"options\" =&gt; self::$options,\n\n \"type\" =&gt; self::$toastType,\n\n \"title\" =&gt; self::$title,\n\n \"message\" =&gt; self::$message\n ];\n\n $toasters[] = $toast;\n\n Session::forget('toasters');\n\n Session::put('toasters', $toasters);\n\n return $this;\n }\n\n public static function renderToasters()\n {\n $toasters = Session::get('toasters');\n\n $string = '';\n\n if(!empty($toasters))\n {\n $string .= '&lt;script type=\"application/javascript\"&gt;';\n\n $string .= \"$(function() {\\n\";\n\n foreach ($toasters as $toast)\n {\n $string .= \"\\n toastr.options = \" . json_encode($toast['options'], JSON_PRETTY_PRINT) . \";\";\n\n $string .= \"\\n toastr['{$toast['type']}']('{$toast['message']}', '{$toast['title']}');\";\n }\n\n $string .= \"\\n});\";\n\n $string .= '&lt;/script&gt;';\n }\n\n Session::forget('toasters');\n\n return new HtmlString($string);\n }\n}\n</code></pre>\n\n<p>This will work as below.</p>\n\n<pre><code>Toaster::success(\"Success Message\", \"Success Title\")\n\n -&gt;setOption('showDuration', 5000)\n\n -&gt;warning(\"Warning Message\", \"Warning Title\")\n\n -&gt;error(\"Error Message\");\n</code></pre>\n" }, { "answer_id": 49113525, "author": "Evehne", "author_id": 9021574, "author_profile": "https://Stackoverflow.com/users/9021574", "pm_score": -1, "selected": false, "text": "<p>Use PHP 7! If your web provider cannot --> change provider! Don't lock in past.</p>\n\n<pre><code>final class TestClass {\n public static $currentValue;\n\n public static function toValue($value) {\n self::$currentValue = $value;\n return __CLASS__;\n }\n\n public static function add($value) {\n self::$currentValue = self::$currentValue + $value;\n return __CLASS__;\n }\n\n public static function subtract($value) {\n self::$currentValue = self::$currentValue - $value;\n return __CLASS__;\n }\n\n public static function result() {\n return self::$currentValue;\n }\n}\n</code></pre>\n\n<p><a href=\"https://3v4l.org/iipko\" rel=\"nofollow noreferrer\">And very simple use:</a></p>\n\n<pre><code>$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();\n\nvar_dump($value);\n</code></pre>\n\n<p>Return (or throw error):</p>\n\n<pre><code>int(14)\n</code></pre>\n\n<p><strong>completed contract.</strong></p>\n\n<p>Rule one: most evolved and maintainable is always better. </p>\n" }, { "answer_id": 52912172, "author": "sanmai", "author_id": 93540, "author_profile": "https://Stackoverflow.com/users/93540", "pm_score": 2, "selected": false, "text": "<p>Technically you can call a static method on an instance like <code>$object::method()</code> in PHP 7+, so returning a new instance should work as a replacement for <code>return self</code>. <a href=\"https://3v4l.org/BspcC\" rel=\"nofollow noreferrer\">And indeed it works.</a></p>\n\n<pre><code>final class TestClass {\n public static $currentValue;\n\n public static function toValue($value) {\n self::$currentValue = $value;\n return new static();\n }\n\n public static function add($value) {\n self::$currentValue = self::$currentValue + $value;\n return new static();\n }\n\n public static function subtract($value) {\n self::$currentValue = self::$currentValue - $value;\n return new static();\n }\n\n public static function result() {\n return self::$currentValue;\n }\n}\n\n$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();\n\nvar_dump($value);\n</code></pre>\n\n<p>Outputs <code>int(14)</code>. </p>\n\n<p>This about same as returning <code>__CLASS__</code> as used <a href=\"https://stackoverflow.com/a/49113525/93540\">in other answer</a>. I rather hope no-one ever decides to actually use these forms of API, but you asked for it.</p>\n" }, { "answer_id": 54139898, "author": "boctulus", "author_id": 980631, "author_profile": "https://Stackoverflow.com/users/980631", "pm_score": 0, "selected": false, "text": "<p>Fully functional example of method chaining with static attributes:</p>\n\n<pre><code>&lt;?php\n\n\nclass Response\n{\n static protected $headers = [];\n static protected $http_code = 200;\n static protected $http_code_msg = '';\n static protected $instance = NULL;\n\n\n protected function __construct() { }\n\n static function getInstance(){\n if(static::$instance == NULL){\n static::$instance = new static();\n }\n return static::$instance;\n }\n\n public function addHeaders(array $headers)\n {\n static::$headers = $headers;\n return static::getInstance();\n }\n\n public function addHeader(string $header)\n {\n static::$headers[] = $header;\n return static::getInstance();\n }\n\n public function code(int $http_code, string $msg = NULL)\n {\n static::$http_code_msg = $msg;\n static::$http_code = $http_code;\n return static::getInstance();\n }\n\n public function send($data, int $http_code = NULL){\n $http_code = $http_code != NULL ? $http_code : static::$http_code;\n\n if ($http_code != NULL)\n header(trim(\"HTTP/1.0 \".$http_code.' '.static::$http_code_msg));\n\n if (is_array($data) || is_object($data))\n $data = json_encode($data);\n\n echo $data; \n exit(); \n }\n\n function sendError(string $msg_error, int $http_code = null){\n $this-&gt;send(['error' =&gt; $msg_error], $http_code);\n }\n}\n</code></pre>\n\n<p>Example of use:</p>\n\n<pre><code>Response::getInstance()-&gt;code(400)-&gt;sendError(\"Lacks id in request\");\n</code></pre>\n" }, { "answer_id": 59297989, "author": "kdion4891", "author_id": 11962169, "author_profile": "https://Stackoverflow.com/users/11962169", "pm_score": 3, "selected": false, "text": "<p>People are overcomplicating this like crazy.</p>\n\n<p>Check this out:</p>\n\n<pre><code>class OopClass\n{\n public $first;\n public $second;\n public $third;\n\n public static function make($first)\n {\n return new OopClass($first);\n }\n\n public function __construct($first)\n {\n $this-&gt;first = $first;\n }\n\n public function second($second)\n {\n $this-&gt;second = $second;\n return $this;\n }\n\n public function third($third)\n {\n $this-&gt;third = $third;\n return $this;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>OopClass::make('Hello')-&gt;second('To')-&gt;third('World');\n</code></pre>\n" }, { "answer_id": 64444897, "author": "Dan", "author_id": 6394404, "author_profile": "https://Stackoverflow.com/users/6394404", "pm_score": 0, "selected": false, "text": "<p>Here's another way without going through a <code>getInstance</code> method (tested on PHP 7.x):</p>\n<pre class=\"lang-php prettyprint-override\"><code>class TestClass\n{\n private $result = 0;\n\n public function __call($method, $args)\n {\n return $this-&gt;call($method, $args);\n }\n\n public static function __callStatic($method, $args)\n {\n return (new static())-&gt;call($method, $args);\n }\n\n private function call($method, $args)\n {\n if (! method_exists($this , '_' . $method)) {\n throw new Exception('Call undefined method ' . $method);\n }\n\n return $this-&gt;{'_' . $method}(...$args);\n }\n\n private function _add($num)\n {\n $this-&gt;result += $num;\n\n return $this;\n }\n\n private function _subtract($num)\n {\n $this-&gt;result -= $num;\n\n return $this;\n }\n\n public function result()\n {\n return $this-&gt;result;\n }\n}\n</code></pre>\n<p>The class can be used as following:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$res1 = TestClass::add(5)\n -&gt;add(3)\n -&gt;subtract(2)\n -&gt;add(8)\n -&gt;result();\n\necho $res1 . PHP_EOL; // 14\n\n$res2 = TestClass::subtract(1)-&gt;add(10)-&gt;result();\necho $res2 . PHP_EOL; // 9\n</code></pre>\n" }, { "answer_id": 71172373, "author": "Samir Mammadhasanov", "author_id": 11387497, "author_profile": "https://Stackoverflow.com/users/11387497", "pm_score": 0, "selected": false, "text": "<p>Also works as:</p>\n<pre><code>ExampleClass::withBanners()-&gt;withoutTranslations()-&gt;collection($values)\n</code></pre>\n<p>Using <code>new static(self::class);</code></p>\n<pre><code>public static function withoutTranslations(): self\n{\n self::$withoutTranslations = true;\n \n return new static(self::class);\n}\n\npublic static function withBanners(): self\n{\n return new static(self::class);\n}\n\npublic static function collection(values): self\n{\n return $values;\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
Is it possible to chain static methods together using a static class? Say I wanted to do something like this: ``` $value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result(); ``` . . . and obviously I would want $value to be assigned the number 14. Is this possible? **Update**: It doesn't work (you can't return "self" - it's not an instance!), but this is where my thoughts have taken me: ``` class TestClass { public static $currentValue; public static function toValue($value) { self::$currentValue = $value; } public static function add($value) { self::$currentValue = self::$currentValue + $value; return self; } public static function subtract($value) { self::$currentValue = self::$currentValue - $value; return self; } public static function result() { return self::$value; } } ``` After working that out, I think it would just make more sense to simply work with a class instance rather than trying to chain static function calls (which doesn't look possible, unless the above example could be tweaked somehow).
I like the solution provided by Camilo above, essentially since all you're doing is altering the value of a static member, and since you do want chaining (even though it's only syntatic sugar), then instantiating TestClass is probably the best way to go. I'd suggest a Singleton pattern if you want to restrict instantiation of the class: ``` class TestClass { public static $currentValue; private static $_instance = null; private function __construct () { } public static function getInstance () { if (self::$_instance === null) { self::$_instance = new self; } return self::$_instance; } public function toValue($value) { self::$currentValue = $value; return $this; } public function add($value) { self::$currentValue = self::$currentValue + $value; return $this; } public function subtract($value) { self::$currentValue = self::$currentValue - $value; return $this; } public function result() { return self::$currentValue; } } // Example Usage: $result = TestClass::getInstance () ->toValue(5) ->add(3) ->subtract(2) ->add(8) ->result(); ```
125,272
<p>I'm relatively new to Mercurial and my team is trying it out right now as a replacement for Subversion. </p> <p>How can I commit and push a single file out to another repository while leaving other modifications in my working directory uncommitted (or at least not pushed to the other repository)?</p> <p>This happens for us with database migrations. We want to commit the migration to source control so a DBA can view and edit it while we're working on the code modifications to go along with that database migration. The changes aren't yet ready to go so we don't want to push all of them out.</p> <p>In subversion, I'd simply do:</p> <pre><code>svn add my_migration.sql # commit only the migration, but not the other files I'm working on svn commit -m "migration notes" my_mygration.sql </code></pre> <p>and continue working locally.</p> <p>This doesn't work with mercurial as when I'm pushing it out to the other repository, if there are changes to it that I haven't pulled down, it wants me to pull them down, merge them, and commit that merge to the repository. Commits after a merge don't allow you to omit files so it forces you to commit everything in your local repository.</p> <p>The easiest thing that I can figure out is to commit the file to my local repository, clone my local repository, fetch any new changes from the actual repository, merge them and commit that merge, and them push my changes out.</p> <pre><code>hg add my_migration.sql hg commit -m "migration notes" my_migration.sql cd .. hg clone project project-clone cd project-clone hg fetch http://hg/project hg push http://hg/project </code></pre> <p>This works, but it feels like I'm missing something easier, some way to tell mercurial to ignore the files already in my working directory, just do the merge and send the files along. I suspect mercurial queues can do this, but I don't fully grok mq yet.</p>
[ { "answer_id": 125301, "author": "Josh Matthews", "author_id": 3830, "author_profile": "https://Stackoverflow.com/users/3830", "pm_score": 6, "selected": true, "text": "<p>There's a Mercurial feature that implements shelve and unshelve commands, which give you an interactive way to specify changes to store away until a later time: <a href=\"http://www.selenic.com/mercurial/wiki/index.cgi/ShelveExtension\" rel=\"nofollow noreferrer\">Shelve</a>.</p>\n\n<p>Then you can <code>hg shelve</code> and <code>hg unshelve</code> to temporarily store changes away. It lets you work at the \"patch hunk\" level to pick and choose the items to shelve away. It didn't appear to shelve a file had listed for adding, only files already in the repo with modifications.</p>\n\n<p>It is included with Mercurial as an \"extension\" which just means you have to enable it in your hg config file.</p>\n\n<hr>\n\n<p>Notes for really old versions of Mercurial (before shelve was included -- this is no longer necessary):</p>\n\n<p>I didn't see any great install instructions with some googling, so here is the combined stuff I used to get it working:</p>\n\n<p>Get it with:</p>\n\n<pre><code>hg clone http://freehg.org/u/tksoh/hgshelve/ hgshelve\n</code></pre>\n\n<p>The only file (currently) in the project is the hgshelve.py file.</p>\n\n<p>Modify your ~/.hgrc to add the shelve extension, pointing to where you cloned the repo:</p>\n\n<pre><code>[extensions] \nhgshelve=/Users/ted/Documents/workspace/hgshelve/hgshelve.py\n</code></pre>\n" }, { "answer_id": 189835, "author": "Derek Slager", "author_id": 18636, "author_profile": "https://Stackoverflow.com/users/18636", "pm_score": 2, "selected": false, "text": "<p>Another option if you don't want to rely on extensions is to keep a clone of your upstream repository locally that you only use for these sorts of integration tasks.</p>\n\n<p>In your example, you could simply pull/merge your change into the integration/upstream repository and push it directly up to the remote server.</p>\n" }, { "answer_id": 569429, "author": "Kobold", "author_id": 36092, "author_profile": "https://Stackoverflow.com/users/36092", "pm_score": 3, "selected": false, "text": "<p>tl;dr: My original explanation looks complicated, but I hope it fully explains how to use a patch queue. Here's the short version:</p>\n\n<pre><code>$ hg qnew -m \"migration notes\" -f migration my_migration.sql\n$ hg qnew -f working-code\n# make some changes to your code\n$ hg qrefresh # update the patch with the changes you just made\n$ hg qfinish -a # turn all the applied patches into normal hg commits\n</code></pre>\n\n<hr>\n\n<p>Mercurial Queues makes this sort of thing a breeze, and it makes more complex manipulation of changesets possible. It's worth learning.</p>\n\n<p>In this situation first you'd probably want to save what's in your current directory before pulling down the changes:</p>\n\n<pre><code># create a patch called migration containing your migration\n$ hg qnew -m \"migration notes\" -f migration.patch my_migration.sql\n$ hg qseries -v # the current state of the patch queue, A means applied\n0 A migration.patch\n$ hg qnew -f working-code.patch # put the rest of the code in a patch\n$ hg qseries -v\n0 A migration.patch\n1 A working-code.patch\n</code></pre>\n\n<p>Now let's do some additional work on the working code. I'm going to keep doing <code>qseries</code> just to be explicit, but once you build up a mental model of patch queues, you won't have to keep looking at the list.</p>\n\n<pre><code>$ hg qtop # show the patch we're currently editing\nworking-code.patch\n$ ...hack, hack, hack...\n$ hg diff # show the changes that have not been incorporated into the patch\nblah, blah\n$ hg qrefresh # update the patch with the changes you just made\n$ hg qdiff # show the top patch's diff\n</code></pre>\n\n<p>Because all your work is saved in the patch queue now, you can unapply those changes and restore them after you've pulled in the remote changes. Normally to unapply all patches, just do <code>hg qpop -a</code>. Just to show the effect upon the patch queue I'll pop them off one at a time.</p>\n\n<pre><code>$ hg qpop # unapply the top patch, U means unapplied\n$ hg qseries -v\n0 A migration.patch\n1 U working-code.patch\n$ hg qtop\nmigration.patch\n$ hg qpop\n$ hg qseries -v\n0 U migration.patch\n1 U working-code.patch\n</code></pre>\n\n<p>At this point, it's as if there are no changes in your directory. Do the <code>hg fetch</code>. Now you can push your patch queue changes back on, and merge them if there are any conflicts. This is conceptually somewhat similar to git's rebase.</p>\n\n<pre><code>$ hg qpush # put the first patch back on\n$ hg qseries -v\n0 A migration.patch\n1 U working-code.patch\n$ hg qfinish -a # turn all the applied patches into normal hg commits\n$ hg qseries -v\n0 U working-code.patch\n$ hg out\nmigration.patch commit info... blah, blah\n$ hg push # push out your changes\n</code></pre>\n\n<p>At this point, you've pushed out the migration while keeping your other local changes. Your other changes are in an patch in the queue. I do most of my personal development using a patch queue to help me structure my changes better. If you want to get rid of the patch queue and go back to a normal style you'll have to export your changes and reimport them in \"normal\" mercurial.</p>\n\n<pre><code>$ hg qpush\n$ hg qseries -v\n0 A working-code.patch\n$ hg export qtip &gt; temp.diff\n$ rm -r .hg/patches # get rid of mq from the repository entirely\n$ hg import --no-commit temp.diff # apply the changes to the working directory\n$ rm temp.diff\n</code></pre>\n\n<hr>\n\n<p>I'm hugely addicted to patch queues for development and <code>mq</code> is one of the nicest implementations out there. The ability to craft several changes simultaneously really does improve how focused and clean your commits are. It takes a while to get used to, but it goes incredibly well with a DVCS workflow.</p>\n" }, { "answer_id": 3239782, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 5, "selected": false, "text": "<p>It's been almost 2 years since I originally posed this question. I'd do it differently now (as I mentioned in a comment above the question above). What I'd do now would be to instead commit my changes to the one file in my local repo (you can use the hg record extension to only commit pieces of a file):</p>\n\n<pre><code>hg commit -m \"commit message\" filename\n</code></pre>\n\n<p>Then just push out.</p>\n\n<pre><code>hg push\n</code></pre>\n\n<p>If there's a conflict because other changes have been made to the repo that I need to merge first, I'd update to the parent revision (seen with \"hg parents -r .\" if you don't know what it is), commit my other changes there so I've got 2 heads. Then revert back to the original single file commit and pull/merge the changes into that version. Then push out the changes with</p>\n\n<pre><code>hg push --rev .\n</code></pre>\n\n<p>To push out only the single file and the merge of that revision. Then you can merge the two heads you've got locally.</p>\n\n<p>This way gets rid of the mq stuff and the potential for rejected hunks and keeps everything tracked by source control. You can also \"hg strip\" revisions off if you later decide you don't want them.</p>\n" }, { "answer_id": 28309560, "author": "Shweta", "author_id": 2242019, "author_profile": "https://Stackoverflow.com/users/2242019", "pm_score": 2, "selected": false, "text": "<p>What i use generally is use to commit a single file : </p>\n\n<pre><code> hg commit -m \"commit message\" filename\n</code></pre>\n\n<p>In case later, I have a merge conflict and I am still not ready to commit my changes,follow these steps:</p>\n\n<p>1) Create a patch file.</p>\n\n<pre><code>hg diff &gt; changes.patch\n</code></pre>\n\n<p>2) Revert all your outstanding uncommitted changes, only after checking your patch file.</p>\n\n<pre><code>hg revert --all\n</code></pre>\n\n<p>3) Pull,update and merge to latest revision </p>\n\n<pre><code>hg pull -u\nhg merge\nhg commit -m \"local merge\"\n</code></pre>\n\n<p>4) Now simply import your patch back and get your changes.</p>\n\n<pre><code>hg import --no-commit changes.patch\n</code></pre>\n\n<p>Remember to use -no-commit flag from auto committing the changes. </p>\n" }, { "answer_id": 47931757, "author": "studgeek", "author_id": 255961, "author_profile": "https://Stackoverflow.com/users/255961", "pm_score": 1, "selected": false, "text": "<p>Since you said easiest, I often use <code>hg commit -i</code> (--interactive) even when committing whole files. With <code>--interactive</code> you can just select the file(s) you want rather than typing their entire path(s) on the command line. As an added bonus you can even selectively include/exclude chunks within the files.</p>\n\n<p>And then just <code>hg push</code> to push that newly created commit.</p>\n\n<p>I put more details on using <code>hg commit --interactive</code> in this answer: <a href=\"https://stackoverflow.com/a/47931672/255961\">https://stackoverflow.com/a/47931672/255961</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8912/" ]
I'm relatively new to Mercurial and my team is trying it out right now as a replacement for Subversion. How can I commit and push a single file out to another repository while leaving other modifications in my working directory uncommitted (or at least not pushed to the other repository)? This happens for us with database migrations. We want to commit the migration to source control so a DBA can view and edit it while we're working on the code modifications to go along with that database migration. The changes aren't yet ready to go so we don't want to push all of them out. In subversion, I'd simply do: ``` svn add my_migration.sql # commit only the migration, but not the other files I'm working on svn commit -m "migration notes" my_mygration.sql ``` and continue working locally. This doesn't work with mercurial as when I'm pushing it out to the other repository, if there are changes to it that I haven't pulled down, it wants me to pull them down, merge them, and commit that merge to the repository. Commits after a merge don't allow you to omit files so it forces you to commit everything in your local repository. The easiest thing that I can figure out is to commit the file to my local repository, clone my local repository, fetch any new changes from the actual repository, merge them and commit that merge, and them push my changes out. ``` hg add my_migration.sql hg commit -m "migration notes" my_migration.sql cd .. hg clone project project-clone cd project-clone hg fetch http://hg/project hg push http://hg/project ``` This works, but it feels like I'm missing something easier, some way to tell mercurial to ignore the files already in my working directory, just do the merge and send the files along. I suspect mercurial queues can do this, but I don't fully grok mq yet.
There's a Mercurial feature that implements shelve and unshelve commands, which give you an interactive way to specify changes to store away until a later time: [Shelve](http://www.selenic.com/mercurial/wiki/index.cgi/ShelveExtension). Then you can `hg shelve` and `hg unshelve` to temporarily store changes away. It lets you work at the "patch hunk" level to pick and choose the items to shelve away. It didn't appear to shelve a file had listed for adding, only files already in the repo with modifications. It is included with Mercurial as an "extension" which just means you have to enable it in your hg config file. --- Notes for really old versions of Mercurial (before shelve was included -- this is no longer necessary): I didn't see any great install instructions with some googling, so here is the combined stuff I used to get it working: Get it with: ``` hg clone http://freehg.org/u/tksoh/hgshelve/ hgshelve ``` The only file (currently) in the project is the hgshelve.py file. Modify your ~/.hgrc to add the shelve extension, pointing to where you cloned the repo: ``` [extensions] hgshelve=/Users/ted/Documents/workspace/hgshelve/hgshelve.py ```
125,281
<p>Given a string file path such as <code>/foo/fizzbuzz.bar</code>, how would I use bash to extract just the <code>fizzbuzz</code> portion of said string?</p>
[ { "answer_id": 125287, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 8, "selected": false, "text": "<p>look at the basename command:</p>\n<pre><code>NAME=&quot;$(basename /foo/fizzbuzz.bar .bar)&quot;\n</code></pre>\n<p>instructs it to remove the suffix <code>.bar</code>, results in <code>NAME=fizzbuzz</code></p>\n" }, { "answer_id": 125292, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<p>Pure bash way:</p>\n\n<pre><code>~$ x=\"/foo/bar/fizzbuzz.bar.quux.zoom\"; \n~$ y=${x/\\/*\\//}; \n~$ echo ${y/.*/}; \nfizzbuzz\n</code></pre>\n\n<p>This functionality is explained on man bash under \"Parameter Expansion\". Non bash ways abound: awk, perl, sed and so on.</p>\n\n<p>EDIT: Works with dots in file <em>suffixes</em> and doesn't need to know the suffix (extension), but <em>doesn’t</em> work with dots in the <em>name</em> itself.</p>\n" }, { "answer_id": 125294, "author": "mopoke", "author_id": 14054, "author_profile": "https://Stackoverflow.com/users/14054", "pm_score": 2, "selected": false, "text": "<pre><code>perl -pe 's/\\..*$//;s{^.*/}{}'\n</code></pre>\n" }, { "answer_id": 125298, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "<p>The basename and dirname functions are what you're after:</p>\n\n<pre><code>mystring=/foo/fizzbuzz.bar\necho basename: $(basename \"${mystring}\")\necho basename + remove .bar: $(basename \"${mystring}\" .bar)\necho dirname: $(dirname \"${mystring}\")\n</code></pre>\n\n<p>Has output:</p>\n\n<pre><code>basename: fizzbuzz.bar\nbasename + remove .bar: fizzbuzz\ndirname: /foo\n</code></pre>\n" }, { "answer_id": 125340, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 10, "selected": true, "text": "<p>Here's how to do it with the # and % operators in Bash.</p>\n\n<pre><code>$ x=\"/foo/fizzbuzz.bar\"\n$ y=${x%.bar}\n$ echo ${y##*/}\nfizzbuzz\n</code></pre>\n\n<p><code>${x%.bar}</code> could also be <code>${x%.*}</code> to remove everything after a dot or <code>${x%%.*}</code> to remove everything after the first dot.</p>\n\n<p>Example:</p>\n\n<pre><code>$ x=\"/foo/fizzbuzz.bar.quux\"\n$ y=${x%.*}\n$ echo $y\n/foo/fizzbuzz.bar\n$ y=${x%%.*}\n$ echo $y\n/foo/fizzbuzz\n</code></pre>\n\n<p>Documentation can be found in the <a href=\"https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion\" rel=\"noreferrer\">Bash manual</a>. Look for <code>${parameter%word}</code> and <code>${parameter%%word}</code> trailing portion matching section.</p>\n" }, { "answer_id": 125511, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 3, "selected": false, "text": "<p>Using <code>basename</code> assumes that you know what the file extension is, doesn't it?</p>\n\n<p>And I believe that the various regular expression suggestions don't cope with a filename containing more than one \".\"</p>\n\n<p>The following seems to cope with double dots. Oh, and filenames that contain a \"/\" themselves (just for kicks)</p>\n\n<p>To paraphrase Pascal, \"Sorry this script is so long. I didn't have time to make it shorter\"</p>\n\n<pre><code>\n #!/usr/bin/perl\n $fullname = $ARGV[0];\n ($path,$name) = $fullname =~ /^(.*[^\\\\]\\/)*(.*)$/;\n ($basename,$extension) = $name =~ /^(.*)(\\.[^.]*)$/;\n print $basename . \"\\n\";\n</code> </pre>\n" }, { "answer_id": 126534, "author": "nymacro", "author_id": 10499, "author_profile": "https://Stackoverflow.com/users/10499", "pm_score": 2, "selected": false, "text": "<p>If you can't use basename as suggested in other posts, you can always use sed. Here is an (ugly) example. It isn't the greatest, but it works by extracting the wanted string and replacing the input with the wanted string.</p>\n\n<pre><code>echo '/foo/fizzbuzz.bar' | sed 's|.*\\/\\([^\\.]*\\)\\(\\..*\\)$|\\1|g'\n</code></pre>\n\n<p>Which will get you the output</p>\n\n<blockquote>\n <blockquote>\n <p>fizzbuzz</p>\n </blockquote>\n</blockquote>\n" }, { "answer_id": 291905, "author": "waynecolvin", "author_id": 35658, "author_profile": "https://Stackoverflow.com/users/35658", "pm_score": 1, "selected": false, "text": "<p>The basename does that, removes the path. It will also remove the suffix if given and if it matches the suffix of the file but you would need to know the suffix to give to the command. Otherwise you can use mv and figure out what the new name should be some other way.</p>\n" }, { "answer_id": 3075186, "author": "mivk", "author_id": 111036, "author_profile": "https://Stackoverflow.com/users/111036", "pm_score": 2, "selected": false, "text": "<p>Beware of the suggested perl solution: it removes anything after the first dot.</p>\n\n<pre><code>$ echo some.file.with.dots | perl -pe 's/\\..*$//;s{^.*/}{}'\nsome\n</code></pre>\n\n<p>If you want to do it with perl, this works:</p>\n\n<pre><code>$ echo some.file.with.dots | perl -pe 's/(.*)\\..*$/$1/;s{^.*/}{}'\nsome.file.with\n</code></pre>\n\n<p>But if you are using Bash, the solutions with <code>y=${x%.*}</code> (or <code>basename \"$x\" .ext</code> if you know the extension) are much simpler.</p>\n" }, { "answer_id": 23018588, "author": "mike", "author_id": 3524685, "author_profile": "https://Stackoverflow.com/users/3524685", "pm_score": 4, "selected": false, "text": "<p>Using basename I used the following to achieve this:</p>\n\n<pre><code>for file in *; do\n ext=${file##*.}\n fname=`basename $file $ext`\n\n # Do things with $fname\ndone;\n</code></pre>\n\n<p>This requires no a priori knowledge of the file extension and works even when you have a filename that has dots in it's filename (in front of it's extension); it does require the program <code>basename</code> though, but this is part of the GNU coreutils so it should ship with any distro.</p>\n" }, { "answer_id": 23497364, "author": "Param", "author_id": 2034354, "author_profile": "https://Stackoverflow.com/users/2034354", "pm_score": 6, "selected": false, "text": "<p>Pure bash, done in two separate operations:</p>\n\n<ol>\n<li><p>Remove the path from a path-string:</p>\n\n<pre><code>path=/foo/bar/bim/baz/file.gif\n\nfile=${path##*/} \n#$file is now 'file.gif'\n</code></pre></li>\n<li><p>Remove the extension from a path-string:</p>\n\n<pre><code>base=${file%.*}\n#${base} is now 'file'.\n</code></pre></li>\n</ol>\n" }, { "answer_id": 25411974, "author": "c.gutierrez", "author_id": 1546381, "author_profile": "https://Stackoverflow.com/users/1546381", "pm_score": 1, "selected": false, "text": "<p>Combining the top-rated answer with the second-top-rated answer to get the filename without the full path: </p>\n\n<pre><code>$ x=\"/foo/fizzbuzz.bar.quux\"\n$ y=(`basename ${x%%.*}`)\n$ echo $y\nfizzbuzz\n</code></pre>\n" }, { "answer_id": 52978500, "author": "Benjamin W.", "author_id": 3266847, "author_profile": "https://Stackoverflow.com/users/3266847", "pm_score": 3, "selected": false, "text": "<p>In addition to the <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/utilities/basename.html\" rel=\"nofollow noreferrer\">POSIX conformant syntax</a> used in <a href=\"https://stackoverflow.com/a/125287/3266847\">this answer</a>,</p>\n\n<pre><code>basename <i>string</i> [<i>suffix</i>]</code></pre>\n\n<p>as in</p>\n\n<pre><code>basename /foo/fizzbuzz.bar .bar\n</code></pre>\n\n<p><a href=\"https://www.gnu.org/software/coreutils/manual/coreutils.html#basename-invocation\" rel=\"nofollow noreferrer\">GNU <code>basename</code></a> supports another syntax:</p>\n\n<pre><code>basename -s .bar /foo/fizzbuzz.bar\n</code></pre>\n\n<p>with the same result. The difference and advantage is that <code>-s</code> implies <code>-a</code>, which supports multiple arguments:</p>\n\n<pre><code>$ basename -s .bar /foo/fizzbuzz.bar /baz/foobar.bar\nfizzbuzz\nfoobar\n</code></pre>\n\n<p>This can even be made filename-safe by separating the output with NUL bytes using the <code>-z</code> option, for example for these files containing blanks, newlines and glob characters (quoted by <code>ls</code>):</p>\n\n<pre><code>$ ls has*\n'has'$'\\n''newline.bar' 'has space.bar' 'has*.bar'\n</code></pre>\n\n<p>Reading into an array:</p>\n\n<pre><code>$ readarray -d $'\\0' arr &lt; &lt;(basename -zs .bar has*)\n$ declare -p arr\ndeclare -a arr=([0]=$'has\\nnewline' [1]=\"has space\" [2]=\"has*\")\n</code></pre>\n\n<p><code>readarray -d</code> requires Bash 4.4 or newer. For older versions, we have to loop:</p>\n\n<pre><code>while IFS= read -r -d '' fname; do arr+=(\"$fname\"); done &lt; &lt;(basename -zs .bar has*)\n</code></pre>\n" }, { "answer_id": 68437453, "author": "sblive", "author_id": 14295103, "author_profile": "https://Stackoverflow.com/users/14295103", "pm_score": -1, "selected": false, "text": "<p>You can use</p>\n<pre><code>mv *&lt;PATTERN&gt;.jar &quot;$(basename *&lt;PATTERN&gt;.jar &lt;PATTERN&gt;.jar).jar&quot;\n</code></pre>\n<p>For e.g:- I wanted to remove <code>-SNAPSHOT</code> from my file name. For that used below command</p>\n<pre><code> mv *-SNAPSHOT.jar &quot;$(basename *-SNAPSHOT.jar -SNAPSHOT.jar).jar&quot;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
Given a string file path such as `/foo/fizzbuzz.bar`, how would I use bash to extract just the `fizzbuzz` portion of said string?
Here's how to do it with the # and % operators in Bash. ``` $ x="/foo/fizzbuzz.bar" $ y=${x%.bar} $ echo ${y##*/} fizzbuzz ``` `${x%.bar}` could also be `${x%.*}` to remove everything after a dot or `${x%%.*}` to remove everything after the first dot. Example: ``` $ x="/foo/fizzbuzz.bar.quux" $ y=${x%.*} $ echo $y /foo/fizzbuzz.bar $ y=${x%%.*} $ echo $y /foo/fizzbuzz ``` Documentation can be found in the [Bash manual](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion). Look for `${parameter%word}` and `${parameter%%word}` trailing portion matching section.
125,306
<p>I'm writing an iPhone app that takes a photo and then uploads it to a server. How do I upload a photo to a server with Cocoa? I suppose I use NSUrl somewhere.</p> <p>Thanks!</p>
[ { "answer_id": 136452, "author": "user19087", "author_id": 19087, "author_profile": "https://Stackoverflow.com/users/19087", "pm_score": 2, "selected": false, "text": "<p>Create an NSURLRequest and then use NSURLConnection to send it off to your server.</p>\n" }, { "answer_id": 136516, "author": "Jon Gilkison", "author_id": 22428, "author_profile": "https://Stackoverflow.com/users/22428", "pm_score": 6, "selected": false, "text": "<p>Header:</p>\n\n<pre><code>@interface EPUploader : NSObject {\n NSURL *serverURL;\n NSString *filePath;\n id delegate;\n SEL doneSelector;\n SEL errorSelector;\n\n BOOL uploadDidSucceed;\n}\n\n- (id)initWithURL: (NSURL *)serverURL \n filePath: (NSString *)filePath \n delegate: (id)delegate \n doneSelector: (SEL)doneSelector \n errorSelector: (SEL)errorSelector;\n\n- (NSString *)filePath;\n\n@end\n</code></pre>\n\n<p>Main:</p>\n\n<pre><code>#import \"EPUploader.h\"\n#import &lt;zlib.h&gt;\n\nstatic NSString * const BOUNDRY = @\"0xKhTmLbOuNdArY\";\nstatic NSString * const FORM_FLE_INPUT = @\"uploaded\";\n\n#define ASSERT(x) NSAssert(x, @\"\")\n\n@interface EPUploader (Private)\n\n- (void)upload;\n- (NSURLRequest *)postRequestWithURL: (NSURL *)url\n boundry: (NSString *)boundry\n data: (NSData *)data;\n\n- (NSData *)compress: (NSData *)data;\n- (void)uploadSucceeded: (BOOL)success;\n- (void)connectionDidFinishLoading:(NSURLConnection *)connection;\n\n@end\n\n@implementation EPUploader\n\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader initWithURL:filePath:delegate:doneSelector:errorSelector:] --\n *\n * Initializer. Kicks off the upload. Note that upload will happen on a\n * separate thread.\n *\n * Results:\n * An instance of Uploader.\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (id)initWithURL: (NSURL *)aServerURL // IN\n filePath: (NSString *)aFilePath // IN\n delegate: (id)aDelegate // IN\n doneSelector: (SEL)aDoneSelector // IN\n errorSelector: (SEL)anErrorSelector // IN\n{\n if ((self = [super init])) {\n ASSERT(aServerURL);\n ASSERT(aFilePath);\n ASSERT(aDelegate);\n ASSERT(aDoneSelector);\n ASSERT(anErrorSelector);\n\n serverURL = [aServerURL retain];\n filePath = [aFilePath retain];\n delegate = [aDelegate retain];\n doneSelector = aDoneSelector;\n errorSelector = anErrorSelector;\n\n [self upload];\n }\n return self;\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader dealloc] --\n *\n * Destructor.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)dealloc\n{\n [serverURL release];\n serverURL = nil;\n [filePath release];\n filePath = nil;\n [delegate release];\n delegate = nil;\n doneSelector = NULL;\n errorSelector = NULL;\n\n [super dealloc];\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader filePath] --\n *\n * Gets the path of the file this object is uploading.\n *\n * Results:\n * Path to the upload file.\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (NSString *)filePath\n{\n return filePath;\n}\n\n\n@end // Uploader\n\n\n@implementation EPUploader (Private)\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) upload] --\n *\n * Uploads the given file. The file is compressed before beign uploaded.\n * The data is uploaded using an HTTP POST command.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)upload\n{\n NSData *data = [NSData dataWithContentsOfFile:filePath];\n ASSERT(data);\n if (!data) {\n [self uploadSucceeded:NO];\n return;\n }\n if ([data length] == 0) {\n // There's no data, treat this the same as no file.\n [self uploadSucceeded:YES];\n return;\n }\n\n// NSData *compressedData = [self compress:data];\n// ASSERT(compressedData &amp;&amp; [compressedData length] != 0);\n// if (!compressedData || [compressedData length] == 0) {\n// [self uploadSucceeded:NO];\n// return;\n// }\n\n NSURLRequest *urlRequest = [self postRequestWithURL:serverURL\n boundry:BOUNDRY\n data:data];\n if (!urlRequest) {\n [self uploadSucceeded:NO];\n return;\n }\n\n NSURLConnection * connection =\n [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];\n if (!connection) {\n [self uploadSucceeded:NO];\n }\n\n // Now wait for the URL connection to call us back.\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) postRequestWithURL:boundry:data:] --\n *\n * Creates a HTML POST request.\n *\n * Results:\n * The HTML POST request.\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (NSURLRequest *)postRequestWithURL: (NSURL *)url // IN\n boundry: (NSString *)boundry // IN\n data: (NSData *)data // IN\n{\n // from http://www.cocoadev.com/index.pl?HTTPFileUpload\n NSMutableURLRequest *urlRequest =\n [NSMutableURLRequest requestWithURL:url];\n [urlRequest setHTTPMethod:@\"POST\"];\n [urlRequest setValue:\n [NSString stringWithFormat:@\"multipart/form-data; boundary=%@\", boundry]\n forHTTPHeaderField:@\"Content-Type\"];\n\n NSMutableData *postData =\n [NSMutableData dataWithCapacity:[data length] + 512];\n [postData appendData:\n [[NSString stringWithFormat:@\"--%@\\r\\n\", boundry] dataUsingEncoding:NSUTF8StringEncoding]];\n [postData appendData:\n [[NSString stringWithFormat:\n @\"Content-Disposition: form-data; name=\\\"%@\\\"; filename=\\\"file.bin\\\"\\r\\n\\r\\n\", FORM_FLE_INPUT]\n dataUsingEncoding:NSUTF8StringEncoding]];\n [postData appendData:data];\n [postData appendData:\n [[NSString stringWithFormat:@\"\\r\\n--%@--\\r\\n\", boundry] dataUsingEncoding:NSUTF8StringEncoding]];\n\n [urlRequest setHTTPBody:postData];\n return urlRequest;\n}\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) compress:] --\n *\n * Uses zlib to compress the given data.\n *\n * Results:\n * The compressed data as a NSData object.\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (NSData *)compress: (NSData *)data // IN\n{\n if (!data || [data length] == 0)\n return nil;\n\n // zlib compress doc says destSize must be 1% + 12 bytes greater than source.\n uLong destSize = [data length] * 1.001 + 12;\n NSMutableData *destData = [NSMutableData dataWithLength:destSize];\n\n int error = compress([destData mutableBytes],\n &amp;destSize,\n [data bytes],\n [data length]);\n if (error != Z_OK) {\n NSLog(@\"%s: self:0x%p, zlib error on compress:%d\\n\",__func__, self, error);\n return nil;\n }\n\n [destData setLength:destSize];\n return destData;\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) uploadSucceeded:] --\n *\n * Used to notify the delegate that the upload did or did not succeed.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)uploadSucceeded: (BOOL)success // IN\n{\n [delegate performSelector:success ? doneSelector : errorSelector\n withObject:self];\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) connectionDidFinishLoading:] --\n *\n * Called when the upload is complete. We judge the success of the upload\n * based on the reply we get from the server.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)connectionDidFinishLoading:(NSURLConnection *)connection // IN\n{\n NSLog(@\"%s: self:0x%p\\n\", __func__, self);\n [connection release];\n [self uploadSucceeded:uploadDidSucceed];\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) connection:didFailWithError:] --\n *\n * Called when the upload failed (probably due to a lack of network\n * connection).\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)connection:(NSURLConnection *)connection // IN\n didFailWithError:(NSError *)error // IN\n{\n NSLog(@\"%s: self:0x%p, connection error:%s\\n\",\n __func__, self, [[error description] UTF8String]);\n [connection release];\n [self uploadSucceeded:NO];\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) connection:didReceiveResponse:] --\n *\n * Called as we get responses from the server.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n-(void) connection:(NSURLConnection *)connection // IN\n didReceiveResponse:(NSURLResponse *)response // IN\n{\n NSLog(@\"%s: self:0x%p\\n\", __func__, self);\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) connection:didReceiveData:] --\n *\n * Called when we have data from the server. We expect the server to reply\n * with a \"YES\" if the upload succeeded or \"NO\" if it did not.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)connection:(NSURLConnection *)connection // IN\n didReceiveData:(NSData *)data // IN\n{\n NSLog(@\"%s: self:0x%p\\n\", __func__, self);\n\n NSString *reply = [[[NSString alloc] initWithData:data\n encoding:NSUTF8StringEncoding]\n autorelease];\n NSLog(@\"%s: data: %s\\n\", __func__, [reply UTF8String]);\n\n if ([reply hasPrefix:@\"YES\"]) {\n uploadDidSucceed = YES;\n }\n}\n\n\n@end\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code> [[EPUploader alloc] initWithURL:[NSURL URLWithString:@\"http://yourserver.com/uploadDB.php\"]\n filePath:@\"path/to/some/file\"\n delegate:self\n doneSelector:@selector(onUploadDone:)\n errorSelector:@selector(onUploadError:)]; \n</code></pre>\n" }, { "answer_id": 1591970, "author": "Pavel Repin", "author_id": 43151, "author_profile": "https://Stackoverflow.com/users/43151", "pm_score": 2, "selected": false, "text": "<p>Looks like <a href=\"http://github.com/joehewitt/three20\" rel=\"nofollow noreferrer\">Three20</a> library has support for POSTing images to HTTP server.</p>\n\n<p>See <a href=\"http://github.com/joehewitt/three20/blob/master/src/TTURLRequest.m\" rel=\"nofollow noreferrer\">TTURLRequest.m</a></p>\n\n<p>And it's released under Apache 2.0 License.</p>\n" }, { "answer_id": 6521021, "author": "Kapil Mandlik", "author_id": 758960, "author_profile": "https://Stackoverflow.com/users/758960", "pm_score": 3, "selected": false, "text": "<p>Hope following code snippet will work for you. I have used NSDateFormatter and NSDate to get unique name each time for the image.</p>\n\n<p>Note: <code>'ImageUploadURL'</code> is the string #define with the base url, you need to replace it with your server url.</p>\n\n<p>//Date format for Image Name...</p>\n\n<pre><code>NSDateFormatter *format = [[NSDateFormatter alloc] init];\n [format setDateFormat:@\"yyyyMMddHHmmss\"];\n\nNSDate *now = [[NSDate alloc] init];\n\nNSString *imageName = [NSString stringWithFormat:@\"Image_%@\", [format stringFromDate:now]];\n\n[now release];\n[format release];\n\nNSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];\n[request setURL:[NSURL URLWithString:ImageUploadURL]];\n[request setHTTPMethod:@\"POST\"];\n\n/*\n Set Header and content type of your request.\n */\nNSString *boundary = [NSString stringWithString:@\"---------------------------Boundary Line---------------------------\"];\nNSString *contentType = [NSString stringWithFormat:@\"multipart/form-data; boundary=%@\",boundary];\n[request addValue:contentType forHTTPHeaderField: @\"Content-Type\"];\n\n/*\n now lets create the body of the request.\n */\nNSMutableData *body = [NSMutableData data];\n[body appendData:[[NSString stringWithFormat:@\"\\r\\n--%@\\r\\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; \n[body appendData:[[NSString stringWithFormat:@\"Content-Disposition: form-data; name=\\\"userfile\\\"; filename=\\\"%@.jpg\\\"\\r\\n\", imageName] dataUsingEncoding:NSUTF8StringEncoding]];\n[body appendData:[[NSString stringWithString:@\"Content-Type: application/octet-stream\\r\\n\\r\\n\"] dataUsingEncoding:NSUTF8StringEncoding]];\n[body appendData:[NSData dataWithData:UIImageJPEGRepresentation(image, 90)]];\n[body appendData:[[NSString stringWithFormat:@\"\\r\\n--%@--\\r\\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]];\n[body appendData:[[NSString stringWithFormat:@\"geotag=%@&amp;\", [self _currentLocationMetadata]] dataUsingEncoding:NSUTF8StringEncoding]];\n[body appendData:[[NSString stringWithFormat:@\"\\r\\n--%@--\\r\\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]];\n\n// set body with request.\n[request setHTTPBody:body];\n[request addValue:[NSString stringWithFormat:@\"%d\", [body length]] forHTTPHeaderField:@\"Content-Length\"];\n\n// now lets make the connection to the web\n[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];\n</code></pre>\n" }, { "answer_id": 10514454, "author": "sinh99", "author_id": 694561, "author_profile": "https://Stackoverflow.com/users/694561", "pm_score": 2, "selected": false, "text": "<pre><code>- (void) uploadImage :(NSString *) strRequest\n{\nif([appdel checkNetwork]==TRUE)\n{\n\nNSString *urlString =[NSString stringWithFormat:@\"Enter Url.........\"];\n NSLog(@\"Upload %@\",urlString);\n// setting up the request object now\n\nisUploadImage=TRUE;\ntotalsize=[[strRequest dataUsingEncoding:NSUTF8StringEncoding]length];\n\nNSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];\n[request setURL:[NSURL URLWithString:urlString]];\n[request setHTTPMethod:@\"POST\"];\n\nNSString *boundary = [NSString stringWithString:@\"_1_19330907_1317415362628\"];\nNSString *contentType = [NSString stringWithFormat:@\"multipart/mixed; boundary=%@\",boundary];\n[request setValue:contentType forHTTPHeaderField: @\"Content-Type\"];\n[request setValue:@\"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\" forHTTPHeaderField:@\"Accept\"];\n[request setValue:@\"2667\" forHTTPHeaderField:@\"Content-Length\"];\n\n\n/*\n now lets create the body of the post\n */\nNSMutableData *body = [NSMutableData data];\n[body appendData:[[NSString stringWithFormat:@\"\\r\\n--%@\\r\\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; \n\n\n[body appendData:[[NSString stringWithString:@\"Content-Type: application/json\\r\\n\\r\\n\"] dataUsingEncoding:NSUTF8StringEncoding]];\n\n//[body appendData:[NSData dataWithData:imageData]];\n\n[body appendData:[strRequest dataUsingEncoding:NSUTF8StringEncoding]];\n\n[body appendData:[[NSString stringWithFormat:@\"\\r\\n--%@--\\r\\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]];\n\n\n// setting the body of the post to the reqeust\n[request setHTTPBody:body];\n\n\n\ntheConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];\nif (theConnection) \n webData = [[NSMutableData data] retain];\nelse \n NSLog(@\"No Connection\"); \n}\n\n}\n</code></pre>\n" }, { "answer_id": 22803439, "author": "sinh99", "author_id": 694561, "author_profile": "https://Stackoverflow.com/users/694561", "pm_score": 0, "selected": false, "text": "<p>If you want to upload multiple images then <a href=\"http://iphoneapp-dev.blogspot.com/2011/05/this-example-shows-how-to-upload-images.html\" rel=\"nofollow\">this demo</a> is good option.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm writing an iPhone app that takes a photo and then uploads it to a server. How do I upload a photo to a server with Cocoa? I suppose I use NSUrl somewhere. Thanks!
Header: ``` @interface EPUploader : NSObject { NSURL *serverURL; NSString *filePath; id delegate; SEL doneSelector; SEL errorSelector; BOOL uploadDidSucceed; } - (id)initWithURL: (NSURL *)serverURL filePath: (NSString *)filePath delegate: (id)delegate doneSelector: (SEL)doneSelector errorSelector: (SEL)errorSelector; - (NSString *)filePath; @end ``` Main: ``` #import "EPUploader.h" #import <zlib.h> static NSString * const BOUNDRY = @"0xKhTmLbOuNdArY"; static NSString * const FORM_FLE_INPUT = @"uploaded"; #define ASSERT(x) NSAssert(x, @"") @interface EPUploader (Private) - (void)upload; - (NSURLRequest *)postRequestWithURL: (NSURL *)url boundry: (NSString *)boundry data: (NSData *)data; - (NSData *)compress: (NSData *)data; - (void)uploadSucceeded: (BOOL)success; - (void)connectionDidFinishLoading:(NSURLConnection *)connection; @end @implementation EPUploader /* *----------------------------------------------------------------------------- * * -[Uploader initWithURL:filePath:delegate:doneSelector:errorSelector:] -- * * Initializer. Kicks off the upload. Note that upload will happen on a * separate thread. * * Results: * An instance of Uploader. * * Side effects: * None * *----------------------------------------------------------------------------- */ - (id)initWithURL: (NSURL *)aServerURL // IN filePath: (NSString *)aFilePath // IN delegate: (id)aDelegate // IN doneSelector: (SEL)aDoneSelector // IN errorSelector: (SEL)anErrorSelector // IN { if ((self = [super init])) { ASSERT(aServerURL); ASSERT(aFilePath); ASSERT(aDelegate); ASSERT(aDoneSelector); ASSERT(anErrorSelector); serverURL = [aServerURL retain]; filePath = [aFilePath retain]; delegate = [aDelegate retain]; doneSelector = aDoneSelector; errorSelector = anErrorSelector; [self upload]; } return self; } /* *----------------------------------------------------------------------------- * * -[Uploader dealloc] -- * * Destructor. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)dealloc { [serverURL release]; serverURL = nil; [filePath release]; filePath = nil; [delegate release]; delegate = nil; doneSelector = NULL; errorSelector = NULL; [super dealloc]; } /* *----------------------------------------------------------------------------- * * -[Uploader filePath] -- * * Gets the path of the file this object is uploading. * * Results: * Path to the upload file. * * Side effects: * None * *----------------------------------------------------------------------------- */ - (NSString *)filePath { return filePath; } @end // Uploader @implementation EPUploader (Private) /* *----------------------------------------------------------------------------- * * -[Uploader(Private) upload] -- * * Uploads the given file. The file is compressed before beign uploaded. * The data is uploaded using an HTTP POST command. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)upload { NSData *data = [NSData dataWithContentsOfFile:filePath]; ASSERT(data); if (!data) { [self uploadSucceeded:NO]; return; } if ([data length] == 0) { // There's no data, treat this the same as no file. [self uploadSucceeded:YES]; return; } // NSData *compressedData = [self compress:data]; // ASSERT(compressedData && [compressedData length] != 0); // if (!compressedData || [compressedData length] == 0) { // [self uploadSucceeded:NO]; // return; // } NSURLRequest *urlRequest = [self postRequestWithURL:serverURL boundry:BOUNDRY data:data]; if (!urlRequest) { [self uploadSucceeded:NO]; return; } NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; if (!connection) { [self uploadSucceeded:NO]; } // Now wait for the URL connection to call us back. } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) postRequestWithURL:boundry:data:] -- * * Creates a HTML POST request. * * Results: * The HTML POST request. * * Side effects: * None * *----------------------------------------------------------------------------- */ - (NSURLRequest *)postRequestWithURL: (NSURL *)url // IN boundry: (NSString *)boundry // IN data: (NSData *)data // IN { // from http://www.cocoadev.com/index.pl?HTTPFileUpload NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setHTTPMethod:@"POST"]; [urlRequest setValue: [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundry] forHTTPHeaderField:@"Content-Type"]; NSMutableData *postData = [NSMutableData dataWithCapacity:[data length] + 512]; [postData appendData: [[NSString stringWithFormat:@"--%@\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData: [[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"%@\"; filename=\"file.bin\"\r\n\r\n", FORM_FLE_INPUT] dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:data]; [postData appendData: [[NSString stringWithFormat:@"\r\n--%@--\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]]; [urlRequest setHTTPBody:postData]; return urlRequest; } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) compress:] -- * * Uses zlib to compress the given data. * * Results: * The compressed data as a NSData object. * * Side effects: * None * *----------------------------------------------------------------------------- */ - (NSData *)compress: (NSData *)data // IN { if (!data || [data length] == 0) return nil; // zlib compress doc says destSize must be 1% + 12 bytes greater than source. uLong destSize = [data length] * 1.001 + 12; NSMutableData *destData = [NSMutableData dataWithLength:destSize]; int error = compress([destData mutableBytes], &destSize, [data bytes], [data length]); if (error != Z_OK) { NSLog(@"%s: self:0x%p, zlib error on compress:%d\n",__func__, self, error); return nil; } [destData setLength:destSize]; return destData; } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) uploadSucceeded:] -- * * Used to notify the delegate that the upload did or did not succeed. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)uploadSucceeded: (BOOL)success // IN { [delegate performSelector:success ? doneSelector : errorSelector withObject:self]; } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) connectionDidFinishLoading:] -- * * Called when the upload is complete. We judge the success of the upload * based on the reply we get from the server. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)connectionDidFinishLoading:(NSURLConnection *)connection // IN { NSLog(@"%s: self:0x%p\n", __func__, self); [connection release]; [self uploadSucceeded:uploadDidSucceed]; } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) connection:didFailWithError:] -- * * Called when the upload failed (probably due to a lack of network * connection). * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)connection:(NSURLConnection *)connection // IN didFailWithError:(NSError *)error // IN { NSLog(@"%s: self:0x%p, connection error:%s\n", __func__, self, [[error description] UTF8String]); [connection release]; [self uploadSucceeded:NO]; } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) connection:didReceiveResponse:] -- * * Called as we get responses from the server. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ -(void) connection:(NSURLConnection *)connection // IN didReceiveResponse:(NSURLResponse *)response // IN { NSLog(@"%s: self:0x%p\n", __func__, self); } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) connection:didReceiveData:] -- * * Called when we have data from the server. We expect the server to reply * with a "YES" if the upload succeeded or "NO" if it did not. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)connection:(NSURLConnection *)connection // IN didReceiveData:(NSData *)data // IN { NSLog(@"%s: self:0x%p\n", __func__, self); NSString *reply = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; NSLog(@"%s: data: %s\n", __func__, [reply UTF8String]); if ([reply hasPrefix:@"YES"]) { uploadDidSucceed = YES; } } @end ``` Usage: ``` [[EPUploader alloc] initWithURL:[NSURL URLWithString:@"http://yourserver.com/uploadDB.php"] filePath:@"path/to/some/file" delegate:self doneSelector:@selector(onUploadDone:) errorSelector:@selector(onUploadError:)]; ```
125,313
<p>I'm running programs from Eclipse (on Windows) that eat a lot of CPU time. To avoid bogging down my whole machine, I set the priority to Low with the Task Manager. However, this is a cumbersome manual process. Is there a way Eclipse can set this priority automatically?</p> <p>EDIT: I realized that each particular launcher (Java, Python etc) has its own configuration method, so I will restrict this question to the Java domain, which is what I need most.</p>
[ { "answer_id": 125322, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 0, "selected": false, "text": "<p>A better alternative is configure the amount of memory that Eclipse will use: <a href=\"http://www.eclipsezone.com/eclipse/forums/t61618.html\" rel=\"nofollow noreferrer\">http://www.eclipsezone.com/eclipse/forums/t61618.html</a></p>\n\n<p>And do a google search about -Xmx and -Xms parameters for JVM (which you could configure for <em>runners</em> inside Eclipse).</p>\n\n<p>Kind Regards</p>\n" }, { "answer_id": 129536, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "<p>I'm assuming that you launch these programs using External Tools. If so, then you can modify the launch command to use the <code>start /low</code> hack described earlier. However, if these applications have a special launch type (like Java Application or similar), then you're in trouble. The only way you could actually change this would be to crack open the source for Eclipse, find that launch type and where it dispatches tasks and then modify it to use <code>start /low</code>. Sorry, but I don't think there's a simple solution to this.</p>\n" }, { "answer_id": 433467, "author": "Thorbjørn Ravn Andersen", "author_id": 53897, "author_profile": "https://Stackoverflow.com/users/53897", "pm_score": 0, "selected": false, "text": "<p>I spent some time a while back to investigate this. There is no method <em>inside</em> Java to lower the priority (as far as I could see), so you need to employ the \"start /min\" approach. I didn't try to get that working.</p>\n\n<p>Instead I got a multi-kernel processor. This gives room for other stuff, even if a Java program runs amok on one kernel.</p>\n\n<p>Strongly recommended.</p>\n" }, { "answer_id": 2813098, "author": "sandos", "author_id": 266486, "author_profile": "https://Stackoverflow.com/users/266486", "pm_score": 0, "selected": false, "text": "<p>I would like this as well, odd that it is not possible, really. I know you can set thread-priorities, but I think in windows-land, threads are all scheduled \"inside\" the process priority so to speak. </p>\n" }, { "answer_id": 3616057, "author": "Martin", "author_id": 436728, "author_profile": "https://Stackoverflow.com/users/436728", "pm_score": -1, "selected": false, "text": "<p>If you need it only in development you can set the priority of all other processes to high...</p>\n" }, { "answer_id": 9075451, "author": "Yon", "author_id": 241684, "author_profile": "https://Stackoverflow.com/users/241684", "pm_score": 0, "selected": false, "text": "<p>I've run into the same question in Linux and have found this:\n<a href=\"http://tech.stolsvik.com/2010/01/linux-java-thread-priorities-workaround.html\" rel=\"nofollow\">http://tech.stolsvik.com/2010/01/linux-java-thread-priorities-workaround.html</a></p>\n\n<p>The interesting bit is about how to convert Java thread priorities to OS priorities. This has solved the problem for me, it may help you too.</p>\n" }, { "answer_id": 41046469, "author": "George Forman", "author_id": 2069400, "author_profile": "https://Stackoverflow.com/users/2069400", "pm_score": 3, "selected": false, "text": "<p>I have the same problem on Windows--- launching subprocesses that use all the CPUs (thread-parallel jobs), yet I want good responsiveness in my Windows development environment. </p>\n\n<p><strong>Solution</strong>: after launching several jobs:</p>\n\n<p>DOS cmd>> <code>wmic process where name=\"javaw.exe\" CALL setpriority \"below normal\"</code></p>\n\n<p>No, this won't affect eclipse.exe process. </p>\n\n<p><strong>Java Solution</strong>: Insert this code into your CPU-intense programs to lower their own Windows priority:</p>\n\n<pre><code>public static void lowerMyProcessPriority() throws IOException {\n String pid = ManagementFactory.getRuntimeMXBean().getName();\n int p = pid.indexOf(\"@\");\n if (p &gt; 0) pid = pid.substring(0,p);\n String cmd = \"wmic process where processid=&lt;pid&gt; CALL setpriority\".replace(\"&lt;pid&gt;\", pid);\n List&lt;String&gt; ls = new ArrayList&lt;&gt;(Arrays.asList(cmd.split(\" \")));\n ls.add(\"\\\"below normal\\\"\");\n ProcessBuilder pb = new ProcessBuilder(ls);\n pb.start();\n}\n</code></pre>\n\n<p>Yes, tested. Works on Win7.</p>\n" }, { "answer_id": 47190005, "author": "englebart", "author_id": 1813300, "author_profile": "https://Stackoverflow.com/users/1813300", "pm_score": 0, "selected": false, "text": "<p>Use an OS tool or a fake java.exe to capture the really long javaw.exe command that the eclipse launcher spawns.</p>\n\n<p>Bypass eclipse.exe and launch the javaw.exe directly.</p>\n\n<p>Once you have the javaw.exe launching directly and correctly.</p>\n\n<blockquote>\n <p>START /BELOWNORMAL \\path\\javaw.exe lots-of-parameters-to-load-workspace</p>\n</blockquote>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9871/" ]
I'm running programs from Eclipse (on Windows) that eat a lot of CPU time. To avoid bogging down my whole machine, I set the priority to Low with the Task Manager. However, this is a cumbersome manual process. Is there a way Eclipse can set this priority automatically? EDIT: I realized that each particular launcher (Java, Python etc) has its own configuration method, so I will restrict this question to the Java domain, which is what I need most.
I have the same problem on Windows--- launching subprocesses that use all the CPUs (thread-parallel jobs), yet I want good responsiveness in my Windows development environment. **Solution**: after launching several jobs: DOS cmd>> `wmic process where name="javaw.exe" CALL setpriority "below normal"` No, this won't affect eclipse.exe process. **Java Solution**: Insert this code into your CPU-intense programs to lower their own Windows priority: ``` public static void lowerMyProcessPriority() throws IOException { String pid = ManagementFactory.getRuntimeMXBean().getName(); int p = pid.indexOf("@"); if (p > 0) pid = pid.substring(0,p); String cmd = "wmic process where processid=<pid> CALL setpriority".replace("<pid>", pid); List<String> ls = new ArrayList<>(Arrays.asList(cmd.split(" "))); ls.add("\"below normal\""); ProcessBuilder pb = new ProcessBuilder(ls); pb.start(); } ``` Yes, tested. Works on Win7.
125,314
<p>Selenium Remote Control has a method of "get_html_source", which returns the source of the current page as a string.</p> <p>AFAIK, this method works in all cases in Firefox and Safari. But when it's invoked in Internet Explorer, it returns an incorrect source.</p> <p>Does anyone know if this is a bug with Selenium or Internet Explorer, and if there's a fix?</p>
[ { "answer_id": 125361, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "<p>I'm 99% sure get_html_source uses the browser's innerHTML property. InnerHTML returns the browser's internal representation of a document, and has always been inconsistent and \"wonky\" between platforms. </p>\n\n<p>You can test this by temporarily adding the following onload attribute to the body tag of your page.</p>\n\n<pre><code>onload=\"var oArea = document.createElement('textarea');oArea.rows=80;oArea.cols=80;oArea.value = document.getElementsByTagName('html')[0].innerHTML;document.getElementsByTagName('body')[0].appendChild(oArea)\"\n</code></pre>\n\n<p>This will add a text area to the bottom of your page with the document's innerHTML. If you see the same \"incorrect\" HTML source you know IE's the culprit here.</p>\n\n<p>Possible workarounds would be running the source through HTML Tidy or some other cleaner if you're after valid markup. I don't know of anything that will give you a consistent rendering between browsers.</p>\n" }, { "answer_id": 141472, "author": "Howard", "author_id": 21479, "author_profile": "https://Stackoverflow.com/users/21479", "pm_score": 1, "selected": false, "text": "<p>thanks Alan. it turns out it was a problem with the different browser's implementation of innerHTML.</p>\n\n<p>for tags having to do with lists, like <LI> , the end tags are optional.</p>\n\n<p>browsers like safari and firefox pick up on the end tags with their respective innerHTML methods, but internet explorer's innerHTML method ignores them.</p>\n\n<p>since lists are structured, e.g.</p>\n\n<p><UL>\n<LI>apple</LI>\n<LI>pear</LI>\n</UL></p>\n\n<p>a regex replace on the html source string should do the trick.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21479/" ]
Selenium Remote Control has a method of "get\_html\_source", which returns the source of the current page as a string. AFAIK, this method works in all cases in Firefox and Safari. But when it's invoked in Internet Explorer, it returns an incorrect source. Does anyone know if this is a bug with Selenium or Internet Explorer, and if there's a fix?
I'm 99% sure get\_html\_source uses the browser's innerHTML property. InnerHTML returns the browser's internal representation of a document, and has always been inconsistent and "wonky" between platforms. You can test this by temporarily adding the following onload attribute to the body tag of your page. ``` onload="var oArea = document.createElement('textarea');oArea.rows=80;oArea.cols=80;oArea.value = document.getElementsByTagName('html')[0].innerHTML;document.getElementsByTagName('body')[0].appendChild(oArea)" ``` This will add a text area to the bottom of your page with the document's innerHTML. If you see the same "incorrect" HTML source you know IE's the culprit here. Possible workarounds would be running the source through HTML Tidy or some other cleaner if you're after valid markup. I don't know of anything that will give you a consistent rendering between browsers.
125,319
<p>I have been running <a href="http://en.wikipedia.org/wiki/StyleCop" rel="noreferrer">StyleCop</a> over some C# code, and it keeps reporting that my <code>using</code> directives should be inside the namespace.</p> <p>Is there a technical reason for putting the <code>using</code> directives inside instead of outside the namespace?</p>
[ { "answer_id": 125330, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 8, "selected": false, "text": "<p>Putting it inside the namespaces makes the declarations local to that namespace for the file (in case you have multiple namespaces in the file) but if you only have one namespace per file then it doesn't make much of a difference whether they go outside or inside the namespace.</p>\n\n<pre><code>using ThisNamespace.IsImported.InAllNamespaces.Here;\n\nnamespace Namespace1\n{ \n using ThisNamespace.IsImported.InNamespace1.AndNamespace2;\n\n namespace Namespace2\n { \n using ThisNamespace.IsImported.InJustNamespace2;\n } \n}\n\nnamespace Namespace3\n{ \n using ThisNamespace.IsImported.InJustNamespace3;\n}\n</code></pre>\n" }, { "answer_id": 125336, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 6, "selected": false, "text": "<p>According to <a href=\"http://www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssemblyLoading.aspx\" rel=\"noreferrer\">Hanselman - Using Directive and Assembly Loading...</a> and other such articles there is technically no difference.</p>\n\n<p>My preference is to put them outside of namespaces.</p>\n" }, { "answer_id": 151560, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 12, "selected": true, "text": "<p>There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:</p>\n\n<pre><code>// File1.cs\nusing System;\nnamespace Outer.Inner\n{\n class Foo\n {\n static void Bar()\n {\n double d = Math.PI;\n }\n }\n}\n</code></pre>\n\n<p>Now imagine that someone adds another file (File2.cs) to the project that looks like this:</p>\n\n<pre><code>// File2.cs\nnamespace Outer\n{\n class Math\n {\n }\n}\n</code></pre>\n\n<p>The compiler searches <code>Outer</code> before looking at those <code>using</code> directives outside the namespace, so it finds <code>Outer.Math</code> instead of <code>System.Math</code>. Unfortunately (or perhaps fortunately?), <code>Outer.Math</code> has no <code>PI</code> member, so File1 is now broken.</p>\n\n<p>This changes if you put the <code>using</code> inside your namespace declaration, as follows:</p>\n\n<pre><code>// File1b.cs\nnamespace Outer.Inner\n{\n using System;\n class Foo\n {\n static void Bar()\n {\n double d = Math.PI;\n }\n }\n}\n</code></pre>\n\n<p>Now the compiler searches <code>System</code> before searching <code>Outer</code>, finds <code>System.Math</code>, and all is well.</p>\n\n<p>Some would argue that <code>Math</code> might be a bad name for a user-defined class, since there's already one in <code>System</code>; the point here is just that there <em>is</em> a difference, and it affects the maintainability of your code.</p>\n\n<p>It's also interesting to note what happens if <code>Foo</code> is in namespace <code>Outer</code>, rather than <code>Outer.Inner</code>. In that case, adding <code>Outer.Math</code> in File2 breaks File1 regardless of where the <code>using</code> goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any <code>using</code> directive.</p>\n" }, { "answer_id": 1422218, "author": "JaredCacurak", "author_id": 16254, "author_profile": "https://Stackoverflow.com/users/16254", "pm_score": 6, "selected": false, "text": "<p>According the to StyleCop Documentation:</p>\n\n<p>SA1200: UsingDirectivesMustBePlacedWithinNamespace </p>\n\n<p>Cause \nA C# using directive is placed outside of a namespace element.</p>\n\n<p>Rule Description \nA violation of this rule occurs when a using directive or a using-alias directive is placed outside of a namespace element, unless the file does not contain any namespace elements.</p>\n\n<p>For example, the following code would result in two violations of this rule.</p>\n\n<pre><code>using System;\nusing Guid = System.Guid;\n\nnamespace Microsoft.Sample\n{\n public class Program\n {\n }\n}\n</code></pre>\n\n<p>The following code, however, would not result in any violations of this rule:</p>\n\n<pre><code>namespace Microsoft.Sample\n{\n using System;\n using Guid = System.Guid;\n\n public class Program\n {\n }\n}\n</code></pre>\n\n<p>This code will compile cleanly, without any compiler errors. However, it is unclear which version of the Guid type is being allocated. If the using directive is moved inside of the namespace, as shown below, a compiler error will occur:</p>\n\n<pre><code>namespace Microsoft.Sample\n{\n using Guid = System.Guid;\n public class Guid\n {\n public Guid(string s)\n {\n }\n }\n\n public class Program\n {\n public static void Main(string[] args)\n {\n Guid g = new Guid(\"hello\");\n }\n }\n}\n</code></pre>\n\n<p>The code fails on the following compiler error, found on the line containing <code>Guid g = new Guid(\"hello\");</code> </p>\n\n<p>CS0576: Namespace 'Microsoft.Sample' contains a definition conflicting with alias 'Guid'</p>\n\n<p>The code creates an alias to the System.Guid type called Guid, and also creates its own type called Guid with a matching constructor interface. Later, the code creates an instance of the type Guid. To create this instance, the compiler must choose between the two different definitions of Guid. When the using-alias directive is placed outside of the namespace element, the compiler will choose the local definition of Guid defined within the local namespace, and completely ignore the using-alias directive defined outside of the namespace. This, unfortunately, is not obvious when reading the code.</p>\n\n<p>When the using-alias directive is positioned within the namespace, however, the compiler has to choose between two different, conflicting Guid types both defined within the same namespace. Both of these types provide a matching constructor. The compiler is unable to make a decision, so it flags the compiler error.</p>\n\n<p>Placing the using-alias directive outside of the namespace is a bad practice because it can lead to confusion in situations such as this, where it is not obvious which version of the type is actually being used. This can potentially lead to a bug which might be difficult to diagnose.</p>\n\n<p>Placing using-alias directives within the namespace element eliminates this as a source of bugs. </p>\n\n<ol start=\"2\">\n<li>Multiple Namespaces</li>\n</ol>\n\n<p>Placing multiple namespace elements within a single file is generally a bad idea, but if and when this is done, it is a good idea to place all using directives within each of the namespace elements, rather than globally at the top of the file. This will scope the namespaces tightly, and will also help to avoid the kind of behavior described above.</p>\n\n<p>It is important to note that when code has been written with using directives placed outside of the namespace, care should be taken when moving these directives within the namespace, to ensure that this is not changing the semantics of the code. As explained above, placing using-alias directives within the namespace element allows the compiler to choose between conflicting types in ways that will not happen when the directives are placed outside of the namespace.</p>\n\n<p>How to Fix Violations\nTo fix a violation of this rule, move all using directives and using-alias directives within the namespace element.</p>\n" }, { "answer_id": 12826266, "author": "Neo", "author_id": 197591, "author_profile": "https://Stackoverflow.com/users/197591", "pm_score": 5, "selected": false, "text": "<p>There is an issue with placing using statements inside the namespace when you wish to use aliases. The alias doesn't benefit from the earlier <code>using</code> statements and has to be fully qualified.</p>\n\n<p>Consider:</p>\n\n<pre><code>namespace MyNamespace\n{\n using System;\n using MyAlias = System.DateTime;\n\n class MyClass\n {\n }\n}\n</code></pre>\n\n<p>versus:</p>\n\n<pre><code>using System;\n\nnamespace MyNamespace\n{\n using MyAlias = DateTime;\n\n class MyClass\n {\n }\n}\n</code></pre>\n\n<p>This can be particularly pronounced if you have a long-winded alias such as the following (which is how I found the problem):</p>\n\n<pre><code>using MyAlias = Tuple&lt;Expression&lt;Func&lt;DateTime, object&gt;&gt;, Expression&lt;Func&lt;TimeSpan, object&gt;&gt;&gt;;\n</code></pre>\n\n<p>With <code>using</code> statements inside the namespace, it suddenly becomes:</p>\n\n<pre><code>using MyAlias = System.Tuple&lt;System.Linq.Expressions.Expression&lt;System.Func&lt;System.DateTime, object&gt;&gt;, System.Linq.Expressions.Expression&lt;System.Func&lt;System.TimeSpan, object&gt;&gt;&gt;;\n</code></pre>\n\n<p>Not pretty.</p>\n" }, { "answer_id": 16092975, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 9, "selected": false, "text": "<p>This thread already has some great answers, but I feel I can bring a little more detail with this additional answer.</p>\n<p>First, remember that a namespace declaration with periods, like:</p>\n<pre><code>namespace MyCorp.TheProduct.SomeModule.Utilities\n{\n ...\n}\n</code></pre>\n<p>is entirely equivalent to:</p>\n<pre><code>namespace MyCorp\n{\n namespace TheProduct\n {\n namespace SomeModule\n {\n namespace Utilities\n {\n ...\n }\n }\n }\n}\n</code></pre>\n<p>If you wanted to, you could put <code>using</code> directives on all of these levels. (Of course, we want to have <code>using</code>s in only one place, but it would be legal according to the language.)</p>\n<p>The rule for resolving which type is implied, can be loosely stated like this: <strong>First search the inner-most &quot;scope&quot; for a match, if nothing is found there go out one level to the next scope and search there, and so on</strong>, until a match is found. If at some level more than one match is found, if one of the types are from the current assembly, pick that one and issue a compiler warning. Otherwise, give up (compile-time error).</p>\n<p>Now, let's be explicit about what this means in a concrete example with the two major conventions.</p>\n<p><strong>(1) With usings outside:</strong></p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n//using MyCorp.TheProduct; &lt;-- uncommenting this would change nothing\nusing MyCorp.TheProduct.OtherModule;\nusing MyCorp.TheProduct.OtherModule.Integration;\nusing ThirdParty;\n\nnamespace MyCorp.TheProduct.SomeModule.Utilities\n{\n class C\n {\n Ambiguous a;\n }\n}\n</code></pre>\n<p>In the above case, to find out what type <code>Ambiguous</code> is, the search goes in this order:</p>\n<ol>\n<li>Nested types inside <code>C</code> (including inherited nested types)</li>\n<li>Types in the current namespace <code>MyCorp.TheProduct.SomeModule.Utilities</code></li>\n<li>Types in namespace <code>MyCorp.TheProduct.SomeModule</code></li>\n<li>Types in <code>MyCorp.TheProduct</code></li>\n<li>Types in <code>MyCorp</code></li>\n<li>Types in the <em>null</em> namespace (the global namespace)</li>\n<li>Types in <code>System</code>, <code>System.Collections.Generic</code>, <code>System.Linq</code>, <code>MyCorp.TheProduct.OtherModule</code>, <code>MyCorp.TheProduct.OtherModule.Integration</code>, and <code>ThirdParty</code></li>\n</ol>\n<p>The other convention:</p>\n<p><strong>(2) With usings inside:</strong></p>\n<pre><code>namespace MyCorp.TheProduct.SomeModule.Utilities\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using MyCorp.TheProduct; // MyCorp can be left out; this using is NOT redundant\n using MyCorp.TheProduct.OtherModule; // MyCorp.TheProduct can be left out\n using MyCorp.TheProduct.OtherModule.Integration; // MyCorp.TheProduct can be left out\n using ThirdParty;\n\n class C\n {\n Ambiguous a;\n }\n}\n</code></pre>\n<p>Now, search for the type <code>Ambiguous</code> goes in this order:</p>\n<ol>\n<li>Nested types inside <code>C</code> (including inherited nested types)</li>\n<li>Types in the current namespace <code>MyCorp.TheProduct.SomeModule.Utilities</code></li>\n<li>Types in <code>System</code>, <code>System.Collections.Generic</code>, <code>System.Linq</code>, <code>MyCorp.TheProduct</code>, <code>MyCorp.TheProduct.OtherModule</code>, <code>MyCorp.TheProduct.OtherModule.Integration</code>, and <code>ThirdParty</code></li>\n<li>Types in namespace <code>MyCorp.TheProduct.SomeModule</code></li>\n<li>Types in <code>MyCorp</code></li>\n<li>Types in the <em>null</em> namespace (the global namespace)</li>\n</ol>\n<p>(Note that <code>MyCorp.TheProduct</code> was a part of &quot;3.&quot; and was therefore not needed between &quot;4.&quot; and &quot;5.&quot;.)</p>\n<p><strong>Concluding remarks</strong></p>\n<p>No matter if you put the usings inside or outside the namespace declaration, there's always the possibility that someone later adds a new type with identical name to one of the namespaces which have higher priority.</p>\n<p>Also, if a nested namespace has the same name as a type, it can cause problems.</p>\n<p>It is always dangerous to move the usings from one location to another because the search hierarchy changes, and another type may be found. Therefore, choose one convention and stick to it, so that you won't have to ever move usings.</p>\n<p>Visual Studio's templates, by default, put the usings <em>outside</em> of the namespace (for example if you make VS generate a new class in a new file).</p>\n<p>One (tiny) advantage of having usings <em>outside</em> is that you can then utilize the using directives for a global attribute, for example <code>[assembly: ComVisible(false)]</code> instead of <code>[assembly: System.Runtime.InteropServices.ComVisible(false)]</code>.</p>\n<hr />\n<p><strong>Update about file-scoped namespace declarations</strong></p>\n<p>Since C# 10.0 (from 2021), you can avoid indentation and use either (convention 1, usings outside):</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing MyCorp.TheProduct.OtherModule;\nusing MyCorp.TheProduct.OtherModule.Integration;\nusing ThirdParty;\n\nnamespace MyCorp.TheProduct.SomeModule.Utilities;\n\nclass C\n{\n Ambiguous a;\n}\n</code></pre>\n<p>or (convention 2, usings inside):</p>\n<pre><code>namespace MyCorp.TheProduct.SomeModule.Utilities;\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing MyCorp.TheProduct;\nusing MyCorp.TheProduct.OtherModule;\nusing MyCorp.TheProduct.OtherModule.Integration;\nusing ThirdParty;\n\nclass C\n{\n Ambiguous a;\n}\n</code></pre>\n<p>But the same considerations as before apply.</p>\n" }, { "answer_id": 26370684, "author": "Israel Ocbina", "author_id": 1990838, "author_profile": "https://Stackoverflow.com/users/1990838", "pm_score": -1, "selected": false, "text": "<p>It is a better practice if those <strong>default</strong> using i.e. \"<em>references</em>\" used in your source solution should be outside the namespaces and those that are <strong>\"new added reference\"</strong> is a good practice is you should put it inside the namespace. This is to distinguish what references are being added.</p>\n" }, { "answer_id": 39545780, "author": "Biscuits", "author_id": 2707705, "author_profile": "https://Stackoverflow.com/users/2707705", "pm_score": 3, "selected": false, "text": "<p>As Jeppe Stig Nielsen <a href=\"https://stackoverflow.com/a/16092975/2707705\">said</a>, this thread already has great answers, but I thought this rather obvious subtlety was worth mentioning too.</p>\n\n<p><code>using</code> directives specified inside namespaces can make for shorter code since they don't need to be fully qualified as when they're specified on the outside.</p>\n\n<p>The following example works because the types <code>Foo</code> and <code>Bar</code> are both in the same global namespace, <code>Outer</code>.</p>\n\n<p>Presume the code file <em>Foo.cs</em>:</p>\n\n<pre><code>namespace Outer.Inner\n{\n class Foo { }\n}\n</code></pre>\n\n<p>And <em>Bar.cs</em>:</p>\n\n<pre><code>namespace Outer\n{\n using Outer.Inner;\n\n class Bar\n {\n public Foo foo;\n }\n}\n</code></pre>\n\n<p>That may omit the outer namespace in the <code>using</code> directive, for short:</p>\n\n<pre><code>namespace Outer\n{\n using Inner;\n\n class Bar\n {\n public Foo foo;\n }\n}\n</code></pre>\n" }, { "answer_id": 50666521, "author": "sotn", "author_id": 944592, "author_profile": "https://Stackoverflow.com/users/944592", "pm_score": 3, "selected": false, "text": "<p>The technical reasons are discussed in the answers and I think that it comes to the personal preferences in the end since the difference is not that <em>big</em> and there are tradeoffs for both of them. Visual Studio's default template for creating <code>.cs</code> files use <code>using</code> directives outside of namespaces e.g.</p>\n\n<p>One can adjust stylecop to check <code>using</code> directives outside of namespaces through adding <code>stylecop.json</code> file in the root of the project file with the following:</p>\n\n<pre><code>{\n \"$schema\": \"https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json\",\n \"orderingRules\": {\n \"usingDirectivesPlacement\": \"outsideNamespace\"\n }\n }\n}\n</code></pre>\n\n<p>You can create this config file in solution level and add it to your projects as 'Existing Link File' to share the config across all of your projects too.</p>\n" }, { "answer_id": 52007574, "author": "Ben Gardner", "author_id": 6898634, "author_profile": "https://Stackoverflow.com/users/6898634", "pm_score": 3, "selected": false, "text": "<p>Another subtlety that I don't believe has been covered by the other answers is for when you have a class and namespace with the same name.</p>\n<p>When you have the import inside the namespace then it will find the class. If the import is outside the namespace then the import will be ignored and the class and namespace have to be fully qualified.</p>\n<pre><code>//file1.cs\nnamespace Foo\n{\n class Foo\n {\n }\n}\n\n//file2.cs\nnamespace ConsoleApp3\n{\n using Foo;\n class Program\n {\n static void Main(string[] args)\n {\n //This will allow you to use the class\n Foo test = new Foo();\n }\n }\n}\n\n//file3.cs\nusing Foo; //Unused and redundant \nnamespace Bar\n{\n class Bar\n {\n Bar()\n {\n Foo.Foo test = new Foo.Foo();\n Foo test = new Foo(); //will give you an error that a namespace is being used like a class.\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 56457715, "author": "Hans Kesting", "author_id": 121309, "author_profile": "https://Stackoverflow.com/users/121309", "pm_score": 4, "selected": false, "text": "<p>One wrinkle I ran into (that isn't covered in other answers):</p>\n\n<p>Suppose you have these namespaces:</p>\n\n<ul>\n<li>Something.Other</li>\n<li>Parent.Something.Other</li>\n</ul>\n\n<p>When you use <code>using Something.Other</code> <em>outside</em> of a <code>namespace Parent</code>, it refers to the first one (Something.Other).</p>\n\n<p>However if you use it <em>inside</em> of that namespace declaration, it refers to the second one (Parent.Something.Other)!</p>\n\n<p>There is a simple solution: add the \"<code>global::</code>\" prefix: <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/how-to-use-the-global-namespace-alias\" rel=\"noreferrer\">docs</a></p>\n\n<pre><code>namespace Parent\n{\n using global::Something.Other;\n // etc\n}\n</code></pre>\n" }, { "answer_id": 63193100, "author": "Yrth", "author_id": 14028710, "author_profile": "https://Stackoverflow.com/users/14028710", "pm_score": 2, "selected": false, "text": "<p>As a rule, external <code>using</code> directives (System and Microsoft namespaces for example) should be placed <em>outside</em> the <code>namespace</code> directive. They are defaults that should be applied in all cases <strong>unless otherwise specified</strong>. This should include any of your own organization's internal libraries that are not part of the current project, or <code>using</code> directives that reference other primary namespaces in the same project. Any <code>using</code> directives that reference other modules in the current project and namespace should be placed <strong>inside</strong> the <code>namespace</code> directive. This serves two specific functions:</p>\n<ul>\n<li>It provides a visual distinction between local modules and 'other' modules, meaning everything else.</li>\n<li>It scopes the local directives to be applied <strong>preferentially</strong> over global directives.</li>\n</ul>\n<p>The latter reason is significant. It means that it's harder to introduce an ambiguous reference issue that can be introduced by a change no more significant than <strong>refactoring code</strong>. That is to say, you move a method from one file to another and suddenly a bug shows up that wasn't there before. Colloquially, a 'heisenbug' - historically fiendishly difficult to track down.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
I have been running [StyleCop](http://en.wikipedia.org/wiki/StyleCop) over some C# code, and it keeps reporting that my `using` directives should be inside the namespace. Is there a technical reason for putting the `using` directives inside instead of outside the namespace?
There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs: ``` // File1.cs using System; namespace Outer.Inner { class Foo { static void Bar() { double d = Math.PI; } } } ``` Now imagine that someone adds another file (File2.cs) to the project that looks like this: ``` // File2.cs namespace Outer { class Math { } } ``` The compiler searches `Outer` before looking at those `using` directives outside the namespace, so it finds `Outer.Math` instead of `System.Math`. Unfortunately (or perhaps fortunately?), `Outer.Math` has no `PI` member, so File1 is now broken. This changes if you put the `using` inside your namespace declaration, as follows: ``` // File1b.cs namespace Outer.Inner { using System; class Foo { static void Bar() { double d = Math.PI; } } } ``` Now the compiler searches `System` before searching `Outer`, finds `System.Math`, and all is well. Some would argue that `Math` might be a bad name for a user-defined class, since there's already one in `System`; the point here is just that there *is* a difference, and it affects the maintainability of your code. It's also interesting to note what happens if `Foo` is in namespace `Outer`, rather than `Outer.Inner`. In that case, adding `Outer.Math` in File2 breaks File1 regardless of where the `using` goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any `using` directive.
125,333
<p>I'm looking for the simplest, most straightforward way to implement the following:</p> <ul> <li>The main program instantiates worker threads to do a task.</li> <li>Only <code>n</code> tasks can be running at once.</li> <li>When <code>n</code> is reached, no more workers are started until the count of running threads drops back below <code>n</code>.</li> </ul>
[ { "answer_id": 125350, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 2, "selected": false, "text": "<p>Use the Executor framework; namely <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)\" rel=\"nofollow noreferrer\">newFixedThreadPool(N)</a></p>\n" }, { "answer_id": 125354, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 7, "selected": true, "text": "<p>I think that <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)\" rel=\"nofollow noreferrer\">Executors.newFixedThreadPool</a> fits your requirements. There are a number of different ways to use the resulting ExecutorService, depending on whether you want a result returned to the main thread, or whether the task is totally self-contained, and whether you have a collection of tasks to perform up front, or whether tasks are queued in response to some event. </p>\n\n<pre><code> Collection&lt;YourTask&gt; tasks = new ArrayList&lt;YourTask&gt;();\n YourTask yt1 = new YourTask();\n ...\n tasks.add(yt1);\n ...\n ExecutorService exec = Executors.newFixedThreadPool(5);\n List&lt;Future&lt;YourResultType&gt;&gt; results = exec.invokeAll(tasks);\n</code></pre>\n\n<p>Alternatively, if you have a new asynchronous task to perform in response to some event, you probably just want to use the ExecutorService's simple <code>execute(Runnable)</code> method.</p>\n" }, { "answer_id": 125358, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)\" rel=\"nofollow noreferrer\">Executors.newFixedThreadPool(int)</a></p>\n\n<pre><code>Executor executor = Executors.newFixedThreadPool(n);\n\nRunnable runnable = new Runnable() {\n public void run() {\n // do your thing here\n }\n}\n\nexecutor.execute(runnable);\n</code></pre>\n" }, { "answer_id": 125370, "author": "rjohnston", "author_id": 246, "author_profile": "https://Stackoverflow.com/users/246", "pm_score": 0, "selected": false, "text": "<p>If you want to roll your own:</p>\n\n<pre><code>private static final int MAX_WORKERS = n;\nprivate List&lt;Worker&gt; workers = new ArrayList&lt;Worker&gt;(MAX_WORKERS);\n\nprivate boolean roomLeft() {\n synchronized (workers) {\n return (workers.size() &lt; MAX_WORKERS);\n }\n}\n\nprivate void addWorker() {\n synchronized (workers) {\n workers.add(new Worker(this));\n }\n}\n\npublic void removeWorker(Worker worker) {\n synchronized (workers) {\n workers.remove(worker);\n }\n}\n\npublic Example() {\n while (true) {\n if (roomLeft()) {\n addWorker();\n } \n }\n}\n</code></pre>\n\n<p>Where Worker is your class that extends Thread. Each worker will call this class's removeWorker method, passing itself in as a parameter, when it's finished doing it's thing.</p>\n\n<p>With that said, the Executor framework looks a lot better.</p>\n\n<p>Edit: Anyone care to explain why this is so bad, instead of just downmodding it?</p>\n" }, { "answer_id": 125390, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 0, "selected": false, "text": "<p>As others here have mentioned, your best bet is to make a thread pool with the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html\" rel=\"nofollow noreferrer\">Executors</a> class: </p>\n\n<p>However, if you want to roll your own, this code should give you an idea how to proceed. Basically, just add every new thread to a thread group and make sure that you never have more than N active threads in the group:</p>\n\n<pre><code>Task[] tasks = getTasks(); // array of tasks to complete\nThreadGroup group = new ThreadGroup();\nint i=0;\nwhile( i&lt;tasks.length || group.activeCount()&gt;0 ) {\n if( group.activeCount()&lt;N &amp;&amp; i&lt;tasks.length ) {\n new TaskThread(group, tasks[i]).start();\n i++;\n } else {\n Thread.sleep(100);\n }\n}\n</code></pre>\n" }, { "answer_id": 126283, "author": "Fabian Steeg", "author_id": 18154, "author_profile": "https://Stackoverflow.com/users/18154", "pm_score": 5, "selected": false, "text": "<pre><code>/* Get an executor service that will run a maximum of 5 threads at a time: */\nExecutorService exec = Executors.newFixedThreadPool(5);\n/* For all the 100 tasks to be done altogether... */\nfor (int i = 0; i &lt; 100; i++) {\n /* ...execute the task to run concurrently as a runnable: */\n exec.execute(new Runnable() {\n public void run() {\n /* do the work to be done in its own thread */\n System.out.println(\"Running in: \" + Thread.currentThread());\n }\n });\n}\n/* Tell the executor that after these 100 steps above, we will be done: */\nexec.shutdown();\ntry {\n /* The tasks are now running concurrently. We wait until all work is done, \n * with a timeout of 50 seconds: */\n boolean b = exec.awaitTermination(50, TimeUnit.SECONDS);\n /* If the execution timed out, false is returned: */\n System.out.println(\"All done: \" + b);\n} catch (InterruptedException e) { e.printStackTrace(); }\n</code></pre>\n" }, { "answer_id": 35117224, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 1, "selected": false, "text": "<ol>\n<li><p>If your task queue is not going to be unbounded and tasks can complete in shorter time intervals, you can use <code>Executors.newFixedThreadPool(n)</code>; as suggests by experts. </p>\n\n<p>The only drawback in this solution is unbounded task queue size. You don't have control over it. The huge pile-up in task queue will degrade performance of application and may cause out of memory in some scenarios.</p></li>\n<li><p>If you want to use <code>ExecutorService</code> and enable <strong><em><code>work stealing</code></em></strong> mechanism where idle worker threads share the work load from busy worker threads by stealing tasks in task queue. It will return ForkJoinPool type of Executor Service. </p>\n\n<blockquote>\n <p>public static <code>ExecutorService newWorkStealingPool</code>(int parallelism)</p>\n \n <p>Creates a thread pool that maintains enough threads to support the given parallelism level, and may use multiple queues to reduce contention. The parallelism level corresponds to the maximum number of threads actively engaged in, or available to engage in, task processing. The actual number of threads may grow and shrink dynamically. A work-stealing pool makes no guarantees about the order in which submitted tasks are executed.</p>\n</blockquote></li>\n<li><p>I prefer <code>ThreadPoolExecutor</code> due to flexibility in APIs to control many paratmeters, which controls the flow task execution. </p>\n\n<pre><code>ThreadPoolExecutor(int corePoolSize, \n int maximumPoolSize, \n long keepAliveTime, \n TimeUnit unit, \n BlockingQueue&lt;Runnable&gt; workQueue, \n ThreadFactory threadFactory,\n RejectedExecutionHandler handler)\n</code></pre></li>\n</ol>\n\n<p>in your case, set both <code>corePoolSize and maximumPoolSize as N</code>. Here you can control task queue size, define your own custom thread factory and rejection handler policy.</p>\n\n<p>Have a look at related SE question to control the pool size dynamically:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/32527078/dynamic-thread-pool/32527532#32527532\">Dynamic Thread Pool</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
I'm looking for the simplest, most straightforward way to implement the following: * The main program instantiates worker threads to do a task. * Only `n` tasks can be running at once. * When `n` is reached, no more workers are started until the count of running threads drops back below `n`.
I think that [Executors.newFixedThreadPool](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)) fits your requirements. There are a number of different ways to use the resulting ExecutorService, depending on whether you want a result returned to the main thread, or whether the task is totally self-contained, and whether you have a collection of tasks to perform up front, or whether tasks are queued in response to some event. ``` Collection<YourTask> tasks = new ArrayList<YourTask>(); YourTask yt1 = new YourTask(); ... tasks.add(yt1); ... ExecutorService exec = Executors.newFixedThreadPool(5); List<Future<YourResultType>> results = exec.invokeAll(tasks); ``` Alternatively, if you have a new asynchronous task to perform in response to some event, you probably just want to use the ExecutorService's simple `execute(Runnable)` method.
125,359
<p>In Java, web apps are bundled in to WARs. By default, many servlet containers will use the WAR name as the context name for the application.</p> <p>Thus myapp.war gets deployed to <a href="http://example.com/myapp" rel="noreferrer">http://example.com/myapp</a>.</p> <p>The problem is that the webapp considers its "root" to be, well, "root", or simply "/", whereas HTML would consider the root of your application to be "/myapp".</p> <p>The Servlet API and JSP have facilities to help manage this. For example, if, in a servlet, you do: response.sendRedirect("/mypage.jsp"), the container will prepend the context and create the url: <a href="http://example.com/myapp/mypage.jsp" rel="noreferrer">http://example.com/myapp/mypage.jsp</a>".</p> <p>However, you can't do that with, say, the IMG tag in HTML. If you do &lt;img src="/myimage.gif"/> you will likely get a 404, because what you really wanted was "/myapp/myimage.gif".</p> <p>Many frameworks have JSP tags that are context aware as well, and there are different ways of making correct URLs within JSP (none particularly elegantly).</p> <p>It's a nitty problem for coders to jump in an out of when to use an "App Relative" url, vs an absolute url.</p> <p>Finally, there's the issue of Javascript code that needs to create URLs on the fly, and embedded URLs within CSS (for background images and the like).</p> <p>I'm curious what techniques others use to mitigate and work around this issue. Many simply punt and hard code it, either to server root or to whatever context they happen to be using. I already know that answer, that's not what I'm looking for.</p> <p>What do you do?</p>
[ { "answer_id": 125420, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 0, "selected": false, "text": "<p>I by <em>no</em> means claim that the following is an elegant issue. In fact, in hindsight, I wouldn't recommend this issue given the (most likely) performance hit. </p>\n\n<p>Our web app's JSPs were strictly XML raw data. This raw data was then sent into an XSL (server-side) which applied the right CSS tags, and spit out the XHTML. </p>\n\n<p>We had a single template.xsl which would be inherited by the multiple XSL files that we had for different components of the website. Our paths were all defined in an XSL file called paths.xml:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;paths&gt;\n &lt;path name=\"account\" parent=\"home\"&gt;Account/&lt;/path&gt;\n &lt;path name=\"css\"&gt;css/&lt;/path&gt;\n &lt;path name=\"home\"&gt;servlet/&lt;/path&gt;\n &lt;path name=\"icons\" parent=\"images\"&gt;icons/&lt;/path&gt;\n &lt;path name=\"images\"&gt;images/&lt;/path&gt;\n &lt;path name=\"js\"&gt;js/&lt;/path&gt;\n&lt;/paths&gt;\n</code></pre>\n\n<p>An internal link would be in the XML as follows:</p>\n\n<pre><code>&lt;ilink name=\"link to icons\" type=\"icons\"&gt;link to icons&lt;/ilink&gt;\n</code></pre>\n\n<p>This would get processed by our XSL:</p>\n\n<pre><code>&lt;xsl:template match=\"ilink\"&gt;\n &lt;xsl:variable name=\"temp\"&gt;\n &lt;xsl:value-of select=\"$rootpath\" /&gt;\n &lt;xsl:call-template name=\"paths\"&gt;\n &lt;xsl:with-param name=\"path-name\"&gt;&lt;xsl:value-of select=\"@type\" /&gt;&lt;/xsl:with-param&gt;\n &lt;/xsl:call-template&gt;\n &lt;xsl:value-of select=\"@file\" /&gt;\n &lt;/xsl:variable&gt;\n &lt;a href=\"{$temp}\" title=\"{@name}\" &gt;&lt;xsl:value-of select=\".\" /&gt;&lt;/a&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p><code>$rootPath</code> was passed onto each file with <code>${applicationScope.contextPath}</code> The idea behind us using XML instead of just hard-coding it in a JSP/Java file was we didn't want to have to recompile. </p>\n\n<p>Again, the solution isn't a good one at all...but we did use it once!</p>\n\n<p><strong>Edit</strong>: Actually, the complexity in our issue arose because we weren't able to use JSPs for our entire view. Why wouldn't someone just use <code>${applicationScope.contextPath}</code> to retrieve the context path? It worked fine for us then.</p>\n" }, { "answer_id": 125737, "author": "kosoant", "author_id": 15114, "author_profile": "https://Stackoverflow.com/users/15114", "pm_score": 1, "selected": false, "text": "<p>I've used <b>helper classes</b> to generate img tags etc. This helper class takes care of <b>prefixing paths</b> with the application's contextPath. (This works, but I don't really like it. If anyone has any better alternatives, please tell.)</p>\n\n<p>For paths in css files etc. I use an <b>Ant build script</b> that uses a site.production.css for site.css in production environment and site.development.css in development encironment. </p>\n\n<p>Alternatively I sometimes use an Ant script that <b>replaces @token@</b> tokens with proper data for different environents. In this case @contextPAth@ token would be replaced with the correct context path.</p>\n" }, { "answer_id": 125770, "author": "Vilmantas Baranauskas", "author_id": 11662, "author_profile": "https://Stackoverflow.com/users/11662", "pm_score": 1, "selected": false, "text": "<p>One option is to use \"flat\" application structure and relative URLs whenever possible.</p>\n\n<p>By \"flat\" I mean that there are no subdirectories under your application root, maybe just few directories for static content as \"images/\". All your JSP's, action URLs, servlets go directly under the root.</p>\n\n<p>This doesn't completely solve your problem but simplifies it greatly.</p>\n" }, { "answer_id": 126017, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>You can use JSTL for creating urls.</p>\n\n<p>For example, <code>&lt;c:url value=\"/images/header.jpg\" /&gt;</code> will prefix the context root.</p>\n\n<p>With CSS, this usually isn't an issue for me.</p>\n\n<p>I have a web root structure like this:</p>\n\n<p>/css<br>\n/images</p>\n\n<p>In the CSS file, you then just need to use relative URLs (../images/header.jpg) and it doesn't need to be aware of the context root.</p>\n\n<p>As for JavaScript, what works for me is including some common JavaScript in the page header like this:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nvar CONTEXT_ROOT = '&lt;%= request.getContextPath() %&gt;';\n&lt;/script&gt;\n</code></pre>\n\n<p>Then you can use the context root in all your scripts (or, you can define a function to build paths - may be a bit more flexible).</p>\n\n<p>Obviously this all depends on your using JSPs and JSTL, but I use JSF with Facelets and the techniques involved are similar - the only real difference is getting the context root in a different way.</p>\n" }, { "answer_id": 128569, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 1, "selected": false, "text": "<p>Vilmantas said the right word here: relative URLs.</p>\n\n<p>All you need to do in your IMG is to use</p>\n\n<pre><code>&lt;img src=\"myimage.gif\"/&gt;\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>&lt;img src=\"/myimage.gif\"/&gt;\n</code></pre>\n\n<p>and it'll be relative to the app context (as the browser is interpreting the URL to go to)</p>\n" }, { "answer_id": 128750, "author": "Travis Wilson", "author_id": 8735, "author_profile": "https://Stackoverflow.com/users/8735", "pm_score": 1, "selected": false, "text": "<p>Except for special cases, I'd recommend against using absolute URLs this way. Ever. Absolute URLs are good for when <em>another webapp</em> is pointing at something in your webapp. Internally -- when one resource is pointing at a second resource in the same context -- the resource should know where it lives, so it should be able to express a relative path to the second resource.</p>\n\n<p>Of course, you'll write modular components, which don't know the resource that's including them. For example:</p>\n\n<pre><code>/myapp/user/email.jsp:\nEmail: &lt;a href=\"../sendmail.jsp\"&gt;${user.email}&lt;/a&gt;\n\n/myapp/browse/profile.jsp:\n&lt;jsp:include page=\"../user/email.jsp\" /&gt;\n\n/myapp/home.jsp:\n&lt;jsp:include page=\"../user/email.jsp\" /&gt;\n</code></pre>\n\n<p>So, how does <code>email.jsp</code> know the relative path of <code>sendmail.jsp</code>? Clearly the link will break on either <code>/myapp/browse/profile.jsp</code> or it will break on <code>/myapp/home.jsp</code> . The answer is, keep all your URLs in the same flat filepath space. That is, every URL should have no slashes after <code>/myapp/</code> .</p>\n\n<p>This is pretty easy to accomplish, as long as you have some kind of mapping between URLs and the actual files that generate the content. (e.g. in Spring, use DispatcherServlet to map URLs to JSP files or to views.)</p>\n\n<p>There are special cases. e.g. if you're writing a browser-side application in Javascript, then it gets harder to maintain a flat filepath space. In that case, or in other special cases, or just if you have a personal preference, it's not really a big deal to use <code>&lt;%= request.getContextPath() %&gt;</code> to create an absolute path.</p>\n" }, { "answer_id": 131903, "author": "Brian Deterling", "author_id": 14619, "author_profile": "https://Stackoverflow.com/users/14619", "pm_score": 1, "selected": false, "text": "<p>You can use request.getContextPath() to build absolute URLs that aren't hard-coded to a specific context. As an earlier answer indicated, for JavaScript you just set a variable at the top of your JSP (or preferably in a template) and prefix that as the context.</p>\n\n<p>That doesn't work for CSS image replacement unless you want to dynamically generate a CSS file, which can cause other issues. But since you know where your CSS file is in relation to your images, you can get away with relative URLs. </p>\n\n<p>For some reason, I've had trouble with IE handling relative URLs and had to fall back to using expressions with a JavaScript variable set to the context. I just split my IE image replacements off into their own file and used IE macros to pull in the correct ones. It wasn't a big deal because I already had to do that to deal with transparent PNGs anyway. It's not pretty, but it works.</p>\n" }, { "answer_id": 137779, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 1, "selected": false, "text": "<p>I've used most of these techniques (save the XSLT architecture).</p>\n\n<p>I think the crux (and consensus) of the problem is having a site with potentially multiple directories.</p>\n\n<p>If your directory depth (for lack of a better term) is constant, then you can rely on relative urls in things like CSS.</p>\n\n<p>Mind, the layout doesn't have to be completely flat, just consistent.</p>\n\n<p>For example, we've done hierarchies like /css, /js, /common, /admin, /user. Putting appropriate pages and resources in the proper directories. Having a structure like this works very well with Container based authentication.</p>\n\n<p>I've also mapped *.css and *.js to the JSP servlet, and made them dynamic so I can build them on the fly.</p>\n\n<p>I was just hoping there was something else I may have missed.</p>\n" }, { "answer_id": 142887, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 0, "selected": false, "text": "<p>When creating a site from scratch, I side with @Will - aim for a consistent and predictable url structure so that you can stick with relative references.</p>\n\n<p>But things can get really messy if you are updating a site that was originally built to work directly under the site root \"/\" (pretty common for simple JSP sites) to formal <a href=\"http://java.sun.com/javaee/5/docs/api/\" rel=\"nofollow noreferrer\">Java EE</a> packaging (where context root will be some path under the root).</p>\n\n<p>That can mean a lot of code changes.</p>\n\n<p>If you want to avoid or postpone the code changes, but still ensure correct context root referencing, a technique I've tested is to use servlet filters. The filter can be dropped into an existing proejct without changing anything (except web.xml), and will remap any url references in the outbound HTML to the correct path, and also ensure redirects are correctly referenced.</p>\n\n<p>An example site and usable code available here: <a href=\"http://github.com/tardate/sources/tree/master%2FEnforceContextRootFilter-1.0-src.zip?raw=true\" rel=\"nofollow noreferrer\">EnforceContextRootFilter-1.0-src.zip</a> \nNB: the actual mapping rules are implemented as regex in the servlet class and provide a pretty general catch-all - but you may need to modify for particular circumstances. </p>\n\n<p><em>btw, I forked a slightly different question to address <a href=\"https://stackoverflow.com/questions/142965/handling-context-path-refs-when-migrating-site-to-java-ee-packaging\">migrating existing code base from \"/\" to a non-root context-path</a></em></p>\n" }, { "answer_id": 169722, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>The Servlet API and JSP have\n facilities to help manage this. For\n example, if, in a servlet, you do:\n response.sendRedirect(\"/mypage.jsp\"),\n the container will prepend the context\n and create the url:\n <a href=\"http://example.com/myapp/mypage.jsp\" rel=\"nofollow noreferrer\">http://example.com/myapp/mypage.jsp</a>\".</p>\n</blockquote>\n\n<p>Ah, maybe, maybe not - it depends on your container and the servlet spec! </p>\n\n<p>From <a href=\"http://java.sun.com/developer/technicalArticles/Servlets/servletapi2.3/index.html\" rel=\"nofollow noreferrer\">Servlet 2.3: New features exposed</a>:</p>\n\n<blockquote>\n <p>And finally, after a lengthy debate by\n a group of experts, Servlet API 2.3\n has clarified once and for all exactly\n what happens on a\n res.sendRedirect(\"/index.html\") call\n for a servlet executing within a\n non-root context. The issue is that\n Servlet API 2.2 requires an incomplete\n path like \"/index.html\" to be\n translated by the servlet container\n into a complete path, but doesn't say\n how context paths are handled. If the\n servlet making the call is in a\n context at the path \"/contextpath,\"\n should the redirect URI translate\n relative to the container root\n (<a href=\"http://server:port/index.html\" rel=\"nofollow noreferrer\">http://server:port/index.html</a>) or the\n context root\n (<a href=\"http://server:port/contextpath/index.html\" rel=\"nofollow noreferrer\">http://server:port/contextpath/index.html</a>)?\n For maximum portability, it's\n imperative to define the behavior;\n after lengthy debate, the experts\n chose to translate relative to the\n container root. For those who want\n context relative, you can prepend the\n output from getContextPath() to your\n URI.</p>\n</blockquote>\n\n<p>So no, with 2.3 your paths are <strong>not</strong> automatically translated to include the context path.</p>\n" }, { "answer_id": 4955473, "author": "Demwis", "author_id": 537246, "author_profile": "https://Stackoverflow.com/users/537246", "pm_score": 2, "selected": false, "text": "<p>I agree with <strong>tardate</strong>.\nI have paid my attention at filters too and have found the solution in face of project <a href=\"http://www.tuckey.org/urlrewrite/\" rel=\"nofollow\">UrlRewriteFilter</a>.\nThe simple configuration like following:</p>\n\n<pre><code>&lt;rule&gt;\n &lt;from&gt;^.+/resources/(.*)$&lt;/from&gt;\n &lt;to&gt;/resources/$1&lt;/to&gt;\n&lt;/rule&gt;\n</code></pre>\n\n<p>helps to forward all requests for */resources path to /resources pass (including context path prefix). So I can simply put all my <strong>images</strong> and <strong>CSS</strong> files under <strong>resources</strong> folder and continue using relative URLs in my styles for background images and other cases.</p>\n" }, { "answer_id": 4956614, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 3, "selected": false, "text": "<p>For HTML pages, I just set the HTML <code>&lt;base&gt;</code> tag. Every relative link (i.e. not starting with scheme or <code>/</code>) will become relative to it. There is no clean way to grab it immediately by <code>HttpServletRequest</code>, so we need little help of JSTL here.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;%@taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %&gt;\n&lt;%@taglib prefix=\"fn\" uri=\"http://java.sun.com/jsp/jstl/functions\" %&gt;\n&lt;c:set var=\"req\" value=\"${pageContext.request}\" /&gt;\n&lt;c:set var=\"url\"&gt;${req.requestURL}&lt;/c:set&gt;\n&lt;c:set var=\"uri\"&gt;${req.requestURI}&lt;/c:set&gt;\n\n&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n &lt;head&gt;\n &lt;base href=\"${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/\" /&gt;\n &lt;link rel=\"stylesheet\" href=\"css/default.css\"&gt;\n &lt;script src=\"js/default.js\"&gt;&lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;img src=\"img/logo.png\" /&gt;\n &lt;a href=\"other.jsp\"&gt;link&lt;/a&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>This has in turn however a caveat: anchors (the <code>#identifier</code> URL's) will become relative to the base path as well. If you have any of them, you would like to make it relative to the request URL (URI) instead. So, change like</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;a href=\"#identifier\"&gt;jump&lt;/a&gt;\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;a href=\"${uri}#identifier\"&gt;jump&lt;/a&gt;\n</code></pre>\n\n<hr>\n\n<p>In JS, you can just access the <code>&lt;base&gt;</code> element from the DOM whenever you'd like to convert a relative URL to an absolute URL. </p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var base = document.getElementsByTagName(\"base\")[0].href;\n</code></pre>\n\n<p>Or if you do jQuery</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var base = $(\"base\").attr(\"href\");\n</code></pre>\n\n<hr>\n\n<p>In CSS, the image URLs are relative to the URL of the stylesheet itself. So, just drop the images in some folder relative to the stylesheet itself. E.g.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>/css/style.css\n/css/images/foo.png\n</code></pre>\n\n<p>and reference them as follows</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>background-image: url('images/foo.png');\n</code></pre>\n\n<p>If you rather like to drop the images in some folder at same level as CSS folder</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>/css/style.css\n/images/foo.png\n</code></pre>\n\n<p>then use <code>../</code> to go to the common parent folder</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>background-image: url('../images/foo.png');\n</code></pre>\n\n<h3>See also:</h3>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1889076/is-it-recommended-to-use-the-base-html-tag\">Is it recommended to use the <code>&lt;base&gt;</code> html tag?</a></li>\n</ul>\n" }, { "answer_id": 39394912, "author": "Brett Ryan", "author_id": 140037, "author_profile": "https://Stackoverflow.com/users/140037", "pm_score": 0, "selected": false, "text": "<p>I tend to write a property as part of my core JavaScript library within my. I don't think it's perfect but I think it's the best I've managed to achieve.</p>\n\n<p>First off, I have a module that's part of my app core that is always available</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>(function (APP) {\n var ctx;\n APP.setContext = function (val) {\n // protect rogue JS from setting the context.\n if (ctx) {\n return;\n }\n val = val || val.trim();\n // Don't allow a double slash for a context.\n if (val.charAt(0) === '/' &amp;&amp; val.charAt(1) === '/') {\n return;\n }\n // Context must both start and end in /.\n if (val.length === 0 || val === '/') {\n val = '/';\n } else {\n if (val.charAt(0) !== '/') {\n val = '/' + val;\n }\n if (val.slice(-1) !== '/') {\n val += '/';\n }\n }\n ctx = val;\n };\n APP.getContext = function () {\n return ctx || '/';\n };\n APP.getUrl = function (val) {\n if (val &amp;&amp; val.length &gt; 0) {\n return APP.getContext() + (val.charAt(0) === '/' ? val.substring(1) : val);\n }\n return APP.getContext();\n };\n})(window.APP = window.APP || {});\n</code></pre>\n\n<p>I then use apache tiles with a common header that always contains the following:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;script type=\"text/javascript\"&gt;\n APP.setContext('${pageContext.request['contextPath']}');\n // If preferred use JSTL cor, but it must be available and declared.\n //APP.setContext('&lt;c:url value='/'/&gt;');\n&lt;/script&gt;\n</code></pre>\n\n<p>Now that I've initialized the context I may use <code>getUrl(path)</code> from anywhere (js files or within jsp/html) which will return an absolute path for the given input string within the context.</p>\n\n<p>Note that the following are both equivalent intentionally. <code>getUrl</code> will always return an absolute path as a relative path does not need you to know the context in the first place.</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>var path = APP.getUrl(\"/some/path\");\nvar path2 = APP.getUrl(\"some/path\");\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13663/" ]
In Java, web apps are bundled in to WARs. By default, many servlet containers will use the WAR name as the context name for the application. Thus myapp.war gets deployed to <http://example.com/myapp>. The problem is that the webapp considers its "root" to be, well, "root", or simply "/", whereas HTML would consider the root of your application to be "/myapp". The Servlet API and JSP have facilities to help manage this. For example, if, in a servlet, you do: response.sendRedirect("/mypage.jsp"), the container will prepend the context and create the url: <http://example.com/myapp/mypage.jsp>". However, you can't do that with, say, the IMG tag in HTML. If you do <img src="/myimage.gif"/> you will likely get a 404, because what you really wanted was "/myapp/myimage.gif". Many frameworks have JSP tags that are context aware as well, and there are different ways of making correct URLs within JSP (none particularly elegantly). It's a nitty problem for coders to jump in an out of when to use an "App Relative" url, vs an absolute url. Finally, there's the issue of Javascript code that needs to create URLs on the fly, and embedded URLs within CSS (for background images and the like). I'm curious what techniques others use to mitigate and work around this issue. Many simply punt and hard code it, either to server root or to whatever context they happen to be using. I already know that answer, that's not what I'm looking for. What do you do?
You can use JSTL for creating urls. For example, `<c:url value="/images/header.jpg" />` will prefix the context root. With CSS, this usually isn't an issue for me. I have a web root structure like this: /css /images In the CSS file, you then just need to use relative URLs (../images/header.jpg) and it doesn't need to be aware of the context root. As for JavaScript, what works for me is including some common JavaScript in the page header like this: ``` <script type="text/javascript"> var CONTEXT_ROOT = '<%= request.getContextPath() %>'; </script> ``` Then you can use the context root in all your scripts (or, you can define a function to build paths - may be a bit more flexible). Obviously this all depends on your using JSPs and JSTL, but I use JSF with Facelets and the techniques involved are similar - the only real difference is getting the context root in a different way.
125,369
<p>I come across this problem when i am writing an event handler in SharePoint. My event handler has a web reference. When i create this web reference, the URL of the web service will be added in the .config file of the assembly. If i have to change the web reference URL i just have to change the link in the config file. </p> <p>Problem comes when I try to GAC the dll. When i GAC the DLL, the config file cannot be GACed along with the dll, and hence, there is no way for me to update the web reference. </p> <p>One workaround i have found is to modify the constructor method Reference.cs class which is autogenerated by visual studio when i add a reference, so that the constructor reads the web service url from some other location, say a registry or an XML file in some predetermined location. But this poses a problem sometimes, as when i update the web referenc using visual studio, this Reference.cs file gets regenerated, and all my modifications would be lost.</p> <p>Is there a better way to solve this problem?</p>
[ { "answer_id": 125375, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": true, "text": "<p>If you have Visual Studio 2008, use a Service Reference instead of a Web Reference, which will generate partial classes that you can use to override functionality without your code overwritten by the generator.</p>\n\n<p>For Visual Studio 2005, you could just add the <em>partial</em> keyword to the class in Reference.cs and keep a separate file with your own partial class:</p>\n\n<pre><code>public partial class WebServiceReference\n { public WebServiceReference(ExampleConfigurationClass config) \n { /* ... */\n }\n }\n\nWebServiceReference svc = new WebServiceReference(myConfig);\n</code></pre>\n" }, { "answer_id": 125397, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 2, "selected": false, "text": "<p>Any application hosted by SharePoint is using the web.config located at the root of your SharePoint web site in IIS. What you need to do is add the configuration generated by the Web/Service Reference wizard to your web.config.</p>\n\n<p>This is roughly how it works:</p>\n\n<ul>\n<li>SharePoint application pool loads your DLL</li>\n<li>Your DLL looks for the service information in the current application configuration file</li>\n<li>Your DLL finds web.config and looks for configuration information there</li>\n</ul>\n\n<p>Basically, the app.config that is being generated in your DLL is not used. As the application in this case is the Application Pool (w3wp.exe) that is hosting the SharePoint application. For SharePoint the app.config is actually named web.config and exists at the root of the SharePoint website.</p>\n" }, { "answer_id": 125408, "author": "ZeroBugBounce", "author_id": 11314, "author_profile": "https://Stackoverflow.com/users/11314", "pm_score": -1, "selected": false, "text": "<p>You could try this: Rather than using the dynamic web reference make it a static reference so that the code in Reference.cs won't go looking for a value in the .config file for the url. Then sub-class the generated web service client code and in that derived class, add your own logic to set the .Url property. Then VS.NET can re-gen Reference.cs all it likes, and your url setting code will remain. Of course, you have to update any downstream code to use your derived class, but that should be a simple global replace.</p>\n" }, { "answer_id": 139430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I resolved this by making the web reference dynamic for my class library and then copying the applicationSettings config section containing the web reference from the app.config file into my Sharepoint site web.config.</p>\n\n<p>Note you will also need to copy the entry for applicationSettings into your web.config as this is not in there normally.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909/" ]
I come across this problem when i am writing an event handler in SharePoint. My event handler has a web reference. When i create this web reference, the URL of the web service will be added in the .config file of the assembly. If i have to change the web reference URL i just have to change the link in the config file. Problem comes when I try to GAC the dll. When i GAC the DLL, the config file cannot be GACed along with the dll, and hence, there is no way for me to update the web reference. One workaround i have found is to modify the constructor method Reference.cs class which is autogenerated by visual studio when i add a reference, so that the constructor reads the web service url from some other location, say a registry or an XML file in some predetermined location. But this poses a problem sometimes, as when i update the web referenc using visual studio, this Reference.cs file gets regenerated, and all my modifications would be lost. Is there a better way to solve this problem?
If you have Visual Studio 2008, use a Service Reference instead of a Web Reference, which will generate partial classes that you can use to override functionality without your code overwritten by the generator. For Visual Studio 2005, you could just add the *partial* keyword to the class in Reference.cs and keep a separate file with your own partial class: ``` public partial class WebServiceReference { public WebServiceReference(ExampleConfigurationClass config) { /* ... */ } } WebServiceReference svc = new WebServiceReference(myConfig); ```
125,377
<p>I've tried this, but get a ClassNotFoundException when calling:</p> <pre><code>Class.forName("com.AClass", false, mySpecialLoader) </code></pre>
[ { "answer_id": 125686, "author": "Brian Deterling", "author_id": 14619, "author_profile": "https://Stackoverflow.com/users/14619", "pm_score": 3, "selected": false, "text": "<p>The ClassLoader will have to call defineClass to get the Class. According to the JavaDoc for defineClass: </p>\n\n<blockquote>\n <p>If name is not null, it must be equal\n to the binary name of the class\n specified by the byte array.</p>\n</blockquote>\n\n<p>If the name is null, it will get it from the bytecode. So you can return any class you want as long as it's called com.AClass. In other words, you could have multiple versions of com.AClass. You could even use something like JavaAssist to create a class on the fly.</p>\n\n<p>But that doesn't explain the ClassNotFoundException - it sounds like your class loader isn't returning anything.</p>\n" }, { "answer_id": 227692, "author": "Jevgeni Kabanov", "author_id": 20022, "author_profile": "https://Stackoverflow.com/users/20022", "pm_score": 1, "selected": false, "text": "<p>It is impossible to return a class named differently than the one requested. However it is possible to use bytecode manipulation tools like ASM to automatically rename the class you want to return to the one requested.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21364/" ]
I've tried this, but get a ClassNotFoundException when calling: ``` Class.forName("com.AClass", false, mySpecialLoader) ```
The ClassLoader will have to call defineClass to get the Class. According to the JavaDoc for defineClass: > > If name is not null, it must be equal > to the binary name of the class > specified by the byte array. > > > If the name is null, it will get it from the bytecode. So you can return any class you want as long as it's called com.AClass. In other words, you could have multiple versions of com.AClass. You could even use something like JavaAssist to create a class on the fly. But that doesn't explain the ClassNotFoundException - it sounds like your class loader isn't returning anything.
125,389
<p>I am writing a custom maven2 MOJO. I need to access the runtime configuration of another plugin, from this MOJO.</p> <p>What is the best way to do this?</p>
[ { "answer_id": 130171, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 0, "selected": false, "text": "<p>I'm not sure how you would do that exactly, but it seems to me that this might not be the best design decision. If at all possible you should aim to decouple your Mojo from any other plugins out there.</p>\n\n<p>Instead I would recommend using custom properties to factor out any duplication in the configuration of separate plugins.</p>\n\n<p>You can set a custom property \"foo\" in your pom by using the properties section:</p>\n\n<pre><code>&lt;project&gt;\n ...\n &lt;properties&gt;\n &lt;foo&gt;value&lt;/foo&gt;\n &lt;/properties&gt;\n ...\n&lt;/project&gt;\n</code></pre>\n\n<p>The property foo is now accessible anywhere in the pom by using the dollar sign + curly brace notation:</p>\n\n<pre><code>&lt;somePluginProperty&gt;${foo}&lt;/somePluginProperty&gt;\n</code></pre>\n" }, { "answer_id": 130872, "author": "npellow", "author_id": 2767300, "author_profile": "https://Stackoverflow.com/users/2767300", "pm_score": 2, "selected": false, "text": "<p>Using properties is certainly one way to go, however not ideal. It still requires a user to define the ${propertyName} in multiple places throughout the pom. I want to allow my plugin to work with no modifications to the user's pom, other than the plugin definition itself.</p>\n\n<p>I don't see accessing the runtime properties of another MOJO as too tight coupling. If the other MOJO is defined anywhere in the build hierarchy, I want my MOJO to respect the same configuration.</p>\n\n<p>My current solution is:</p>\n\n<pre><code>private Plugin lookupPlugin(String key) {\n\n List plugins = getProject().getBuildPlugins();\n\n for (Iterator iterator = plugins.iterator(); iterator.hasNext();) {\n Plugin plugin = (Plugin) iterator.next();\n if(key.equalsIgnoreCase(plugin.getKey())) {\n return plugin;\n }\n }\n return null;\n}\n\n\n/**\n * Extracts nested values from the given config object into a List.\n * \n * @param childname the name of the first subelement that contains the list\n * @param config the actual config object\n */\nprivate List extractNestedStrings(String childname, Xpp3Dom config) {\n\n final Xpp3Dom subelement = config.getChild(childname);\n if (subelement != null) {\n List result = new LinkedList();\n final Xpp3Dom[] children = subelement.getChildren();\n for (int i = 0; i &lt; children.length; i++) {\n final Xpp3Dom child = children[i];\n result.add(child.getValue());\n }\n getLog().info(\"Extracted strings: \" + result);\n return result;\n }\n\n return null;\n}\n</code></pre>\n\n<p>This has worked for the few small builds I've tested with. Including a multi-module build.</p>\n" }, { "answer_id": 1073554, "author": "Kingamajick", "author_id": 131693, "author_profile": "https://Stackoverflow.com/users/131693", "pm_score": 2, "selected": false, "text": "<p>You can get a list of plugins currently been used in the build using the following steps:</p>\n\n<p>First you need to get Maven to inject the current project into your mojo, you use the class variable defined below to get this.</p>\n\n<pre><code>/**\n * The maven project.\n * \n * @parameter expression=\"${project}\"\n * @readonly\n */\n private MavenProject project;\n</code></pre>\n\n<p>Then you can use the following to get a list of plugins used in this build.</p>\n\n<pre><code>mavenProject.getBuildPlugins()\n</code></pre>\n\n<p>You can iterate though this list until you find the plugin from which you want to extract configuration.</p>\n\n<p>Finally, you can get the configuration as a Xpp3Dom.</p>\n\n<pre><code>plugin.getConfiguration()\n</code></pre>\n\n<p>Note: If your altering the other plugins configuration (rather than just extracting information), it will only remain altered for the current phase and not subsequent phases.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2767300/" ]
I am writing a custom maven2 MOJO. I need to access the runtime configuration of another plugin, from this MOJO. What is the best way to do this?
Using properties is certainly one way to go, however not ideal. It still requires a user to define the ${propertyName} in multiple places throughout the pom. I want to allow my plugin to work with no modifications to the user's pom, other than the plugin definition itself. I don't see accessing the runtime properties of another MOJO as too tight coupling. If the other MOJO is defined anywhere in the build hierarchy, I want my MOJO to respect the same configuration. My current solution is: ``` private Plugin lookupPlugin(String key) { List plugins = getProject().getBuildPlugins(); for (Iterator iterator = plugins.iterator(); iterator.hasNext();) { Plugin plugin = (Plugin) iterator.next(); if(key.equalsIgnoreCase(plugin.getKey())) { return plugin; } } return null; } /** * Extracts nested values from the given config object into a List. * * @param childname the name of the first subelement that contains the list * @param config the actual config object */ private List extractNestedStrings(String childname, Xpp3Dom config) { final Xpp3Dom subelement = config.getChild(childname); if (subelement != null) { List result = new LinkedList(); final Xpp3Dom[] children = subelement.getChildren(); for (int i = 0; i < children.length; i++) { final Xpp3Dom child = children[i]; result.add(child.getValue()); } getLog().info("Extracted strings: " + result); return result; } return null; } ``` This has worked for the few small builds I've tested with. Including a multi-module build.
125,400
<p>Not sure if this is possible or if I'm expressing correctly what I'm looking for, but I have the following piece of code in my library repeatedly and would like to practice some DRY. I have set of SQL Server tables that I'm querying based on a simple user-supplied search field ala Google. I'm using LINQ to compose the final query based on what's in the search string. I'm looking for a way to use generics and passed in lambda functions to create a reusable routine out of this: </p> <pre><code>string[] arrayOfQueryTerms = getsTheArray(); var somequery = from q in dataContext.MyTable select q; if (arrayOfQueryTerms.Length == 1) { somequery = somequery.Where&lt;MyTableEntity&gt;( e =&gt; e.FieldName.StartsWith(arrayOfQueryTerms[0])); } else { foreach(string queryTerm in arrayOfQueryTerms) { if (!String.IsNullOrEmpty(queryTerm)) { somequery = somequery .Where&lt;MyTableEntity&gt;( e =&gt; e.FieldName.Contains(queryTerm)); } } } </code></pre> <p>I was hoping to create a generic method with signature that looks something like:</p> <pre><code>private IQueryable&lt;T&gt; getQuery( T MyTableEntity, string[] arrayOfQueryTerms, Func&lt;T, bool&gt; predicate) </code></pre> <p>I'm using the same search strategy across all my tables, so the only thing that really differs from usage to usage is the MyTable &amp; MyTableEntity searched and the FieldName searched. Does this make sense? Is there a way with LINQ to dynamically pass in the name of the field to query in the where clause? Or can I pass in this as a predicate lambda?</p> <pre><code>e =&gt; e.FieldName.Contains(queryTerm) </code></pre> <p>I realize there a million and a half ways to do this in SQL, probably easier, but I'd love to keep everything in the LINQ family for this one. Also, I feel that generics should be handy for a problem like this. Any ideas?</p>
[ { "answer_id": 125414, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 3, "selected": false, "text": "<p>What it sounds like is you want basically a conditional predicate builder.. </p>\n\n<p>I hope you can mold this into something you are looking for, good luck!</p>\n\n<p><a href=\"http://www.albahari.com/nutshell/predicatebuilder.aspx\" rel=\"noreferrer\">http://www.albahari.com/nutshell/predicatebuilder.aspx</a></p>\n" }, { "answer_id": 125418, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 5, "selected": true, "text": "<p>It sounds like you're looking for Dynamic Linq. Take a look <a href=\"http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx\" rel=\"noreferrer\">here</a>. This allows you to pass strings as arguments to the query methods, like:</p>\n\n<pre><code>var query = dataSource.Where(\"CategoryID == 2 &amp;&amp; UnitPrice &gt; 3\")\n .OrderBy(\"SupplierID\");\n</code></pre>\n\n<p>Edit: Another set of posts on this subject, using C# 4's Dynamic support: <a href=\"http://weblogs.asp.net/davidfowler/archive/2010/08/04/dynamic-linq-a-little-more-dynamic.aspx\" rel=\"noreferrer\">Part 1</a> and <a href=\"http://weblogs.asp.net/davidfowler/archive/2010/08/19/dynamic-linq-part-2-evolution.aspx\" rel=\"noreferrer\">Part 2</a>.</p>\n" }, { "answer_id": 125429, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>You might want to look at expression trees:</p>\n\n<pre><code>IQueryable&lt;T&gt; getQuery&lt;T&gt;(T myTableEntity, string[] arrayOfQueryTerms, Expression&lt;Func&lt;T, bool&gt;&gt; predicate)\n { var fieldOrProperty = getMemberInfo(predicate);\n /* ... */\n }\n\nMemberInfo getmemberInfo&lt;T&gt;(Expression&lt;Func&lt;T,bool&gt; expr)\n { var memberExpr = expr as MemberExpression;\n if (memberExpr != null) return memberExpr.Member;\n throw new ArgumentException();\n }\n\nvar q = getQuery&lt;FooTable&gt;(foo, new[]{\"Bar\",\"Baz\"}, x=&gt;x.FieldName);\n</code></pre>\n" }, { "answer_id": 275215, "author": "user17060", "author_id": 17060, "author_profile": "https://Stackoverflow.com/users/17060", "pm_score": 0, "selected": false, "text": "<p>I recently had to do this same thing. You will need <a href=\"http://talesfromthebleedingedge.blogspot.com/2008/10/linq-to-entities-dynamic-linq-to.html\" rel=\"nofollow noreferrer\">Dynamic Linq</a> <a href=\"http://talesfromthebleedingedge.blogspot.com/2008/10/linq-to-entities-dynamic-linq-to.html\" rel=\"nofollow noreferrer\">here</a> is a way to keep this strongly typed. </p>\n" }, { "answer_id": 69234899, "author": "AliReza Sabouri", "author_id": 786376, "author_profile": "https://Stackoverflow.com/users/786376", "pm_score": 0, "selected": false, "text": "<p>I suggest trying the <strong><a href=\"https://github.com/alirezanet/Gridify\" rel=\"nofollow noreferrer\">Gridify</a></strong> library.\nIt is much easier to work with also it has better performance.</p>\n<p>usage example:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>query = dataSource.ApplyFiltering(&quot;FiledName=John&quot;);\n</code></pre>\n<p>this is a performance comparison between dynamic LINQ libraries.\n<a href=\"https://i.stack.imgur.com/rj3az.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rj3az.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17729/" ]
Not sure if this is possible or if I'm expressing correctly what I'm looking for, but I have the following piece of code in my library repeatedly and would like to practice some DRY. I have set of SQL Server tables that I'm querying based on a simple user-supplied search field ala Google. I'm using LINQ to compose the final query based on what's in the search string. I'm looking for a way to use generics and passed in lambda functions to create a reusable routine out of this: ``` string[] arrayOfQueryTerms = getsTheArray(); var somequery = from q in dataContext.MyTable select q; if (arrayOfQueryTerms.Length == 1) { somequery = somequery.Where<MyTableEntity>( e => e.FieldName.StartsWith(arrayOfQueryTerms[0])); } else { foreach(string queryTerm in arrayOfQueryTerms) { if (!String.IsNullOrEmpty(queryTerm)) { somequery = somequery .Where<MyTableEntity>( e => e.FieldName.Contains(queryTerm)); } } } ``` I was hoping to create a generic method with signature that looks something like: ``` private IQueryable<T> getQuery( T MyTableEntity, string[] arrayOfQueryTerms, Func<T, bool> predicate) ``` I'm using the same search strategy across all my tables, so the only thing that really differs from usage to usage is the MyTable & MyTableEntity searched and the FieldName searched. Does this make sense? Is there a way with LINQ to dynamically pass in the name of the field to query in the where clause? Or can I pass in this as a predicate lambda? ``` e => e.FieldName.Contains(queryTerm) ``` I realize there a million and a half ways to do this in SQL, probably easier, but I'd love to keep everything in the LINQ family for this one. Also, I feel that generics should be handy for a problem like this. Any ideas?
It sounds like you're looking for Dynamic Linq. Take a look [here](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx). This allows you to pass strings as arguments to the query methods, like: ``` var query = dataSource.Where("CategoryID == 2 && UnitPrice > 3") .OrderBy("SupplierID"); ``` Edit: Another set of posts on this subject, using C# 4's Dynamic support: [Part 1](http://weblogs.asp.net/davidfowler/archive/2010/08/04/dynamic-linq-a-little-more-dynamic.aspx) and [Part 2](http://weblogs.asp.net/davidfowler/archive/2010/08/19/dynamic-linq-part-2-evolution.aspx).
125,449
<p>I am using Excel where certain fields are allowed for user input and other cells are to be protected. I have used Tools Protect sheet, however after doing this I am not able to change the values in the VBA script. I need to restrict the sheet to stop user input, at the same time allow the VBA code to change the cell values based on certain computations.</p>
[ { "answer_id": 125505, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 2, "selected": false, "text": "<p><strike>I don't think you can set any part of the sheet to be editable only by VBA</strike>, but you can do something that has basically the same effect -- you can unprotect the worksheet in VBA before you need to make changes:</p>\n\n<pre><code>wksht.Unprotect()\n</code></pre>\n\n<p>and re-protect it after you're done:</p>\n\n<pre><code>wksht.Protect()\n</code></pre>\n\n<p>Edit: Looks like this workaround may have solved Dheer's immediate problem, but for anyone who comes across this question/answer later, I was wrong about the first part of my answer, as Joe points out below. You <em>can</em> protect a sheet to be editable by VBA-only, but it appears the \"UserInterfaceOnly\" option can only be set when calling \"Worksheet.Protect\" in code.</p>\n" }, { "answer_id": 126032, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 8, "selected": true, "text": "<p>Try using </p>\n\n<pre><code>Worksheet.Protect \"Password\", UserInterfaceOnly := True\n</code></pre>\n\n<p>If the UserInterfaceOnly parameter is set to true, VBA code can modify protected cells.</p>\n" }, { "answer_id": 126748, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 4, "selected": false, "text": "<p>You can modify a sheet via code by taking these actions</p>\n\n<ul>\n<li>Unprotect</li>\n<li>Modify</li>\n<li>Protect</li>\n</ul>\n\n<p>In code this would be:</p>\n\n<pre><code>Sub UnProtect_Modify_Protect()\n\n ThisWorkbook.Worksheets(\"Sheet1\").Unprotect Password:=\"Password\"\n'Unprotect\n\n ThisWorkbook.ActiveSheet.Range(\"A1\").FormulaR1C1 = \"Changed\"\n'Modify\n\n ThisWorkbook.Worksheets(\"Sheet1\").Protect Password:=\"Password\"\n'Protect\n\nEnd Sub\n</code></pre>\n\n<p>The <strong>weakness</strong> of this method is that if the code is interrupted and error handling does not capture it, the worksheet could be left in an unprotected state.</p>\n\n<p>The code could be <strong>improved</strong> by taking these actions</p>\n\n<ul>\n<li>Re-protect</li>\n<li>Modify</li>\n</ul>\n\n<p>The code to do this would be:</p>\n\n<pre><code>Sub Re-Protect_Modify()\n\nThisWorkbook.Worksheets(\"Sheet1\").Protect Password:=\"Password\", _\n UserInterfaceOnly:=True\n'Protect, even if already protected\n\n ThisWorkbook.ActiveSheet.Range(\"A1\").FormulaR1C1 = \"Changed\"\n'Modify\n\nEnd Sub\n</code></pre>\n\n<p>This code renews the protection on the worksheet, but with the ‘UserInterfaceOnly’ set to true. This allows VBA code to modify the worksheet, while keeping the worksheet protected from user input via the UI, even if execution is interrupted.</p>\n\n<p>This setting is <strong>lost</strong> when the workbook is closed and re-opened. The worksheet protection is still maintained.</p>\n\n<p>So the 'Re-protection' code needs to be included at the start of any procedure that attempts to modify the worksheet or can just be run once when the workbook is opened.</p>\n" }, { "answer_id": 21682830, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>A basic but simple to understand answer:</p>\n\n<pre><code>Sub Example()\n ActiveSheet.Unprotect\n Program logic...\n ActiveSheet.Protect\nEnd Sub\n</code></pre>\n" }, { "answer_id": 42381226, "author": "hegemon", "author_id": 113083, "author_profile": "https://Stackoverflow.com/users/113083", "pm_score": 2, "selected": false, "text": "<p>As a workaround, you can create a <strong>hidden worksheet</strong>, which would hold the changed value. The cell on the visible, protected worksheet should display the value from the hidden worksheet using a simple formula. </p>\n\n<p>You will be able to <strong>change the displayed value through the hidden worksheet</strong>, while your users won't be able to edit it.</p>\n" }, { "answer_id": 43930958, "author": "Alan", "author_id": 8001267, "author_profile": "https://Stackoverflow.com/users/8001267", "pm_score": 0, "selected": false, "text": "<p>I selected the cells I wanted locked out in sheet1 and place the suggested code in the open_workbook() function and worked like a charm.</p>\n\n<pre><code>ThisWorkbook.Worksheets(\"Sheet1\").Protect Password:=\"Password\", _\nUserInterfaceOnly:=True\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17266/" ]
I am using Excel where certain fields are allowed for user input and other cells are to be protected. I have used Tools Protect sheet, however after doing this I am not able to change the values in the VBA script. I need to restrict the sheet to stop user input, at the same time allow the VBA code to change the cell values based on certain computations.
Try using ``` Worksheet.Protect "Password", UserInterfaceOnly := True ``` If the UserInterfaceOnly parameter is set to true, VBA code can modify protected cells.
125,457
<p>If I need to copy a stored procedure (SP) from one SQL Server to another I right click on the SP in SSMS and select Script Stored Procedure as > CREATE to > New Query Editor Window. I then change the connection by right clicking on that window and selecting Connection > Change Connection... and then selecting the new server and F5 to run the create on the new server.</p> <p>So my question is "What is the T-SQL syntax to connect to another SQL Server?" so that I can just paste that in the top of the create script and F5 to run it and it would switch to the new server and run the create script.</p> <p>While typing the question I realized that if I gave you the back ground to what I'm trying to do that you might come up with a faster and better way from me to accomplish this.</p>
[ { "answer_id": 125469, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<p>Try creating a linked server (which you can do with <a href=\"http://msdn.microsoft.com/en-us/library/ms190479.aspx\" rel=\"nofollow noreferrer\">sp_addlinkedserver</a>) and then using <a href=\"http://msdn.microsoft.com/en-us/library/ms188427.aspx\" rel=\"nofollow noreferrer\">OPENQUERY</a></p>\n" }, { "answer_id": 125472, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 5, "selected": false, "text": "<p>Update: for connecting to another sql server and executing sql statements, you have to use <a href=\"http://msdn.microsoft.com/en-us/library/ms162773.aspx\" rel=\"noreferrer\">sqlcmd Utility</a>. This is typically done in a batch file.\nYou can combine this with <a href=\"http://msdn.microsoft.com/en-us/library/aa260689(SQL.80).aspx\" rel=\"noreferrer\">xmp_cmdshell</a> if you want to execute it within management studio.</p>\n\n<hr>\n\n<p>one way is to configure a <a href=\"http://msdn.microsoft.com/en-us/library/aa259589(SQL.80).aspx\" rel=\"noreferrer\">linked server</a>. then you can append the linked server and the database name to the table name. (select * from linkedserver.database.dbo.TableName)</p>\n\n<pre><code>USE master\nGO\nEXEC sp_addlinkedserver \n 'SEATTLESales',\n N'SQL Server'\nGO\n</code></pre>\n" }, { "answer_id": 125499, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 7, "selected": true, "text": "<p>Also, make sure when you write the query involving the linked server, you include brackets like this:</p>\n\n<pre><code>SELECT * FROM [LinkedServer].[RemoteDatabase].[User].[Table]\n</code></pre>\n\n<p>I've found that at least on 2000/2005 the [] brackets are necessary, at least around the server name.</p>\n" }, { "answer_id": 125508, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 3, "selected": false, "text": "<p>If I were to paraphrase the question - is it possible to pick server context for query execution in the DDL - the answer is no. Only database context can be programmatically chosen with USE. (having already preselected the server context externally)</p>\n\n<p>Linked server and OPEN QUERY can give access to the DDL but require somewhat a rewrite of your code to encapsulate as a string - making it difficult to develop/debug. </p>\n\n<p>Alternately you could resort to an external driver program to pickup SQL files to send to the remote server via OPEN QUERY. However in most cases you might as well have connected to the server directly in the 1st place to evaluate the DDL.</p>\n" }, { "answer_id": 3065265, "author": "MikeV", "author_id": 369753, "author_profile": "https://Stackoverflow.com/users/369753", "pm_score": -1, "selected": false, "text": "<p>If possible, check out SSIS (SQL Server Integration Services). I am just getting my feet wet with this toolkit, but already am looping over 40+ servers and preparing to wreak all kinds of havoc ;)</p>\n" }, { "answer_id": 3153405, "author": "mwg2002", "author_id": 380525, "author_profile": "https://Stackoverflow.com/users/380525", "pm_score": 7, "selected": false, "text": "<p>In SQL Server Management Studio, turn on SQLCMD mode from the Query menu.\nThen at the top of your script, type in the command below</p>\n\n<pre><code>:Connect server_name[\\instance_name] [-l timeout] [-U user_name [-P password]\n</code></pre>\n\n<p>If you are connecting to multiple servers, be sure to insert <code>GO</code> between connections; <a href=\"http://www.sqlmatters.com/Articles/Changing%20the%20SQL%20Server%20connection%20within%20an%20SSMS%20Query%20Windows%20using%20SQLCMD%20Mode.aspx\" rel=\"noreferrer\">otherwise your T-SQL won't execute on the server you're thinking it will.</a></p>\n" }, { "answer_id": 8182097, "author": "SASMITA MOHAPATRA", "author_id": 1053749, "author_profile": "https://Stackoverflow.com/users/1053749", "pm_score": 3, "selected": false, "text": "<p>Whenever we are trying to retrieve any data from another server we need two steps.</p>\n\n<p>First step:</p>\n\n<pre><code>-- Server one scalar variable\nDECLARE @SERVER VARCHAR(MAX)\n--Oracle is the server to which we want to connect\nEXEC SP_ADDLINKEDSERVER @SERVER='ORACLE'\n</code></pre>\n\n<p>Second step:</p>\n\n<pre><code>--DBO is the owner name to know table owner name execute (SP_HELP TABLENAME) \nSELECT * INTO DESTINATION_TABLE_NAME \nFROM ORACLE.SOURCE_DATABASENAME.DBO.SOURCE_TABLE\n</code></pre>\n" }, { "answer_id": 22917476, "author": "Oscar Fraxedas", "author_id": 1074245, "author_profile": "https://Stackoverflow.com/users/1074245", "pm_score": 2, "selected": false, "text": "<p>If you are connecting to multiple servers you should add a 'GO' before switching servers, or your sql statements will run against the wrong server.</p>\n\n<p>e.g.</p>\n\n<pre><code>:CONNECT SERVER1\nSelect * from Table\nGO\nenter code here\n:CONNECT SERVER1\nSelect * from Table\nGO\n</code></pre>\n\n<p><a href=\"http://www.sqlmatters.com/Articles/Changing%20the%20SQL%20Server%20connection%20within%20an%20SSMS%20Query%20Windows%20using%20SQLCMD%20Mode.aspx\" rel=\"noreferrer\">http://www.sqlmatters.com/Articles/Changing%20the%20SQL%20Server%20connection%20within%20an%20SSMS%20Query%20Windows%20using%20SQLCMD%20Mode.aspx</a></p>\n" }, { "answer_id": 30951573, "author": "frans eilering", "author_id": 4962958, "author_profile": "https://Stackoverflow.com/users/4962958", "pm_score": 2, "selected": false, "text": "<p>on my C drive I first create a txt file to create a new table. You can use what ever you want in this text file</p>\n\n<p>in this case the text file is called \"Bedrijf.txt\"</p>\n\n<p>the content:</p>\n\n<pre><code>Print 'START(A) create table'\n\nGO 1\n\nIf not EXISTS\n(\n SELECT *\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_NAME = 'Bedrijf'\n)\nBEGIN\nCREATE TABLE [dbo].[Bedrijf] (\n[IDBedrijf] [varchar] (38) NOT NULL ,\n[logo] [varbinary] (max) NULL ,\n[VolledigeHandelsnaam] [varchar] (100) NULL \n) ON [PRIMARY]\n</code></pre>\n\n<p>save it</p>\n\n<p>then I create an other txt file with the name \"Bedrijf.bat\" and the extension bat.\nIt's content:</p>\n\n<pre><code>OSQL.EXE -U Username -P Password -S IPaddress -i C:Bedrijf.txt -o C:Bedrijf.out -d myDatabaseName\n</code></pre>\n\n<p>save it and from explorer double click to execute</p>\n\n<p>The results will be saved in a txt file on your C drive with the name \"Bedrijf.out\"</p>\n\n<p>it shows</p>\n\n<pre><code>1&gt; 2&gt; 3&gt; START(A) create table\n</code></pre>\n\n<p>if all goes well</p>\n\n<p>That's it</p>\n" }, { "answer_id": 54652341, "author": "Igor Krupitsky", "author_id": 1781849, "author_profile": "https://Stackoverflow.com/users/1781849", "pm_score": 0, "selected": false, "text": "<p>Try PowerShell Type like:</p>\n\n<pre><code>$cn = new-object system.data.SqlClient.SQLConnection(\"Data Source=server1;Initial Catalog=db1;User ID=user1;Password=password1\");\n$cmd = new-object system.data.sqlclient.sqlcommand(\"exec Proc1\", $cn);\n$cn.Open();\n$cmd.CommandTimeout = 0\n$cmd.ExecuteNonQuery()\n$cn.Close();\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
If I need to copy a stored procedure (SP) from one SQL Server to another I right click on the SP in SSMS and select Script Stored Procedure as > CREATE to > New Query Editor Window. I then change the connection by right clicking on that window and selecting Connection > Change Connection... and then selecting the new server and F5 to run the create on the new server. So my question is "What is the T-SQL syntax to connect to another SQL Server?" so that I can just paste that in the top of the create script and F5 to run it and it would switch to the new server and run the create script. While typing the question I realized that if I gave you the back ground to what I'm trying to do that you might come up with a faster and better way from me to accomplish this.
Also, make sure when you write the query involving the linked server, you include brackets like this: ``` SELECT * FROM [LinkedServer].[RemoteDatabase].[User].[Table] ``` I've found that at least on 2000/2005 the [] brackets are necessary, at least around the server name.
125,468
<p>I have a repository of files which are unrelated to each other but are common to multiple projects. Each project might only need a subset of these files. For example:</p> <pre><code>/myRepo: /jquery.js /jquery.form.js /jquery.ui.js </code></pre> <p>Project A requires <code>jquery.js</code> and <code>jquery.form.js</code>, whereas Project B requires <code>jquery.js</code> and <code>jquery.ui.js</code></p> <p>I could just do a checkout of <code>myRepo</code> into both projects, but that'd add a lot of unnecessary files into both. What I'd like is some sort of way for each Project to only get the files it needs. One way I thought it might be possible is if I put just the required files into each project and then run an <code>svn update</code> on it, but somehow stop SVN from adding new files to each directory. They'd still get the modifications to the existing files, but no unnecessary files would be added.</p> <p>Is this possible at all?</p>
[ { "answer_id": 125478, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": 1, "selected": false, "text": "<p>If I understood your question correctly, you want to share code across projects? If so, look at the svn:externals property.</p>\n\n<p><a href=\"http://svnbook.red-bean.com/en/1.4/svn.advanced.externals.html\" rel=\"nofollow noreferrer\">Externals explained in Subversion Red Book</a></p>\n\n<p><a href=\"http://www.systemwidgets.com/Support/SubversionArticles/SharedRepositoriesusingsvnexternals/tabid/81/Default.aspx\" rel=\"nofollow noreferrer\">svn:externals in Windows</a></p>\n" }, { "answer_id": 125480, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 3, "selected": true, "text": "<p>Don't complicate yourself. Either pull out all files (what is the disadvatage of this ? a few more 100s of Ks of space ?), or divide the files into several directories, and only check out the needed directories (using the 'externals' property) in relevant projects.</p>\n" }, { "answer_id": 125525, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 1, "selected": false, "text": "<p>K, this isn't perfect, but it will do. The biggest problem is that it will update each file individually:</p>\n\n<pre><code>find . -print | grep -v '\\.svn' | xargs svn update\n</code></pre>\n\n<p>I am sure that someone with more find mojo can figure out a better way of handling the svn directory exclusion.</p>\n" }, { "answer_id": 125527, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 1, "selected": false, "text": "<p>In our company we store all projects in the same repository, but within their own project folder. Then if code needs to be shared we move it out to a library folder. This helps reusability, and not violating the DRY principle.</p>\n\n<p>So as far as the server is concerned you can export all of your libraries to a central place, and your projects wherever, without overlapping.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
I have a repository of files which are unrelated to each other but are common to multiple projects. Each project might only need a subset of these files. For example: ``` /myRepo: /jquery.js /jquery.form.js /jquery.ui.js ``` Project A requires `jquery.js` and `jquery.form.js`, whereas Project B requires `jquery.js` and `jquery.ui.js` I could just do a checkout of `myRepo` into both projects, but that'd add a lot of unnecessary files into both. What I'd like is some sort of way for each Project to only get the files it needs. One way I thought it might be possible is if I put just the required files into each project and then run an `svn update` on it, but somehow stop SVN from adding new files to each directory. They'd still get the modifications to the existing files, but no unnecessary files would be added. Is this possible at all?
Don't complicate yourself. Either pull out all files (what is the disadvatage of this ? a few more 100s of Ks of space ?), or divide the files into several directories, and only check out the needed directories (using the 'externals' property) in relevant projects.
125,470
<p>I need to create a configuration section, that is able to store key-value pairs in an app.config file and the key-value pairs can be added runtime regardless of their type. It is also important that the value keeps its original type. I need to extend the following interface </p> <pre><code>public interface IPreferencesBackend { bool TryGet&lt;T&gt;(string key, out T value); bool TrySet&lt;T&gt;(string key, T value); } </code></pre> <p>At runtime, I can say something like: </p> <pre><code>My.Foo.Data data = new My.Foo.Data("blabla"); Pref pref = new Preferences(); pref.TrySet("foo.data", data); pref.Save(); My.Foo.Data date = new My.Foo.Data(); pref.TryGet("foo.data", out data); </code></pre> <p>I tried with System.Configuration.Configuration.AppSettings, but the problem with that that it is storing the key-value pairs in a string array. </p> <p>What I need is to have an implementation of System.Configuration.ConfigurationSection, where I can control the how the individual setting is serialized. I noticed that the settings generated by Visual Studio kind of do this. It is using reflection to create all the setting keys. what I need is to do this runtime and dynamically. </p> <pre><code>[System.Configuration.UserScopedSettingAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.Configuration.DefaultSettingValueAttribute("2008-09-24")] public global::System.DateTime DateTime { get { return ((global::System.DateTime)(this["DateTime"])); } set { this["DateTime"] = value; } } </code></pre>
[ { "answer_id": 125479, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<p>Phil Haack has a great article on <a href=\"http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-steps.aspx\" rel=\"nofollow noreferrer\">Creating Custom Configuration Sections</a></p>\n" }, { "answer_id": 125490, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 1, "selected": false, "text": "<p>That's all you get in a an ASCII text file - strings. :-)</p>\n\n<p>However, you can encode the \"value\" strings to include a type parameter like:</p>\n\n<pre><code>&lt;key=\"myParam\" value=\"type, value\" /&gt;\n</code></pre>\n\n<p>for example:</p>\n\n<pre><code>&lt;key=\"payRate\" value=\"money,85.79\"/&gt;\n</code></pre>\n\n<p>then have your app do the conversion ...</p>\n" }, { "answer_id": 145320, "author": "gyurisc", "author_id": 260, "author_profile": "https://Stackoverflow.com/users/260", "pm_score": 3, "selected": true, "text": "<p>I found two great articles on codeproject.com that are explaining these issues in great detail. </p>\n\n<p>Unraveling the Mysteries of .NET 2.0 Configuration\n<a href=\"http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx</a></p>\n\n<p>User Settings Applied\n<a href=\"http://www.codeproject.com/KB/dotnet/user_settings.aspx?display=PrintAll&amp;fid=1286606&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2647446&amp;fr=26\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/dotnet/user_settings.aspx?display=PrintAll&amp;fid=1286606&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2647446&amp;fr=26</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260/" ]
I need to create a configuration section, that is able to store key-value pairs in an app.config file and the key-value pairs can be added runtime regardless of their type. It is also important that the value keeps its original type. I need to extend the following interface ``` public interface IPreferencesBackend { bool TryGet<T>(string key, out T value); bool TrySet<T>(string key, T value); } ``` At runtime, I can say something like: ``` My.Foo.Data data = new My.Foo.Data("blabla"); Pref pref = new Preferences(); pref.TrySet("foo.data", data); pref.Save(); My.Foo.Data date = new My.Foo.Data(); pref.TryGet("foo.data", out data); ``` I tried with System.Configuration.Configuration.AppSettings, but the problem with that that it is storing the key-value pairs in a string array. What I need is to have an implementation of System.Configuration.ConfigurationSection, where I can control the how the individual setting is serialized. I noticed that the settings generated by Visual Studio kind of do this. It is using reflection to create all the setting keys. what I need is to do this runtime and dynamically. ``` [System.Configuration.UserScopedSettingAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.Configuration.DefaultSettingValueAttribute("2008-09-24")] public global::System.DateTime DateTime { get { return ((global::System.DateTime)(this["DateTime"])); } set { this["DateTime"] = value; } } ```
I found two great articles on codeproject.com that are explaining these issues in great detail. Unraveling the Mysteries of .NET 2.0 Configuration <http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx> User Settings Applied <http://www.codeproject.com/KB/dotnet/user_settings.aspx?display=PrintAll&fid=1286606&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2647446&fr=26>
125,496
<p>On my rails app I have a list of items (like a task list) and for each item there is a couple of check box to set parameters.</p> <p>When I submit the form, the checked box are stored as zero and the unchecked as null on DB. </p> <p>the question is: Is there a way to configure it? To store the data on a more traditional 0 or 1, because I think that storing null as false and 0 as true is a bit confusing, specially if another app (like a C app) needs to read the data.</p>
[ { "answer_id": 125517, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 2, "selected": false, "text": "<p>There are a number of potential reasons for this:</p>\n\n<ul>\n<li>Make sure that the column in the database is of type \"boolean\" in the migration</li>\n<li>Place a default on boolean values</li>\n<li>Use \"check_box\" on the form, not \"check_box_tag\"</li>\n<li>Some versions of Rails had this behaviour on generated scaffolds, I think setting the default fixed this, but I can't quite remember.</li>\n</ul>\n" }, { "answer_id": 127702, "author": "Yardboy", "author_id": 9550, "author_profile": "https://Stackoverflow.com/users/9550", "pm_score": 3, "selected": true, "text": "<p>Let's assume that the attribute you are working with is <code>club_member</code> as in \"are you a club_member?\".</p>\n\n<p>Note that in Ruby/Rails, the way it is working now, <code>if model.club_member</code> will return false if it is not checked (value is null or in Ruby, nil) and true if it is checked (value is 0).</p>\n\n<p>On the whole, I would strongly recommend that instead of letting other applications (like a C app) directly at your data, you should instead build an API in Ruby/Rails to expose the data from your application to external entities. In this manner, you will better encapsulate your application's internals and you won't have to worry about things like this.</p>\n\n<hr>\n\n<p>However, all that being said, here is your answer:</p>\n\n<p>Use:</p>\n\n<pre><code>value=\"1\"\n</code></pre>\n\n<p>...attribute in your checkbox HTML tags, and set the default value of the <strong>boolean</strong> attribute (in your migration) to 0.</p>\n" }, { "answer_id": 2599922, "author": "Fabian ", "author_id": 311894, "author_profile": "https://Stackoverflow.com/users/311894", "pm_score": 1, "selected": false, "text": "<p>What about:</p>\n\n<p><code>value.to_i.zero?</code></p>\n\n<pre><code>&gt;&gt; a=nil\n=&gt; nil\n&gt;&gt; a.to_i.zero?\n=&gt; true\n&gt;&gt; a=0\n=&gt; 0\n&gt;&gt; a.to_i.zero?\n=&gt; true\n&gt;&gt; a=3\n=&gt; 3\n&gt;&gt; a.to_i.zero?\n=&gt; false\n</code></pre>\n" }, { "answer_id": 3641326, "author": "robodo", "author_id": 309959, "author_profile": "https://Stackoverflow.com/users/309959", "pm_score": 0, "selected": false, "text": "<p>From the rails documentation:</p>\n\n<p>An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ “, nil, [], and {} are blank.</p>\n\n<p>This simplifies:\n if !address.nil? &amp;&amp; !address.empty?</p>\n\n<p>…to:\n if !address.blank?</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440867/" ]
On my rails app I have a list of items (like a task list) and for each item there is a couple of check box to set parameters. When I submit the form, the checked box are stored as zero and the unchecked as null on DB. the question is: Is there a way to configure it? To store the data on a more traditional 0 or 1, because I think that storing null as false and 0 as true is a bit confusing, specially if another app (like a C app) needs to read the data.
Let's assume that the attribute you are working with is `club_member` as in "are you a club\_member?". Note that in Ruby/Rails, the way it is working now, `if model.club_member` will return false if it is not checked (value is null or in Ruby, nil) and true if it is checked (value is 0). On the whole, I would strongly recommend that instead of letting other applications (like a C app) directly at your data, you should instead build an API in Ruby/Rails to expose the data from your application to external entities. In this manner, you will better encapsulate your application's internals and you won't have to worry about things like this. --- However, all that being said, here is your answer: Use: ``` value="1" ``` ...attribute in your checkbox HTML tags, and set the default value of the **boolean** attribute (in your migration) to 0.
125,523
<p>Is it possible to use an attribute of a child to group a query?</p> <pre><code>Post.find(:all, :include =&gt; [ :authors, :comments ], :group=&gt;'authors.city') </code></pre> <p>does not work. </p> <p>However, I am able to use <code>author.city</code> as part of the conditions.</p>
[ { "answer_id": 125537, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 1, "selected": false, "text": "<p>If that's what you're using, then the syntax is wrong for the :group argument, it should be:</p>\n\n<pre><code>Post.find(:all, :include =&gt; [ :author, :comments ], :group=&gt;'authors.city')\n</code></pre>\n\n<p>Make sure your :author and :comments associations are correct. If 'authors' is the actual table name, then you'll need a 'has_one :author' association in you Post model, and an Author model. </p>\n\n<p>Associations need to be correct, too:</p>\n\n<pre><code> class Post &lt; AR:Base\n belongs_to :author\n has_many :comments\n end\n\n class Author &lt; AR:Base\n has_many :posts\n end\n\n class Comment &lt; AR:Base\n belongs_to :post\n end\n</code></pre>\n\n<p>And the db schema:</p>\n\n<pre><code> posts\n id\n author_id\n authors\n id\n comments\n id\n post_id\n</code></pre>\n\n<p>This will let the query run correctly, however, now <em>I'm</em> getting an error with the results... the :group clause doesn't seem to be applied when :include is used.</p>\n" }, { "answer_id": 125551, "author": "Toby Hede", "author_id": 14971, "author_profile": "https://Stackoverflow.com/users/14971", "pm_score": 0, "selected": false, "text": "<p>Have a look at the query that is generated in your log file - you can often paste the query into your favourite MySQL tool to get a more detailed error. </p>\n\n<p>You might actually need to provide an aggregate function to get the database to group correctly (this happens in MySQL rather than a syntax error sometimes). </p>\n" }, { "answer_id": 126677, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 0, "selected": false, "text": "<p>Should the author include be pluralized?</p>\n\n<pre><code>Post.find(:all, :include =&gt; [ :authors, :comments ], :group=&gt;'authors.city')\n</code></pre>\n" }, { "answer_id": 137698, "author": "sutee", "author_id": 1227001, "author_profile": "https://Stackoverflow.com/users/1227001", "pm_score": 2, "selected": false, "text": "<p>The solution is to force the necessary join so that ActiveRecord can resolve \"authors.city\":</p>\n\n<pre><code>Post.find(:all, :include =&gt; [ :author, :comments ], :joins=&gt;\"INNER JOIN authors ON posts.author_id=authors.id\", :group=&gt;'authors.city')\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
Is it possible to use an attribute of a child to group a query? ``` Post.find(:all, :include => [ :authors, :comments ], :group=>'authors.city') ``` does not work. However, I am able to use `author.city` as part of the conditions.
The solution is to force the necessary join so that ActiveRecord can resolve "authors.city": ``` Post.find(:all, :include => [ :author, :comments ], :joins=>"INNER JOIN authors ON posts.author_id=authors.id", :group=>'authors.city') ```
125,532
<p>I decided to teach myself assembly language.</p> <p>I have realized that my program will not compile if I attempt to change the value of any segment register.</p> <p>Every article that I have found says that I can indeed change the value of at least 4 segment registers, so what gives? </p> <p>I am really only interested in the why at this point, I don't have any real purpose in changing these addresses.</p>
[ { "answer_id": 125565, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 2, "selected": false, "text": "<p>Are you writing windows executables?</p>\n\n<p>In protected-mode (Win32), segment registers are not used any more.</p>\n\n<p><a href=\"http://www.codebreakers-journal.com/content/view/141/104/\" rel=\"nofollow noreferrer\">Reference</a>:</p>\n\n<blockquote>\n <p>Memory model is also drastically\n different from the old days of the\n 16-bit world. Under Win32, we need not\n be concerned with memory model or\n segment anymore! There's only one\n memory model: Flat memory model.\n There's no more 64K segments. The\n memory is a large continuous space of\n 4 GB. That also means you don't have\n to play with segment registers. You\n can use any segment register to\n address any point in the memory space.\n That's a GREAT help to programmers.\n This is what makes Win32 assembly\n programming as easy as C.</p>\n</blockquote>\n" }, { "answer_id": 304672, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 4, "selected": true, "text": "<p>You said you were interested in why, so:</p>\n\n<p>In real mode, a segment is a 64K \"window\" to physical memory and these windows are spaced 16 bytes apart. In protected mode, a segment is a window to either physical or virtual memory, whose size and location is determined by the OS, and it has many other properties, including what privilege level a process must have to access it.</p>\n\n<p>From here on, everything I say refers to protected mode.</p>\n\n<p>There is a table in memory called the global descriptor table (GDT), which is where the information about these window sizes and locations and other properties are kept. There may also be local descriptor tables on a per-process basis, and they work in a similar way, so I'll just focus on the GDT.</p>\n\n<p>The value you load into a segment register is known as a <em>segment selector</em>. It is an index into the GDT or LDT, with a bit of extra security information. Naturally if a program tries to load a descriptor which is outside the bounds of the GDT, an exception occurs. Also if the process does not have enough privilege to access the segment, or something else is invalid, an exception occurs.</p>\n\n<p>When an exception occurs, the kernel handles it. This sort of exception would probably be classed as a segmentation fault. So the OS kills your program.</p>\n\n<p>There's one final caveat: in the x86 instruction set, you can't load immediate values into segment registers. You must use an intermediate register or a memory operand or POP into the segment register.</p>\n\n<pre>\nMOV DS, 160 ;INVALID - won't assemble\n\nMOV AX, 160 ;VALID - assembles, but will probably result in an\nMOV DS, AX ;exception, and thus the death of your program\n</pre>\n\n<p>I think it should be pointed out that the architecture allows for heaps of segments. But AFAIK, when it comes to the mainstream x86 operating systems, segment registers serve only a few purposes:</p>\n\n<ul>\n<li>Security mechanisms, such as keeping user space processes from harming each other or the OS</li>\n<li>Dealing with multiple/multi-core processors</li>\n<li>Thread-local storage: as an optimization, some operating systems (including Linux and Windows) use segment registers for thread-local storage (TLS). Since threads share the same address space, it is hard for a thread to \"know\" where its TLS region is without using a system call or wasting a register... but since segment registers are practically useless, there's no harm in \"wasting\" them for the sake of fast TLS. Note that when setting this up, an OS might skip the segment registers and write directly to descriptor cache registers, which are \"hidden\" registers used to cache the GDT/LDT lookups triggered by references to the segment registers, in which case if you try to read from the segment registers you won't see it.</li>\n</ul>\n\n<p>Apart from a segment per thread for TLS, really only a handful of segments (times the number of processors) are used, and only by the OS. Application programs can <em>completely</em> ignore the segment registers.</p>\n\n<p>This is due to OS design, not to any technical limitations. There may be embedded operating systems that require user-space programs to work with the segment registers, though I don't know of any.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053/" ]
I decided to teach myself assembly language. I have realized that my program will not compile if I attempt to change the value of any segment register. Every article that I have found says that I can indeed change the value of at least 4 segment registers, so what gives? I am really only interested in the why at this point, I don't have any real purpose in changing these addresses.
You said you were interested in why, so: In real mode, a segment is a 64K "window" to physical memory and these windows are spaced 16 bytes apart. In protected mode, a segment is a window to either physical or virtual memory, whose size and location is determined by the OS, and it has many other properties, including what privilege level a process must have to access it. From here on, everything I say refers to protected mode. There is a table in memory called the global descriptor table (GDT), which is where the information about these window sizes and locations and other properties are kept. There may also be local descriptor tables on a per-process basis, and they work in a similar way, so I'll just focus on the GDT. The value you load into a segment register is known as a *segment selector*. It is an index into the GDT or LDT, with a bit of extra security information. Naturally if a program tries to load a descriptor which is outside the bounds of the GDT, an exception occurs. Also if the process does not have enough privilege to access the segment, or something else is invalid, an exception occurs. When an exception occurs, the kernel handles it. This sort of exception would probably be classed as a segmentation fault. So the OS kills your program. There's one final caveat: in the x86 instruction set, you can't load immediate values into segment registers. You must use an intermediate register or a memory operand or POP into the segment register. ``` MOV DS, 160 ;INVALID - won't assemble MOV AX, 160 ;VALID - assembles, but will probably result in an MOV DS, AX ;exception, and thus the death of your program ``` I think it should be pointed out that the architecture allows for heaps of segments. But AFAIK, when it comes to the mainstream x86 operating systems, segment registers serve only a few purposes: * Security mechanisms, such as keeping user space processes from harming each other or the OS * Dealing with multiple/multi-core processors * Thread-local storage: as an optimization, some operating systems (including Linux and Windows) use segment registers for thread-local storage (TLS). Since threads share the same address space, it is hard for a thread to "know" where its TLS region is without using a system call or wasting a register... but since segment registers are practically useless, there's no harm in "wasting" them for the sake of fast TLS. Note that when setting this up, an OS might skip the segment registers and write directly to descriptor cache registers, which are "hidden" registers used to cache the GDT/LDT lookups triggered by references to the segment registers, in which case if you try to read from the segment registers you won't see it. Apart from a segment per thread for TLS, really only a handful of segments (times the number of processors) are used, and only by the OS. Application programs can *completely* ignore the segment registers. This is due to OS design, not to any technical limitations. There may be embedded operating systems that require user-space programs to work with the segment registers, though I don't know of any.
125,536
<p>I want to add a constant value onto an incoming bound integer. In fact I have several places where I want to bind to the same source value but add different constants. So the ideal solution would be something like this...</p> <pre><code>&lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=5}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=8}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=24}"/&gt; </code></pre> <p>(NOTE: This is an example to show the idea, my actual binding scenario is not to the canvas property of a TextBox. But this shows the idea more clearly) </p> <p>At the moment the only solution I can think of is to expose many different source properties each of which adds on a different constant to the same internal value. So I could do something like this...</p> <pre><code>&lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus5}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus8}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus24}"/&gt; </code></pre> <p>But this is pretty grim because in the future I might need to keep adding new properties for new constants. Also if I need to change the value added I need to go an alter the source object which is pretty naff. </p> <p>There must be a more generic way than this? Any WPF experts got any ideas?</p>
[ { "answer_id": 125582, "author": "Steve Steiner", "author_id": 3892, "author_profile": "https://Stackoverflow.com/users/3892", "pm_score": 4, "selected": true, "text": "<p>I believe you can do this with a value converter. Here is a <a href=\"http://weblogs.asp.net/marianor/archive/2007/09/18/using-ivalueconverter-to-format-binding-values-in-wpf.aspx\" rel=\"noreferrer\">blog entry</a> that addresses passing a parameter to the value converter in the xaml. And <a href=\"http://blogs.msdn.com/bencon/archive/2006/05/10/594886.aspx\" rel=\"noreferrer\">this blog</a> gives some details of implementing a value converter. </p>\n" }, { "answer_id": 125592, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 0, "selected": false, "text": "<p>I've never used WPF, but I have a possible solution.</p>\n\n<p>Can your binding Path map to a Map? If so, it should then be able to take an argument (the key). You'd need to create a class that implements the Map interface, but really just returns the base value that you initialized the \"Map\" with added to the key.</p>\n\n<pre><code>public Integer get( Integer key ) { return baseInt + key; } // or some such\n</code></pre>\n\n<p>Without some ability to pass the number from the tag, I don't see how you're going to get it to return different deltas from the original value.</p>\n" }, { "answer_id": 126483, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 3, "selected": false, "text": "<p>Using a value converter is a good solution to the problem as it allows you to modify the source value as it's being bound to the UI. </p>\n\n<p>I've used the following in a couple of places.</p>\n\n<pre><code>public class AddValueConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n object result = value;\n int parameterValue;\n\n if (value != null &amp;&amp; targetType == typeof(Int32) &amp;&amp; \n int.TryParse((string)parameter, \n NumberStyles.Integer, culture, out parameterValue))\n {\n result = (int)value + (int)parameterValue;\n }\n\n return result;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n</code></pre>\n\n<p>Example\n </p>\n\n<pre><code> &lt;Setter Property=\"Grid.ColumnSpan\"\n Value=\"{Binding \n Path=ColumnDefinitions.Count,\n RelativeSource={RelativeSource AncestorType=Grid},\n Converter={StaticResource addValueConverter},\n ConverterParameter=1}\"\n /&gt;\n</code></pre>\n" }, { "answer_id": 7133443, "author": "Rachel", "author_id": 302677, "author_profile": "https://Stackoverflow.com/users/302677", "pm_score": 5, "selected": false, "text": "<p>I use a <code>MathConverter</code>that I created to do all simple arithmatic operations with. The code for the converter is <a href=\"http://rachel53461.wordpress.com/2011/08/20/the-math-converter/\" rel=\"noreferrer\">here</a> and it can be used like this:</p>\n\n<pre><code>&lt;TextBox Canvas.Top=\"{Binding SomeValue, \n Converter={StaticResource MathConverter},\n ConverterParameter=@VALUE+5}\" /&gt;\n</code></pre>\n\n<p>You can even use it with more advanced arithmatic operations such as</p>\n\n<pre><code>Width=\"{Binding ElementName=RootWindow, Path=ActualWidth,\n Converter={StaticResource MathConverter},\n ConverterParameter=((@VALUE-200)*.3)}\"\n</code></pre>\n" }, { "answer_id": 61399582, "author": "Péter Hidvégi", "author_id": 4994278, "author_profile": "https://Stackoverflow.com/users/4994278", "pm_score": 0, "selected": false, "text": "<p>I would use multibinding converter such as the following example:</p>\n\n<p>C# code:</p>\n\n<pre><code>namespace Example.Converters\n{\n public class ArithmeticConverter : IMultiValueConverter\n { \n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n double result = 0;\n\n for (int i = 0; i &lt; values.Length; i++)\n {\n if (!double.TryParse(values[i]?.ToString(), out var parsedNumber)) continue;\n\n if (TryGetOperations(parameter, i, out var operation))\n {\n result = operation(result, parsedNumber);\n }\n }\n\n return result;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n return new[] { Binding.DoNothing, false };\n }\n\n\n private static bool TryGetOperations(object parameter, int operationIndex, out Func&lt;double, double, double&gt; operation)\n {\n operation = null;\n var operations = parameter?.ToString().Split(',');\n\n if (operations == null || operations.Length == 0) return false;\n\n if (operations.Length &lt;= operationIndex)\n {\n operationIndex = operations.Length - 1;\n }\n\n return Operations.TryGetValue(operations[operationIndex]?.ToString(), out operation);\n }\n\n public const string Add = \"+\";\n public const string Subtract = \"-\";\n public const string Multiply = \"*\";\n public const string Divide = \"/\";\n\n private static IDictionary&lt;string, Func&lt;double, double, double&gt;&gt; Operations = new Dictionary&lt;string, Func&lt;double, double, double&gt;&gt;\n {\n { Add, (x, y) =&gt; x + y },\n { Subtract, (x, y) =&gt; x - y },\n { Multiply, (x, y) =&gt; x * y },\n { Divide, (x, y) =&gt; x / y }\n };\n }\n}\n</code></pre>\n\n<p>XAML code:</p>\n\n<pre><code>&lt;UserControl \n xmlns:converters=\"clr-namespace:Example.Converters\"&gt;\n &lt;UserControl.Resources&gt;\n &lt;converters:ArithmeticConverter x:Key=\"ArithmeticConverter\" /&gt;\n &lt;/UserControl.Resources&gt;\n</code></pre>\n\n<p>...</p>\n\n<pre><code>&lt;MultiBinding Converter=\"{StaticResource ArithmeticConverter}\" ConverterParameter=\"+,-\"&gt;\n &lt;Binding Path=\"NumberToAdd\" /&gt;\n &lt;Binding Path=\"NumberToSubtract\" /&gt;\n&lt;/MultiBinding&gt;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ]
I want to add a constant value onto an incoming bound integer. In fact I have several places where I want to bind to the same source value but add different constants. So the ideal solution would be something like this... ``` <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=5}"/> <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=8}"/> <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=24}"/> ``` (NOTE: This is an example to show the idea, my actual binding scenario is not to the canvas property of a TextBox. But this shows the idea more clearly) At the moment the only solution I can think of is to expose many different source properties each of which adds on a different constant to the same internal value. So I could do something like this... ``` <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus5}"/> <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus8}"/> <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus24}"/> ``` But this is pretty grim because in the future I might need to keep adding new properties for new constants. Also if I need to change the value added I need to go an alter the source object which is pretty naff. There must be a more generic way than this? Any WPF experts got any ideas?
I believe you can do this with a value converter. Here is a [blog entry](http://weblogs.asp.net/marianor/archive/2007/09/18/using-ivalueconverter-to-format-binding-values-in-wpf.aspx) that addresses passing a parameter to the value converter in the xaml. And [this blog](http://blogs.msdn.com/bencon/archive/2006/05/10/594886.aspx) gives some details of implementing a value converter.
125,570
<p>I am actually working on SP in SQL 2005. Using SP i am creating a job and am scheduling it for a particular time. These jobs take atleast 5 to 10 min to complete as the database is very huge. But I am not aware of how to check the status of the Job. I want to know if it has got completed successfully or was there any error in execution. On exception i also return proper error code. But i am not aware of where i can check for this error code.</p>
[ { "answer_id": 125738, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 3, "selected": true, "text": "<p>This is what I could find, maybe it solves your problem:</p>\n\n<ol>\n<li>SP to get the current job activiity.</li>\n</ol>\n\n<blockquote>\n<pre><code> exec msdb.dbo.sp_help_jobactivity @job_id = (your job_id here)\n</code></pre>\n</blockquote>\n\n<p>You can execute this SP and place the result in a temp table and get the required result from there.</p>\n\n<p>Otherwise have a look at these tables:</p>\n\n<ul>\n<li><p>msdb.dbo.sysjobactivity</p></li>\n<li><p>msdb.dbo.sysjobhistory</p></li>\n</ul>\n\n<p>Run the following to see the association between these tables. </p>\n\n<blockquote>\n <p>exec sp_helptext sp_help_jobactivity</p>\n</blockquote>\n" }, { "answer_id": 572636, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>--Copy in Query analizer and format it properly so you can understand it easyly\n--To execute your task(Job) using Query\nexec msdb.dbo.sp_start_job @job_name ='Job Name',@server_name = server name\n-- After executing query to check weateher it finished or not\nDeclare @JobId as varchar(36)\nSelect @JobId = job_id from sysjobs where name = 'Your Job Name'\nDeclare @JobStatus as int set @JobStatus = -1\nWhile @JobStatus &lt;= -1\nBegin\n --Provide TimeDelay according your Job\n select @JobStatus = isnull(run_status ,-1)\n from sysjobactivity JA,sysjobhistory JH\n where JA.job_history_id = JH.instance_id and JA.job_id = @JobId\nEnd\nselect @JobStatus</p>\n\n<p>null = Running\n1 = Fininshed successfully\n0 = Finished with error</p>\n\n<p>--Once your Job will fininsh you'll get result</p>\n" }, { "answer_id": 1497976, "author": "Faiz", "author_id": 82961, "author_profile": "https://Stackoverflow.com/users/82961", "pm_score": 0, "selected": false, "text": "<p>I got a better code from <a href=\"http://www.sqlservercentral.com/scripts/Miscellaneous/30916/\" rel=\"nofollow noreferrer\">here</a></p>\n\n<pre><code>Use msdb\ngo\n\nselect distinct j.Name as \"Job Name\", j.description as \"Job Description\", h.run_date as LastStatusDate, \ncase h.run_status \nwhen 0 then 'Failed' \nwhen 1 then 'Successful' \nwhen 3 then 'Cancelled' \n--when 4 then 'In Progress' \nend as JobStatus\nfrom sysJobHistory h, sysJobs j\nwhere j.job_id = h.job_id and h.run_date = \n(select max(hi.run_date) from sysJobHistory hi where h.job_id = hi.job_id)\norder by 1\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
I am actually working on SP in SQL 2005. Using SP i am creating a job and am scheduling it for a particular time. These jobs take atleast 5 to 10 min to complete as the database is very huge. But I am not aware of how to check the status of the Job. I want to know if it has got completed successfully or was there any error in execution. On exception i also return proper error code. But i am not aware of where i can check for this error code.
This is what I could find, maybe it solves your problem: 1. SP to get the current job activiity. > > > ``` > exec msdb.dbo.sp_help_jobactivity @job_id = (your job_id here) > > ``` > > You can execute this SP and place the result in a temp table and get the required result from there. Otherwise have a look at these tables: * msdb.dbo.sysjobactivity * msdb.dbo.sysjobhistory Run the following to see the association between these tables. > > exec sp\_helptext sp\_help\_jobactivity > > >
125,577
<p>I open a connection like this:</p> <pre><code>Using conn as New OdbcConnection(connectionString) conn.Open() //do stuff End Using </code></pre> <p>If connection pooling is enabled, the connection is not physically closed but released to the pool and will get reused. If it is disabled, it will be physically closed.</p> <p>Is there any way of knowing <strong>programmatically</strong> <em>if</em> connection pooling is enabled or not? and the number of used and unused connections currently open in the pool?</p> <p><strong>EDIT:</strong> I need to get this information from within the program, I can't go and check it manually on every single PC where the program will be deployed.</p>
[ { "answer_id": 125581, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": false, "text": "<p>MSDN as <a href=\"http://msdn.microsoft.com/en-us/library/ms810829.aspx\" rel=\"nofollow noreferrer\">in-depth guidelines on this</a></p>\n<blockquote>\n<p><strong>Configuring Connection Pooling from\nthe Data Source Administrator</strong></p>\n<p>[snip]</p>\n<p>Alternatively, you can start the ODBC\nData Source Administrator at the Run\nprompt. On the taskbar, <strong>click Start,\nclick Run, and then type Odbcad32.</strong></p>\n<p>The tab for managing connection\npooling is found in the ODBC Data\nSource Administrator dialog box in\nversion ODBC 3.5 and later.\nConfiguring Connection Pooling from\nthe Registry</p>\n<p>For versions prior to version 3.5 of\nthe ODBC core components, you need to\nmodify the registry directly to\ncontrol the connection pooling\nCPTimeout value.</p>\n</blockquote>\n<p>Pooling is always handled by data server software. The whole point being is that in .NET you shouldn't have to worry about it (for example, this is why you should always use the SqlConnection when working with SQL Server - part of it is that it enables the connection pooling).</p>\n<h2>Update</h2>\n<p>On Vista, just type &quot;ODBC&quot; in the Start menu and it will find the app for you.</p>\n<h2>Update Following Clarification from OP</h2>\n<p>In terms of determining if connection pooling is enabled on each machine, looking at the <a href=\"http://msdn.microsoft.com/en-us/library/ms810829.aspx\" rel=\"nofollow noreferrer\">MSDN guidelines</a> I whould say you would best best if you check the registry values (See <a href=\"http://www.csharphelp.com/archives2/archive430.html\" rel=\"nofollow noreferrer\">this article</a> for pointers on registry access).</p>\n<p>TBH though, unless the client machines are really crappy, I would possibly not even bother.. AFAIK it is enabled by default, and opening connections on a client machine (in my experience) has never been a big deal. It only really becomes a big deal when <em>lots</em> are being opened.</p>\n" }, { "answer_id": 125668, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 2, "selected": true, "text": "<p>Looks like you can just read this registry key:</p>\n\n<p>[HKEYLOCALMACHINE]\\SOFTWARE\\ODBC\\ODBCINST.INI\\SQL Server\\CPTimeout</p>\n\n<p>(or some variant thereof, depending on your OS and user account). If the value is 0, then connection pooling is disabled. If it's any value above 0, it's enabled.</p>\n\n<p>See:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms810829.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms810829.aspx</a></p>\n\n<p>I'm not sure about getting the number of open connections. Just curious: why do you need to know the number?</p>\n" }, { "answer_id": 838566, "author": "Anand", "author_id": 57817, "author_profile": "https://Stackoverflow.com/users/57817", "pm_score": 0, "selected": false, "text": "<p>To determine the number of open connections on each db, try this sql - I got it from a document on internet</p>\n\n<pre><code>select db_name(dbid) , count(*) 'connections count'\n from master..sysprocesses\n where spid &gt; 50 and spid @@spid\n group by db_name(dbid)\n order by count(*) desc\n</code></pre>\n\n<p>Spids &lt;=50 are used by sqlserver. So the above sql would tell you the connection used by your programs.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10786/" ]
I open a connection like this: ``` Using conn as New OdbcConnection(connectionString) conn.Open() //do stuff End Using ``` If connection pooling is enabled, the connection is not physically closed but released to the pool and will get reused. If it is disabled, it will be physically closed. Is there any way of knowing **programmatically** *if* connection pooling is enabled or not? and the number of used and unused connections currently open in the pool? **EDIT:** I need to get this information from within the program, I can't go and check it manually on every single PC where the program will be deployed.
Looks like you can just read this registry key: [HKEYLOCALMACHINE]\SOFTWARE\ODBC\ODBCINST.INI\SQL Server\CPTimeout (or some variant thereof, depending on your OS and user account). If the value is 0, then connection pooling is disabled. If it's any value above 0, it's enabled. See: <http://msdn.microsoft.com/en-us/library/ms810829.aspx> I'm not sure about getting the number of open connections. Just curious: why do you need to know the number?
125,606
<p>I'm working on a C#/ASP.NET web application, and I have a number of situations where I need to do locking. Ideally, I want the locks to act independently, since they have nothing to do with each other. I've been considering <code>[MethodImpl(MethodImplOptions.Synchronized)]</code> and a few ways of using <code>lock()</code>, but I have a few questions/concerns. </p> <p>It seems like MethodImplOptions.Synchronized<code>will essentially do</code>lock(this)`. If that's the case, it seems like a thread entering any synchronized method would block <em>all other</em> threads from entering <em>any</em> synchronized method. Is that right? If so, this isn't granular enough. At that point, it seems like I may as well use Application.Lock. (But please correct me if I'm wrong.)</p> <p>Concerning <code>lock()</code>, I'm trying to figure out what I should pass in. Should I create a set of objects solely for this purpose, and use each one for a different lock? Is there a better way?</p> <p>Thanks in advance!</p>
[ { "answer_id": 125614, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 0, "selected": false, "text": "<p>You can expose some static reference or a singleton, and lock() that.</p>\n\n<p>Maybe you can care to explain why you need such locking and what you will use it for?</p>\n" }, { "answer_id": 125621, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 0, "selected": false, "text": "<p>Creating discrete object instances at static/application level is the best way for plain exclusive locking. </p>\n\n<p>Should also consider if reader/writer lock instances at application level could also help improve your application concurrency e.g. for reading and updating lists, hashes etc.</p>\n" }, { "answer_id": 125622, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 2, "selected": false, "text": "<p>My preference is to create an object specifically for the lock. </p>\n\n<pre><code>private object lockForSomeResource = new object();\n</code></pre>\n\n<p>in the class that is managing the contentious resource.\nJeff Richter posted an <a href=\"http://msdn.microsoft.com/en-us/magazine/cc188793.aspx\" rel=\"nofollow noreferrer\">article</a> I read some time ago that recommended this.</p>\n\n<p>You need to think carefully about designing these as a hierarchy if there is any code within a lock that needs another lock. Make sure you always request them in the same order.</p>\n" }, { "answer_id": 125782, "author": "pradeeptp", "author_id": 20933, "author_profile": "https://Stackoverflow.com/users/20933", "pm_score": 1, "selected": false, "text": "<p>I have posted a similar question on this forum, that may help you. Following is the link</p>\n\n<p><a href=\"https://stackoverflow.com/questions/119548/problem-in-writing-to-single-file-in-web-service-in-net\">Issue writing to single file in Web service in .NET</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13348/" ]
I'm working on a C#/ASP.NET web application, and I have a number of situations where I need to do locking. Ideally, I want the locks to act independently, since they have nothing to do with each other. I've been considering `[MethodImpl(MethodImplOptions.Synchronized)]` and a few ways of using `lock()`, but I have a few questions/concerns. It seems like MethodImplOptions.Synchronized`will essentially do`lock(this)`. If that's the case, it seems like a thread entering any synchronized method would block *all other* threads from entering *any* synchronized method. Is that right? If so, this isn't granular enough. At that point, it seems like I may as well use Application.Lock. (But please correct me if I'm wrong.) Concerning `lock()`, I'm trying to figure out what I should pass in. Should I create a set of objects solely for this purpose, and use each one for a different lock? Is there a better way? Thanks in advance!
My preference is to create an object specifically for the lock. ``` private object lockForSomeResource = new object(); ``` in the class that is managing the contentious resource. Jeff Richter posted an [article](http://msdn.microsoft.com/en-us/magazine/cc188793.aspx) I read some time ago that recommended this. You need to think carefully about designing these as a hierarchy if there is any code within a lock that needs another lock. Make sure you always request them in the same order.
125,612
<p>I have a menu running off of a sitemap which one of the SiteMapNode looks like this: </p> <pre><code>&lt;siteMapNode title="Gear" description="" url=""&gt; &lt;siteMapNode title="Armor" description="" url="~/Armor.aspx" /&gt; &lt;siteMapNode title="Weapons" description="" url="~/Weapons.aspx" /&gt; &lt;/siteMapNode&gt; </code></pre> <p>I also have a Skin applied to the asp:menu which uses the following css definition:</p> <pre><code>.nav-bar { z-index: 2; margin-top: -5%; position: absolute; top: 281px; font-family: Jokewood; font-style: italic; } </code></pre> <p>When I run the website and mouseOver the Gear link, the Jokewood font is not applied to those items, how can I apply the css to the Armor and Weapons titles?</p> <p><strong>Update</strong><br> I should of mentioned that the font is displayed correctly on all non-nested siteMapNodes.</p>
[ { "answer_id": 125629, "author": "Devin Ceartas", "author_id": 14897, "author_profile": "https://Stackoverflow.com/users/14897", "pm_score": 2, "selected": false, "text": "<p>you can nest CSS commands by listing them in sequence</p>\n\n<p>siteMapNode siteMapNode { .... css code ... } would be applied to the inner node.</p>\n\n<p>for instance, </p>\n\n<p>#menu ul ul { ... }</p>\n\n<p>would be applied to <br>\n&lt;ul&gt; &lt;-- not here<br>\n&lt;li&gt;<br>\n&lt;/li&gt;<br>\n&lt;/ul&gt;<br>\n&lt;div id=\"menu\"&gt;<br>\n &lt;ul&gt; &lt;-- not here<br>\n &lt;ul&gt; &lt;---- <b>here</b><br></p>\n" }, { "answer_id": 125667, "author": "kosoant", "author_id": 15114, "author_profile": "https://Stackoverflow.com/users/15114", "pm_score": 1, "selected": false, "text": "<p>Firefox's <a href=\"https://addons.mozilla.org/en-US/firefox/addon/60\" rel=\"nofollow noreferrer\">Web Developer (<a href=\"https://addons.mozilla.org/en-US/firefox/addon/60\" rel=\"nofollow noreferrer\">https://addons.mozilla.org/en-US/firefox/addon/60</a>)</a> addon is a good alternative/companion to firebug. It's <b>easier to use for CSS debugging</b> (IMO)</p>\n" }, { "answer_id": 125706, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 1, "selected": true, "text": "<p>You should bind styles like this (for both static and dynamic menu items):</p>\n\n<pre><code>&lt;asp:Menu ID=\"Menu1\" runat=\"server\" &gt;\n &lt;StaticMenuStyle CssClass=\"nav-bar\" /&gt;\n &lt;DynamicMenuStyle CssClass=\"nav-bar\" /&gt;\n&lt;/asp:Menu&gt;\n</code></pre>\n" }, { "answer_id": 125742, "author": "Matt R", "author_id": 4298, "author_profile": "https://Stackoverflow.com/users/4298", "pm_score": 0, "selected": false, "text": "<p>The skin is applied through a .skin template.</p>\n\n<pre><code>&lt;asp:Menu runat=\"server\" CssClass=\"nav-bar\" /&gt;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4298/" ]
I have a menu running off of a sitemap which one of the SiteMapNode looks like this: ``` <siteMapNode title="Gear" description="" url=""> <siteMapNode title="Armor" description="" url="~/Armor.aspx" /> <siteMapNode title="Weapons" description="" url="~/Weapons.aspx" /> </siteMapNode> ``` I also have a Skin applied to the asp:menu which uses the following css definition: ``` .nav-bar { z-index: 2; margin-top: -5%; position: absolute; top: 281px; font-family: Jokewood; font-style: italic; } ``` When I run the website and mouseOver the Gear link, the Jokewood font is not applied to those items, how can I apply the css to the Armor and Weapons titles? **Update** I should of mentioned that the font is displayed correctly on all non-nested siteMapNodes.
You should bind styles like this (for both static and dynamic menu items): ``` <asp:Menu ID="Menu1" runat="server" > <StaticMenuStyle CssClass="nav-bar" /> <DynamicMenuStyle CssClass="nav-bar" /> </asp:Menu> ```
125,619
<p>I'm working on an app that requires no user input, but I don't want the iPhone to enter the power saving mode.</p> <p>Is it possible to disable power saving from an app?</p>
[ { "answer_id": 125645, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 9, "selected": true, "text": "<p><strong>Objective-C</strong></p>\n\n<pre><code>[[UIApplication sharedApplication] setIdleTimerDisabled:YES];\n</code></pre>\n\n<p><strong>Swift</strong></p>\n\n<pre><code>UIApplication.shared.isIdleTimerDisabled = true\n</code></pre>\n" }, { "answer_id": 29295059, "author": "Vettiyanakan", "author_id": 2082723, "author_profile": "https://Stackoverflow.com/users/2082723", "pm_score": 5, "selected": false, "text": "<p>In <strong>swift</strong> you can use this as </p>\n\n<pre><code>UIApplication.sharedApplication().idleTimerDisabled = true\n</code></pre>\n" }, { "answer_id": 36068248, "author": "JMStudios.jrichardson", "author_id": 2232919, "author_profile": "https://Stackoverflow.com/users/2232919", "pm_score": 2, "selected": false, "text": "<p>I have put this line of code in my view controller yet we still get customers saying the screen will dim or turn off until someone touches the screen. I have seen other posts where not only do you programatically set </p>\n\n<pre><code>UIApplication.sharedApplication().idleTimerDisabled = true \n</code></pre>\n\n<p>to true but you must reset it to false first</p>\n\n<pre><code>UIApplication.sharedApplication().idleTimerDisabled = false\nUIApplication.sharedApplication().idleTimerDisabled = true\n</code></pre>\n\n<p>Sadly this still did not work and customers are still getting dimmed screens. We have Apple Configurator profile preventing the device from going to sleep, and still some devices screen go dim and the customer needs to press the home button to wake the screen. I now put this code into a timer that fires every 2.5 hours to reset the idle timer, hopefully this will work.</p>\n" }, { "answer_id": 37054674, "author": "JMStudios.jrichardson", "author_id": 2232919, "author_profile": "https://Stackoverflow.com/users/2232919", "pm_score": 0, "selected": false, "text": "<p>We were having the same issue. Turned out to be a rogue process on our MDM server that was deleted in our account but on the server was still sending the command to dim our devices. </p>\n" }, { "answer_id": 40866960, "author": "Charlie Seligman", "author_id": 646818, "author_profile": "https://Stackoverflow.com/users/646818", "pm_score": 4, "selected": false, "text": "<p><strong>Swift 3:</strong></p>\n\n<pre><code>UIApplication.shared.isIdleTimerDisabled = true\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
I'm working on an app that requires no user input, but I don't want the iPhone to enter the power saving mode. Is it possible to disable power saving from an app?
**Objective-C** ``` [[UIApplication sharedApplication] setIdleTimerDisabled:YES]; ``` **Swift** ``` UIApplication.shared.isIdleTimerDisabled = true ```
125,627
<p>I want to call a web service, but I won't know the url till runtime.</p> <p>Whats the best way to get the web reference in, without actually committing to a url.</p> <p>What about having 1 client hit the same web service on say 10 different domains?</p>
[ { "answer_id": 125637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>Create the web reference, and convert the web service to a dynamic web service. A dynamic web service allows you to modify the Url.</p>\n\n<p>You need to create the web reference now to ensure your application understands the interfaces available. By switching to a dynamic web service you can then modify the .Url property after you have initialised the web reference in your code.</p>\n\n<pre><code>service = new MyWebService.MyWebService();\nservice.Url = myWebServiceUrl;\n</code></pre>\n" }, { "answer_id": 125643, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 1, "selected": false, "text": "<p>You can change the Url property of the class generated by the Web Reference wizard.</p>\n\n<p>Here is a very similiar question; <a href=\"https://stackoverflow.com/questions/125399/how-can-i-dynamically-switch-web-service-addresses-in-net-without-a-recompile\">How can I dynamically switch web service addresses in .NET without a recompile?</a></p>\n" }, { "answer_id": 125649, "author": "stefano m", "author_id": 19261, "author_profile": "https://Stackoverflow.com/users/19261", "pm_score": 0, "selected": false, "text": "<p>you could call your web service by a simple http Request:\nExample:</p>\n\n<p><a href=\"http://serverName/appName/WSname.asmx/yourMethod\" rel=\"nofollow noreferrer\">http://serverName/appName/WSname.asmx/yourMethod</a>?\nparam1=val1&amp;param2=val2;</p>\n\n<p>if you call via Http, http response will be serialized result.</p>\n\n<p>But if you use a web reference, you always can change Url, by Url property in web service proxy class. Url tipically will be stored in your web.config</p>\n\n<p>I hope i help you</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
I want to call a web service, but I won't know the url till runtime. Whats the best way to get the web reference in, without actually committing to a url. What about having 1 client hit the same web service on say 10 different domains?
Create the web reference, and convert the web service to a dynamic web service. A dynamic web service allows you to modify the Url. You need to create the web reference now to ensure your application understands the interfaces available. By switching to a dynamic web service you can then modify the .Url property after you have initialised the web reference in your code. ``` service = new MyWebService.MyWebService(); service.Url = myWebServiceUrl; ```
125,632
<p>When providing a link to a PDF file on a website, is it possible to include information in the URL (request parameters) which will make the PDF browser plugin (if used) jump to a particular bookmark instead of just opening at the beginning?</p> <p>Something like: <a href="http://www.somehost.com/user-guide.pdf?bookmark=chapter3" rel="noreferrer">http://www.somehost.com/user-guide.pdf?bookmark=chapter3</a> ?</p> <p>If not a bookmark, would it be possible to go to a particular page?</p> <p>I'm assuming that if there is an answer it may be specific to Adobe's PDF reader plugin or something, and may have version limitations, but I'm mostly interested in whether the technique exists at all.</p>
[ { "answer_id": 125650, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 7, "selected": true, "text": "<p>Yes, you can link to specific pages by number or named locations and that will always work <strong>if the user's browser uses Adobe Reader as plugin for viewing PDF files</strong>.</p>\n\n<p>For a specific page by number:</p>\n\n<pre><code>&lt;a href=\"http://www.domain.com/file.pdf#page=3\"&gt;Link text&lt;/a&gt;\n</code></pre>\n\n<p>For a named location (destination):</p>\n\n<pre><code>&lt;a href=\"http://www.domain.com/file.pdf#nameddest=TOC\"&gt;Link text&lt;/a&gt;\n</code></pre>\n\n<p><br/></p>\n\n<p>To create destinations within a PDF with Acrobat:</p>\n\n<ol>\n<li>Manually navigate through the PDF for the desired location</li>\n<li>Go to View > Navigation Tabs > Destinations</li>\n<li>Under Options, choose Scan Document</li>\n<li>Once this is completed, select New Destination from the Options menu and enter an appropriate name </li>\n</ol>\n" }, { "answer_id": 125793, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://www.rfc-editor.org/rfc/rfc3778#section-3\" rel=\"nofollow noreferrer\">RFC 3778 section 3</a> specifies &quot;Fragment Identifiers&quot; that can be used with PDF files, which include nameddest and page.</p>\n" }, { "answer_id": 30381925, "author": "rslemos", "author_id": 1535706, "author_profile": "https://Stackoverflow.com/users/1535706", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#page=5&amp;zoom=auto,-169,394\" rel=\"noreferrer\" title=\"PDF Open Parameters\">PDF Open Parameters</a> documents the available URL fragments you can use.</p>\n" }, { "answer_id": 32258750, "author": "Greg Dubicki", "author_id": 2693875, "author_profile": "https://Stackoverflow.com/users/2693875", "pm_score": 3, "selected": false, "text": "<p>It's worth adding that <a href=\"https://stackoverflow.com/a/125650/2693875\">Wayne's solution</a> also <strong>works</strong> in:</p>\n<ul>\n<li>Chrome (since v. 14 from 2011, see <a href=\"https://code.google.com/p/chromium/issues/detail?id=65851\" rel=\"nofollow noreferrer\">this issue</a> for details) (tested on v. 87 and v. 44),</li>\n<li>Firefox (tested on v. 84.0.1 and v. 40),</li>\n<li>Opera (tested on v. 73 and v. 31),</li>\n<li>Safari (tested on v. 14.0.2, it <em>didn't</em> work on v. 8),</li>\n</ul>\n<p>(Updated with the current versions as of <strong>January 2021</strong>.)</p>\n" }, { "answer_id": 38049428, "author": "Matas Vaitkevicius", "author_id": 1509764, "author_profile": "https://Stackoverflow.com/users/1509764", "pm_score": 4, "selected": false, "text": "<p>There are multiple query parameters that can be handled.\nFull list below:</p>\n\n<p><a href=\"http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#page=5&amp;zoom=auto,-169,394\" rel=\"noreferrer\">Source</a> </p>\n\n<pre><code>+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| Syntax | Description | Example |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| nameddest=destination | Specifies a named destination in the PDF document | http://example.org/doc.pdf#Chapter6 |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| page=pagenum | Specifies a numbered page in the document, using an integer | http://example.org/doc.pdf#page=3 |\n| | value. The document’s first page has a pagenum value of 1. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| comment=commentID | Specifies a comment on a given page in the PDF document. Use | #page=1&amp;comment=452fde0e-fd22-457c-84aa- |\n| | the page command before this command. | 2cf5bed5a349 |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| collab=setting | Sets the comment repository to be used to supply and store | #collab=DAVFDF@http://review_server/Collab |\n| | comments for the document. This overrides the default comment | /user1 |\n| | server for the review or the default preference. The setting is of the | |\n| | form store_type@location, where valid values for store_type are: | |\n| | ● DAVFDF (WebDAV) | |\n| | ● FSFDF (Network folder) | |\n| | ● DB (ADBC) | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| zoom=scale | Sets the zoom and scroll factors, using float or integer values. For | http://example.org/doc.pdf#page=3&amp;zoom=200,250,100 |\n| zoom=scale,left,top | example, a scale value of 100 indicates a zoom value of 100%. | |\n| | Scroll values left and top are in a coordinate system where 0,0 | |\n| | represents the top left corner of the visible page, regardless of | |\n| | document rotation | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| view=Fit | Set the view of the displayed page, using the keyword values | http://example.org/doc.pdf#page=72&amp;view=fitH,100 |\n| view=FitH | defined in the PDF language specification. For more information, | |\n| view=FitH,top | see the PDF Reference. | |\n| view=FitV | Scroll values left and top are floats or integers in a coordinate | |\n| view=FitV,left | system where 0,0 represents the top left corner of the visible | |\n| view=FitB | page, regardless of document rotation. | |\n| view=FitBH | Use the page command before this command. | |\n| view=FitBH,top | | |\n| view=FitBV | | |\n| view=FitBV,left | | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| viewrect=left,top,wd,ht | Sets the view rectangle using float or integer values in a | |\n| | coordinate system where 0,0 represents the top left corner of the | |\n| | visible page, regardless of document rotation. | |\n| | Use the page command before this command. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| pagemode=bookmarks | Displays bookmarks or thumbnails. | http://example.org/doc.pdf#pagemode=bookmarks&amp;page=2 |\n| pagemode=thumbs | | |\n| pagemode=none | | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| scrollbar=1|0 | Turns scrollbars on or off | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| search=wordList | Opens the Search panel and performs a search for any of thewords in the specified word list. | #search=\"word1 word2\" |\n| | The first matching word ishighlighted in the document. | |\n| | The words must be enclosed in quotation marks and separated byspaces. | |\n| | You can search only for single words. You cannot search for a string of words. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| toolbar=1|0 | Turns the toolbar on or off. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| statusbar=1|0 | Turns the status bar on or off. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| messages=1|0 | Turns the document message bar on or off. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| navpanes=1|0 | Turns the navigation panes and tabs on or off. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| highlight=lt,rt,top,btm | Highlights a specified rectangle on the displayed page. Use the | |\n| | page command before this command. | |\n| | The rectangle values are integers in a coordinate system where | |\n| | 0,0 represents the top left corner of the visible page, regardless of | |\n| | document rotation | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| fdf=URL | Specifies an FDF file to populate form fields in the PDF file beingopened. | #fdf=http://example.org/doc.fdf |\n| | Note: The fdf parameter should be specified last in a URL. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
When providing a link to a PDF file on a website, is it possible to include information in the URL (request parameters) which will make the PDF browser plugin (if used) jump to a particular bookmark instead of just opening at the beginning? Something like: <http://www.somehost.com/user-guide.pdf?bookmark=chapter3> ? If not a bookmark, would it be possible to go to a particular page? I'm assuming that if there is an answer it may be specific to Adobe's PDF reader plugin or something, and may have version limitations, but I'm mostly interested in whether the technique exists at all.
Yes, you can link to specific pages by number or named locations and that will always work **if the user's browser uses Adobe Reader as plugin for viewing PDF files**. For a specific page by number: ``` <a href="http://www.domain.com/file.pdf#page=3">Link text</a> ``` For a named location (destination): ``` <a href="http://www.domain.com/file.pdf#nameddest=TOC">Link text</a> ``` To create destinations within a PDF with Acrobat: 1. Manually navigate through the PDF for the desired location 2. Go to View > Navigation Tabs > Destinations 3. Under Options, choose Scan Document 4. Once this is completed, select New Destination from the Options menu and enter an appropriate name
125,638
<p>At run time I want to dynamically build grid columns (or another display layout) in a WPF ListView. I do not know the number and names of the columns before hand.</p> <p>I want to be able to do:<br/> MyListView.ItemSource = MyDataset;<br/> MyListView.CreateColumns();</p>
[ { "answer_id": 125736, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 0, "selected": false, "text": "<p>Have a <strong>DataTemplateselector</strong> to select one of the predefined templates(Of same DataType) and apply the selector on to the ListView. You can have as many DataTemplates with different columns.</p>\n" }, { "answer_id": 128093, "author": "Greg", "author_id": 11013, "author_profile": "https://Stackoverflow.com/users/11013", "pm_score": 2, "selected": true, "text": "<p>i'd try following approach:</p>\n\n<p>A) you need to have the list box display grid view - i believe this you've done already <br>\nB) define a style for GridViewColumnHeader:</p>\n\n<pre><code> &lt;Style TargetType=\"{x:Type GridViewColumnHeader}\" x:Key=\"gridViewColumnStyle\"&gt;\n &lt;EventSetter Event=\"Click\" Handler=\"OnHeaderClicked\"/&gt;\n &lt;EventSetter Event=\"Loaded\" Handler=\"OnHeaderLoaded\"/&gt;\n &lt;/Style&gt;\n</code></pre>\n\n<p>in my case, i had a whole bunch of other properties set, but in the basic scenario - you'd need Loaded event. Clicked - this is useful if you want to add sorting and filtering functionality.</p>\n\n<p>C) in your listview code, bind the template with your gridview:</p>\n\n<pre><code> public MyListView()\n {\n InitializeComponent();\n GridView gridViewHeader = this.listView.View as GridView;\n System.Diagnostics.Debug.Assert(gridViewHeader != null, \"Expected ListView.View should be GridView\");\n if (null != gridViewHeader)\n {\n gridViewHeader.ColumnHeaderContainerStyle = (Style)this.FindResource(\"gridViewColumnStyle\");\n }\n }\n</code></pre>\n\n<p>D) then in you OnHeaderLoaded handler, you can set a proper template based on the column's data</p>\n\n<pre><code> void OnHeaderLoaded(object sender, RoutedEventArgs e)\n {\n GridViewColumnHeader header = (GridViewColumnHeader)sender;\n GridViewColumn column = header.Column;\n</code></pre>\n\n<p>//select and apply your data template here.</p>\n\n<pre><code> e.Handled = true;\n }\n</code></pre>\n\n<p>E) I guess you'd need also to acquire ownership of ItemsSource dependency property and handle it's changed event. </p>\n\n<pre><code> ListView.ItemsSourceProperty.AddOwner(typeof(MyListView), new PropertyMetadata(OnItemsSourceChanged));\n\n static void OnItemsSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)\n {\n MyListView view = (MyListView)sender;\n //do reflection to get column names and types\n //and for each column, add it to your grid view:\n GridViewColumn column = new GridViewColumn();\n //set column properties here...\n view.Columns.Add(column);\n }\n</code></pre>\n\n<p>the GridViewColumn class itself doesn't have much properties, so you might want to add some information there using attached properties - i.e. like unique column tag - header most likely will be used for localization, and you will not relay on this one. </p>\n\n<p>In general, this approach, even though quite complicated, will allow you to easily extend your list view functionality. </p>\n" }, { "answer_id": 208994, "author": "EFrank", "author_id": 28572, "author_profile": "https://Stackoverflow.com/users/28572", "pm_score": 0, "selected": false, "text": "<p>You can use a <strong>DataTemplateSelector</strong> to return a DataTemplate that you have created dynamically in code. However, this is a bit tedious and more complicated than using a predefined one from XAML, but it is still possible.\nHave a look at this example: <a href=\"http://dedjo.blogspot.com/2007/03/creating-datatemplates-from-code.html\" rel=\"nofollow noreferrer\">http://dedjo.blogspot.com/2007/03/creating-datatemplates-from-code.html</a></p>\n" }, { "answer_id": 867181, "author": "Tawani", "author_id": 61525, "author_profile": "https://Stackoverflow.com/users/61525", "pm_score": 2, "selected": false, "text": "<p>You can add columns dynamically to a ListView by using Attached Properties. Check out this article on the <b>CodeProject</b> it explains exactly that...</p>\n\n<p><a href=\"http://www.codeproject.com/KB/WPF/WPF_DynamicListView.aspx\" rel=\"nofollow noreferrer\">WPF DynamicListView - Binding to a DataMatrix</a></p>\n" }, { "answer_id": 872322, "author": "treehouse", "author_id": 106402, "author_profile": "https://Stackoverflow.com/users/106402", "pm_score": 2, "selected": false, "text": "<p>From MSDN:</p>\n\n<pre><code> MyListBox.ItemsSource = view;\n ListView myListView = new ListView();\n\n GridView myGridView = new GridView();\n myGridView.AllowsColumnReorder = true;\n myGridView.ColumnHeaderToolTip = \"Employee Information\";\n\n GridViewColumn gvc1 = new GridViewColumn();\n gvc1.DisplayMemberBinding = new Binding(\"FirstName\");\n gvc1.Header = \"FirstName\";\n gvc1.Width = 100;\n myGridView.Columns.Add(gvc1);\n GridViewColumn gvc2 = new GridViewColumn();\n gvc2.DisplayMemberBinding = new Binding(\"LastName\");\n gvc2.Header = \"Last Name\";\n gvc2.Width = 100;\n myGridView.Columns.Add(gvc2);\n GridViewColumn gvc3 = new GridViewColumn();\n gvc3.DisplayMemberBinding = new Binding(\"EmployeeNumber\");\n gvc3.Header = \"Employee No.\";\n gvc3.Width = 100;\n myGridView.Columns.Add(gvc3);\n\n //ItemsSource is ObservableCollection of EmployeeInfo objects\n myListView.ItemsSource = new myEmployees();\n myListView.View = myGridView;\n myStackPanel.Children.Add(myListView);\n</code></pre>\n" }, { "answer_id": 902409, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 0, "selected": false, "text": "<p>From experience I can recommend steering clear of dynamic data templates if you can help it... rather use the advice given here to explictly create the ListView columns, rather than trying to create a DataTemplate dynamically.</p>\n\n<p>Reason is that the FrameworkElementFactory (or whatever the class name is for producing DataTemplates at run time) is somewhat cludgey to use (and is deprecated in favor of using XAML for dynamic templates) - either way you take a performance hit.</p>\n" }, { "answer_id": 74018748, "author": "Ali Nehme", "author_id": 7932581, "author_profile": "https://Stackoverflow.com/users/7932581", "pm_score": 0, "selected": false, "text": "<p>This function will <strong>bind columns to a specified class and dynamically set header, binding, width, and string format.</strong></p>\n<pre><code>private void AddListViewColumns&lt;T&gt;(GridView GvFOO)\n {\n foreach (System.Reflection.PropertyInfo property in typeof(T).GetProperties().Where(p =&gt; p.CanWrite)) //loop through the fields of the object\n {\n if (property.Name != &quot;Id&quot;) //if you don't want to add the id in the list view\n {\n GridViewColumn gvc = new GridViewColumn(); //initialize the new column\n gvc.DisplayMemberBinding = new Binding(property.Name); // bind the column to the field\n if (property.PropertyType == typeof(DateTime)) { gvc.DisplayMemberBinding.StringFormat = &quot;yyyy-MM-dd&quot;; } //[optional] if you want to display dates only for DateTime data\n gvc.Header = property.Name; //set header name like the field name\n gvc.Width = (property.Name == &quot;Description&quot;) ? 200 : 100; //set width dynamically\n GvFOO.Columns.Add(gvc); //add new column to the Gridview\n }\n }\n }\n</code></pre>\n<p>Let's say you have a GridView with Name=&quot;GvFoo&quot; in your XAML, which you would like to bind to a class FOO.\nthen, you can call the function by passing your class &quot;FOO and GridView &quot;GvFoo&quot; as arguments in your MainWindow.xaml.cs <strong>on Window loading</strong></p>\n<pre><code>AddLvTodoColumns&lt;FOO&gt;(GvFoo);\n</code></pre>\n<p>your MainWindow.xaml file should include the following</p>\n<pre><code>&lt;ListView x:Name=&quot;LvFOO&quot;&gt;\n &lt;ListView.View&gt;\n &lt;GridView x:Name=&quot;GvTodos&quot;/&gt;\n &lt;/ListView.View&gt;\n &lt;/ListView&gt;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
At run time I want to dynamically build grid columns (or another display layout) in a WPF ListView. I do not know the number and names of the columns before hand. I want to be able to do: MyListView.ItemSource = MyDataset; MyListView.CreateColumns();
i'd try following approach: A) you need to have the list box display grid view - i believe this you've done already B) define a style for GridViewColumnHeader: ``` <Style TargetType="{x:Type GridViewColumnHeader}" x:Key="gridViewColumnStyle"> <EventSetter Event="Click" Handler="OnHeaderClicked"/> <EventSetter Event="Loaded" Handler="OnHeaderLoaded"/> </Style> ``` in my case, i had a whole bunch of other properties set, but in the basic scenario - you'd need Loaded event. Clicked - this is useful if you want to add sorting and filtering functionality. C) in your listview code, bind the template with your gridview: ``` public MyListView() { InitializeComponent(); GridView gridViewHeader = this.listView.View as GridView; System.Diagnostics.Debug.Assert(gridViewHeader != null, "Expected ListView.View should be GridView"); if (null != gridViewHeader) { gridViewHeader.ColumnHeaderContainerStyle = (Style)this.FindResource("gridViewColumnStyle"); } } ``` D) then in you OnHeaderLoaded handler, you can set a proper template based on the column's data ``` void OnHeaderLoaded(object sender, RoutedEventArgs e) { GridViewColumnHeader header = (GridViewColumnHeader)sender; GridViewColumn column = header.Column; ``` //select and apply your data template here. ``` e.Handled = true; } ``` E) I guess you'd need also to acquire ownership of ItemsSource dependency property and handle it's changed event. ``` ListView.ItemsSourceProperty.AddOwner(typeof(MyListView), new PropertyMetadata(OnItemsSourceChanged)); static void OnItemsSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { MyListView view = (MyListView)sender; //do reflection to get column names and types //and for each column, add it to your grid view: GridViewColumn column = new GridViewColumn(); //set column properties here... view.Columns.Add(column); } ``` the GridViewColumn class itself doesn't have much properties, so you might want to add some information there using attached properties - i.e. like unique column tag - header most likely will be used for localization, and you will not relay on this one. In general, this approach, even though quite complicated, will allow you to easily extend your list view functionality.
125,664
<p>How do I write a program that tells when my other program ends?</p>
[ { "answer_id": 125671, "author": "Viktor", "author_id": 17424, "author_profile": "https://Stackoverflow.com/users/17424", "pm_score": -1, "selected": false, "text": "<p>This is called the \"halting problem\" and is not solvable.\nSee <a href=\"http://en.wikipedia.org/wiki/Halting_problem\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Halting_problem</a></p>\n" }, { "answer_id": 125678, "author": "elephantum", "author_id": 844, "author_profile": "https://Stackoverflow.com/users/844", "pm_score": -1, "selected": false, "text": "<p>If you want analyze one program without execution than it's unsolvable problem.</p>\n" }, { "answer_id": 125683, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>On Windows, a technique I've used is to create a global named object (such as a mutex with CreateMutex), and then have the monitoring program open that same named mutex and wait for it (with WaitForSingleObject). As soon as the first program exits, the second program obtains the mutex and knows that the first program exited.</p>\n\n<p>On Unix, a usual way to solve this is to have the first program write its pid (getpid()) to a file. A second program can monitor this pid (using kill(pid, 0)) to see whether the first program is gone yet. This method is subject to race conditions and there are undoubtedly better ways to solve it.</p>\n" }, { "answer_id": 125692, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 0, "selected": false, "text": "<p>Most operating systems its generally the same kind of thing....</p>\n\n<p>you record the process ID of the program in question and just monitor it by querying the actives processes periodically</p>\n\n<p>In windows at least, you can trigger off events to do it... </p>\n" }, { "answer_id": 125698, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "<p>The only way to do a waitpid() or waitid() on a program that isn't spawned by yourself is to become its parent by ptrace'ing it.</p>\n\n<p>Here is an example of how to use ptrace on a posix operating system to temporarily become another processes parent, and then wait until that program exits. As a side effect you can also get the exit code, and the signal that caused that program to exit.:</p>\n\n<pre><code>#include &lt;sys/ptrace.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;signal.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;sys/wait.h&gt;\n\nint main(int argc, char** argv) {\n\n int pid = atoi(argv[1]);\n int status;\n siginfo_t si;\n\n switch (ptrace(PTRACE_ATTACH, pid, NULL)) {\n case 0:\n break;\n case -ESRCH:\n case -EPERM:\n return 0;\n default:\n fprintf(stderr, \"Failed to attach child\\n\");\n return 1;\n }\n if (pid != wait(&amp;status)) {\n fprintf(stderr, \"wrong wait signal\\n\");\n return 1;\n }\n if (!WIFSTOPPED(status) || (WSTOPSIG(status) != SIGSTOP)) {\n /* The pid might not be running */\n if (!kill(pid, 0)) {\n fprintf(stderr, \"SIGSTOP didn't stop child\\n\");\n return 1;\n } else {\n return 0;\n }\n }\n if (ptrace(PTRACE_CONT, pid, 0, 0)) {\n fprintf(stderr, \"Failed to restart child\\n\");\n return 1;\n }\n\n while (1) {\n if (waitid(P_PID, pid, &amp;si, WSTOPPED | WEXITED)) {\n // an error occurred.\n if (errno == ECHILD)\n return 0;\n return 1;\n }\n errno = 0;\n\n if (si.si_code &amp; (CLD_STOPPED | CLD_TRAPPED)) {\n /* If the child gets stopped, we have to PTRACE_CONT it\n * this will happen when the child has a child that exits.\n **/\n if (ptrace(PTRACE_CONT, pid, 1, si.si_status)) {\n if (errno == ENOSYS) {\n /* Wow, we're stuffed. Stop and return */\n return 0;\n }\n }\n continue;\n }\n\n if (si.si_code &amp; (CLD_EXITED | CLD_KILLED | CLD_DUMPED)) {\n return si.si_status;\n }\n // Fall through to exiting.\n return 1;\n }\n}\n</code></pre>\n" }, { "answer_id": 125699, "author": "Justin Yost", "author_id": 657, "author_profile": "https://Stackoverflow.com/users/657", "pm_score": -1, "selected": false, "text": "<p>Umm you can't, this is an impossible task given the nature of it.</p>\n\n<p>Let's say you have a program foo that takes as input another program foo-sub.</p>\n\n<pre><code>Foo {\n func Stops(foo_sub) { run foo_sub; return 1; }\n}\n</code></pre>\n\n<p>The problem with this all be it rather simplistic design is that quite simply if foo-sub is a program that never ends, foo itself never ends. There is no way to tell from the outside if foo-sub or foo is what is causing the program to stop and what determines if your program simply takes a century to run?</p>\n\n<p>Essentially this is one of the questions that a computer can't answer. For a more complete overview, Wikipedia has an article on <a href=\"http://en.wikipedia.org/wiki/The_halting_problem\" rel=\"nofollow noreferrer\" title=\"Wikipedia: The Halting Problem\">this</a>.</p>\n" }, { "answer_id": 125723, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 2, "selected": false, "text": "<p>If you want to spawn another process, and then do nothing while it runs, then most higher-level languages already have built-ins for doing this. In Perl, for example, there's both <code>system</code> and backticks for running processes and waiting for them to finish, and modules such as <a href=\"http://search.cpan.org/perldoc?IPC::System::Simple\" rel=\"nofollow noreferrer\">IPC::System::Simple</a> for making it easier to figure how the program terminated, and whether you're happy or sad about that having happened. Using a language feature that handles everything for you is <em>way</em> easier than trying to do it yourself.</p>\n\n<p>If you're on a Unix-flavoured system, then the termination of a process that you've forked will generate a SIGCHLD signal. This means your program can do other things your child process is running. </p>\n\n<p>Catching the SIGCHLD signal varies depending upon your language. In Perl, you set a signal handler like so:</p>\n\n<pre><code>use POSIX qw(:sys_wait_h);\n\nsub child_handler {\n\n while ((my $child = waitpid(-1, WNOHANG)) &gt; 0) {\n # We've caught a process dying, its PID is now in $child.\n # The exit value and other information is in $?\n }\n\n $SIG{CHLD} \\&amp;child_handler; # SysV systems clear handlers when called,\n # so we need to re-instate it.\n}\n\n# This establishes our handler.\n$SIG{CHLD} = \\&amp;child_handler;\n</code></pre>\n\n<p>There's almost certainly modules on the CPAN that do a better job than the sample code above. You can use <code>waitpid</code> with a specific process ID (rather than -1 for all), and without <code>WNOHANG</code> if you want to have your program sleep until the other process has completed.</p>\n\n<p>Be aware that while you're inside a signal handler, all sorts of weird things can happen. Another signal may come in (hence we use a while loop, to catch all dead processes), and depending upon your language, you may be part-way through another operation!</p>\n\n<p>If you're using Perl on Windows, then you can use the <a href=\"http://search.cpan.org/perldoc?Win32::Process\" rel=\"nofollow noreferrer\">Win32::Process</a> module to spawn a process, and call <code>-&gt;Wait</code> on the resulting object to wait for it to die. I'm not familiar with all the guts of <code>Win32::Process</code>, but you should be able to wait for a length of <code>0</code> (or <code>1</code> for a single millisecond) to check to see if a process is dead yet.</p>\n\n<p>In other languages and environments, your mileage may vary. Please make sure that when your other process dies you check to see <em>how</em> it dies. Having a sub-process die because a user killed it usually requires a different response than it exiting because it successfully finished its task.</p>\n\n<p>All the best,</p>\n\n<p>Paul</p>\n" }, { "answer_id": 125928, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 2, "selected": false, "text": "<p>Are you on Windows ? If so, the following should solve the problem - you need to pass the process ID:</p>\n\n<pre><code> bool WaitForProcessExit( DWORD _dwPID )\n { \n HANDLE hProc = NULL;\n bool bReturn = false;\n\n hProc = OpenProcess(SYNCHRONIZE, FALSE, _dwPID);\n\n if(hProc != NULL)\n {\n if ( WAIT_OBJECT_0 == WaitForSingleObject(hProc, INFINITE) )\n {\n bReturn = true;\n }\n }\n\n CloseHandle(hProc) ;\n }\n\n return bReturn;\n}\n</code></pre>\n\n<p>Note: This is a blocking function. If you want non-blocking then you'll need to change the INFINITE to a smaller value and call it in a loop (probably keeping the hProc handle open to avoid reopening on a different process of the same PID).</p>\n\n<p>Also, I've not had time to test this piece of source code, but I lifted it from an app of mine which does work.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I write a program that tells when my other program ends?
The only way to do a waitpid() or waitid() on a program that isn't spawned by yourself is to become its parent by ptrace'ing it. Here is an example of how to use ptrace on a posix operating system to temporarily become another processes parent, and then wait until that program exits. As a side effect you can also get the exit code, and the signal that caused that program to exit.: ``` #include <sys/ptrace.h> #include <errno.h> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char** argv) { int pid = atoi(argv[1]); int status; siginfo_t si; switch (ptrace(PTRACE_ATTACH, pid, NULL)) { case 0: break; case -ESRCH: case -EPERM: return 0; default: fprintf(stderr, "Failed to attach child\n"); return 1; } if (pid != wait(&status)) { fprintf(stderr, "wrong wait signal\n"); return 1; } if (!WIFSTOPPED(status) || (WSTOPSIG(status) != SIGSTOP)) { /* The pid might not be running */ if (!kill(pid, 0)) { fprintf(stderr, "SIGSTOP didn't stop child\n"); return 1; } else { return 0; } } if (ptrace(PTRACE_CONT, pid, 0, 0)) { fprintf(stderr, "Failed to restart child\n"); return 1; } while (1) { if (waitid(P_PID, pid, &si, WSTOPPED | WEXITED)) { // an error occurred. if (errno == ECHILD) return 0; return 1; } errno = 0; if (si.si_code & (CLD_STOPPED | CLD_TRAPPED)) { /* If the child gets stopped, we have to PTRACE_CONT it * this will happen when the child has a child that exits. **/ if (ptrace(PTRACE_CONT, pid, 1, si.si_status)) { if (errno == ENOSYS) { /* Wow, we're stuffed. Stop and return */ return 0; } } continue; } if (si.si_code & (CLD_EXITED | CLD_KILLED | CLD_DUMPED)) { return si.si_status; } // Fall through to exiting. return 1; } } ```
125,677
<p>So I'm writing a framework on which I want to base a few apps that I'm working on (the framework is there so I have an environment to work with, and a system that will let me, for example, use a single sign-on)</p> <p>I want to make this framework, and the apps it has use a Resource Oriented Architecture.</p> <p>Now, I want to create a URL routing class that is expandable by APP writers (and possibly also by CMS App users, but that's WAYYYY ahead in the future) and I'm trying to figure out the best way to do it by looking at how other apps do it.</p>
[ { "answer_id": 125799, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 1, "selected": false, "text": "<p>Use a list of Regexs to match which object I should be using</p>\n\n<p>For example</p>\n\n<pre><code>^/users/[\\w-]+/bookmarks/(.+)/$\n^/users/[\\w-]+/bookmarks/$\n^/users/[\\w-]+/$\n</code></pre>\n\n<p>Pros: Nice and simple, lets me define routes directly\nCons: Would have to be ordered, not making it easy to add new things in (very error prone)</p>\n\n<p>This is, afaik, how Django does it</p>\n" }, { "answer_id": 126340, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": -1, "selected": false, "text": "<p>Try taking look at <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"nofollow noreferrer\">MVC</a> pattern.<br />\nZend Framework uses it for example, but also CakePHP, CodeIgniter, ...</p>\n\n<p>Me personally don't like the MVC model, but it's most of the time implemented as \"View for web\" component.</p>\n\n<p>The decision pretty much depends on preference...</p>\n" }, { "answer_id": 126685, "author": "Unlabeled Meat", "author_id": 20291, "author_profile": "https://Stackoverflow.com/users/20291", "pm_score": 0, "selected": false, "text": "<p>I think a lot of frameworks use a combination of Apache's mod_rewrite and a front controller. With mod_rewrite, you can turn a URL like this: /people/get/3 into this:\nindex.php?controller=people&amp;method=get&amp;id=3. Index.php would implement your front controller which routes the page request based on the parameters given. </p>\n" }, { "answer_id": 127196, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": -1, "selected": false, "text": "<p>Zend's MVC framework by default uses a structure like</p>\n\n<pre><code>/router/controller/action/key1/value1/key2/value2\n</code></pre>\n\n<p>where <code>router</code> is the router file (mapped via <code>mod_rewrite</code>, <code>controller</code> is from a controller action handler which is defined by a class that derives from <code>Zend_Controller_Action</code> and <code>action</code> references a method in the controller, named <code>actionAction</code>. The key/value pairs can go in any order and are available to the action method as an associative array.</p>\n\n<p>I've used something similar in the past in my own code, and so far it's worked fairly well.</p>\n" }, { "answer_id": 128619, "author": "gradbot", "author_id": 17919, "author_profile": "https://Stackoverflow.com/users/17919", "pm_score": 5, "selected": true, "text": "<p>I prefer to use reg ex over making my own format since it is common knowledge. I wrote a small class that I use which allows me to nest these reg ex routing tables. I use to use something similar that was implemented by inheritance but it didn't need inheritance so I rewrote it.</p>\n\n<p>I do a reg ex on a key and map to my own control string. Take the below example. I visit <code>/api/related/joe</code> and my router class creates a new object <code>ApiController</code> and calls it's method <code>relatedDocuments(array('tags' =&gt; 'joe'));</code></p>\n\n<pre><code>// the 12 strips the subdirectory my app is running in\n$index = urldecode(substr($_SERVER[\"REQUEST_URI\"], 12)); \n\nRoute::process($index, array(\n \"#^api/related/(.*)$#Di\" =&gt; \"ApiController/relatedDocuments/tags\",\n\n \"#^thread/(.*)/post$#Di\" =&gt; \"ThreadController/post/title\",\n \"#^thread/(.*)/reply$#Di\" =&gt; \"ThreadController/reply/title\",\n \"#^thread/(.*)$#Di\" =&gt; \"ThreadController/thread/title\",\n\n \"#^ajax/tag/(.*)/(.*)$#Di\" =&gt; \"TagController/add/id/tags\",\n \"#^ajax/reply/(.*)/post$#Di\"=&gt; \"ThreadController/ajaxPost/id\",\n \"#^ajax/reply/(.*)$#Di\" =&gt; \"ArticleController/newReply/id\",\n \"#^ajax/toggle/(.*)$#Di\" =&gt; \"ApiController/toggle/toggle\",\n\n \"#^$#Di\" =&gt; \"HomeController\",\n));\n</code></pre>\n\n<p>In order to keep errors down and simplicity up you can subdivide your table. This way you can put the routing table into the class that it controls. Taking the above example you can combine the three thread calls into a single one.</p>\n\n<pre><code>Route::process($index, array(\n \"#^api/related/(.*)$#Di\" =&gt; \"ApiController/relatedDocuments/tags\",\n\n \"#^thread/(.*)$#Di\" =&gt; \"ThreadController/route/uri\",\n\n \"#^ajax/tag/(.*)/(.*)$#Di\" =&gt; \"TagController/add/id/tags\",\n \"#^ajax/reply/(.*)/post$#Di\"=&gt; \"ThreadController/ajaxPost/id\",\n \"#^ajax/reply/(.*)$#Di\" =&gt; \"ArticleController/newReply/id\",\n \"#^ajax/toggle/(.*)$#Di\" =&gt; \"ApiController/toggle/toggle\",\n\n \"#^$#Di\" =&gt; \"HomeController\",\n));\n</code></pre>\n\n<p>Then you define ThreadController::route to be like this.</p>\n\n<pre><code>function route($args) {\n Route::process($args['uri'], array(\n \"#^(.*)/post$#Di\" =&gt; \"ThreadController/post/title\",\n \"#^(.*)/reply$#Di\" =&gt; \"ThreadController/reply/title\",\n \"#^(.*)$#Di\" =&gt; \"ThreadController/thread/title\",\n ));\n}\n</code></pre>\n\n<p>Also you can define whatever defaults you want for your routing string on the right. Just don't forget to document them or you will confuse people. I'm currently calling index if you don't include a function name on the right. <a href=\"http://pastie.org/278748\" rel=\"nofollow noreferrer\">Here</a> is my current code. You may want to change it to handle errors how you like and or default actions.</p>\n" }, { "answer_id": 758029, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Yet another framework? -- anyway...</p>\n\n<p>The trick is with routing is to pass it all over to your routing controller.</p>\n\n<p>You'd probably want to use something similar to what I've documented here:</p>\n\n<p><a href=\"http://www.hm2k.com/posts/friendly-urls\" rel=\"nofollow noreferrer\">http://www.hm2k.com/posts/friendly-urls</a></p>\n\n<p>The second solution allows you to use URLs similar to Zend Framework.</p>\n" }, { "answer_id": 11280912, "author": "Gindi Bar Yahav", "author_id": 568867, "author_profile": "https://Stackoverflow.com/users/568867", "pm_score": 0, "selected": false, "text": "<p>As you might expect, there are a lot of ways to do it.</p>\n\n<p>For example, in <a href=\"http://www.slimframework.com/\" rel=\"nofollow\">Slim Framework</a> , an example of the routing engine may be the folllowing (based on the pattern <code>${OBJECT}-&gt;${REQUEST METHOD}(${PATTERM}, ${CALLBACK})</code> ):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$app-&gt;get(\"/Home\", function() {\n print('Welcome to the home page');\n}\n\n$app-&gt;get('/Profile/:memberName', function($memberName) {\n print( 'I\\'m viewing ' . $memberName . '\\'s profile.' );\n}\n\n$app-&gt;post('/ContactUs', function() {\n print( 'This action will be fired only if a POST request will occure');\n}\n</code></pre>\n\n<p>So, the initialized instance (<code>$app</code>) gets a method per request method (e.g. get, post, put, delete etc.) and gets a route as the first parameter and callback as the second. </p>\n\n<p>The route can get tokens - which is \"variable\" that will change at runtime based on some data (such as member name, article id, organization location name or whatever - you know, just like in every routing controller).</p>\n\n<p>Personally, I do like this way but I don't think it will be flexible enough for an advanced framework.</p>\n\n<p>Since I'm working currently with ZF and Yii, I do have an example of a router I've created as part of a framework to a company I'm working for:</p>\n\n<p>The route engine is based on regex (similar to @gradbot's one) but got a two-way conversation, so if a client of yours can't run mod_rewrite (in Apache) or add rewrite rules on his or her server, he or she can still use the traditional URLs with query string.</p>\n\n<p>The file contains an array, each of it, each item is similar to this example:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$_FURLTEMPLATES['login'] = array(\n 'i' =&gt; array( // Input - how the router parse an incomming path into query string params\n 'pattern' =&gt; '@Members/Login/?@i',\n 'matches' =&gt; array( 'Application' =&gt; 'Members', 'Module' =&gt; 'Login' ),\n ),\n 'o' =&gt; array( // Output - how the router parse a query string into a route\n '@Application=Members(&amp;|&amp;amp;)Module=Login/?@' =&gt; 'Members/Login/'\n )\n);\n</code></pre>\n\n<p>You can also use more complex combinations, such as:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$_FURLTEMPLATES['article'] = array(\n 'i' =&gt; array(\n 'pattern' =&gt; '@CMS/Articles/([\\d]+)/?@i',\n 'matches' =&gt; array( 'Application' =&gt; \"CMS\",\n 'Module' =&gt; 'Articles',\n 'Sector' =&gt; 'showArticle',\n 'ArticleID' =&gt; '$1' ),\n ),\n 'o' =&gt; array(\n '@Application=CMS(&amp;|&amp;amp;)Module=Articles(&amp;|&amp;amp;)Sector=showArticle(&amp;|&amp;amp;)ArticleID=([\\d]+)@' =&gt; 'CMS/Articles/$4'\n )\n);\n</code></pre>\n\n<p>The bottom line, as I think, is that the possibilities are endless, it just depend on how complex you wish your framework to be and what you wish to do with it. </p>\n\n<p>If it is, for example, just intended to be a web service or simple website wrapper - just go with Slim framework's style of writing - very easy and good-looking code. </p>\n\n<p>However, if you wish to develop complex sites using it, I think regex is the solution. </p>\n\n<p>Good luck! :)</p>\n" }, { "answer_id": 21405881, "author": "c9s", "author_id": 780629, "author_profile": "https://Stackoverflow.com/users/780629", "pm_score": 0, "selected": false, "text": "<p>You should check out Pux <a href=\"https://github.com/c9s/Pux\" rel=\"nofollow\">https://github.com/c9s/Pux</a></p>\n\n<p>Here is the synopsis</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\nrequire 'vendor/autoload.php'; // use PCRE patterns you need Pux\\PatternCompiler class.\nuse Pux\\Executor;\n\nclass ProductController {\n public function listAction() {\n return 'product list';\n }\n public function itemAction($id) { \n return \"product $id\";\n }\n}\n$mux = new Pux\\Mux;\n$mux-&gt;any('/product', ['ProductController','listAction']);\n$mux-&gt;get('/product/:id', ['ProductController','itemAction'] , [\n 'require' =&gt; [ 'id' =&gt; '\\d+', ],\n 'default' =&gt; [ 'id' =&gt; '1', ]\n]);\n$mux-&gt;post('/product/:id', ['ProductController','updateAction'] , [\n 'require' =&gt; [ 'id' =&gt; '\\d+', ],\n 'default' =&gt; [ 'id' =&gt; '1', ]\n]);\n$mux-&gt;delete('/product/:id', ['ProductController','deleteAction'] , [\n 'require' =&gt; [ 'id' =&gt; '\\d+', ],\n 'default' =&gt; [ 'id' =&gt; '1', ]\n]);\n$route = $mux-&gt;dispatch('/product/1');\nExecutor::execute($route);\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20010/" ]
So I'm writing a framework on which I want to base a few apps that I'm working on (the framework is there so I have an environment to work with, and a system that will let me, for example, use a single sign-on) I want to make this framework, and the apps it has use a Resource Oriented Architecture. Now, I want to create a URL routing class that is expandable by APP writers (and possibly also by CMS App users, but that's WAYYYY ahead in the future) and I'm trying to figure out the best way to do it by looking at how other apps do it.
I prefer to use reg ex over making my own format since it is common knowledge. I wrote a small class that I use which allows me to nest these reg ex routing tables. I use to use something similar that was implemented by inheritance but it didn't need inheritance so I rewrote it. I do a reg ex on a key and map to my own control string. Take the below example. I visit `/api/related/joe` and my router class creates a new object `ApiController` and calls it's method `relatedDocuments(array('tags' => 'joe'));` ``` // the 12 strips the subdirectory my app is running in $index = urldecode(substr($_SERVER["REQUEST_URI"], 12)); Route::process($index, array( "#^api/related/(.*)$#Di" => "ApiController/relatedDocuments/tags", "#^thread/(.*)/post$#Di" => "ThreadController/post/title", "#^thread/(.*)/reply$#Di" => "ThreadController/reply/title", "#^thread/(.*)$#Di" => "ThreadController/thread/title", "#^ajax/tag/(.*)/(.*)$#Di" => "TagController/add/id/tags", "#^ajax/reply/(.*)/post$#Di"=> "ThreadController/ajaxPost/id", "#^ajax/reply/(.*)$#Di" => "ArticleController/newReply/id", "#^ajax/toggle/(.*)$#Di" => "ApiController/toggle/toggle", "#^$#Di" => "HomeController", )); ``` In order to keep errors down and simplicity up you can subdivide your table. This way you can put the routing table into the class that it controls. Taking the above example you can combine the three thread calls into a single one. ``` Route::process($index, array( "#^api/related/(.*)$#Di" => "ApiController/relatedDocuments/tags", "#^thread/(.*)$#Di" => "ThreadController/route/uri", "#^ajax/tag/(.*)/(.*)$#Di" => "TagController/add/id/tags", "#^ajax/reply/(.*)/post$#Di"=> "ThreadController/ajaxPost/id", "#^ajax/reply/(.*)$#Di" => "ArticleController/newReply/id", "#^ajax/toggle/(.*)$#Di" => "ApiController/toggle/toggle", "#^$#Di" => "HomeController", )); ``` Then you define ThreadController::route to be like this. ``` function route($args) { Route::process($args['uri'], array( "#^(.*)/post$#Di" => "ThreadController/post/title", "#^(.*)/reply$#Di" => "ThreadController/reply/title", "#^(.*)$#Di" => "ThreadController/thread/title", )); } ``` Also you can define whatever defaults you want for your routing string on the right. Just don't forget to document them or you will confuse people. I'm currently calling index if you don't include a function name on the right. [Here](http://pastie.org/278748) is my current code. You may want to change it to handle errors how you like and or default actions.
125,703
<p>I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?</p>
[ { "answer_id": 125713, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 7, "selected": false, "text": "<p>Depends on what you want to do. To append you can open it with \"a\":</p>\n\n<pre><code> with open(\"foo.txt\", \"a\") as f:\n f.write(\"new line\\n\")\n</code></pre>\n\n<p>If you want to preprend something you have to read from the file first:</p>\n\n<pre><code>with open(\"foo.txt\", \"r+\") as f:\n old = f.read() # read everything in the file\n f.seek(0) # rewind\n f.write(\"new line\\n\" + old) # write the new line before\n</code></pre>\n" }, { "answer_id": 125759, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 7, "selected": false, "text": "<p>Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it.</p>\n\n<p>This is an operating system thing, not a Python thing. It is the same in all languages.</p>\n\n<p>What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file.</p>\n\n<p>This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file.</p>\n" }, { "answer_id": 126389, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": false, "text": "<p>Rewriting a file in place is often done by saving the old copy with a modified name. Unix folks add a <code>~</code> to mark the old one. Windows folks do all kinds of things -- add .bak or .old -- or rename the file entirely or put the ~ on the front of the name.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import shutil\nshutil.move(afile, afile + &quot;~&quot;)\n\ndestination= open(aFile, &quot;w&quot;)\nsource= open(aFile + &quot;~&quot;, &quot;r&quot;)\nfor line in source:\n destination.write(line)\n if &lt;some condition&gt;:\n destination.write(&lt;some additional line&gt; + &quot;\\n&quot;)\n\nsource.close()\ndestination.close()\n</code></pre>\n<p>Instead of <code>shutil</code>, you can use the following.</p>\n<pre><code>import os\nos.rename(aFile, aFile + &quot;~&quot;)\n</code></pre>\n" }, { "answer_id": 130844, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 4, "selected": false, "text": "<p>Python's mmap module will allow you to insert into a file. The following sample shows how it can be done in Unix (Windows mmap may be different). Note that this does not handle all error conditions and you might corrupt or lose the original file. Also, this won't handle unicode strings.</p>\n\n<pre><code>import os\nfrom mmap import mmap\n\ndef insert(filename, str, pos):\n if len(str) &lt; 1:\n # nothing to insert\n return\n\n f = open(filename, 'r+')\n m = mmap(f.fileno(), os.path.getsize(filename))\n origSize = m.size()\n\n # or this could be an error\n if pos &gt; origSize:\n pos = origSize\n elif pos &lt; 0:\n pos = 0\n\n m.resize(origSize + len(str))\n m[pos+len(str):] = m[pos:origSize]\n m[pos:pos+len(str)] = str\n m.close()\n f.close()\n</code></pre>\n\n<p>It is also possible to do this without mmap with files opened in 'r+' mode, but it is less convenient and less efficient as you'd have to read and temporarily store the contents of the file from the insertion position to EOF - which might be huge.</p>\n" }, { "answer_id": 1811866, "author": "Dave", "author_id": 220371, "author_profile": "https://Stackoverflow.com/users/220371", "pm_score": 6, "selected": false, "text": "<p>The <a href=\"https://docs.python.org/2/library/fileinput.html\" rel=\"noreferrer\"><strong><code>fileinput</code></strong></a> module of the Python standard library will rewrite a file inplace if you use the inplace=1 parameter:</p>\n\n<pre><code>import sys\nimport fileinput\n\n# replace all occurrences of 'sit' with 'SIT' and insert a line after the 5th\nfor i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)):\n sys.stdout.write(line.replace('sit', 'SIT')) # replace 'sit' and write\n if i == 4: sys.stdout.write('\\n') # write a blank line after the 5th line\n</code></pre>\n" }, { "answer_id": 13464228, "author": "Maxime R.", "author_id": 1792823, "author_profile": "https://Stackoverflow.com/users/1792823", "pm_score": 4, "selected": false, "text": "<p>As mentioned by Adam you have to take your system limitations into consideration before you can decide on approach whether you have enough memory to read it all into memory replace parts of it and re-write it. </p>\n\n<p>If you're dealing with a small file or have no memory issues this might help:</p>\n\n<p><strong>Option 1)</strong>\nRead entire file into memory, do a regex substitution on the entire or part of the line and replace it with that line plus the extra line. You will need to make sure that the 'middle line' is unique in the file or if you have timestamps on each line this should be pretty reliable.</p>\n\n<pre><code># open file with r+b (allow write and binary mode)\nf = open(\"file.log\", 'r+b') \n# read entire content of file into memory\nf_content = f.read()\n# basically match middle line and replace it with itself and the extra line\nf_content = re.sub(r'(middle line)', r'\\1\\nnew line', f_content)\n# return pointer to top of file so we can re-write the content with replaced string\nf.seek(0)\n# clear file content \nf.truncate()\n# re-write the content with the updated content\nf.write(f_content)\n# close file\nf.close()\n</code></pre>\n\n<p><strong>Option 2)</strong>\nFigure out middle line, and replace it with that line plus the extra line. </p>\n\n<pre><code># open file with r+b (allow write and binary mode)\nf = open(\"file.log\" , 'r+b') \n# get array of lines\nf_content = f.readlines()\n# get middle line\nmiddle_line = len(f_content)/2\n# overwrite middle line\nf_content[middle_line] += \"\\nnew line\"\n# return pointer to top of file so we can re-write the content with replaced string\nf.seek(0)\n# clear file content \nf.truncate()\n# re-write the content with the updated content\nf.write(''.join(f_content))\n# close file\nf.close()\n</code></pre>\n" }, { "answer_id": 35149780, "author": "ananth krishnan", "author_id": 5871801, "author_profile": "https://Stackoverflow.com/users/5871801", "pm_score": 1, "selected": false, "text": "<p>Wrote a small class for doing this cleanly.</p>\n\n<pre><code>import tempfile\n\nclass FileModifierError(Exception):\n pass\n\nclass FileModifier(object):\n\n def __init__(self, fname):\n self.__write_dict = {}\n self.__filename = fname\n self.__tempfile = tempfile.TemporaryFile()\n with open(fname, 'rb') as fp:\n for line in fp:\n self.__tempfile.write(line)\n self.__tempfile.seek(0)\n\n def write(self, s, line_number = 'END'):\n if line_number != 'END' and not isinstance(line_number, (int, float)):\n raise FileModifierError(\"Line number %s is not a valid number\" % line_number)\n try:\n self.__write_dict[line_number].append(s)\n except KeyError:\n self.__write_dict[line_number] = [s]\n\n def writeline(self, s, line_number = 'END'):\n self.write('%s\\n' % s, line_number)\n\n def writelines(self, s, line_number = 'END'):\n for ln in s:\n self.writeline(s, line_number)\n\n def __popline(self, index, fp):\n try:\n ilines = self.__write_dict.pop(index)\n for line in ilines:\n fp.write(line)\n except KeyError:\n pass\n\n def close(self):\n self.__exit__(None, None, None)\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n with open(self.__filename,'w') as fp:\n for index, line in enumerate(self.__tempfile.readlines()):\n self.__popline(index, fp)\n fp.write(line)\n for index in sorted(self.__write_dict):\n for line in self.__write_dict[index]:\n fp.write(line)\n self.__tempfile.close()\n</code></pre>\n\n<p>Then you can use it this way:</p>\n\n<pre><code>with FileModifier(filename) as fp:\n fp.writeline(\"String 1\", 0)\n fp.writeline(\"String 2\", 20)\n fp.writeline(\"String 3\") # To write at the end of the file\n</code></pre>\n" }, { "answer_id": 53124215, "author": "G. LC", "author_id": 9877204, "author_profile": "https://Stackoverflow.com/users/9877204", "pm_score": -1, "selected": false, "text": "<p>If you know some unix you could try the following:</p>\n\n<p>Notes: $ means the command prompt </p>\n\n<p>Say you have a file my_data.txt with content as such:</p>\n\n<pre><code>$ cat my_data.txt\nThis is a data file\nwith all of my data in it.\n</code></pre>\n\n<p>Then using the <code>os</code> module you can use the usual <code>sed</code> commands</p>\n\n<pre><code>import os\n\n# Identifiers used are:\nmy_data_file = \"my_data.txt\"\ncommand = \"sed -i 's/all/none/' my_data.txt\"\n\n# Execute the command\nos.system(command)\n</code></pre>\n\n<p>If you aren't aware of sed, check it out, it is extremely useful. </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
Depends on what you want to do. To append you can open it with "a": ``` with open("foo.txt", "a") as f: f.write("new line\n") ``` If you want to preprend something you have to read from the file first: ``` with open("foo.txt", "r+") as f: old = f.read() # read everything in the file f.seek(0) # rewind f.write("new line\n" + old) # write the new line before ```
125,730
<p>Why do I get following error when trying to start a ruby on rails application with <pre>mongrel_rails start</pre>?</p> <pre> C:\RailsTest\cookbook2>mongrel_rails start ** WARNING: Win32 does not support daemon mode. ** Daemonized, any open files are closed. Look at log/mongrel.pid and log/mongr el.log for info. ** Starting Mongrel listening at 0.0.0.0:3000 c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../lib/mongrel/t cphack.rb:12:in `initialize_without_backlog': Only one usage of each socket addr ess (protocol/network address/port) is normally permitted. - bind(2) (Errno::EAD DRINUSE) from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/tcphack.rb:12:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel.rb:93:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel.rb:93:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:139:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:139:in `listener' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:99:in `cloaker_' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:50:in `call' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:50:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:84:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:84:in `run' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/command.rb:212:in `run' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:281 from c:/ruby/bin/mongrel_rails:19:in `load' from c:/ruby/bin/mongrel_rails:19 </pre>
[ { "answer_id": 125748, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "<p>I don't use mongrel on windows myself, but I guess that error is the equivalent of Linux' \"port in use\" error. Are you trying to bind the server to a port where something else is already listening?</p>\n" }, { "answer_id": 126769, "author": "Dave Nolan", "author_id": 9474, "author_profile": "https://Stackoverflow.com/users/9474", "pm_score": 3, "selected": true, "text": "<p>You already have a process listening on port 3000 (the default port for mongrel).</p>\n\n<p>Try:</p>\n\n<pre><code>mongrel_rails start -p 3001\n</code></pre>\n\n<p>and see whether you get a similar error.</p>\n\n<p>If you're trying to install more than one Rails app, you need to assign each mongrel to a separate port and edit you apache conf accordingly.</p>\n\n<p>If you not trying to do that, the most direct way of killing all mongrels is to open windows task manager and kill all the 'ruby' processes.</p>\n\n<p>Note that if you have mongrel installed as a service that starts automatically</p>\n\n<pre><code>mongrel_rails install::service ...\n</code></pre>\n\n<p>...the ruby process will regenerate automatically. In that case, you'll have to edit the process properties through the windows services panel. Let me know if you need more info.</p>\n" }, { "answer_id": 1301901, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>On Windows, I found two possible ways for fixing this issue:</p>\n\n<ol>\n<li>Work around: Start the mongrel web server in another port</li>\n<li>Solution: Find the ruby.exe process in your task manager and finish it</li>\n</ol>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14027/" ]
Why do I get following error when trying to start a ruby on rails application with ``` mongrel_rails start ``` ? ``` C:\RailsTest\cookbook2>mongrel_rails start ** WARNING: Win32 does not support daemon mode. ** Daemonized, any open files are closed. Look at log/mongrel.pid and log/mongr el.log for info. ** Starting Mongrel listening at 0.0.0.0:3000 c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../lib/mongrel/t cphack.rb:12:in `initialize_without_backlog': Only one usage of each socket addr ess (protocol/network address/port) is normally permitted. - bind(2) (Errno::EAD DRINUSE) from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/tcphack.rb:12:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel.rb:93:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel.rb:93:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:139:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:139:in `listener' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:99:in `cloaker_' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:50:in `call' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:50:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:84:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:84:in `run' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/command.rb:212:in `run' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:281 from c:/ruby/bin/mongrel_rails:19:in `load' from c:/ruby/bin/mongrel_rails:19 ```
You already have a process listening on port 3000 (the default port for mongrel). Try: ``` mongrel_rails start -p 3001 ``` and see whether you get a similar error. If you're trying to install more than one Rails app, you need to assign each mongrel to a separate port and edit you apache conf accordingly. If you not trying to do that, the most direct way of killing all mongrels is to open windows task manager and kill all the 'ruby' processes. Note that if you have mongrel installed as a service that starts automatically ``` mongrel_rails install::service ... ``` ...the ruby process will regenerate automatically. In that case, you'll have to edit the process properties through the windows services panel. Let me know if you need more info.
125,735
<p>I'm using the following code for setting/getting deleting cookies:</p> <pre><code>function get_cookie(cookie_name) { var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)'); if (results) return ( decodeURI(results[2]) ); else return null; } function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure) { var cookie_string = name + "=" + encodeURI(value); if (exp_y) { var expires = new Date(exp_y, exp_m, exp_d); cookie_string += "; expires=" + expires.toGMTString(); } if (path) cookie_string += "; path=" + encodeURI(path); if (domain) cookie_string += "; domain=" + encodeURI(domain); if (secure) cookie_string += "; secure"; document.cookie = cookie_string; } function delete_cookie(cookie_name) { var cookie_date = new Date(); // current date &amp; time cookie_date.setTime(cookie_date.getTime() - 1); document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString(); } </code></pre> <p>but i am getting inconsistent results. for example, a cookie set on the startpage (www.example.com/start) , will not always show up on a subsequent page (www.example.com/foo/thing.jsp). i am setting a cookie "onUnload" of the page using </p> <pre><code>set_cookie("beginrequest", (new Date()).getTime(), null, null, null, "/"); </code></pre> <p>and retrieving + deleting it "onLoad" via </p> <pre><code>loadDur = (new Date()).getTime() - get_cookie("beginrequest"); delete_cookie("beginrequest"); </code></pre> <p>to measure the total amount of time the page took to load.</p> <p>when using firebug, i often see "leftover" beginrequest-cookies and multiple instances of beginrequest with past timestamps.</p> <p>how can i achieve to see just one beginrequest-cookie on every page?</p>
[ { "answer_id": 126115, "author": "amix", "author_id": 20081, "author_profile": "https://Stackoverflow.com/users/20081", "pm_score": 0, "selected": false, "text": "<p>Your code for set_cookie, get_cookie and delete_cookie seems to be correct. And your usage as well.</p>\n\n<p>I think you should move this into your Java code - for me it seems an easier option than to hack this via cookies.</p>\n" }, { "answer_id": 126265, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 1, "selected": false, "text": "<p>If you're getting old cookies that might be because your page contains a lot of content and onload isn't called before onunload (because the page doesn't finish loading). So delete the cookie by calling something like this from both onload and onunload:</p>\n\n<pre><code>var deleted_cookie = false;\nfunction delete_timestamp() {\n if(!deleted_cookie) delete_cookie(\"beginrequest\");\n deleted_cookie = true;\n}\n</code></pre>\n\n<p>You might also have a race condition if you're loading the next page quick enough that the 'delete_cookie' cookie hasn't expired properly, and your get_cookie implementation is picking that up. So try changing the regular expression in get_cookie to only pick up cookies with a value:</p>\n\n<pre><code>var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]+)(;|$)');\n</code></pre>\n\n<p>Also, if you're viewing the site in more than one window (or tab), their cookies can get mixed up, so don't do that. But try using a global regular expression to pick up all the values, and only using the latest one.</p>\n" }, { "answer_id": 181400, "author": "joh6nn", "author_id": 21837, "author_profile": "https://Stackoverflow.com/users/21837", "pm_score": 0, "selected": false, "text": "<p>i agree with amix on both counts: your code looks ok at first glance, and this would probably be better handled by something on the server side.</p>\n\n<p>regardless, at a guess, i'd say the issue you're running into at the moment is likely that the events aren't firing the way that you think they are. two ways you can clear up what's happening, are by making it visually obvious that the event is firing , and by increasing the verbosity of your output. any number of things could be interfering with the events actually firing: plugins, addons, keypresses, etc. if you open a new window (or an alert, or whatever) when the onload and onunload events fire, you'll be able to tell for certain that the functions are being called. likewise, if you store more data in the cookies, like originating URL, etc, you'll be able to better figure out which pages are generating the extra cookies.</p>\n\n<p>i'd guess that one of your Firefox extensions is intermittently interfering with the onunload event.</p>\n" }, { "answer_id": 204337, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 1, "selected": false, "text": "<p>Echoing the other's suggestion to do some of the work on the server side - I've done this in the past:</p>\n\n<p>1) Capture the time of request on the server side, and include a script tag with the time variable in the page:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt; var start = 1224068624230;&lt;/script&gt;\n</code></pre>\n\n<p>2) At the end of the page, in JavaScript, get a new time and calculate the total time.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16542/" ]
I'm using the following code for setting/getting deleting cookies: ``` function get_cookie(cookie_name) { var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)'); if (results) return ( decodeURI(results[2]) ); else return null; } function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure) { var cookie_string = name + "=" + encodeURI(value); if (exp_y) { var expires = new Date(exp_y, exp_m, exp_d); cookie_string += "; expires=" + expires.toGMTString(); } if (path) cookie_string += "; path=" + encodeURI(path); if (domain) cookie_string += "; domain=" + encodeURI(domain); if (secure) cookie_string += "; secure"; document.cookie = cookie_string; } function delete_cookie(cookie_name) { var cookie_date = new Date(); // current date & time cookie_date.setTime(cookie_date.getTime() - 1); document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString(); } ``` but i am getting inconsistent results. for example, a cookie set on the startpage (www.example.com/start) , will not always show up on a subsequent page (www.example.com/foo/thing.jsp). i am setting a cookie "onUnload" of the page using ``` set_cookie("beginrequest", (new Date()).getTime(), null, null, null, "/"); ``` and retrieving + deleting it "onLoad" via ``` loadDur = (new Date()).getTime() - get_cookie("beginrequest"); delete_cookie("beginrequest"); ``` to measure the total amount of time the page took to load. when using firebug, i often see "leftover" beginrequest-cookies and multiple instances of beginrequest with past timestamps. how can i achieve to see just one beginrequest-cookie on every page?
If you're getting old cookies that might be because your page contains a lot of content and onload isn't called before onunload (because the page doesn't finish loading). So delete the cookie by calling something like this from both onload and onunload: ``` var deleted_cookie = false; function delete_timestamp() { if(!deleted_cookie) delete_cookie("beginrequest"); deleted_cookie = true; } ``` You might also have a race condition if you're loading the next page quick enough that the 'delete\_cookie' cookie hasn't expired properly, and your get\_cookie implementation is picking that up. So try changing the regular expression in get\_cookie to only pick up cookies with a value: ``` var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]+)(;|$)'); ``` Also, if you're viewing the site in more than one window (or tab), their cookies can get mixed up, so don't do that. But try using a global regular expression to pick up all the values, and only using the latest one.
125,756
<p>I'm looking for a way to set the default language for visitors comming to a site built in EPiServer for the first time. Not just administrators/editors in the backend, people comming to the public site.</p>
[ { "answer_id": 126318, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 3, "selected": true, "text": "<p>Depends on your setup.</p>\n\n<p>If the site languages is to change under different domains you can do this.\nAdd to configuration -> configSections nodes in web.config:</p>\n\n<pre><code>&lt;sectionGroup name=\"episerver\"&gt;\n &lt;section name=\"domainLanguageMappings\" allowDefinition=\"MachineToApplication\" allowLocation=\"false\" type=\"EPiServer.Util.DomainLanguageConfigurationHandler,EPiServer\" /&gt;\n</code></pre>\n\n<p>..and add this to episerver node in web.config:</p>\n\n<pre><code> &lt;domainLanguageMappings&gt;\n &lt;map domain=\"site.com\" language=\"EN\" /&gt;\n &lt;map domain=\"site.se\" language=\"SV\" /&gt;\n &lt;/domainLanguageMappings&gt;\n</code></pre>\n\n<p>Otherwhise you can do something like this.\nAdd to appSettings in web.config:</p>\n\n<pre><code>&lt;add name=\"EPsDefaultLanguageBranch\" key=\"EN\"/&gt;\n</code></pre>\n" }, { "answer_id": 126342, "author": "mannu", "author_id": 15858, "author_profile": "https://Stackoverflow.com/users/15858", "pm_score": 0, "selected": false, "text": "<p>I have this on EPiServer CMS5:</p>\n\n<pre><code>&lt;globalization culture=\"sv-SE\" uiCulture=\"sv\" requestEncoding=\"utf-8\" responseEncoding=\"utf-8\" resourceProviderFactoryType=\"EPiServer.Resources.XmlResourceProviderFactory, EPiServer\" /&gt;\n</code></pre>\n" }, { "answer_id": 559007, "author": "Fredrik Haglund", "author_id": 67593, "author_profile": "https://Stackoverflow.com/users/67593", "pm_score": 0, "selected": false, "text": "<p>In EPiServer CMS 5, add the following setting to your web.config:</p>\n\n<pre><code>&lt;site description=\"Example Site\"&gt;\n &lt;siteHosts&gt;\n &lt;add name=\"www.site.se\" language=\"sv\" /&gt;\n &lt;add name=\"www.site.no\" language=\"no\" /&gt;\n &lt;add name=\"www.site.co.uk\" language=\"en-GB\" /&gt;\n &lt;add name=\"*\" /&gt;\n &lt;/siteHosts&gt;\n</code></pre>\n\n<p>The language choosen for the start page is depending on the host header in the request.</p>\n\n<p>If you set attribute <code>pageUseBrowserLanguagePreferences=\"true\"</code> in your siteSettings tag in web.config the browsers request may be used to select language for the startpage.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452521/" ]
I'm looking for a way to set the default language for visitors comming to a site built in EPiServer for the first time. Not just administrators/editors in the backend, people comming to the public site.
Depends on your setup. If the site languages is to change under different domains you can do this. Add to configuration -> configSections nodes in web.config: ``` <sectionGroup name="episerver"> <section name="domainLanguageMappings" allowDefinition="MachineToApplication" allowLocation="false" type="EPiServer.Util.DomainLanguageConfigurationHandler,EPiServer" /> ``` ..and add this to episerver node in web.config: ``` <domainLanguageMappings> <map domain="site.com" language="EN" /> <map domain="site.se" language="SV" /> </domainLanguageMappings> ``` Otherwhise you can do something like this. Add to appSettings in web.config: ``` <add name="EPsDefaultLanguageBranch" key="EN"/> ```
125,785
<p>I need a function written in Excel VBA that will hash passwords using a standard algorithm such as SHA-1. Something with a simple interface like:</p> <pre><code>Public Function CreateHash(Value As String) As String ... End Function </code></pre> <p>The function needs to work on an XP workstation with Excel 2003 installed, but otherwise must use no third party components. It can reference and use DLLs that are available with XP, such as CryptoAPI. </p> <p>Does anyone know of a sample to achieve this hashing functionality?</p>
[ { "answer_id": 482150, "author": "Chris", "author_id": 59198, "author_profile": "https://Stackoverflow.com/users/59198", "pm_score": 6, "selected": false, "text": "<p>Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH(\"test\")'. To use it, make a new module called 'module_sha1' and copy and paste it all in.\nThis is based on some VBA code from <a href=\"http://vb.wikia.com/wiki/SHA-1.bas\" rel=\"noreferrer\">http://vb.wikia.com/wiki/SHA-1.bas</a>, with changes to support passing it a string, and executable from formulas in Excel cells.</p>\n\n<pre><code>' Based on: http://vb.wikia.com/wiki/SHA-1.bas\nOption Explicit\n\nPrivate Type FourBytes\n A As Byte\n B As Byte\n C As Byte\n D As Byte\nEnd Type\nPrivate Type OneLong\n L As Long\nEnd Type\n\nFunction HexDefaultSHA1(Message() As Byte) As String\n Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long\n DefaultSHA1 Message, H1, H2, H3, H4, H5\n HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)\nEnd Function\n\nFunction HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String\n Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long\n xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5\n HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)\nEnd Function\n\nSub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)\n xSHA1 Message, &amp;H5A827999, &amp;H6ED9EBA1, &amp;H8F1BBCDC, &amp;HCA62C1D6, H1, H2, H3, H4, H5\nEnd Sub\n\nSub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)\n 'CA62C1D68F1BBCDC6ED9EBA15A827999 + \"abc\" = \"A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D\"\n '\"abc\" = \"A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D\"\n\n Dim U As Long, P As Long\n Dim FB As FourBytes, OL As OneLong\n Dim i As Integer\n Dim W(80) As Long\n Dim A As Long, B As Long, C As Long, D As Long, E As Long\n Dim T As Long\n\n H1 = &amp;H67452301: H2 = &amp;HEFCDAB89: H3 = &amp;H98BADCFE: H4 = &amp;H10325476: H5 = &amp;HC3D2E1F0\n\n U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \\ &amp;H20000000: LSet FB = OL 'U32ShiftRight29(U)\n\n ReDim Preserve Message(0 To (U + 8 And -64) + 63)\n Message(U) = 128\n\n U = UBound(Message)\n Message(U - 4) = A\n Message(U - 3) = FB.D\n Message(U - 2) = FB.C\n Message(U - 1) = FB.B\n Message(U) = FB.A\n\n While P &lt; U\n For i = 0 To 15\n FB.D = Message(P)\n FB.C = Message(P + 1)\n FB.B = Message(P + 2)\n FB.A = Message(P + 3)\n LSet OL = FB\n W(i) = OL.L\n P = P + 4\n Next i\n\n For i = 16 To 79\n W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))\n Next i\n\n A = H1: B = H2: C = H3: D = H4: E = H5\n\n For i = 0 To 19\n T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))\n E = D: D = C: C = U32RotateLeft30(B): B = A: A = T\n Next i\n For i = 20 To 39\n T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))\n E = D: D = C: C = U32RotateLeft30(B): B = A: A = T\n Next i\n For i = 40 To 59\n T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))\n E = D: D = C: C = U32RotateLeft30(B): B = A: A = T\n Next i\n For i = 60 To 79\n T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))\n E = D: D = C: C = U32RotateLeft30(B): B = A: A = T\n Next i\n\n H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)\n Wend\nEnd Sub\n\nFunction U32Add(ByVal A As Long, ByVal B As Long) As Long\n If (A Xor B) &lt; 0 Then\n U32Add = A + B\n Else\n U32Add = (A Xor &amp;H80000000) + B Xor &amp;H80000000\n End If\nEnd Function\n\nFunction U32ShiftLeft3(ByVal A As Long) As Long\n U32ShiftLeft3 = (A And &amp;HFFFFFFF) * 8\n If A And &amp;H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &amp;H80000000\nEnd Function\n\nFunction U32ShiftRight29(ByVal A As Long) As Long\n U32ShiftRight29 = (A And &amp;HE0000000) \\ &amp;H20000000 And 7\nEnd Function\n\nFunction U32RotateLeft1(ByVal A As Long) As Long\n U32RotateLeft1 = (A And &amp;H3FFFFFFF) * 2\n If A And &amp;H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &amp;H80000000\n If A And &amp;H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1\nEnd Function\nFunction U32RotateLeft5(ByVal A As Long) As Long\n U32RotateLeft5 = (A And &amp;H3FFFFFF) * 32 Or (A And &amp;HF8000000) \\ &amp;H8000000 And 31\n If A And &amp;H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &amp;H80000000\nEnd Function\nFunction U32RotateLeft30(ByVal A As Long) As Long\n U32RotateLeft30 = (A And 1) * &amp;H40000000 Or (A And &amp;HFFFC) \\ 4 And &amp;H3FFFFFFF\n If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &amp;H80000000\nEnd Function\n\nFunction DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String\n Dim H As String, L As Long\n DecToHex5 = \"00000000 00000000 00000000 00000000 00000000\"\n H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H\n H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H\n H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H\n H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H\n H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H\nEnd Function\n\n' Convert the string into bytes so we can use the above functions\n' From Chris Hulbert: http://splinter.com.au/blog\n\nPublic Function SHA1HASH(str)\n Dim i As Integer\n Dim arr() As Byte\n ReDim arr(0 To Len(str) - 1) As Byte\n For i = 0 To Len(str) - 1\n arr(i) = Asc(Mid(str, i + 1, 1))\n Next i\n SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), \" \", \"\")\nEnd Function\n</code></pre>\n" }, { "answer_id": 29271611, "author": "Leiver Espinoza", "author_id": 4715077, "author_profile": "https://Stackoverflow.com/users/4715077", "pm_score": 3, "selected": false, "text": "<p>Here is the MD5 code inserted in an Excel Module with the name \"module_md5\":</p>\n\n<pre><code> Private Const BITS_TO_A_BYTE = 8\n Private Const BYTES_TO_A_WORD = 4\n Private Const BITS_TO_A_WORD = 32\n\n Private m_lOnBits(30)\n Private m_l2Power(30)\n\n Sub SetUpArrays()\n m_lOnBits(0) = CLng(1)\n m_lOnBits(1) = CLng(3)\n m_lOnBits(2) = CLng(7)\n m_lOnBits(3) = CLng(15)\n m_lOnBits(4) = CLng(31)\n m_lOnBits(5) = CLng(63)\n m_lOnBits(6) = CLng(127)\n m_lOnBits(7) = CLng(255)\n m_lOnBits(8) = CLng(511)\n m_lOnBits(9) = CLng(1023)\n m_lOnBits(10) = CLng(2047)\n m_lOnBits(11) = CLng(4095)\n m_lOnBits(12) = CLng(8191)\n m_lOnBits(13) = CLng(16383)\n m_lOnBits(14) = CLng(32767)\n m_lOnBits(15) = CLng(65535)\n m_lOnBits(16) = CLng(131071)\n m_lOnBits(17) = CLng(262143)\n m_lOnBits(18) = CLng(524287)\n m_lOnBits(19) = CLng(1048575)\n m_lOnBits(20) = CLng(2097151)\n m_lOnBits(21) = CLng(4194303)\n m_lOnBits(22) = CLng(8388607)\n m_lOnBits(23) = CLng(16777215)\n m_lOnBits(24) = CLng(33554431)\n m_lOnBits(25) = CLng(67108863)\n m_lOnBits(26) = CLng(134217727)\n m_lOnBits(27) = CLng(268435455)\n m_lOnBits(28) = CLng(536870911)\n m_lOnBits(29) = CLng(1073741823)\n m_lOnBits(30) = CLng(2147483647)\n\n m_l2Power(0) = CLng(1)\n m_l2Power(1) = CLng(2)\n m_l2Power(2) = CLng(4)\n m_l2Power(3) = CLng(8)\n m_l2Power(4) = CLng(16)\n m_l2Power(5) = CLng(32)\n m_l2Power(6) = CLng(64)\n m_l2Power(7) = CLng(128)\n m_l2Power(8) = CLng(256)\n m_l2Power(9) = CLng(512)\n m_l2Power(10) = CLng(1024)\n m_l2Power(11) = CLng(2048)\n m_l2Power(12) = CLng(4096)\n m_l2Power(13) = CLng(8192)\n m_l2Power(14) = CLng(16384)\n m_l2Power(15) = CLng(32768)\n m_l2Power(16) = CLng(65536)\n m_l2Power(17) = CLng(131072)\n m_l2Power(18) = CLng(262144)\n m_l2Power(19) = CLng(524288)\n m_l2Power(20) = CLng(1048576)\n m_l2Power(21) = CLng(2097152)\n m_l2Power(22) = CLng(4194304)\n m_l2Power(23) = CLng(8388608)\n m_l2Power(24) = CLng(16777216)\n m_l2Power(25) = CLng(33554432)\n m_l2Power(26) = CLng(67108864)\n m_l2Power(27) = CLng(134217728)\n m_l2Power(28) = CLng(268435456)\n m_l2Power(29) = CLng(536870912)\n m_l2Power(30) = CLng(1073741824)\n End Sub\n\n Private Function LShift(lValue, iShiftBits)\n If iShiftBits = 0 Then\n LShift = lValue\n Exit Function\n ElseIf iShiftBits = 31 Then\n If lValue And 1 Then\n LShift = &amp;H80000000\n Else\n LShift = 0\n End If\n Exit Function\n ElseIf iShiftBits &lt; 0 Or iShiftBits &gt; 31 Then\n Err.Raise 6\n End If\n\n If (lValue And m_l2Power(31 - iShiftBits)) Then\n LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &amp;H80000000\n Else\n LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))\n End If\n End Function\n\n Private Function RShift(lValue, iShiftBits)\n If iShiftBits = 0 Then\n RShift = lValue\n Exit Function\n ElseIf iShiftBits = 31 Then\n If lValue And &amp;H80000000 Then\n RShift = 1\n Else\n RShift = 0\n End If\n Exit Function\n ElseIf iShiftBits &lt; 0 Or iShiftBits &gt; 31 Then\n Err.Raise 6\n End If\n\n RShift = (lValue And &amp;H7FFFFFFE) \\ m_l2Power(iShiftBits)\n\n If (lValue And &amp;H80000000) Then\n RShift = (RShift Or (&amp;H40000000 \\ m_l2Power(iShiftBits - 1)))\n End If\n End Function\n\n Private Function RotateLeft(lValue, iShiftBits)\n RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))\n End Function\n\n Private Function AddUnsigned(lX, lY)\n Dim lX4\n Dim lY4\n Dim lX8\n Dim lY8\n Dim lResult\n\n lX8 = lX And &amp;H80000000\n lY8 = lY And &amp;H80000000\n lX4 = lX And &amp;H40000000\n lY4 = lY And &amp;H40000000\n\n lResult = (lX And &amp;H3FFFFFFF) + (lY And &amp;H3FFFFFFF)\n\n If lX4 And lY4 Then\n lResult = lResult Xor &amp;H80000000 Xor lX8 Xor lY8\n ElseIf lX4 Or lY4 Then\n If lResult And &amp;H40000000 Then\n lResult = lResult Xor &amp;HC0000000 Xor lX8 Xor lY8\n Else\n lResult = lResult Xor &amp;H40000000 Xor lX8 Xor lY8\n End If\n Else\n lResult = lResult Xor lX8 Xor lY8\n End If\n\n AddUnsigned = lResult\n End Function\n\n Private Function F(x, y, z)\n F = (x And y) Or ((Not x) And z)\n End Function\n\n Private Function G(x, y, z)\n G = (x And z) Or (y And (Not z))\n End Function\n\n Private Function H(x, y, z)\n H = (x Xor y Xor z)\n End Function\n\n Private Function I(x, y, z)\n I = (y Xor (x Or (Not z)))\n End Function\n\n Private Sub FF(a, b, c, d, x, s, ac)\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))\n a = RotateLeft(a, s)\n a = AddUnsigned(a, b)\n End Sub\n\n Private Sub GG(a, b, c, d, x, s, ac)\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))\n a = RotateLeft(a, s)\n a = AddUnsigned(a, b)\n End Sub\n\n Private Sub HH(a, b, c, d, x, s, ac)\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))\n a = RotateLeft(a, s)\n a = AddUnsigned(a, b)\n End Sub\n\n Private Sub II(a, b, c, d, x, s, ac)\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))\n a = RotateLeft(a, s)\n a = AddUnsigned(a, b)\n End Sub\n\n Private Function ConvertToWordArray(sMessage)\n Dim lMessageLength\n Dim lNumberOfWords\n Dim lWordArray()\n Dim lBytePosition\n Dim lByteCount\n Dim lWordCount\n\n Const MODULUS_BITS = 512\n Const CONGRUENT_BITS = 448\n\n lMessageLength = Len(sMessage)\n\n lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \\ BITS_TO_A_BYTE)) \\ (MODULUS_BITS \\ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \\ BITS_TO_A_WORD)\n ReDim lWordArray(lNumberOfWords - 1)\n\n lBytePosition = 0\n lByteCount = 0\n Do Until lByteCount &gt;= lMessageLength\n lWordCount = lByteCount \\ BYTES_TO_A_WORD\n lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE\n lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)\n lByteCount = lByteCount + 1\n Loop\n\n lWordCount = lByteCount \\ BYTES_TO_A_WORD\n lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE\n\n lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&amp;H80, lBytePosition)\n\n lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)\n lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)\n\n ConvertToWordArray = lWordArray\n End Function\n\n Private Function WordToHex(lValue)\n Dim lByte\n Dim lCount\n\n For lCount = 0 To 3\n lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)\n WordToHex = WordToHex &amp; Right(\"0\" &amp; Hex(lByte), 2)\n Next\n End Function\n\n Public Function MD5(sMessage)\n\n module_md5.SetUpArrays\n\n Dim x\n Dim k\n Dim AA\n Dim BB\n Dim CC\n Dim DD\n Dim a\n Dim b\n Dim c\n Dim d\n\n Const S11 = 7\n Const S12 = 12\n Const S13 = 17\n Const S14 = 22\n Const S21 = 5\n Const S22 = 9\n Const S23 = 14\n Const S24 = 20\n Const S31 = 4\n Const S32 = 11\n Const S33 = 16\n Const S34 = 23\n Const S41 = 6\n Const S42 = 10\n Const S43 = 15\n Const S44 = 21\n\n x = ConvertToWordArray(sMessage)\n\n a = &amp;H67452301\n b = &amp;HEFCDAB89\n c = &amp;H98BADCFE\n d = &amp;H10325476\n\n For k = 0 To UBound(x) Step 16\n AA = a\n BB = b\n CC = c\n DD = d\n\n FF a, b, c, d, x(k + 0), S11, &amp;HD76AA478\n FF d, a, b, c, x(k + 1), S12, &amp;HE8C7B756\n FF c, d, a, b, x(k + 2), S13, &amp;H242070DB\n FF b, c, d, a, x(k + 3), S14, &amp;HC1BDCEEE\n FF a, b, c, d, x(k + 4), S11, &amp;HF57C0FAF\n FF d, a, b, c, x(k + 5), S12, &amp;H4787C62A\n FF c, d, a, b, x(k + 6), S13, &amp;HA8304613\n FF b, c, d, a, x(k + 7), S14, &amp;HFD469501\n FF a, b, c, d, x(k + 8), S11, &amp;H698098D8\n FF d, a, b, c, x(k + 9), S12, &amp;H8B44F7AF\n FF c, d, a, b, x(k + 10), S13, &amp;HFFFF5BB1\n FF b, c, d, a, x(k + 11), S14, &amp;H895CD7BE\n FF a, b, c, d, x(k + 12), S11, &amp;H6B901122\n FF d, a, b, c, x(k + 13), S12, &amp;HFD987193\n FF c, d, a, b, x(k + 14), S13, &amp;HA679438E\n FF b, c, d, a, x(k + 15), S14, &amp;H49B40821\n\n GG a, b, c, d, x(k + 1), S21, &amp;HF61E2562\n GG d, a, b, c, x(k + 6), S22, &amp;HC040B340\n GG c, d, a, b, x(k + 11), S23, &amp;H265E5A51\n GG b, c, d, a, x(k + 0), S24, &amp;HE9B6C7AA\n GG a, b, c, d, x(k + 5), S21, &amp;HD62F105D\n GG d, a, b, c, x(k + 10), S22, &amp;H2441453\n GG c, d, a, b, x(k + 15), S23, &amp;HD8A1E681\n GG b, c, d, a, x(k + 4), S24, &amp;HE7D3FBC8\n GG a, b, c, d, x(k + 9), S21, &amp;H21E1CDE6\n GG d, a, b, c, x(k + 14), S22, &amp;HC33707D6\n GG c, d, a, b, x(k + 3), S23, &amp;HF4D50D87\n GG b, c, d, a, x(k + 8), S24, &amp;H455A14ED\n GG a, b, c, d, x(k + 13), S21, &amp;HA9E3E905\n GG d, a, b, c, x(k + 2), S22, &amp;HFCEFA3F8\n GG c, d, a, b, x(k + 7), S23, &amp;H676F02D9\n GG b, c, d, a, x(k + 12), S24, &amp;H8D2A4C8A\n\n HH a, b, c, d, x(k + 5), S31, &amp;HFFFA3942\n HH d, a, b, c, x(k + 8), S32, &amp;H8771F681\n HH c, d, a, b, x(k + 11), S33, &amp;H6D9D6122\n HH b, c, d, a, x(k + 14), S34, &amp;HFDE5380C\n HH a, b, c, d, x(k + 1), S31, &amp;HA4BEEA44\n HH d, a, b, c, x(k + 4), S32, &amp;H4BDECFA9\n HH c, d, a, b, x(k + 7), S33, &amp;HF6BB4B60\n HH b, c, d, a, x(k + 10), S34, &amp;HBEBFBC70\n HH a, b, c, d, x(k + 13), S31, &amp;H289B7EC6\n HH d, a, b, c, x(k + 0), S32, &amp;HEAA127FA\n HH c, d, a, b, x(k + 3), S33, &amp;HD4EF3085\n HH b, c, d, a, x(k + 6), S34, &amp;H4881D05\n HH a, b, c, d, x(k + 9), S31, &amp;HD9D4D039\n HH d, a, b, c, x(k + 12), S32, &amp;HE6DB99E5\n HH c, d, a, b, x(k + 15), S33, &amp;H1FA27CF8\n HH b, c, d, a, x(k + 2), S34, &amp;HC4AC5665\n\n II a, b, c, d, x(k + 0), S41, &amp;HF4292244\n II d, a, b, c, x(k + 7), S42, &amp;H432AFF97\n II c, d, a, b, x(k + 14), S43, &amp;HAB9423A7\n II b, c, d, a, x(k + 5), S44, &amp;HFC93A039\n II a, b, c, d, x(k + 12), S41, &amp;H655B59C3\n II d, a, b, c, x(k + 3), S42, &amp;H8F0CCC92\n II c, d, a, b, x(k + 10), S43, &amp;HFFEFF47D\n II b, c, d, a, x(k + 1), S44, &amp;H85845DD1\n II a, b, c, d, x(k + 8), S41, &amp;H6FA87E4F\n II d, a, b, c, x(k + 15), S42, &amp;HFE2CE6E0\n II c, d, a, b, x(k + 6), S43, &amp;HA3014314\n II b, c, d, a, x(k + 13), S44, &amp;H4E0811A1\n II a, b, c, d, x(k + 4), S41, &amp;HF7537E82\n II d, a, b, c, x(k + 11), S42, &amp;HBD3AF235\n II c, d, a, b, x(k + 2), S43, &amp;H2AD7D2BB\n II b, c, d, a, x(k + 9), S44, &amp;HEB86D391\n\n a = AddUnsigned(a, AA)\n b = AddUnsigned(b, BB)\n c = AddUnsigned(c, CC)\n d = AddUnsigned(d, DD)\n Next\n\n MD5 = LCase(WordToHex(a) &amp; WordToHex(b) &amp; WordToHex(c) &amp; WordToHex(d))\n End Function\n</code></pre>\n" }, { "answer_id": 51087561, "author": "Seva Alekseyev", "author_id": 219159, "author_profile": "https://Stackoverflow.com/users/219159", "pm_score": 4, "selected": false, "text": "<p>These days, you can leverage the .NET library from VBA. The following works for me in Excel 2016. Returns the hash as uppercase hex.</p>\n\n<pre><code>Public Function SHA1(ByVal s As String) As String\n Dim Enc As Object, Prov As Object\n Dim Hash() As Byte, i As Integer\n\n Set Enc = CreateObject(\"System.Text.UTF8Encoding\")\n Set Prov = CreateObject(\"System.Security.Cryptography.SHA1CryptoServiceProvider\")\n\n Hash = Prov.ComputeHash_2(Enc.GetBytes_4(s))\n\n SHA1 = \"\"\n For i = LBound(Hash) To UBound(Hash)\n SHA1 = SHA1 &amp; Hex(Hash(i) \\ 16) &amp; Hex(Hash(i) Mod 16)\n Next\nEnd Function\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13087/" ]
I need a function written in Excel VBA that will hash passwords using a standard algorithm such as SHA-1. Something with a simple interface like: ``` Public Function CreateHash(Value As String) As String ... End Function ``` The function needs to work on an XP workstation with Excel 2003 installed, but otherwise must use no third party components. It can reference and use DLLs that are available with XP, such as CryptoAPI. Does anyone know of a sample to achieve this hashing functionality?
Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module\_sha1' and copy and paste it all in. This is based on some VBA code from <http://vb.wikia.com/wiki/SHA-1.bas>, with changes to support passing it a string, and executable from formulas in Excel cells. ``` ' Based on: http://vb.wikia.com/wiki/SHA-1.bas Option Explicit Private Type FourBytes A As Byte B As Byte C As Byte D As Byte End Type Private Type OneLong L As Long End Type Function HexDefaultSHA1(Message() As Byte) As String Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long DefaultSHA1 Message, H1, H2, H3, H4, H5 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5) End Function Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5) End Function Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long) xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5 End Sub Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long) 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D" '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D" Dim U As Long, P As Long Dim FB As FourBytes, OL As OneLong Dim i As Integer Dim W(80) As Long Dim A As Long, B As Long, C As Long, D As Long, E As Long Dim T As Long H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U) ReDim Preserve Message(0 To (U + 8 And -64) + 63) Message(U) = 128 U = UBound(Message) Message(U - 4) = A Message(U - 3) = FB.D Message(U - 2) = FB.C Message(U - 1) = FB.B Message(U) = FB.A While P < U For i = 0 To 15 FB.D = Message(P) FB.C = Message(P + 1) FB.B = Message(P + 2) FB.A = Message(P + 3) LSet OL = FB W(i) = OL.L P = P + 4 Next i For i = 16 To 79 W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16)) Next i A = H1: B = H2: C = H3: D = H4: E = H5 For i = 0 To 19 T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D))) E = D: D = C: C = U32RotateLeft30(B): B = A: A = T Next i For i = 20 To 39 T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D)) E = D: D = C: C = U32RotateLeft30(B): B = A: A = T Next i For i = 40 To 59 T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D))) E = D: D = C: C = U32RotateLeft30(B): B = A: A = T Next i For i = 60 To 79 T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D)) E = D: D = C: C = U32RotateLeft30(B): B = A: A = T Next i H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E) Wend End Sub Function U32Add(ByVal A As Long, ByVal B As Long) As Long If (A Xor B) < 0 Then U32Add = A + B Else U32Add = (A Xor &H80000000) + B Xor &H80000000 End If End Function Function U32ShiftLeft3(ByVal A As Long) As Long U32ShiftLeft3 = (A And &HFFFFFFF) * 8 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000 End Function Function U32ShiftRight29(ByVal A As Long) As Long U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7 End Function Function U32RotateLeft1(ByVal A As Long) As Long U32RotateLeft1 = (A And &H3FFFFFFF) * 2 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1 End Function Function U32RotateLeft5(ByVal A As Long) As Long U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000 End Function Function U32RotateLeft30(ByVal A As Long) As Long U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000 End Function Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String Dim H As String, L As Long DecToHex5 = "00000000 00000000 00000000 00000000 00000000" H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H End Function ' Convert the string into bytes so we can use the above functions ' From Chris Hulbert: http://splinter.com.au/blog Public Function SHA1HASH(str) Dim i As Integer Dim arr() As Byte ReDim arr(0 To Len(str) - 1) As Byte For i = 0 To Len(str) - 1 arr(i) = Asc(Mid(str, i + 1, 1)) Next i SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "") End Function ```
125,806
<p>First, yes I know about <a href="https://stackoverflow.com/questions/50182/linuxx11-input-library-without-creating-a-window">this question</a>, but I'm looking for a bit more information that that. I have actually, a fairly similar problem, in that I need to be able to capture input for mouse/keyboard/joystick, and I'd also like to avoid SDL if at all possible. I was more or less wondering if anyone knows where I can get some decent primers on handling input from devices in Linux, perhaps even some tutorials. SDL works great for cross-platform input handling, but I'm not going to be using anything else at all from SDL, so I'd like to cut it out altogether. Suggestion, comments, and help are all appreciated. Thanks!</p> <p>Edit for clarity:</p> <p>The point is to capture mouse motion, keyboard press/release, mouse clicks, and potentially joystick handling for a game.</p>
[ { "answer_id": 125830, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 1, "selected": false, "text": "<p>You could start by reading <a href=\"http://tldp.org/LDP/khg/HyperNews/get/devices/devices.html\" rel=\"nofollow noreferrer\">This Tutorial</a> form <a href=\"http://tldp.org/\" rel=\"nofollow noreferrer\">The Linux Documentation Project</a></p>\n" }, { "answer_id": 125863, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 1, "selected": false, "text": "<p>You didn't state the purpose of your application but reading raw data from the input devices is seldom what you want unless you just do it for fun (or school project or whatever)</p>\n\n<p>If you're writing a GUI application (one that runs in an X11 graphical environment) you can rely on the graphical toolkits (or raw X) input drivers. </p>\n\n<p>If you're writing a text-mode client, then maybe <a href=\"http://tiswww.case.edu/php/chet/readline/rltop.html\" rel=\"nofollow noreferrer\">readline</a> or even <a href=\"http://en.wikipedia.org/wiki/Ncurses\" rel=\"nofollow noreferrer\">ncurses</a> could be good alternatives.</p>\n" }, { "answer_id": 125935, "author": "skymt", "author_id": 18370, "author_profile": "https://Stackoverflow.com/users/18370", "pm_score": 2, "selected": false, "text": "<p>If you know your project will only be run under Linux (not Windows or even one of the BSDs), you should look into the Linux kernel's input system. Download the <a href=\"http://kernel.org/pub/linux/kernel/v2.6/linux-2.6.26.5.tar.bz2\" rel=\"nofollow noreferrer\">kernel source</a> and read <code>Documentation/input/input.txt</code>, particularly the description of the <code>evdev</code> system.</p>\n\n<p>For a significantly higher-level (and more portable) solution, <a href=\"http://users.actcom.co.il/~choo/lupg/tutorials/xlib-programming/xlib-programming.html\" rel=\"nofollow noreferrer\">read up on Xlib</a>. Obviously it requires a running X server, but it has the advantage of inheriting the user's keyboard settings. Joystick events are unfortunately not included, you'd probably need to use the kernel joystick API for those.</p>\n" }, { "answer_id": 128327, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 4, "selected": true, "text": "<p>Using the link below look at the function void kGUISystemX::Loop(void)</p>\n\n<p>This is my main loop for getting input via keyboard and mouse using X Windows on Linux.</p>\n\n<p><a href=\"http://code.google.com/p/kgui/source/browse/trunk/kguilinux.cpp\" rel=\"noreferrer\">http://code.google.com/p/kgui/source/browse/trunk/kguilinux.cpp</a></p>\n\n<p>Here is a snippet:</p>\n\n<pre><code> if(XPending(m_display))\n {\n XNextEvent(m_display, &amp;m_e);\n switch(m_e.type)\n {\n case MotionNotify:\n m_mousex=m_e.xmotion.x;\n m_mousey=m_e.xmotion.y;\n break;\n case ButtonPress:\n switch(m_e.xbutton.button)\n {\n case Button1:\n m_mouseleft=true;\n break;\n case Button3:\n m_mouseright=true;\n break;\n case Button4:/* middle mouse wheel moved */\n m_mousewheel=1;\n break;\n case Button5:/* middle mouse wheel moved */\n m_mousewheel=-1;\n break;\n }\n break;\n case ButtonRelease:\n switch(m_e.xbutton.button)\n {\n case Button1:\n m_mouseleft=false;\n break;\n case Button3:\n m_mouseright=false;\n break;\n }\n break;\n case KeyPress:\n {\n XKeyEvent *ke;\n int ks;\n int key;\n\n ke=&amp;m_e.xkey;\n kGUI::SetKeyShift((ke-&gt;state&amp;ShiftMask)!=0);\n kGUI::SetKeyControl((ke-&gt;state&amp;ControlMask)!=0);\n ks=XLookupKeysym(ke,(ke-&gt;state&amp;ShiftMask)?1:0);\n......\n</code></pre>\n" }, { "answer_id": 14016145, "author": "Sal", "author_id": 1766191, "author_profile": "https://Stackoverflow.com/users/1766191", "pm_score": -1, "selected": false, "text": "<p>You can get direct input from the files in /dev/input. This is simplest way to do it, and you don't need any extra software. </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14838/" ]
First, yes I know about [this question](https://stackoverflow.com/questions/50182/linuxx11-input-library-without-creating-a-window), but I'm looking for a bit more information that that. I have actually, a fairly similar problem, in that I need to be able to capture input for mouse/keyboard/joystick, and I'd also like to avoid SDL if at all possible. I was more or less wondering if anyone knows where I can get some decent primers on handling input from devices in Linux, perhaps even some tutorials. SDL works great for cross-platform input handling, but I'm not going to be using anything else at all from SDL, so I'd like to cut it out altogether. Suggestion, comments, and help are all appreciated. Thanks! Edit for clarity: The point is to capture mouse motion, keyboard press/release, mouse clicks, and potentially joystick handling for a game.
Using the link below look at the function void kGUISystemX::Loop(void) This is my main loop for getting input via keyboard and mouse using X Windows on Linux. <http://code.google.com/p/kgui/source/browse/trunk/kguilinux.cpp> Here is a snippet: ``` if(XPending(m_display)) { XNextEvent(m_display, &m_e); switch(m_e.type) { case MotionNotify: m_mousex=m_e.xmotion.x; m_mousey=m_e.xmotion.y; break; case ButtonPress: switch(m_e.xbutton.button) { case Button1: m_mouseleft=true; break; case Button3: m_mouseright=true; break; case Button4:/* middle mouse wheel moved */ m_mousewheel=1; break; case Button5:/* middle mouse wheel moved */ m_mousewheel=-1; break; } break; case ButtonRelease: switch(m_e.xbutton.button) { case Button1: m_mouseleft=false; break; case Button3: m_mouseright=false; break; } break; case KeyPress: { XKeyEvent *ke; int ks; int key; ke=&m_e.xkey; kGUI::SetKeyShift((ke->state&ShiftMask)!=0); kGUI::SetKeyControl((ke->state&ControlMask)!=0); ks=XLookupKeysym(ke,(ke->state&ShiftMask)?1:0); ...... ```
125,828
<p>I'm trying to start an external application through <code>system()</code> - for example, <code>system("ls")</code>. I would like to capture its output as it happens so I can send it to another function for further processing. What's the best way to do that in C/C++?</p>
[ { "answer_id": 125851, "author": "Blank", "author_id": 19521, "author_profile": "https://Stackoverflow.com/users/19521", "pm_score": 0, "selected": false, "text": "<p>I'm not entirely certain that its possible in standard C, as two different processes don't typically share memory space. The simplest way I can think of to do it would be to have the second program redirect its output to a text file (programname > textfile.txt) and then read that text file back in for processing. However, that may not be the best way.</p>\n" }, { "answer_id": 125856, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 3, "selected": false, "text": "<p>EDIT: misread question as wanting to pass output to another program, not another function. popen() is almost certainly what you want.</p>\n\n<p>System gives you full access to the shell. If you want to continue using it, you can\n redirect it's output to a temporary file, by system(\"ls > tempfile.txt\"), but choosing a secure temporary file is a pain. Or, you can even redirect it through another program: system(\"ls | otherprogram\");</p>\n\n<p>Some may recommend the popen() command. This is what you want if you can process the output yourself:</p>\n\n<pre><code>FILE *output = popen(\"ls\", \"r\");\n</code></pre>\n\n<p>which will give you a FILE pointer you can read from with the command's output on it.</p>\n\n<p>You can also use the pipe() call to create a connection in combination with fork() to create new processes, dup2() to change the standard input and output of them, exec() to run the new programs, and wait() in the main program to wait for them. This is just setting up the pipeline much like the shell would. See the pipe() man page for details and an example.</p>\n" }, { "answer_id": 125858, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 1, "selected": false, "text": "<p>In Windows, instead of using system(), use CreateProcess, redirect the output to a pipe and connect to the pipe.</p>\n\n<p>I'm guessing this is also possible in some POSIX way?</p>\n" }, { "answer_id": 125859, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 5, "selected": false, "text": "<p>From the popen manual:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nFILE *popen(const char *command, const char *type);\n\nint pclose(FILE *stream);\n</code></pre>\n" }, { "answer_id": 125866, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Try the popen() function. It executes a command, like system(), but directs the output into a new file. A pointer to the stream is returned.</p>\n\n<pre><code> FILE *lsofFile_p = popen(\"lsof\", \"r\");\n\n if (!lsofFile_p)\n {\n return -1;\n }\n\n char buffer[1024];\n char *line_p = fgets(buffer, sizeof(buffer), lsofFile_p);\n pclose(lsofFile_p);\n</code></pre>\n" }, { "answer_id": 125876, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "<p>The functions <code>popen()</code> and <code>pclose()</code> could be what you're looking for.</p>\n\n<p>Take a look at the <a href=\"http://www.gnu.org/software/libc/manual/html_mono/libc.html#Pipe-to-a-Subprocess\" rel=\"nofollow noreferrer\">glibc manual</a> for an example.</p>\n" }, { "answer_id": 5224650, "author": "Will", "author_id": 15721, "author_profile": "https://Stackoverflow.com/users/15721", "pm_score": 2, "selected": false, "text": "<p>The functions <code>popen()</code> and such don't redirect stderr and such; I wrote <a href=\"http://sites.google.com/site/williamedwardscoder/popen3\" rel=\"nofollow noreferrer\"><code>popen3()</code></a> for that purpose.</p>\n\n<p>Here's a bowdlerised version of my popen3():</p>\n\n<pre><code>int popen3(int fd[3],const char **const cmd) {\n int i, e;\n int p[3][2];\n pid_t pid;\n // set all the FDs to invalid\n for(i=0; i&lt;3; i++)\n p[i][0] = p[i][1] = -1;\n // create the pipes\n for(int i=0; i&lt;3; i++)\n if(pipe(p[i]))\n goto error;\n // and fork\n pid = fork();\n if(-1 == pid)\n goto error;\n // in the parent?\n if(pid) {\n // parent\n fd[STDIN_FILENO] = p[STDIN_FILENO][1];\n close(p[STDIN_FILENO][0]);\n fd[STDOUT_FILENO] = p[STDOUT_FILENO][0];\n close(p[STDOUT_FILENO][1]);\n fd[STDERR_FILENO] = p[STDERR_FILENO][0];\n close(p[STDERR_FILENO][1]);\n // success\n return 0;\n } else {\n // child\n dup2(p[STDIN_FILENO][0],STDIN_FILENO);\n close(p[STDIN_FILENO][1]);\n dup2(p[STDOUT_FILENO][1],STDOUT_FILENO);\n close(p[STDOUT_FILENO][0]);\n dup2(p[STDERR_FILENO][1],STDERR_FILENO);\n close(p[STDERR_FILENO][0]);\n // here we try and run it\n execv(*cmd,const_cast&lt;char*const*&gt;(cmd));\n // if we are there, then we failed to launch our program\n perror(\"Could not launch\");\n fprintf(stderr,\" \\\"%s\\\"\\n\",*cmd);\n _exit(EXIT_FAILURE);\n }\n\n // preserve original error\n e = errno;\n for(i=0; i&lt;3; i++) {\n close(p[i][0]);\n close(p[i][1]);\n }\n errno = e;\n return -1;\n}\n</code></pre>\n" }, { "answer_id": 20686582, "author": "mousomer", "author_id": 281617, "author_profile": "https://Stackoverflow.com/users/281617", "pm_score": 1, "selected": false, "text": "<p>Actually, I just checked, and:</p>\n\n<ol>\n<li><p>popen is problematic, because the process is forked. So if you need to wait for the shell command to execute, then you're in danger of missing it. In my case, my program closed even before the pipe got to do it's work.</p></li>\n<li><p>I ended up using <em>system</em> call with tar command on linux. The return value from <em>system</em> was the result of <em>tar</em>.</p></li>\n</ol>\n\n<p>So: <strong>if you need the return value</strong>, then not no only is there no need to use popen, it probably won't do what you want.</p>\n" }, { "answer_id": 26177496, "author": "nephewtom", "author_id": 316232, "author_profile": "https://Stackoverflow.com/users/316232", "pm_score": 1, "selected": false, "text": "<p>In this page: <a href=\"http://www.microhowto.info/howto/capture_the_output_of_a_child_process_in_c.html#idp146944\" rel=\"nofollow\">capture_the_output_of_a_child_process_in_c</a> describes the limitations of using popen vs. using fork/exec/dup2/STDOUT_FILENO approach.</p>\n\n<p>I'm having problems <a href=\"https://stackoverflow.com/questions/26177333/capturing-tshark-standard-output-with-popen-in-c\">capturing <strong>tshark</strong> output with popen</a>.</p>\n\n<p>And I'm guessing that this limitation might be my problem:</p>\n\n<blockquote>\n <p>It returns a stdio stream as opposed to a raw file descriptor, which\n is unsuitable for handling the output asynchronously.</p>\n</blockquote>\n\n<p>I'll come back to this answer if I have a solution with the other approach.</p>\n" }, { "answer_id": 26178074, "author": "GreenScape", "author_id": 966376, "author_profile": "https://Stackoverflow.com/users/966376", "pm_score": 2, "selected": false, "text": "<p>The most efficient way is to use <code>stdout</code> file descriptor directly, bypassing <code>FILE</code> stream:</p>\n\n<pre><code>pid_t popen2(const char *command, int * infp, int * outfp)\n{\n int p_stdin[2], p_stdout[2];\n pid_t pid;\n\n if (pipe(p_stdin) == -1)\n return -1;\n\n if (pipe(p_stdout) == -1) {\n close(p_stdin[0]);\n close(p_stdin[1]);\n return -1;\n }\n\n pid = fork();\n\n if (pid &lt; 0) {\n close(p_stdin[0]);\n close(p_stdin[1]);\n close(p_stdout[0]);\n close(p_stdout[1]);\n return pid;\n } else if (pid == 0) {\n close(p_stdin[1]);\n dup2(p_stdin[0], 0);\n close(p_stdout[0]);\n dup2(p_stdout[1], 1);\n dup2(::open(\"/dev/null\", O_WRONLY), 2);\n\n /// Close all other descriptors for the safety sake.\n for (int i = 3; i &lt; 4096; ++i) {\n ::close(i);\n }\n\n setsid();\n execl(\"/bin/sh\", \"sh\", \"-c\", command, NULL);\n _exit(1);\n }\n\n close(p_stdin[0]);\n close(p_stdout[1]);\n\n if (infp == NULL) {\n close(p_stdin[1]);\n } else {\n *infp = p_stdin[1];\n }\n\n if (outfp == NULL) {\n close(p_stdout[0]);\n } else {\n *outfp = p_stdout[0];\n }\n\n return pid;\n}\n</code></pre>\n\n<p>To read output from <em>child</em> use <code>popen2()</code> like this:</p>\n\n<pre><code>int child_stdout = -1;\npid_t child_pid = popen2(\"ls\", 0, &amp;child_stdout);\n\nif (!child_pid) {\n handle_error();\n}\n\nchar buff[128];\nssize_t bytes_read = read(child_stdout, buff, sizeof(buff));\n</code></pre>\n\n<p>To both write and read:</p>\n\n<pre><code>int child_stdin = -1;\nint child_stdout = -1;\npid_t child_pid = popen2(\"grep 123\", &amp;child_stdin, &amp;child_stdout);\n\nif (!child_pid) {\n handle_error();\n}\n\nconst char text = \"1\\n2\\n123\\n3\";\nssize_t bytes_written = write(child_stdin, text, sizeof(text) - 1);\n\nchar buff[128];\nssize_t bytes_read = read(child_stdout, buff, sizeof(buff));\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10010/" ]
I'm trying to start an external application through `system()` - for example, `system("ls")`. I would like to capture its output as it happens so I can send it to another function for further processing. What's the best way to do that in C/C++?
From the popen manual: ``` #include <stdio.h> FILE *popen(const char *command, const char *type); int pclose(FILE *stream); ```
125,850
<p>I have this RewriteRule that works too well :-)</p> <pre><code>RewriteRule ^([^/]*)/$ /script.html?id=$1 [L] </code></pre> <p>The bad thing about this rule is that it also matches physical directories which I don't want.</p> <p>How can I tell the <code>mod_rewrite</code> to ignore physical directories and apply the above rule only when the directory matched does not exist?</p>
[ { "answer_id": 125864, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 3, "selected": true, "text": "<p>Take a look at <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond\" rel=\"nofollow noreferrer\">RewriteCond</a>. Put the following before your rule to exempt out directories and files</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_FILENAME} !-f\n</code></pre>\n" }, { "answer_id": 125886, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 0, "selected": false, "text": "<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^([^/]*)/$ /script.html?id=$1 [L]\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have this RewriteRule that works too well :-) ``` RewriteRule ^([^/]*)/$ /script.html?id=$1 [L] ``` The bad thing about this rule is that it also matches physical directories which I don't want. How can I tell the `mod_rewrite` to ignore physical directories and apply the above rule only when the directory matched does not exist?
Take a look at [RewriteCond](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond). Put the following before your rule to exempt out directories and files ``` RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f ```
125,857
<p>Having a problem getting a TreeView control to display node images. The code below works sometimes but fails to show any image at other times.</p> <pre><code> private TreeNode AddNodeForCore(TreeNode root, Core c) { string key = GetImageKey(c); TreeNode t = root.Nodes.Add(c.Name, c.Name, key, key); t.Tag = c; return t; } </code></pre> <p>Note that when it fails, the TreeView fails to show any images for any node. The TreeView does have an ImageList assigned to it, and the image key is definitely in the images collection.</p> <p>Edit:<br> My google-fu is weak. Can't believe I didn't find that answer myself.</p>
[ { "answer_id": 125871, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "<p>A quick google search found this answer: <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?siteid=1&amp;PostID=965968\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/MSDN/ShowPost.aspx?siteid=1&amp;PostID=965968</a></p>\n\n<p><strong>Quote</strong> from that page:</p>\n\n<blockquote>\n <p>If the Form containing the TreeView is instantiated in the add-in startup function as below, the icons appear!</p>\n</blockquote>\n\n<pre><code>public partial class ThisApplication\n{\n Form1 frm;\n\n private void ThisApplication_Startup(object sender, System.EventArgs e)\n {\n frm = new Form1();\n frm.Show();\n\n }\n</code></pre>\n\n<blockquote>\n <p>BUT, if instantiated with the class, as below:</p>\n</blockquote>\n\n<pre><code>public partial class ThisApplication\n{\n Form1 frm = new Form1();\n\n\n private void ThisApplication_Startup(object sender, System.EventArgs e)\n {\n frm.Show();\n\n }\n</code></pre>\n\n<blockquote>\n <p>Then they do NOT appear. Furthermore, if \"VisualStyles\" (new with XP) are disabled, the icons work in both instances.</p>\n</blockquote>\n" }, { "answer_id": 125908, "author": "Matt Jacobsen", "author_id": 15608, "author_profile": "https://Stackoverflow.com/users/15608", "pm_score": 4, "selected": true, "text": "<p>The helpful bit of the googled posts above is in fact:</p>\n\n<p>\"This is a known bug in the Windows XP visual styles implementation. Certain controls, like ImageList, do not get properly initialized when they've been created before the app calls Application.EnableVisualStyles(). The normal Main() implementation in a C#'s Program.cs avoids this. Thanks for posting back!\"</p>\n\n<p>So basically, guarantee that Application.EnableVisualStyles() is called before you initialise your imagelist.</p>\n" }, { "answer_id": 125933, "author": "Johan Buret", "author_id": 15366, "author_profile": "https://Stackoverflow.com/users/15366", "pm_score": 1, "selected": false, "text": "<p>According to [the Add method section](<a href=\"http://msdn.microsoft.com/en-us/library/ydx6whxs(VS.80).aspx)\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ydx6whxs(VS.80).aspx)</a> in MSDN library, you need to fill both <code>TreeView.ImageList</code> and <code>TreeView.SelectedImageList</code> since the fourth arguments refers to the second list.</p>\n\n<p>If this bug happens when you select a node, then look no further.</p>\n" }, { "answer_id": 571214, "author": "Richard Morgan", "author_id": 2258, "author_profile": "https://Stackoverflow.com/users/2258", "pm_score": 0, "selected": false, "text": "<p>The solution posted by Yossarian nor the popular \"Call Application.DoEvents() between Application.EnableVisualStyles() and Application.Run()\" worked for me.</p>\n\n<p>After much flailing, gnashing of teeth, and Googling, the solution posted by <a href=\"http://blogs.msdn.com/asanto/archive/2004/08/18/216825.aspx\" rel=\"nofollow noreferrer\">Addy Santo</a> did the trick.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1389021/" ]
Having a problem getting a TreeView control to display node images. The code below works sometimes but fails to show any image at other times. ``` private TreeNode AddNodeForCore(TreeNode root, Core c) { string key = GetImageKey(c); TreeNode t = root.Nodes.Add(c.Name, c.Name, key, key); t.Tag = c; return t; } ``` Note that when it fails, the TreeView fails to show any images for any node. The TreeView does have an ImageList assigned to it, and the image key is definitely in the images collection. Edit: My google-fu is weak. Can't believe I didn't find that answer myself.
The helpful bit of the googled posts above is in fact: "This is a known bug in the Windows XP visual styles implementation. Certain controls, like ImageList, do not get properly initialized when they've been created before the app calls Application.EnableVisualStyles(). The normal Main() implementation in a C#'s Program.cs avoids this. Thanks for posting back!" So basically, guarantee that Application.EnableVisualStyles() is called before you initialise your imagelist.
125,875
<p>I need to change the credentials of an already existing Windows service using C#. I am aware of two different ways of doing this.</p> <ol> <li>ChangeServiceConfig, see <a href="http://www.pinvoke.net/default.aspx/advapi32.ChangeServiceConfig" rel="nofollow noreferrer">ChangeServiceConfig on pinvoke.net</a></li> <li>ManagementObject.InvokeMethod using Change as the method name.</li> </ol> <p>Neither seems a very "friendly" way of doing this and I was wondering if I am missing another and better way to do this.</p>
[ { "answer_id": 126549, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 3, "selected": false, "text": "<p>Here is one quick and dirty method using the System.Management classes.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Management;\n\nnamespace ServiceTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n string theServiceName = \"My Windows Service\";\n string objectPath = string.Format(\"Win32_Service.Name='{0}'\", theServiceName);\n using (ManagementObject mngService = new ManagementObject(new ManagementPath(objectPath)))\n {\n object[] wmiParameters = new object[11];\n wmiParameters[6] = @\"domain\\username\";\n wmiParameters[7] = \"password\";\n mngService.InvokeMethod(\"Change\", wmiParameters);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 855093, "author": "Adam Ruth", "author_id": 10262, "author_profile": "https://Stackoverflow.com/users/10262", "pm_score": 1, "selected": false, "text": "<p>ChangeServiceConfig is the way that I've done it in the past. WMI can be a bit flaky and I only ever want to use it when I have no other option, especially when going to a remote computer.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19676/" ]
I need to change the credentials of an already existing Windows service using C#. I am aware of two different ways of doing this. 1. ChangeServiceConfig, see [ChangeServiceConfig on pinvoke.net](http://www.pinvoke.net/default.aspx/advapi32.ChangeServiceConfig) 2. ManagementObject.InvokeMethod using Change as the method name. Neither seems a very "friendly" way of doing this and I was wondering if I am missing another and better way to do this.
Here is one quick and dirty method using the System.Management classes. ``` using System; using System.Collections.Generic; using System.Text; using System.Management; namespace ServiceTest { class Program { static void Main(string[] args) { string theServiceName = "My Windows Service"; string objectPath = string.Format("Win32_Service.Name='{0}'", theServiceName); using (ManagementObject mngService = new ManagementObject(new ManagementPath(objectPath))) { object[] wmiParameters = new object[11]; wmiParameters[6] = @"domain\username"; wmiParameters[7] = "password"; mngService.InvokeMethod("Change", wmiParameters); } } } } ```
125,878
<p>I am new to java so excuse my lame questions:)</p> <p>I am trying to build a web service in Java NetBeans 6.1 , but I have some troubles with configuration parameters ( like .settings in .net).</p> <p>What is the right way to save and access such settings in a java web service.</p> <p>Is there a way to read context parameters from web.xml in a web method?</p> <p>If no what are the alternatives for storing your configuration variables like pathnames ?</p> <p>Thank you</p>
[ { "answer_id": 125949, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 2, "selected": false, "text": "<p>If you are using servlets, you can configure parameters in web.xml:</p>\n\n<pre><code>&lt;servlet&gt;\n &lt;servlet-name&gt;jsp&lt;/servlet-name&gt;\n &lt;servlet-class&gt;org.apache.jasper.servlet.JspServlet&lt;/servlet-class&gt;\n &lt;init-param&gt;\n &lt;param-name&gt;fork&lt;/param-name&gt;\n &lt;param-value&gt;false&lt;/param-value&gt;\n &lt;/init-param&gt;\n&lt;/servlet&gt;\n</code></pre>\n\n<p>These properties will be passed in a ServletConfig object to your servlet's \"init\" method.</p>\n\n<p>Another way is to read your system's environment variables with</p>\n\n<pre><code>System.getProperty(String name);\n</code></pre>\n\n<p>But this is not recommended for other than small programs and tests.</p>\n\n<p>There is also the Properties API if you want to use \".properties\" files.\n<a href=\"http://java.sun.com/javase/6/docs/api/java/util/Properties.html\" rel=\"nofollow noreferrer\">http://java.sun.com/javase/6/docs/api/java/util/Properties.html</a></p>\n\n<p>Finally, I believe looking up configurations with JNDI is pretty common when developing modern web service applications, Netbeans and app containers have pretty good support for that. Google it.</p>\n" }, { "answer_id": 127716, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Is there a way to read context parameters from web.xml in a web method?</p>\n</blockquote>\n\n<p>No, this is not easily done using the out-of-the-box. The Web Service system (JAX-WS) has minimal awareness of the Servlet engine (Tomcat). They are designed to be isolated.</p>\n\n<p>If you wanted to use the context parameters, your web service class would need to implement ServletContextListener and retrieve the desired parameters in the initialization parameter (or save the context for later use). Since the Servlet engine and JAX-WS would each have different instances of the object, you'd need to save the values to a static member.</p>\n\n<p>As Lars mentioned, the Properties API or JNDI are your best bets as they're included with Java and are fairly well-known ways to retrieve options. Use Classloader.getResource() to retrieve the Properties in a web context. </p>\n" }, { "answer_id": 7735823, "author": "dosER_42", "author_id": 990812, "author_profile": "https://Stackoverflow.com/users/990812", "pm_score": 1, "selected": false, "text": "<pre><code>MessageContext ctx = MessageContext.getCurrentThreadsContext(); \nServlet wsServlet = (Servlet) ctx.getProperty(HTTPConstants.MC_HTTP_SERVLET); \nServletConfig wsServletConfig = wsServlet.getServletConfig(); \nServletContext wsContext = wsServletConfig.getServletContext(); \n</code></pre>\n" }, { "answer_id": 17209743, "author": "StartupGuy", "author_id": 390722, "author_profile": "https://Stackoverflow.com/users/390722", "pm_score": 0, "selected": false, "text": "<p>I think the correct answer is ... as always ... \"It depends\". If you are just running a small implementation with a single server then it depend much on the WS technology you want to use. Some make the servlet context and the context-params easy to access, others don't, in which case accessing properties from a properties file may be easier. Are you going to have an array of servers in a load balanced environment with high traffic where updating the setting for all servers must be instant and centralized in-case of fail-over? If that's the case then do you really want to update the config files for all servers in the farm? How do you synchronize those changes to all those servers? Does it matter to you? If you're storing path-names in a config file then you probably intend to be able to update the path-names to another host in case certain host goes down (\"\\file_server_host\\doc_store\" --> \"\\backup_file_server_host\\doc_store\") in which case is may actually be better to fail-over using DNS instead. There are too many variables. It really depends on the design; needs; scale of the app.</p>\n\n<hr>\n\n<p>For simplicity sake, if you just want a simple equivalent of a .settings file then you want a .properties file. Here is an example where I have recently used this in a project: <a href=\"https://github.com/sylnsr/docx4j-ws/blob/master/src/docx4j/TextSubstitution.java\" rel=\"nofollow\">https://github.com/sylnsr/docx4j-ws/blob/master/src/docx4j/TextSubstitution.java</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18834/" ]
I am new to java so excuse my lame questions:) I am trying to build a web service in Java NetBeans 6.1 , but I have some troubles with configuration parameters ( like .settings in .net). What is the right way to save and access such settings in a java web service. Is there a way to read context parameters from web.xml in a web method? If no what are the alternatives for storing your configuration variables like pathnames ? Thank you
If you are using servlets, you can configure parameters in web.xml: ``` <servlet> <servlet-name>jsp</servlet-name> <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class> <init-param> <param-name>fork</param-name> <param-value>false</param-value> </init-param> </servlet> ``` These properties will be passed in a ServletConfig object to your servlet's "init" method. Another way is to read your system's environment variables with ``` System.getProperty(String name); ``` But this is not recommended for other than small programs and tests. There is also the Properties API if you want to use ".properties" files. <http://java.sun.com/javase/6/docs/api/java/util/Properties.html> Finally, I believe looking up configurations with JNDI is pretty common when developing modern web service applications, Netbeans and app containers have pretty good support for that. Google it.
125,885
<p>I'm working on a fairly complex project, a custom encryption routine if you will (just for fun) and I've run into this issue in designing my code layout.</p> <p>I have a number of functions that I want to be able to call by index. Specifically, I need to be able to call one randomly for the encrypt process, but then address that by a specific index in the decrypt process.</p> <p>I was considering a classic function array, but my main concern is that a function array would be tricky to maintain, and a little ugly. (The goal is to get each function pair in a separate file, to reduce compile times and make the code easier to manage.) Does anyone have a more elegant C++ solution as an alternative to a function array? Speed isn't really an issue, I'm more worried about maintainability.</p> <p>-Nicholas</p>
[ { "answer_id": 125906, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 0, "selected": false, "text": "<p>An object with an operator() method defined can act a lot like a function but be generally nicer to work with.</p>\n" }, { "answer_id": 125915, "author": "NeARAZ", "author_id": 6799, "author_profile": "https://Stackoverflow.com/users/6799", "pm_score": 3, "selected": false, "text": "<p>What's wrong with function array?</p>\n\n<p>You need to call functions by index. So they must be put into some \"indexable by index\" structure <em>somehow</em>. Array is probably the simplest structure that suits this need.</p>\n\n<p>Example (typing out of my head, might not compile):</p>\n\n<pre><code>struct FunctionPair {\n EncodeFunction encode;\n DecodeFunction decode;\n};\nFunctionPair g_Functions[] = {\n { MyEncode1, MyDecode1 },\n { MySuperEncode, MySuperDecode },\n { MyTurboEncode, MyTurboDecode },\n};\n</code></pre>\n\n<p>What is \"ugly\" or \"hard to maintain\" in the approach above?</p>\n" }, { "answer_id": 125942, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 3, "selected": true, "text": "<p>You could write something like:</p>\n\n<pre><code>class EncryptionFunction\n{\npublic:\n virtual Foo Run(Bar input) = 0;\n virtual ~MyFunction() {}\n};\n\nclass SomeSpecificEncryptionFunction : public EncryptionFunction\n{\n // override the Run function\n};\n\n// ...\n\nstd::vector&lt;EncryptionFunction*&gt; functions;\n\n// ...\n\nfunctions[2]-&gt;Run(data);\n</code></pre>\n\n<p>You could use <code>operator()</code> instead of <code>Run</code> as the function name, if you prefer.</p>\n" }, { "answer_id": 125956, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "<p>Polymorphism could do the trick: you couldf follow the strategy pattern, considering each strategy to implement one of your functions (or a pair of them).</p>\n\n<p>Then create a vector of strategies, and use this one instead of the function list.</p>\n\n<p>But frankly, I don't see the problem with the function array; you can easily create a typedef to ease the readability. Effectifely, you will end up with exactly the same file structure when using the strategy pattern.</p>\n\n<pre><code>// functiontype.h\ntypedef bool (*forwardfunction)( double*, double* );\n\n// f1.h\n#include \"functiontype.h\"\nbool f1( double*, double* );\n\n// f1.c\n#include \"functiontype.h\"\n#include \"f1.h\"\nbool f1( double* p1, double* p2 ) { return false; }\n\n\n// functioncontainer.c \n#include \"functiontype.h\"\n#include \"f1.h\"\n#include \"f2.h\"\n#include \"f3.h\"\n\nforwardfunction my_functions[] = { f1, f2, f3 };\n</code></pre>\n\n<ul>\n<li>The function declaration and definitions are in separate files - compile time is ok.</li>\n<li>The function grouping is in a separate file, having a dependency to the declarations only</li>\n</ul>\n" }, { "answer_id": 125986, "author": "Jonas", "author_id": 16047, "author_profile": "https://Stackoverflow.com/users/16047", "pm_score": 0, "selected": false, "text": "<p>You could take a look at the <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/signals.html\" rel=\"nofollow noreferrer\">Boost.Signals library</a>. I believe it has the ability to call its registered functions using an index.</p>\n" }, { "answer_id": 126035, "author": "Igor Semenov", "author_id": 11401, "author_profile": "https://Stackoverflow.com/users/11401", "pm_score": 0, "selected": false, "text": "<p>Try Loki::Functor class. More info at <a href=\"http://www.codeproject.com/KB/cpp/genfunctors.aspx\" rel=\"nofollow noreferrer\">CodeProject.com</a></p>\n" }, { "answer_id": 126232, "author": "Eddie", "author_id": 21116, "author_profile": "https://Stackoverflow.com/users/21116", "pm_score": 0, "selected": false, "text": "<p>If you looked in <code>boost::signals</code> library, you'll see an example very nice, that is very elegant:\n<br> Suppose you have 4 functions like:</p>\n\n<pre><code>void print_sum(float x, float y)\n{\n std::cout &lt;&lt; \"The sum is \" &lt;&lt; x+y &lt;&lt; std::endl;\n}\n\nvoid print_product(float x, float y)\n{\n std::cout &lt;&lt; \"The product is \" &lt;&lt; x*y &lt;&lt; std::endl;\n}\n\nvoid print_difference(float x, float y)\n{\n std::cout &lt;&lt; \"The difference is \" &lt;&lt; x-y &lt;&lt; std::endl;\n}\n\nvoid print_quotient(float x, float y)\n{\n std::cout &lt;&lt; \"The quotient is \" &lt;&lt; x/y &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>Then if you want to call them in a elegant way try:</p>\n\n<pre><code>boost::signal&lt;void (float, float)&gt; sig;\n\nsig.connect(&amp;print_sum);\nsig.connect(&amp;print_product);\nsig.connect(&amp;print_difference);\nsig.connect(&amp;print_quotient);\n\nsig(5, 3);\n</code></pre>\n\n<p>And the output is:</p>\n\n<pre><code>The sum is 8\nThe product is 15\nThe difference is 2\nThe quotient is 1.66667\n</code></pre>\n" }, { "answer_id": 3111657, "author": "Jim Fell", "author_id": 214296, "author_profile": "https://Stackoverflow.com/users/214296", "pm_score": 0, "selected": false, "text": "<p>You need to use an array of function pointers. The only catch is that all the functions have to have basically the same prototype, only the name of the function and passed argument names can vary. The return type and argument types (as well as the number of arguments and order) must be identical.</p>\n\n<pre><code>int Proto1( void );\nint Proto2( void );\nint Proto3( void );\n\nint (*functinPointer[3])( void ) =\n{\n Proto1,\n Proto2,\n Proto3\n};\n</code></pre>\n\n<p>Then you can do something like this:</p>\n\n<pre><code>int iFuncIdx = 0;\nint iRetCode = functinPointer[iFuncIdx++]();\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
I'm working on a fairly complex project, a custom encryption routine if you will (just for fun) and I've run into this issue in designing my code layout. I have a number of functions that I want to be able to call by index. Specifically, I need to be able to call one randomly for the encrypt process, but then address that by a specific index in the decrypt process. I was considering a classic function array, but my main concern is that a function array would be tricky to maintain, and a little ugly. (The goal is to get each function pair in a separate file, to reduce compile times and make the code easier to manage.) Does anyone have a more elegant C++ solution as an alternative to a function array? Speed isn't really an issue, I'm more worried about maintainability. -Nicholas
You could write something like: ``` class EncryptionFunction { public: virtual Foo Run(Bar input) = 0; virtual ~MyFunction() {} }; class SomeSpecificEncryptionFunction : public EncryptionFunction { // override the Run function }; // ... std::vector<EncryptionFunction*> functions; // ... functions[2]->Run(data); ``` You could use `operator()` instead of `Run` as the function name, if you prefer.
125,921
<p>I'm trying to handle Winsock_Connect event (Actually I need it in Excel macro) using the following code:</p> <pre><code>Dim Winsock1 As Winsock 'Object type definition Sub Init() Set Winsock1 = CreateObject("MSWinsock.Winsock") 'Object initialization Winsock1.RemoteHost = "MyHost" Winsock1.RemotePort = "22" Winsock1.Connect Do While (Winsock1.State &lt;&gt; sckConnected) Sleep 200 Loop End Sub 'Callback handler Private Sub Winsock1_Connect() MsgBox "Winsock1::Connect" End Sub </code></pre> <p>But it never goes to Winsock1_Connect subroutine although Winsock1.State is "Connected". I want to use standard MS library because I don't have administrative rights on my PC and I'm not able to register some custom libraries. Can anybody tell me, where I'm wrong?</p>
[ { "answer_id": 125975, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": true, "text": "<p>Are you stuck using MSWinsock?<br>\n<a href=\"http://www.ostrosoft.com/oswinsck/oswinsck_reference.aspx\" rel=\"nofollow noreferrer\">Here</a> is a site/tutorial using a custom winsock object.</p>\n\n<p>Also... You need to declare Winsock1 <strong>WithEvents</strong> within a \"Class\" module:</p>\n\n<pre><code>Private WithEvents Winsock1 As Winsock\n</code></pre>\n\n<p>And finally, make sure you reference the winsock ocx control.<br>\nTools -> References -> Browse -> %SYSEM%\\MSWINSCK.OCX</p>\n" }, { "answer_id": 27361729, "author": "befzz", "author_id": 1079200, "author_profile": "https://Stackoverflow.com/users/1079200", "pm_score": 0, "selected": false, "text": "<p>Documentation about <strong>Winsock Control</strong>: <br/>\n<a href=\"http://msdn.microsoft.com/en-us/library/aa228119%28v=vs.60%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/aa228119%28v=vs.60%29.aspx</a> <br/>\nExample here: <br/>\n<a href=\"http://support.microsoft.com/kb/163999/en-us\" rel=\"nofollow\">http://support.microsoft.com/kb/163999/en-us</a> <br/></p>\n\n<p>My short example with event handling in VBscript:</p>\n\n<pre class=\"lang-vbs prettyprint-override\"><code>Dim sock\nSet sock = WScript.CreateObject(\"MSWinsock.Winsock\",\"sock_\")\nsock.RemoteHost = \"www.yandex.com\"\nsock.RemotePort = \"80\"\nsock.Connect\n\nDim received\nreceived = 0\n\nSub sock_Connect()\n WScript.Echo \"[sock] Connection Successful!\"\n sock.SendData \"GET / HTTP/1.1\"&amp; vbCrLf &amp; \"Host: \" &amp; sock.RemoteHost &amp; vbCrLf &amp; vbCrLf\nEnd Sub\n\nSub sock_Close()\n WScript.Echo \"[sock] Connection closed!\"\nEnd Sub\n\nSub sock_DataArrival(Byval b)\n Dim data\n sock.GetData data, vbString\n received = received + b\n WScript.Echo \"---------------------------------------\"\n WScript.Echo \" Bytes received: \" &amp; b &amp; \" ( Total: \" &amp; received &amp; \" )\"\n WScript.Echo \"---------------------------------------\"\n WScript.Echo data\nEnd Sub\n\n'Wait for server close connection\nDo While sock.State &lt;&gt; 8\n rem WScript.Echo sock.State\n WScript.Sleep 1000\nLoop\n</code></pre>\n\n<p>Output will be:</p>\n\n<p><code>cscript /nologo sockhttp.vbs</code></p>\n\n<pre><code>[sock] Connection Successful!\n-------------------------------\n Bytes received: 1376 ( Total: 1376 )\n-------------------------------\nHTTP/1.1 200 Ok\nDate: Mon, 08 Dec 2014 15:41:36 GMT\nContent-Type: text/html; charset=UTF-8\nCache-Control: no-cache,no-store,max-age=0,must-revalidate\nExpires: Mon, 08 Dec 2014 15:41:36 GMT\n...\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21530/" ]
I'm trying to handle Winsock\_Connect event (Actually I need it in Excel macro) using the following code: ``` Dim Winsock1 As Winsock 'Object type definition Sub Init() Set Winsock1 = CreateObject("MSWinsock.Winsock") 'Object initialization Winsock1.RemoteHost = "MyHost" Winsock1.RemotePort = "22" Winsock1.Connect Do While (Winsock1.State <> sckConnected) Sleep 200 Loop End Sub 'Callback handler Private Sub Winsock1_Connect() MsgBox "Winsock1::Connect" End Sub ``` But it never goes to Winsock1\_Connect subroutine although Winsock1.State is "Connected". I want to use standard MS library because I don't have administrative rights on my PC and I'm not able to register some custom libraries. Can anybody tell me, where I'm wrong?
Are you stuck using MSWinsock? [Here](http://www.ostrosoft.com/oswinsck/oswinsck_reference.aspx) is a site/tutorial using a custom winsock object. Also... You need to declare Winsock1 **WithEvents** within a "Class" module: ``` Private WithEvents Winsock1 As Winsock ``` And finally, make sure you reference the winsock ocx control. Tools -> References -> Browse -> %SYSEM%\MSWINSCK.OCX
125,934
<p>I'm writing an application to start and monitor other applications in C#. I'm using the System.Diagnostics.Process class to start applications and then monitor the applications using the Process.Responding property to poll the state of the application every 100 milisecs. I use Process.CloseMainWindow to stop the application or Process.Kill to kill it if it's not responding.</p> <p>I've noticed a weird behaviour where sometimes the process object gets into a state where the responding property always returns true even when the underlying process hangs in a loop and where it doesn't respond to CloseMainWindow.</p> <p>One way to reproduce it is to poll the Responding property right after starting the process instance. So for example</p> <pre><code>_process.Start(); bool responding = _process.Responding; </code></pre> <p>will reproduce the error state while</p> <pre><code>_process.Start(); Thread.Sleep(1000); bool responding = _process.Responding; </code></pre> <p>will work. Reducing the sleep period to 500 will introduce the error state again.</p> <p>Something in calling _process.Responding too fast after starting seems to prevent the object from getting the right windows message queue handler. I guess I need to wait for _process.Start to finish doing it's asynchronous work. Is there a better way to wait for this than calling Thread.Sleep ? I'm not too confident that the 1000 ms will always be enough.</p>
[ { "answer_id": 125961, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 2, "selected": false, "text": "<p>I think it may be better to enhance the check for _process.Responding so that you only try to stop/kill the process if the Responding property returns false for more than 5 seconds (for example).</p>\n\n<p>I think you may find that quite often, applications may be \"not responding\" for a split second whilst they are doing more intensive processing.</p>\n\n<p>I believe a more lenient approach will work better, allowing a process to be \"not responding\" for a short amount of time, only taking action if it is repeatedly \"not responding\" for several seconds (or however long you want).</p>\n\n<p>Further note: The Microsoft documentation indicates that the Responding property specifically relates to the user interface, which is why a newly started process may not have it's UI responding immediately.</p>\n" }, { "answer_id": 126001, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 4, "selected": true, "text": "<p>Now, I need to check this out later, but I am sure there is a method that tells the thread to wait until it is ready for input. Are you monitoring GUI processes only?</p>\n<p>Isn't <a href=\"http://msdn.microsoft.com/en-us/library/kcdbkyt4.aspx\" rel=\"noreferrer\">Process.WaitForInputIdle</a> of any help to you? Or am I missing the point? :)</p>\n<h2>Update</h2>\n<p>Following a chit-chat on Twitter (or tweet-tweet?) with Mendelt I thought I should update my answer so the community is fully aware..</p>\n<ul>\n<li><code>WaitForInputIdle</code> will only work on applications that have a GUI.</li>\n<li>You specify the time to wait, and the method returns a bool if the process reaches an idle state within that time frame, you can obviously use this to loop if required, or handle as appropriate.</li>\n</ul>\n<p>Hope that helps :)</p>\n" }, { "answer_id": 126140, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 2, "selected": false, "text": "<p>Thanks for the answers. This</p>\n\n<pre><code>_process.Start();\n_process.WaitForInputIdle();\n</code></pre>\n\n<p>Seems to solve the problem. It's still strange because Responding and WaitForInputIdle should both be using the same win32 api call under the covers.</p>\n\n<p>Some more background info<br>\nGUI applications have a main window with a message queue. Responding and WaitForInputIdle work by checking if the process still processes messages from this message queue. This is why they only work with GUI apps. Somehow it seems that calling Responding too fast interferes with getting the Process getting a handle to that message queue. Calling WaitForInputIdle seems to solve that problem.</p>\n\n<p>I'll have to dive into reflector to see if I can make sense of this.</p>\n\n<p><em>update</em><br>\nIt seems that retrieving the window handle associated with the process just after starting is enough to trigger the weird behaviour. Like this:</p>\n\n<pre><code>_process.Start();\nIntPtr mainWindow = _process.MainWindowHandle;\n</code></pre>\n\n<p>I checked with Reflector and this is what Responding does under the covers. It seems that if you get the MainWindowHandle too soon you get the wrong one and it uses this wrong handle it for the rest of the lifetime of the process or until you call Refresh();</p>\n\n<p><em>update</em><br>\nCalling WaitForInputIdle() only solves the problem some of the time. Calling Refresh() everytime you read the Responding property seems to work better.</p>\n" }, { "answer_id": 214381, "author": "GregUzelac", "author_id": 27068, "author_profile": "https://Stackoverflow.com/users/27068", "pm_score": 1, "selected": false, "text": "<p>I too noticed that in a project about 2 years ago. I called .Refresh() before requesting certain prop values. IT was a trial-and-error approach to find when I needed to call .Refresh().</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3320/" ]
I'm writing an application to start and monitor other applications in C#. I'm using the System.Diagnostics.Process class to start applications and then monitor the applications using the Process.Responding property to poll the state of the application every 100 milisecs. I use Process.CloseMainWindow to stop the application or Process.Kill to kill it if it's not responding. I've noticed a weird behaviour where sometimes the process object gets into a state where the responding property always returns true even when the underlying process hangs in a loop and where it doesn't respond to CloseMainWindow. One way to reproduce it is to poll the Responding property right after starting the process instance. So for example ``` _process.Start(); bool responding = _process.Responding; ``` will reproduce the error state while ``` _process.Start(); Thread.Sleep(1000); bool responding = _process.Responding; ``` will work. Reducing the sleep period to 500 will introduce the error state again. Something in calling \_process.Responding too fast after starting seems to prevent the object from getting the right windows message queue handler. I guess I need to wait for \_process.Start to finish doing it's asynchronous work. Is there a better way to wait for this than calling Thread.Sleep ? I'm not too confident that the 1000 ms will always be enough.
Now, I need to check this out later, but I am sure there is a method that tells the thread to wait until it is ready for input. Are you monitoring GUI processes only? Isn't [Process.WaitForInputIdle](http://msdn.microsoft.com/en-us/library/kcdbkyt4.aspx) of any help to you? Or am I missing the point? :) Update ------ Following a chit-chat on Twitter (or tweet-tweet?) with Mendelt I thought I should update my answer so the community is fully aware.. * `WaitForInputIdle` will only work on applications that have a GUI. * You specify the time to wait, and the method returns a bool if the process reaches an idle state within that time frame, you can obviously use this to loop if required, or handle as appropriate. Hope that helps :)
125,951
<p>What is a good command line tool to create screenshots of websites on Linux? I need to automatically generate screenshots of websites without human interaction. The only tool that I found was <a href="http://khtml2png.sourceforge.net/" rel="noreferrer">khtml2png</a>, but I wonder if there are others that aren't based on khtml (i.e. have good JavaScript support, ...).</p>
[ { "answer_id": 126000, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 2, "selected": false, "text": "<p>I know its not a command line tool but you could easily script up something to use <a href=\"http://browsershots.org/\" rel=\"nofollow noreferrer\">http://browsershots.org/</a> Not that useful for applications not hosted on external IPs.</p>\n\n<p>A great tool none the less.</p>\n" }, { "answer_id": 126003, "author": "Jim T", "author_id": 7298, "author_profile": "https://Stackoverflow.com/users/7298", "pm_score": 1, "selected": false, "text": "<p>I don't know of anything custom built, I'm sure there could be something done with the gecko engine to render to a png file instead of the screen ...</p>\n\n<p>Or, you could fire up firefox in full screen mode in a dedicated VNC server instance and use a screenshot grabber to take the screenshot. Fullscreen = minimal chrome, VNC server instance = no visible UI + you can choose your resolution.</p>\n\n<p>Use xinit with Xvnc as the X server to do this - you'll need to read all the manpages.</p>\n\n<p>Downsides are that the screenshot is always the same size, doesn't resize according to the web page ...</p>\n" }, { "answer_id": 126126, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 1, "selected": false, "text": "<p>There is the <strong>import</strong> command, but you'll need X, and a little bash script that open the browser window, then take the screenshot and close the browser.</p>\n\n<p>You can find more information <a href=\"http://www.linux.com/articles/113595\" rel=\"nofollow noreferrer\">here</a>, or just typing <strong>import --help</strong> in a shell ;)</p>\n" }, { "answer_id": 143148, "author": "Shannon Nelson", "author_id": 14450, "author_profile": "https://Stackoverflow.com/users/14450", "pm_score": 7, "selected": true, "text": "<p>A little more detail might be useful...</p>\n\n<p>Start a firefox (or other browser) in an X session, either on your console or using a vncserver. You can use the <code>--height</code> and <code>--width</code> options to set the size of the window to full screen. Another firefox command can be used to set the URL being displayed in the first firefox window. Now you can grab the screen image with one of several commands, such as the \"import\" command from the Imagemagick package, or using gimp, or fbgrab, or xv.</p>\n\n<pre><code>#!/bin/sh\n\n# start a server with a specific DISPLAY\nvncserver :11 -geometry 1024x768\n\n# start firefox in this vnc session\nfirefox --display :11\n\n# read URLs from a data file in a loop\ncount=1\nwhile read url\ndo\n # send URL to the firefox session\n firefox --display :11 $url\n\n # take a picture after waiting a bit for the load to finish\n sleep 5\n import -window root image$count.jpg\n\n count=`expr $count + 1`\ndone &lt; url_list.txt\n\n# clean up when done\nvncserver -kill :11\n</code></pre>\n" }, { "answer_id": 164568, "author": "Hamish Downer", "author_id": 3189, "author_profile": "https://Stackoverflow.com/users/3189", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://freshmeat.net/projects/scrot/\" rel=\"nofollow noreferrer\">scrot</a> is a command line tool for taking screenshots. See the <a href=\"http://pwet.fr/man/linux/commandes/scrot\" rel=\"nofollow noreferrer\">man page</a> and this <a href=\"http://www.freesoftwaremagazine.com/columns/how_to_take_screenshots_with_scrot\" rel=\"nofollow noreferrer\">tutorial</a>.</p>\n\n<p>You might also want to look at scripting the browser. There are firefox add-ons that take screenshots such as <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1146\" rel=\"nofollow noreferrer\">screengrab</a> (which can capture the entire page if you want, not just the visible bit) and you could then script the browser with <a href=\"http://en.wikipedia.org/wiki/Greasemonkey\" rel=\"nofollow noreferrer\">greasemonkey</a> to take the screenshots.</p>\n" }, { "answer_id": 2197580, "author": "Stephan Wehner", "author_id": 219130, "author_profile": "https://Stackoverflow.com/users/219130", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://khtml2png.sourceforge.net/\" rel=\"nofollow noreferrer\">http://khtml2png.sourceforge.net/</a></p>\n\n<p>The deb file </p>\n\n<ul>\n<li><a href=\"http://sourceforge.net/projects/khtml2png/files/khtml2png2/2.7.6/khtml2png_2.7.6_i386.deb/download\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/khtml2png/files/khtml2png2/2.7.6/khtml2png_2.7.6_i386.deb/download</a></li>\n</ul>\n\n<p>worked on my Ubuntu after installing libkonq4 ... but you may have to cover other dependencies.</p>\n\n<p>I think javascript support may be better now!</p>\n\n<p>Stephan</p>\n" }, { "answer_id": 9325435, "author": "SLN", "author_id": 1097789, "author_profile": "https://Stackoverflow.com/users/1097789", "pm_score": 1, "selected": false, "text": "<p>Not for the command line but at least for usage in batch operation for a larger set of urls you may use firefox with its addon fireshot (licensed version?).</p>\n\n<ol>\n<li>Open tabs for all urls in your set (e.g. \"open tabs for all bookmarks in this folder...\").</li>\n<li>Then in fireshot launch \"Capture all tabs\"</li>\n<li>In the edit window then call \"select all shots -> save all shots\"</li>\n</ol>\n\n<p>Having set the screenshot properties (size, fileformat, etc.) before you end with a nice set of shotfiles.</p>\n\n<p>Steffen</p>\n" }, { "answer_id": 11459254, "author": "m7n7", "author_id": 1521815, "author_profile": "https://Stackoverflow.com/users/1521815", "pm_score": 5, "selected": false, "text": "<p>Try nice small tool <a href=\"http://cutycapt.sourceforge.net/\" rel=\"noreferrer\">CutyCapt</a>, which depends only on Qt and QtWebkit. ;)</p>\n" }, { "answer_id": 15667501, "author": "Luke H", "author_id": 289203, "author_profile": "https://Stackoverflow.com/users/289203", "pm_score": 2, "selected": false, "text": "<p>See <a href=\"http://www.paulhammond.org/webkit2png/\" rel=\"nofollow\">Webkit2png</a>.</p>\n\n<p>I think this is what I used in the past.</p>\n\n<p><strong>Edit</strong> I discover I haven't used the above, but found <a href=\"http://www.techmaze.net/take-webpage-screenshot-from-command-line-in-ubuntu-linux/\" rel=\"nofollow\">this page</a> with reviews of many different programs and techniques.</p>\n" }, { "answer_id": 16941150, "author": "MaxiWheat", "author_id": 165055, "author_profile": "https://Stackoverflow.com/users/165055", "pm_score": 3, "selected": false, "text": "<p>Have a look at <a href=\"http://phantomjs.org/\"><strong>PhantomJS</strong></a>, which seems to be a free scritable Webkit engine that runs on Linux, OSX and Windows. I've not used it since we currently use <a href=\"https://browshot.com/\">Browshot</a> (commercial solution), but when all our credits run out, we will seriously have a loot at it (since it's free and can run on our servers)</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4936/" ]
What is a good command line tool to create screenshots of websites on Linux? I need to automatically generate screenshots of websites without human interaction. The only tool that I found was [khtml2png](http://khtml2png.sourceforge.net/), but I wonder if there are others that aren't based on khtml (i.e. have good JavaScript support, ...).
A little more detail might be useful... Start a firefox (or other browser) in an X session, either on your console or using a vncserver. You can use the `--height` and `--width` options to set the size of the window to full screen. Another firefox command can be used to set the URL being displayed in the first firefox window. Now you can grab the screen image with one of several commands, such as the "import" command from the Imagemagick package, or using gimp, or fbgrab, or xv. ``` #!/bin/sh # start a server with a specific DISPLAY vncserver :11 -geometry 1024x768 # start firefox in this vnc session firefox --display :11 # read URLs from a data file in a loop count=1 while read url do # send URL to the firefox session firefox --display :11 $url # take a picture after waiting a bit for the load to finish sleep 5 import -window root image$count.jpg count=`expr $count + 1` done < url_list.txt # clean up when done vncserver -kill :11 ```
125,957
<p>I know this is not directly a programming question, but people on stackoverflow seems to be able to answer any question.</p> <p>I have a server running Centos 5.2 64 bit. Pretty powerful dual core 2 server with 4GB memory. It mostly serves static files, flash and pictures. When I use lighttpd it easily serves over 80 MB/sec, but when I test with nginx it drops down to less than 20 MB/sec.</p> <p>My setup is pretty straight forward, uses the default setup file, and I have added the following</p> <pre><code>user lighttpd; worker_processes 8; worker_rlimit_nofile 206011; #worker_rlimit_nofile 110240; error_log /var/log/nginx/error.log; #error_log /var/log/nginx/error.log notice; #error_log /var/log/nginx/error.log info; pid /var/run/nginx.pid; events { worker_connections 4096; } http { .... keepalive_timeout 2; .... } </code></pre> <p>And I thought nginx was supposed to be at least as powerful, so I must be not doing something.</p>
[ { "answer_id": 129855, "author": "Ross", "author_id": 14794, "author_profile": "https://Stackoverflow.com/users/14794", "pm_score": 2, "selected": false, "text": "<p>Perhaps lighttpd is using some kind of caching? There's a great article <a href=\"http://www.igvita.com/2008/02/11/nginx-and-memcached-a-400-boost/\" rel=\"nofollow noreferrer\">here</a> that describes how to set up memcached with nginx for a reported 400% performance boost.</p>\n\n<p>The nginx doc on the memcached module is <a href=\"http://wiki.codemongers.com/NginxHttpMemcachedModule\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 156642, "author": "Dave Cheney", "author_id": 6449, "author_profile": "https://Stackoverflow.com/users/6449", "pm_score": 3, "selected": false, "text": "<p>When you reload your nginx (kiil -HUP) you'll get something like this in your error logs</p>\n\n<pre>\n2008/10/01 03:57:26 [notice] 4563#0: signal 1 (SIGHUP) received, reconfiguring\n2008/10/01 03:57:26 [notice] 4563#0: reconfiguring\n2008/10/01 03:57:26 [notice] 4563#0: using the \"epoll\" event method\n2008/10/01 03:57:26 [notice] 4563#0: start worker processes\n2008/10/01 03:57:26 [notice] 4563#0: start worker process 3870\n</pre>\n\n<p>What event method is your nginx compiled to use?</p>\n\n<p>Are you doing any access_log'ing ? Consider adding buffer=32k, which will reduce the contention on the write lock for the log file.</p>\n\n<p>Consider reducing the number of workers, it sounds counter intuitive, but the workers need to synchronize with each other for sys calls like accept(). Try reducing the number of workers, ideally I would suggest 1.</p>\n\n<p>You might try explicitly setting the read and write socket buffers on the listening socket, see <a href=\"http://wiki.codemongers.com/NginxHttpCoreModule#listen\" rel=\"noreferrer\">http://wiki.codemongers.com/NginxHttpCoreModule#listen</a></p>\n" }, { "answer_id": 196019, "author": "Seun Osewa", "author_id": 6475, "author_profile": "https://Stackoverflow.com/users/6475", "pm_score": 1, "selected": false, "text": "<p>Suggestions:\n- Use 1 worker per processor.\n- Check the various nginx buffer settings</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6801/" ]
I know this is not directly a programming question, but people on stackoverflow seems to be able to answer any question. I have a server running Centos 5.2 64 bit. Pretty powerful dual core 2 server with 4GB memory. It mostly serves static files, flash and pictures. When I use lighttpd it easily serves over 80 MB/sec, but when I test with nginx it drops down to less than 20 MB/sec. My setup is pretty straight forward, uses the default setup file, and I have added the following ``` user lighttpd; worker_processes 8; worker_rlimit_nofile 206011; #worker_rlimit_nofile 110240; error_log /var/log/nginx/error.log; #error_log /var/log/nginx/error.log notice; #error_log /var/log/nginx/error.log info; pid /var/run/nginx.pid; events { worker_connections 4096; } http { .... keepalive_timeout 2; .... } ``` And I thought nginx was supposed to be at least as powerful, so I must be not doing something.
When you reload your nginx (kiil -HUP) you'll get something like this in your error logs ``` 2008/10/01 03:57:26 [notice] 4563#0: signal 1 (SIGHUP) received, reconfiguring 2008/10/01 03:57:26 [notice] 4563#0: reconfiguring 2008/10/01 03:57:26 [notice] 4563#0: using the "epoll" event method 2008/10/01 03:57:26 [notice] 4563#0: start worker processes 2008/10/01 03:57:26 [notice] 4563#0: start worker process 3870 ``` What event method is your nginx compiled to use? Are you doing any access\_log'ing ? Consider adding buffer=32k, which will reduce the contention on the write lock for the log file. Consider reducing the number of workers, it sounds counter intuitive, but the workers need to synchronize with each other for sys calls like accept(). Try reducing the number of workers, ideally I would suggest 1. You might try explicitly setting the read and write socket buffers on the listening socket, see <http://wiki.codemongers.com/NginxHttpCoreModule#listen>
125,964
<p>Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It's kind of cumbersome and I'm wondering if there is a more straightforward approach.</p>
[ { "answer_id": 125980, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 3, "selected": false, "text": "<p>You can also start the service through the command prompt (sc.exe).</p>\n\n<p>Personally, I'd run the code as a stand-alone program in the debugging phase, and when most bugs are ironed out, change to running as service.</p>\n" }, { "answer_id": 125982, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "<p>What I used to do was to have a command line switch which would start the program either as a service or as a regular application. Then, in my IDE I would set the switch so that I could step through my code.</p>\n\n<p>With some languages you can actually detect if it's running in an IDE, and perform this switch automatically.</p>\n\n<p>What language are you using?</p>\n" }, { "answer_id": 125983, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 5, "selected": false, "text": "<p>What I usually do is encapsulate the logic of the service in a separate class and start that from a 'runner' class. This runner class can be the actual service or just a console application. So your solution has (atleast) 3 projects:</p>\n\n<pre><code>/ConsoleRunner\n /....\n/ServiceRunner\n /....\n/ApplicationLogic\n /....\n</code></pre>\n" }, { "answer_id": 125985, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 3, "selected": false, "text": "<p>I think it depends on what OS you are using, Vista is much harder to attach to Services, because of the separation between sessions.</p>\n\n<p>The two options I've used in the past are:</p>\n\n<ul>\n<li>Use GFlags (in the Debugging Tools for Windows) to setup a permanent debugger for a process. This exists in the \"Image File Execution Options\" registry key and is incredibly useful. I think you'll need to tweak the Service settings to enable \"Interact with Desktop\". I use this for all types of debugging, not just services.</li>\n<li>The other option, is to separate the code a bit, so that the service part is interchangable with a normal app startup. That way, you can use a simple command line flag, and launch as a process (rather than a Service), which makes it much easier to debug.</li>\n</ul>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 125987, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 1, "selected": false, "text": "<p>For routine small-stuff programming I've done a very simple trick to easily debug my service:</p>\n\n<p>On start of the service, I check for a command line parameter \"/debug\". If the service is called with this parameter, I don't do the usual service startup, but instead start all the listeners and just display a messagebox \"Debug in progress, press ok to end\".</p>\n\n<p>So if my service is started the usual way, it will start as service, if it is started with the command line parameter /debug it will act like a normal program.</p>\n\n<p>In VS I'll just add /debug as debugging parameter and start the service program directly.</p>\n\n<p>This way I can easily debug for most small kind problems. Of course, some stuff still will need to be debugged as service, but for 99% this is good enough.</p>\n" }, { "answer_id": 125990, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 3, "selected": false, "text": "<p>When I write a service I put all the service logic in a dll project and create two \"hosts\" that call into this dll, one is a Windows service and the other is a command line application.</p>\n\n<p>I use the command line application for debugging and attach the debugger to the real service only for bugs I can't reproduce in the command line application.</p>\n\n<p>I you use this approach just remember that you have to test all the code while running in a real service, while the command line tool is a nice debugging aid it's a different environment and it doesn't behave exactly like a real service.</p>\n" }, { "answer_id": 125995, "author": "Maurice", "author_id": 19676, "author_profile": "https://Stackoverflow.com/users/19676", "pm_score": 2, "selected": false, "text": "<p>When developing and debugging a Windows service I typically run it as a console application by adding a /console startup parameter and checking this. Makes life much easier.</p>\n\n<pre><code>static void Main(string[] args) {\n if (Console.In != StreamReader.Null) {\n if (args.Length &gt; 0 &amp;&amp; args[0] == \"/console\") {\n // Start your service work.\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 125998, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>How about Debugger.Break() in the first line?</p>\n" }, { "answer_id": 126016, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 9, "selected": true, "text": "<p>If I want to quickly debug the service, I just drop in a <code>Debugger.Break()</code> in there. When that line is reached, it will drop me back to VS. Don't forget to remove that line when you are done.</p>\n<p><strong>UPDATE:</strong> As an alternative to <code>#if DEBUG</code> pragmas, you can also use <code>Conditional(&quot;DEBUG_SERVICE&quot;)</code> attribute.</p>\n<pre><code>[Conditional(&quot;DEBUG_SERVICE&quot;)]\nprivate static void DebugMode()\n{\n Debugger.Break();\n}\n</code></pre>\n<p>On your <code>OnStart</code>, just call this method:</p>\n<pre><code>public override void OnStart()\n{\n DebugMode();\n /* ... do the rest */\n}\n</code></pre>\n<p>There, the code will only be enabled during Debug builds. While you're at it, it might be useful to create a separate Build Configuration for service debugging.</p>\n" }, { "answer_id": 126110, "author": "rohancragg", "author_id": 5351, "author_profile": "https://Stackoverflow.com/users/5351", "pm_score": 4, "selected": false, "text": "<p><strong>UPDATE</strong></p>\n\n<p>This approach is by far the easiest:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx</a></p>\n\n<p>I leave my original answer below for posterity.</p>\n\n<hr>\n\n<p>My services tend to have a class that encapsulates a Timer as I want the service to check at regular intervals whether there is any work for it to do.</p>\n\n<p>We new up the class and call StartEventLoop() during the service start-up. (This class could easily be used from a console app too.)</p>\n\n<p>The nice side-effect of this design is that the arguments with which you set up the Timer can be used to have a delay before the service actually starts working, so that you have time to attach a debugger manually.</p>\n\n<blockquote>\n <p>p.s. <a href=\"http://msdn.microsoft.com/en-us/library/c6wf8e4z.aspx\" rel=\"noreferrer\">How to attach the debugger manually</a> to a running process...?</p>\n</blockquote>\n\n<pre><code>using System;\nusing System.Threading;\nusing System.Configuration; \n\npublic class ServiceEventHandler\n{\n Timer _timer;\n public ServiceEventHandler()\n {\n // get configuration etc.\n _timer = new Timer(\n new TimerCallback(EventTimerCallback)\n , null\n , Timeout.Infinite\n , Timeout.Infinite);\n }\n\n private void EventTimerCallback(object state)\n {\n // do something\n }\n\n public void StartEventLoop()\n {\n // wait a minute, then run every 30 minutes\n _timer.Change(TimeSpan.Parse(\"00:01:00\"), TimeSpan.Parse(\"00:30:00\");\n }\n}\n</code></pre>\n\n<p>Also I used to do the following (already mentioned in previous answers but with the conditional compiler [#if] flags to help avoid it firing in a Release build).</p>\n\n<p>I stopped doing it this way because sometimes we'd forget to build in Release and have a debugger break in an app running on a client demo (embarrasing!).</p>\n\n<pre><code>#if DEBUG\nif (!System.Diagnostics.Debugger.IsAttached)\n{\n System.Diagnostics.Debugger.Break();\n}\n#endif\n</code></pre>\n" }, { "answer_id": 126163, "author": "Christian.K", "author_id": 21567, "author_profile": "https://Stackoverflow.com/users/21567", "pm_score": 8, "selected": false, "text": "<p>I also think having a separate \"version\" for normal execution and as a service is the way to go, but is it really required to dedicate a separate command line switch for that purpose?</p>\n\n<p>Couldn't you just do:</p>\n\n<pre><code>public static int Main(string[] args)\n{\n if (!Environment.UserInteractive)\n {\n // Startup as service.\n }\n else\n {\n // Startup as application\n }\n}\n</code></pre>\n\n<p>That would have the \"benefit\", that you can just start your app via doubleclick (OK, if you really need that) and that you can just hit <kbd>F5</kbd> in Visual Studio (without the need to modify the project settings to include that <code>/console</code> Option).</p>\n\n<p>Technically, the <code>Environment.UserInteractive</code> checks if the <code>WSF_VISIBLE</code> Flag is set for the current window station, but is there any other reason where it would return <code>false</code>, apart from being run as a (non-interactive) service?</p>\n" }, { "answer_id": 127127, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>To debug Windows Services I combine GFlags and a .reg file created by regedit.</p>\n\n<ol>\n<li>Run GFlags, specifying the exe-name and vsjitdebugger</li>\n<li>Run regedit and go to the location where GFlags sets his options</li>\n<li>Choose \"Export Key\" from the file-menu</li>\n<li>Save that file somewhere with the .reg extension</li>\n<li>Anytime you want to debug the service: doubleclick on the .reg file</li>\n<li>If you want to stop debugging, doubleclick on the second .reg file</li>\n</ol>\n\n<p>Or save the following snippets and replace servicename.exe with the desired executable name.</p>\n\n<hr>\n\n<p>debugon.reg:</p>\n\n<pre>Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\servicename.exe]\n\"GlobalFlag\"=\"0x00000000\"\n\"Debugger\"=\"vsjitdebugger.exe\"</pre>\n\n<hr>\n\n<p>debugoff.reg:</p>\n\n<pre>Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\servicename.exe]\n\"GlobalFlag\"=\"0x00000000\"</pre>\n" }, { "answer_id": 150855, "author": "Thomas Bratt", "author_id": 15985, "author_profile": "https://Stackoverflow.com/users/15985", "pm_score": 4, "selected": false, "text": "<hr>\n\n<pre><code>static void Main()\n{\n#if DEBUG\n // Run as interactive exe in debug mode to allow easy\n // debugging.\n\n var service = new MyService();\n service.OnStart(null);\n\n // Sleep the main thread indefinitely while the service code\n // runs in .OnStart\n\n Thread.Sleep(Timeout.Infinite);\n#else\n // Run normally as service in release mode.\n\n ServiceBase[] ServicesToRun;\n ServicesToRun = new ServiceBase[]{ new MyService() };\n ServiceBase.Run(ServicesToRun);\n#endif\n}\n</code></pre>\n" }, { "answer_id": 313618, "author": "Ervin Ter", "author_id": 34983, "author_profile": "https://Stackoverflow.com/users/34983", "pm_score": 1, "selected": false, "text": "<pre><code>#if DEBUG\n System.Diagnostics.Debugger.Break();\n#endif\n</code></pre>\n" }, { "answer_id": 795682, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I use a variation on JOP's answer. Using command line parameters you can set the debugging mode in the IDE with project properties or through the Windows service manager.</p>\n\n<pre><code>protected override void OnStart(string[] args)\n{\n if (args.Contains&lt;string&gt;(\"DEBUG_SERVICE\"))\n {\n Debugger.Break();\n }\n ...\n}\n</code></pre>\n" }, { "answer_id": 6551189, "author": "BitMask777", "author_id": 509891, "author_profile": "https://Stackoverflow.com/users/509891", "pm_score": 3, "selected": false, "text": "<p>I like to be able to debug every aspect of my service, including any initialization in OnStart(), while still executing it with full service behavior within the framework of the SCM... no \"console\" or \"app\" mode. </p>\n\n<p>I do this by creating a second service, in the same project, to use for debugging. The debug service, when started as usual (i.e. in the services MMC plugin), creates the service host process. This gives you a process to attach the debugger to even though you haven't started your real service yet. After attaching the debugger to the process, start your real service and you can break into it anywhere in the service lifecycle, including OnStart().</p>\n\n<p>Because it requires very minimal code intrusion, the debug service can easily be included in your service setup project, and is easily removed from your production release by commenting out a single line of code and deleting a single project installer.</p>\n\n<p><strong>Details:</strong></p>\n\n<p>1) Assuming you are implementing <code>MyService</code>, also create <code>MyServiceDebug</code>. Add both to the <code>ServiceBase</code> array in <code>Program.cs</code> like so:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// The main entry point for the application.\n /// &lt;/summary&gt;\n static void Main()\n {\n ServiceBase[] ServicesToRun;\n ServicesToRun = new ServiceBase[] \n { \n new MyService(),\n new MyServiceDebug()\n };\n ServiceBase.Run(ServicesToRun);\n }\n</code></pre>\n\n<p>2) Add the real service AND the debug service to the project installer for the service project:</p>\n\n<p><img src=\"https://i.stack.imgur.com/1Jbm5.png\" alt=\"enter image description here\"></p>\n\n<p>Both services (real and debug) get included when you add the service project output to the setup project for the service. After installation, both services will appear in the service.msc MMC plugin.</p>\n\n<p>3) Start the debug service in MMC.</p>\n\n<p>4) In Visual Studio, attach the debugger to the process started by the debug service.</p>\n\n<p>5) Start the real service and enjoy debugging.</p>\n" }, { "answer_id": 10838170, "author": "Anders Abel", "author_id": 280222, "author_profile": "https://Stackoverflow.com/users/280222", "pm_score": 7, "selected": false, "text": "<p>When I set up a new service project a few weeks ago I found this post. While there are many great suggestions, I still didn't find the solution I wanted: The possibility to call the service classes' <code>OnStart</code> and <code>OnStop</code> methods without any modification to the service classes.</p>\n\n<p>The solution I came up with uses the <code>Environment.Interactive</code> the select running mode, as suggested by other answers to this post.</p>\n\n<pre><code>static void Main()\n{\n ServiceBase[] servicesToRun;\n servicesToRun = new ServiceBase[] \n {\n new MyService()\n };\n if (Environment.UserInteractive)\n {\n RunInteractive(servicesToRun);\n }\n else\n {\n ServiceBase.Run(servicesToRun);\n }\n}\n</code></pre>\n\n<p>The <code>RunInteractive</code> helper uses reflection to call the protected <code>OnStart</code> and <code>OnStop</code> methods:</p>\n\n<pre><code>static void RunInteractive(ServiceBase[] servicesToRun)\n{\n Console.WriteLine(\"Services running in interactive mode.\");\n Console.WriteLine();\n\n MethodInfo onStartMethod = typeof(ServiceBase).GetMethod(\"OnStart\", \n BindingFlags.Instance | BindingFlags.NonPublic);\n foreach (ServiceBase service in servicesToRun)\n {\n Console.Write(\"Starting {0}...\", service.ServiceName);\n onStartMethod.Invoke(service, new object[] { new string[] { } });\n Console.Write(\"Started\");\n }\n\n Console.WriteLine();\n Console.WriteLine();\n Console.WriteLine(\n \"Press any key to stop the services and end the process...\");\n Console.ReadKey();\n Console.WriteLine();\n\n MethodInfo onStopMethod = typeof(ServiceBase).GetMethod(\"OnStop\", \n BindingFlags.Instance | BindingFlags.NonPublic);\n foreach (ServiceBase service in servicesToRun)\n {\n Console.Write(\"Stopping {0}...\", service.ServiceName);\n onStopMethod.Invoke(service, null);\n Console.WriteLine(\"Stopped\");\n }\n\n Console.WriteLine(\"All services stopped.\");\n // Keep the console alive for a second to allow the user to see the message.\n Thread.Sleep(1000);\n}\n</code></pre>\n\n<p>This is all the code required, but I also wrote <a href=\"http://coding.abel.nu/2012/05/debugging-a-windows-service-project/\" rel=\"noreferrer\">walkthrough</a> with explanations.</p>\n" }, { "answer_id": 12783287, "author": "Matt", "author_id": 1016343, "author_profile": "https://Stackoverflow.com/users/1016343", "pm_score": 6, "selected": false, "text": "\n<p>Sometimes it is important to analyze what's going on <strong>during the start up of the service.</strong> Attaching to the process does not help here, because you are not quick enough to attach the debugger while the service is starting up.</p>\n<hr />\n<p>The short answer is, I am using the following <strong>4 lines of code</strong> to do this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>#if DEBUG\n base.RequestAdditionalTime(600000); // 600*1000ms = 10 minutes timeout\n Debugger.Launch(); // launch and attach debugger\n#endif\n</code></pre>\n<hr />\n<p>These are inserted into the <code>OnStart</code> method of the service as follows:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>protected override void OnStart(string[] args)\n{\n #if DEBUG\n base.RequestAdditionalTime(600000); // 10 minutes timeout for startup\n Debugger.Launch(); // launch and attach debugger\n #endif\n MyInitOnstart(); // my individual initialization code for the service\n // allow the base class to perform any work it needs to do\n base.OnStart(args);\n}\n</code></pre>\n<hr />\n<p>For those who haven't done it before, I have included <strong>detailed hints below</strong>, because you can easily get stuck. The following hints refer to <em>Windows 7x64</em> and <em>Visual Studio 2010 Team Edition</em>, but should be valid for other (newer) environments, too.</p>\n<hr />\n<p><strong>Important:</strong> Deploy the service in <em>&quot;manual&quot; mode</em> (using either the <code>InstallUtil</code> utility from the VS command prompt or run a service installer project you have prepared). Open Visual Studio <strong>before</strong> you start the service and load the solution containing the service's source code - set up additional breakpoints as you require them in Visual Studio - then start the service via the <em>Service Control Panel.</em></p>\n<p>Because of the <code>Debugger.Launch</code> code, this will cause a dialog &quot;An unhandled Microsoft .NET Framework exception occured in <em>Servicename.exe</em>.&quot; to appear. Click <strong><kbd><a href=\"https://i.stack.imgur.com/4j4ua.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4j4ua.jpg\" alt=\"Elevate\" /></a> Yes, debug <em>Servicename.exe</em></kbd></strong> as shown in the screenshot:<br/>\n<img src=\"https://i.stack.imgur.com/raMT9.jpg\" alt=\"FrameworkException\" /></p>\n<hr />\n<p>Afterwards, <strong>Windows UAC</strong> might prompt you to enter admin credentials. Enter them and proceed with <strong><kbd>Yes</kbd></strong>:</p>\n<p><img src=\"https://i.stack.imgur.com/7bsxR.jpg\" alt=\"UACPrompt\" /></p>\n<p>After that, the well known <strong>Visual Studio Just-In-Time Debugger window</strong> appears. It asks you if you want to debug using the delected debugger. <strong>Before you click <kbd>Yes</kbd>,</strong> select that you <strong>don't want to open a new instance</strong> (2nd option) - a new instance would not be helpful here, because the source code wouldn't be displayed. So you select the Visual Studio instance you've opened earlier instead: <br/>\n<img src=\"https://i.stack.imgur.com/pHQTm.jpg\" alt=\"VSDebuggerPrompt\" /></p>\n<p><strong>After you have clicked <kbd>Yes</kbd>,</strong> after a while Visual Studio will show the yellow arrow right in the line where the <code>Debugger.Launch</code> statement is and you are able to debug your code (method <code>MyInitOnStart</code>, which contains your initialization).\n<img src=\"https://i.stack.imgur.com/LXJAC.png\" alt=\"VSDebuggerBreakpoint\" /></p>\n<p><strong>Pressing <kbd>F5</kbd> continues execution immediately,</strong> until the next breakpoint you have prepared is reached.</p>\n<p><strong>Hint:</strong> To keep the service running, select <strong>Debug -&gt; Detach all</strong>. This allows you to run a client communicating with the service after it started up correctly and you're finished debugging the startup code. If you press <strong><kbd>Shift</kbd>+<kbd>F5</kbd></strong> (stop debugging), this will terminate the service. Instead of doing this, you should use the <em>Service Control Panel</em> to stop it.</p>\n<hr />\n<hr />\n<p><strong>Note</strong> that</p>\n<ul>\n<li><p>If you build a <strong>Release,</strong> then the <strong>debug code is automatically removed</strong> and the service runs normally.</p>\n</li>\n<li><p>I am using <strong><code>Debugger.Launch()</code></strong>, which <strong>starts and attaches a debugger</strong>. I have tested <strong><code>Debugger.Break()</code></strong> as well, which <strong>did not work</strong>, because there is no debugger attached on start up of the service yet (causing the <em>&quot;Error 1067: The process terminated unexpectedly.&quot;</em>).</p>\n</li>\n<li><p><strong><code>RequestAdditionalTime</code></strong> sets a longer <strong>timeout for the startup of the service</strong> (it is <strong>not</strong> delaying the code itself, but will immediately continue with the <code>Debugger.Launch</code> statement). Otherwise the default timeout for starting the service is too short and starting the service fails if you don't call <code>base.Onstart(args)</code> quickly enough from the debugger. Practically, a timeout of 10 minutes avoids that you see the message &quot;<em>the service did not respond...&quot;</em> immediately after the debugger is started.</p>\n</li>\n<li><p>Once you get used to it, this method is very easy because it just requires you to <strong>add 4 lines</strong> to an existing service code, allowing you quickly to gain control and debug.</p>\n</li>\n</ul>\n" }, { "answer_id": 17038801, "author": "Misterhex", "author_id": 1610747, "author_profile": "https://Stackoverflow.com/users/1610747", "pm_score": 3, "selected": false, "text": "<p>Use the <a href=\"https://github.com/Topshelf/Topshelf\" rel=\"noreferrer\">TopShelf</a> library.</p>\n\n<p>Create a console application then configure setup in your Main</p>\n\n<pre><code>class Program\n {\n static void Main(string[] args)\n {\n HostFactory.Run(x =&gt;\n {\n\n // setup service start and stop.\n x.Service&lt;Controller&gt;(s =&gt;\n {\n s.ConstructUsing(name =&gt; new Controller());\n s.WhenStarted(controller =&gt; controller.Start());\n s.WhenStopped(controller =&gt; controller.Stop());\n });\n\n // setup recovery here\n x.EnableServiceRecovery(rc =&gt;\n {\n rc.RestartService(delayInMinutes: 0);\n rc.SetResetPeriod(days: 0);\n });\n\n x.RunAsLocalSystem();\n });\n }\n}\n\npublic class Controller\n {\n public void Start()\n {\n\n }\n\n public void Stop()\n {\n\n }\n }\n</code></pre>\n\n<p>To debug your service, just hit F5 in visual studio.</p>\n\n<p>To install service, type in cmd \"console.exe install\"</p>\n\n<p>You can then start and stop service in the windows service manager.</p>\n" }, { "answer_id": 18728886, "author": "Jason Miller", "author_id": 1543423, "author_profile": "https://Stackoverflow.com/users/1543423", "pm_score": 5, "selected": false, "text": "<p>This <a href=\"http://www.youtube.com/watch?v=uM9o8GsO_u4\" rel=\"noreferrer\">YouTube video by Fabio Scopel</a> explains how to debug a Windows service quite nicely... the actual method of doing it starts at 4:45 in the video...</p>\n\n<p>Here is the code explained in the video... in your Program.cs file, add the stuff for the Debug section... </p>\n\n<pre><code>namespace YourNamespace\n{\n static class Program\n {\n /// &lt;summary&gt;\n /// The main entry point for the application.\n /// &lt;/summary&gt;\n static void Main()\n {\n#if DEBUG\n Service1 myService = new Service1();\n myService.OnDebug();\n System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);\n#else\n ServiceBase[] ServicesToRun;\n ServicesToRun = new ServiceBase[]\n {\n new Service1()\n };\n ServiceBase.Run(ServicesToRun);\n#endif\n\n }\n }\n}\n</code></pre>\n\n<p>In your Service1.cs file, add the OnDebug() method...</p>\n\n<pre><code> public Service1()\n {\n InitializeComponent();\n }\n\n public void OnDebug()\n {\n OnStart(null);\n }\n\n protected override void OnStart(string[] args)\n {\n // your code to do something\n }\n\n protected override void OnStop()\n {\n }\n</code></pre>\n\n<blockquote>\n <p>How it works</p>\n</blockquote>\n\n<p>Basically you have to create a <code>public void OnDebug()</code> that calls the <code>OnStart(string[] args)</code> as it's protected and not accessible outside. The <code>void Main()</code> program is added with <code>#if</code> preprocessor with <code>#DEBUG</code>. </p>\n\n<p>Visual Studio defines <code>DEBUG</code> if project is compiled in Debug mode.This will allow the debug section(below) to execute when the condition is true</p>\n\n<pre><code>Service1 myService = new Service1();\nmyService.OnDebug();\nSystem.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);\n</code></pre>\n\n<p>And it will run just like a console application, once things go OK you can change the mode <code>Release</code> and the regular <code>else</code> section will trigger the logic</p>\n" }, { "answer_id": 30337571, "author": "Yang You", "author_id": 9531816, "author_profile": "https://Stackoverflow.com/users/9531816", "pm_score": 1, "selected": false, "text": "<p>For trouble-shooting on existing Windows Service program, use 'Debugger.Break()' as other guys suggested.</p>\n\n<p>For new Windows Service program, I would suggest using James Michael Hare's method <a href=\"http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx\" rel=\"nofollow\">http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx</a> </p>\n" }, { "answer_id": 31533784, "author": "Sandaru", "author_id": 2008334, "author_profile": "https://Stackoverflow.com/users/2008334", "pm_score": 0, "selected": false, "text": "<p>You have two options to do the debugging.</p>\n\n<ol>\n<li>create a log file : Personally i prefer a separate log file like text file rather using the application log or event log.But this will cost you a lot on behalf of time, because its still hard to figure our where the exact error location is</li>\n<li>Convert the application to console application : this will enable you, all the debugging tools which we can use in VS.</li>\n</ol>\n\n<p>Please refer <a href=\"http://sandaruwmp.blogspot.com/2015/07/debug-windows-service-application_21.html\" rel=\"nofollow\">THIS</a> blog post that i created for the topic. </p>\n" }, { "answer_id": 35715389, "author": "wotanii", "author_id": 5132456, "author_profile": "https://Stackoverflow.com/users/5132456", "pm_score": 1, "selected": false, "text": "<p>Just put your debugger launch anywhere and attach Visualstudio on startup</p>\n<pre><code>#if DEBUG\n Debugger.Launch();\n#endif\n</code></pre>\n<p>Also you need to start VS as Administatrator and you need to allow, that a process can automatically be debugged by a different user (as explained <a href=\"http://blogs.msdn.com/b/dsvc/archive/2012/12/30/jit-debugging-using-visual-studio-may-fail-when-trying-to-debug-a-session-0-process-on-windows-8.aspx\" rel=\"nofollow noreferrer\" title=\"here\">here</a>):</p>\n<pre><code>reg add &quot;HKCR\\AppID{E62A7A31-6025-408E-87F6-81AEB0DC9347}&quot; /v AppIDFlags /t REG_DWORD /d 8 /f\n</code></pre>\n" }, { "answer_id": 36979288, "author": "HarpyWar", "author_id": 701779, "author_profile": "https://Stackoverflow.com/users/701779", "pm_score": 2, "selected": false, "text": "<p>Use Windows Service Template C# project to create a new service app <a href=\"https://github.com/HarpyWar/windows-service-template\" rel=\"nofollow\">https://github.com/HarpyWar/windows-service-template</a></p>\n\n<p>There are console/service mode automatically detected, auto installer/deinstaller of your service and several most used features are included.</p>\n" }, { "answer_id": 41464830, "author": "MisterDr", "author_id": 1895206, "author_profile": "https://Stackoverflow.com/users/1895206", "pm_score": 2, "selected": false, "text": "<p>Here is the simple method which I used to test the service, without any additional \"Debug\" methods and with integrated VS Unit Tests.</p>\n\n<pre><code>[TestMethod]\npublic void TestMyService()\n{\n MyService fs = new MyService();\n\n var OnStart = fs.GetType().BaseType.GetMethod(\"OnStart\", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);\n\n OnStart.Invoke(fs, new object[] { null });\n}\n\n// As an extension method\npublic static void Start(this ServiceBase service, List&lt;string&gt; parameters)\n{\n string[] par = parameters == null ? null : parameters.ToArray();\n\n var OnStart = service.GetType().GetMethod(\"OnStart\", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);\n\n OnStart.Invoke(service, new object[] { par });\n}\n</code></pre>\n" }, { "answer_id": 42830685, "author": "Chutipong Roobklom", "author_id": 4896926, "author_profile": "https://Stackoverflow.com/users/4896926", "pm_score": 0, "selected": false, "text": "<p>Just paste</p>\n<pre><code>Debugger.Break();\n</code></pre>\n<p>any where in you code.</p>\n<p>For Example ,</p>\n<pre><code>internal static class Program\n{\n /// &lt;summary&gt;\n /// The main entry point for the application.\n /// &lt;/summary&gt;\n private static void Main()\n {\n Debugger.Break();\n ServiceBase[] ServicesToRun;\n ServicesToRun = new ServiceBase[]\n {\n new Service1()\n };\n ServiceBase.Run(ServicesToRun);\n }\n}\n</code></pre>\n<p>It will hit <code>Debugger.Break();</code> when you run your program.</p>\n" }, { "answer_id": 49274260, "author": "Mansoor", "author_id": 4240382, "author_profile": "https://Stackoverflow.com/users/4240382", "pm_score": 1, "selected": false, "text": "<pre><code>static class Program\n{\n static void Main()\n {\n #if DEBUG\n\n // TODO: Add code to start application here\n\n // //If the mode is in debugging\n // //create a new service instance\n Service1 myService = new Service1();\n\n // //call the start method - this will start the Timer.\n myService.Start();\n\n // //Set the Thread to sleep\n Thread.Sleep(300000);\n\n // //Call the Stop method-this will stop the Timer.\n myService.Stop();\n\n #else\n ServiceBase[] ServicesToRun;\n ServicesToRun = new ServiceBase[] \n { \n new Service1() \n };\n\n ServiceBase.Run(ServicesToRun);\n #endif\n }\n}\n</code></pre>\n" }, { "answer_id": 49314576, "author": "Amey P Naik", "author_id": 3754966, "author_profile": "https://Stackoverflow.com/users/3754966", "pm_score": 0, "selected": false, "text": "<p>The best option is to use the '<strong>System.Diagnostics</strong>' namespace.</p>\n\n<p>Enclose your code in if else block for debug mode and release mode as shown below to switch between debug and release mode in visual studio,</p>\n\n<pre><code>#if DEBUG // for debug mode\n **Debugger.Launch();** //debugger will hit here\n foreach (var job in JobFactory.GetJobs())\n {\n //do something \n }\n\n#else // for release mode\n **Debugger.Launch();** //debugger will hit here\n // write code here to do something in Release mode.\n\n#endif\n</code></pre>\n" }, { "answer_id": 71468251, "author": "singh_v", "author_id": 3243125, "author_profile": "https://Stackoverflow.com/users/3243125", "pm_score": 0, "selected": false, "text": "<p>I was able to debug a windows service easily following this <strong>official documentation from Microsoft</strong> - <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/windows-services/how-to-debug-windows-service-applications#how-to-run-a-windows-service-as-a-console-application\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/framework/windows-services/how-to-debug-windows-service-applications#how-to-run-a-windows-service-as-a-console-application</a>.</p>\n<p>It tells to run the windows service as a console app for debugging.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It's kind of cumbersome and I'm wondering if there is a more straightforward approach.
If I want to quickly debug the service, I just drop in a `Debugger.Break()` in there. When that line is reached, it will drop me back to VS. Don't forget to remove that line when you are done. **UPDATE:** As an alternative to `#if DEBUG` pragmas, you can also use `Conditional("DEBUG_SERVICE")` attribute. ``` [Conditional("DEBUG_SERVICE")] private static void DebugMode() { Debugger.Break(); } ``` On your `OnStart`, just call this method: ``` public override void OnStart() { DebugMode(); /* ... do the rest */ } ``` There, the code will only be enabled during Debug builds. While you're at it, it might be useful to create a separate Build Configuration for service debugging.
125,997
<p>I'm a newbie in C# bu I'm experienced Delphi developer. In Delphi I can use same code for MenuItem and ToolButton using TAction.OnExecute event and I can disable/enable MenuItem and ToolButton together using TAction.OnUpdate event. Is there a similar way to do this in C# without using external libraries? Or more - How C# developers share code between different controls? </p> <hr> <p>Ok, may be I write my question in wrong way. I want to know not witch property to use (I know about Enabled property) but I want to know on witch event I should attach to if I want to enable/disable more than one control. In delphi TAction.OnUpdate event ocurs when Application is idle - is there similar event in C#?</p>
[ { "answer_id": 126008, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 0, "selected": false, "text": "<p>You can enable or disable a control and all its children by setting its <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.enabled.aspx\" rel=\"nofollow noreferrer\">Enabled property</a>.</p>\n" }, { "answer_id": 126315, "author": "sh_kamalh", "author_id": 9794, "author_profile": "https://Stackoverflow.com/users/9794", "pm_score": 0, "selected": false, "text": "<p>You can hook the code for the MenuItem and the ToolButton in the same handler. For example: <br/>\nmenuItem.Click += HandleClick;<br/>\ntoolbarButton.Click += handleClick;<br/>\nThis way clicking both the MenuItem and the Button will execute the same code and provide the same functionality.</p>\n" }, { "answer_id": 127214, "author": "Michael Meadows", "author_id": 7643, "author_profile": "https://Stackoverflow.com/users/7643", "pm_score": 1, "selected": false, "text": "<p>Try the a modification of the command pattern:</p>\n\n<pre><code>public abstract class ToolStripItemCommand\n{\n private bool enabled = true;\n private bool visible = true;\n private readonly List&lt;ToolStripItem&gt; controls;\n\n protected ToolStripItemCommand()\n {\n controls = new List&lt;ToolStripItem&gt;();\n }\n\n public void RegisterControl(ToolStripItem item, string eventName)\n {\n item.Click += delegate { Execute(); };\n controls.Add(item);\n }\n\n public bool Enabled\n {\n get { return enabled; }\n set\n {\n enabled = value;\n foreach (ToolStripItem item in controls)\n item.Enabled = value;\n }\n }\n\n public bool Visible\n {\n get { return visible; }\n set\n {\n visible = value;\n foreach (ToolStripItem item in controls)\n item.Visible = value;\n }\n }\n\n protected abstract void Execute();\n}\n</code></pre>\n\n<p>Your implementations of this command can be stateful in order to support your view's state. This also enables the ability to build \"undo\" into your form. Here's some toy code that consumes this:</p>\n\n<pre><code>private ToolStripItemCommand fooCommand;\n\nprivate void wireUpCommands()\n{\n fooCommand = new HelloWorldCommand();\n fooCommand.RegisterControl(fooToolStripMenuItem, \"Click\");\n fooCommand.RegisterControl(fooToolStripButton, \"Click\"); \n}\n\nprivate void toggleEnabledClicked(object sender, EventArgs e)\n{\n fooCommand.Enabled = !fooCommand.Enabled;\n}\n\nprivate void toggleVisibleClicked(object sender, EventArgs e)\n{\n fooCommand.Visible = !fooCommand.Visible;\n}\n</code></pre>\n\n<p>HelloWorldCommand:</p>\n\n<pre><code>public class HelloWorldCommand : ToolStripItemCommand\n{\n #region Overrides of ControlCommand\n protected override void Execute()\n {\n MessageBox.Show(\"Hello World\");\n }\n #endregion\n}\n</code></pre>\n\n<p>It's unfortunate that Control and ToolStripItem do not share a common interface since they both have \"Enabled\" and \"Visible\" properties. In order to support both types, you would have to composite a command for both, or use reflection. Both solutions infringe on the elegance afforded by simple inheritance.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21540/" ]
I'm a newbie in C# bu I'm experienced Delphi developer. In Delphi I can use same code for MenuItem and ToolButton using TAction.OnExecute event and I can disable/enable MenuItem and ToolButton together using TAction.OnUpdate event. Is there a similar way to do this in C# without using external libraries? Or more - How C# developers share code between different controls? --- Ok, may be I write my question in wrong way. I want to know not witch property to use (I know about Enabled property) but I want to know on witch event I should attach to if I want to enable/disable more than one control. In delphi TAction.OnUpdate event ocurs when Application is idle - is there similar event in C#?
Try the a modification of the command pattern: ``` public abstract class ToolStripItemCommand { private bool enabled = true; private bool visible = true; private readonly List<ToolStripItem> controls; protected ToolStripItemCommand() { controls = new List<ToolStripItem>(); } public void RegisterControl(ToolStripItem item, string eventName) { item.Click += delegate { Execute(); }; controls.Add(item); } public bool Enabled { get { return enabled; } set { enabled = value; foreach (ToolStripItem item in controls) item.Enabled = value; } } public bool Visible { get { return visible; } set { visible = value; foreach (ToolStripItem item in controls) item.Visible = value; } } protected abstract void Execute(); } ``` Your implementations of this command can be stateful in order to support your view's state. This also enables the ability to build "undo" into your form. Here's some toy code that consumes this: ``` private ToolStripItemCommand fooCommand; private void wireUpCommands() { fooCommand = new HelloWorldCommand(); fooCommand.RegisterControl(fooToolStripMenuItem, "Click"); fooCommand.RegisterControl(fooToolStripButton, "Click"); } private void toggleEnabledClicked(object sender, EventArgs e) { fooCommand.Enabled = !fooCommand.Enabled; } private void toggleVisibleClicked(object sender, EventArgs e) { fooCommand.Visible = !fooCommand.Visible; } ``` HelloWorldCommand: ``` public class HelloWorldCommand : ToolStripItemCommand { #region Overrides of ControlCommand protected override void Execute() { MessageBox.Show("Hello World"); } #endregion } ``` It's unfortunate that Control and ToolStripItem do not share a common interface since they both have "Enabled" and "Visible" properties. In order to support both types, you would have to composite a command for both, or use reflection. Both solutions infringe on the elegance afforded by simple inheritance.
126,005
<p>Specifically I have a PHP command-line script that at a certain point requires input from the user. I would like to be able to execute an external editor (such as vi), and wait for the editor to finish execution before resuming the script.</p> <p>My basic idea was to use a temporary file to do the editing in, and to retrieve the contents of the file afterwards. Something along the lines of:</p> <pre><code>$filename = '/tmp/script_' . time() . '.tmp'; get_user_input ($filename); $input = file_get_contents ($filename); unlink ($filename); </code></pre> <p>I suspect that this isn't possible from a PHP command-line script, however I'm hoping that there's some sort of shell scripting trick that can be employed to achieve the same effect.</p> <p>Suggestions for how this can be achieved in other scripting languages are also more than welcome.</p>
[ { "answer_id": 126031, "author": "lms", "author_id": 21359, "author_profile": "https://Stackoverflow.com/users/21359", "pm_score": 0, "selected": false, "text": "<pre><code>system('vi');\n</code></pre>\n\n<p><a href=\"http://www.php.net/system\" rel=\"nofollow noreferrer\">http://www.php.net/system</a></p>\n" }, { "answer_id": 126037, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 2, "selected": false, "text": "<p>I just tried this and it works fine in windows, so you can probably replicate with vi or whatever app you want on Linux.</p>\n\n<p>The key is that <code>exec()</code> hangs the php process while notepad (in this case) is running.</p>\n\n<pre><code>&lt;?php\n\nexec('notepad c:\\test'); \necho file_get_contents('c:\\test');\n\n?&gt;\n\n$ php -r test.php\n</code></pre>\n\n<p>Edit: As your attempt shows and bstark pointed out, my notepad test fires up a new window so all is fine, but any editor that runs in console mode fails because it has no terminal to attach to.</p>\n\n<p>That being said, I tried on a Linux box with <code>exec('nano test'); echo file_get_contents('test');</code> and it doesn't fail as badly as vi, it just runs without displaying anything. I could type some stuff, press \"ctrl-X, y\" to close and save the file, and then the php script continued and displayed what I had written. Anyway.. I found the proper solution, so new answer coming in.</p>\n" }, { "answer_id": 126484, "author": "bstark", "author_id": 4056, "author_profile": "https://Stackoverflow.com/users/4056", "pm_score": 0, "selected": false, "text": "<p>I don't know if it's at all possible to connect vi to the terminal php is running on, but the quick and easy solution is not to use a screen editor on the same terminal. </p>\n\n<p>You can either use a line editor such as ed (you probably don't want that) or open a new window, like system(\"xterm -e vi\") (replace xterm with the name of your terminal app).</p>\n\n<p>Edited to add: In perl, system(\"vi\") just works, because perl doesn't do the kind of fancy pipelining/buffering php does.</p>\n" }, { "answer_id": 126648, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 0, "selected": false, "text": "<p>So it seems your idea of writing a file lead us to try crazy things while there is an easy solution :)</p>\n\n<pre><code>&lt;?php\n\n$out = fopen('php://stdout', 'w+');\n$in = fopen('php://stdin', 'r+');\n\nfwrite($out, \"foo?\\n\");\n$var = fread($in, 1024);\necho strtoupper($var);\n</code></pre>\n\n<p>The fread() call will hang the php process until it receives something (1024 bytes or end of line I think), producing this :</p>\n\n<pre><code>$ php test.php\nfoo?\nbar &lt;= my input\nBAR\n</code></pre>\n" }, { "answer_id": 130049, "author": "Ole Helgesen", "author_id": 21892, "author_profile": "https://Stackoverflow.com/users/21892", "pm_score": 4, "selected": true, "text": "<p>You can redirect the editor's output to the terminal: </p>\n\n<pre><code>system(\"vim &gt; `tty`\");\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10942/" ]
Specifically I have a PHP command-line script that at a certain point requires input from the user. I would like to be able to execute an external editor (such as vi), and wait for the editor to finish execution before resuming the script. My basic idea was to use a temporary file to do the editing in, and to retrieve the contents of the file afterwards. Something along the lines of: ``` $filename = '/tmp/script_' . time() . '.tmp'; get_user_input ($filename); $input = file_get_contents ($filename); unlink ($filename); ``` I suspect that this isn't possible from a PHP command-line script, however I'm hoping that there's some sort of shell scripting trick that can be employed to achieve the same effect. Suggestions for how this can be achieved in other scripting languages are also more than welcome.
You can redirect the editor's output to the terminal: ``` system("vim > `tty`"); ```
126,028
<p>We have a 3D viewer that uses OpenGL, but our clients sometimes complain about it "not working". We suspect that most of these issues stem from them trying to use, what is in effect a modern 3d realtime game, on a businiss laptop computer.</p> <p><strong>How can we, in the windows msi installer we use, check for support for openGL?</strong></p> <p>And as a side note, if you can answer "List of OpenGL supported graphic cards?", that would also be greate. Strange that google doesnt help here..</p>
[ { "answer_id": 126082, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 1, "selected": false, "text": "<p>OpenGL is part of Windows since Windows NT or Win95. It's unlikely that you'll ever find a windows system where OpenGL is not pre-installed (e.g. Windows 3.1)</p>\n\n<p>However, your application may need a more recent version of OpenGL than the default OpenGL 1.1 that comes with very old versions of windows. You can check that from your program. I don't know of any way how to find that from msi.</p>\n\n<p>Note that the OpenGL gets updated via the graphic drivers, not by installing a service pack or so.</p>\n\n<p>Regarding OpenGL enabled graphic cards: All have OpenGL. Even if the customer uses a ISA ET4000 graphic card from the stone ages he at least has OpenGL 1.1 via software-rendering.</p>\n" }, { "answer_id": 126553, "author": "NeARAZ", "author_id": 6799, "author_profile": "https://Stackoverflow.com/users/6799", "pm_score": 4, "selected": true, "text": "<p>Depends on what the customers mean by \"not working\". It could be one of:</p>\n\n<ol>\n<li>it does not install/launch at all, because of lack of some OpenGL support.</li>\n<li>it launches, but crashes further on.</li>\n<li>it launches, does not crash, but rendering is corrupt.</li>\n<li>it launches and renders everything correctly, but performance is abysmal.</li>\n</ol>\n\n<p>All Windows versions (since 95) have OpenGL support built-in. So it's unlikely to cause situation 1) above, unless you application <em>requires</em> higher OpenGL version.</p>\n\n<p>However, that default OpenGL implementation is OpenGL 1.1 with <em>software rendering</em>. If user did not manually install drivers that have OpenGL support (any driver downloaded from NVIDIA/AMD/Intel site will have OpenGL), they will default to this slow and old implementation. This is quite likely to cause situations 3) and 4) above.</p>\n\n<p>Even if OpenGL is available, on Windows OpenGL drivers are not very robust, to say mildly. Various bugs in the drivers are very likely to cause situation 2), where doing something valid causes a crash in the driver.</p>\n\n<p>Here's a C++/WinAPI code snippet that creates a dummy OpenGL context and retrieves info (GL version, graphics card name, extensions etc.):</p>\n\n<pre><code>// setup minimal required GL\nHWND wnd = CreateWindow(\n \"STATIC\",\n \"GL\",\n WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,\n 0, 0, 16, 16,\n NULL, NULL,\n AfxGetInstanceHandle(), NULL );\nHDC dc = GetDC( wnd );\n\nPIXELFORMATDESCRIPTOR pfd = {\n sizeof(PIXELFORMATDESCRIPTOR), 1,\n PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL,\n PFD_TYPE_RGBA, 32,\n 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0,\n 16, 0,\n 0, PFD_MAIN_PLANE, 0, 0, 0, 0\n};\n\nint fmt = ChoosePixelFormat( dc, &amp;pfd );\nSetPixelFormat( dc, fmt, &amp;pfd );\n\nHGLRC rc = wglCreateContext( dc );\nwglMakeCurrent( dc, rc );\n\n// get information\nconst char* vendor = (const char*)glGetString(GL_VENDOR);\nconst char* renderer = (const char*)glGetString(GL_RENDERER);\nconst char* extensions = (const char*)glGetString(GL_EXTENSIONS);\nconst char* version = (const char*)glGetString(GL_VERSION);\n\n// DO SOMETHING WITH THOSE STRINGS HERE!\n\n// cleanup\nwglDeleteContext( rc );\nReleaseDC( wnd, dc );\nDestroyWindow( wnd );\n</code></pre>\n\n<p>You could somehow plug that code into your installer or application and at least check GL version for being 1.1; this will detect \"driver is not installed\" situation. To work around actual OpenGL driver bugs, well, you have to figure them out and work around them. Lots of work.</p>\n" }, { "answer_id": 137959, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 1, "selected": false, "text": "<p>Windows ships with support for OpenGL 1.1 (as others have noted here). So, the problems your users are facing is due to extensions which have been added to OpenGL after 1.1. If you are using the GLEW library, it is pretty easy to check support for all the extensions you are using programmatically. Here's how to check for support of Occlusion Query:</p>\n\n<pre><code>if (GLEW_OK != glewInit())\n{\n // GLEW failed!\n exit(1);\n}\n\n// Check if required extensions are supported\nif (!GLEW_ARB_occlusion_query)\n cout &lt;&lt; \"Occlusion query not supported\" &lt;&lt; endl;\n</code></pre>\n\n<p>For more on using GLEW, see <a href=\"https://stackoverflow.com/questions/17370/using-glew-to-use-opengl-extensions-under-windows\">here</a>.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
We have a 3D viewer that uses OpenGL, but our clients sometimes complain about it "not working". We suspect that most of these issues stem from them trying to use, what is in effect a modern 3d realtime game, on a businiss laptop computer. **How can we, in the windows msi installer we use, check for support for openGL?** And as a side note, if you can answer "List of OpenGL supported graphic cards?", that would also be greate. Strange that google doesnt help here..
Depends on what the customers mean by "not working". It could be one of: 1. it does not install/launch at all, because of lack of some OpenGL support. 2. it launches, but crashes further on. 3. it launches, does not crash, but rendering is corrupt. 4. it launches and renders everything correctly, but performance is abysmal. All Windows versions (since 95) have OpenGL support built-in. So it's unlikely to cause situation 1) above, unless you application *requires* higher OpenGL version. However, that default OpenGL implementation is OpenGL 1.1 with *software rendering*. If user did not manually install drivers that have OpenGL support (any driver downloaded from NVIDIA/AMD/Intel site will have OpenGL), they will default to this slow and old implementation. This is quite likely to cause situations 3) and 4) above. Even if OpenGL is available, on Windows OpenGL drivers are not very robust, to say mildly. Various bugs in the drivers are very likely to cause situation 2), where doing something valid causes a crash in the driver. Here's a C++/WinAPI code snippet that creates a dummy OpenGL context and retrieves info (GL version, graphics card name, extensions etc.): ``` // setup minimal required GL HWND wnd = CreateWindow( "STATIC", "GL", WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, 16, 16, NULL, NULL, AfxGetInstanceHandle(), NULL ); HDC dc = GetDC( wnd ); PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int fmt = ChoosePixelFormat( dc, &pfd ); SetPixelFormat( dc, fmt, &pfd ); HGLRC rc = wglCreateContext( dc ); wglMakeCurrent( dc, rc ); // get information const char* vendor = (const char*)glGetString(GL_VENDOR); const char* renderer = (const char*)glGetString(GL_RENDERER); const char* extensions = (const char*)glGetString(GL_EXTENSIONS); const char* version = (const char*)glGetString(GL_VERSION); // DO SOMETHING WITH THOSE STRINGS HERE! // cleanup wglDeleteContext( rc ); ReleaseDC( wnd, dc ); DestroyWindow( wnd ); ``` You could somehow plug that code into your installer or application and at least check GL version for being 1.1; this will detect "driver is not installed" situation. To work around actual OpenGL driver bugs, well, you have to figure them out and work around them. Lots of work.
126,036
<p>Is there a way to know and output the stack size needed by a function at compile time in C ? Here is what I would like to know :</p> <p>Let's take some function :</p> <pre><code>void foo(int a) { char c[5]; char * s; //do something return; } </code></pre> <p>When compiling this function, I would like to know how much stack space it will consume whent it is called. This might be useful to detect the on stack declaration of a structure hiding a big buffer.</p> <p>I am looking for something that would print something like this :</p> <p>file foo.c : function foo stack usage is <code>n</code> bytes</p> <p>Is there a way not to look at the generated assembly to know that ? Or a limit that can be set for the compiler ?</p> <p>Update : I am not trying to avoid runtime stack overflow for a given process, I am looking for a way to find before runtime, if a function stack usage, as determined by the compiler, is available as an output of the compilation process.</p> <p>Let's put it another way : is it possible to know the size of all the objects local to a function ? I guess compiler optimization won't be my friend, because some variable will disappear but a superior limit is fine.</p>
[ { "answer_id": 126047, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>Only the compiler would really know, since it is the guy that puts all your stuff together. You'd have to look at the generated assembly and see how much space is reserved in the preamble, but that doesn't really account for things like <code>alloca</code> which do their thing at runtime.</p>\n" }, { "answer_id": 126252, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 0, "selected": false, "text": "<p>Not in general. The Halting Problem in theoretical computer science suggests that you can't even predict if a general program halts on a given input. Calculating the stack used for a program run in general would be even more complicated. So: no. Maybe in special cases.</p>\n\n<p>Let's say you have a recursive function whose recursion level depends on the input which can be of arbitrary length and you are already out of luck.</p>\n" }, { "answer_id": 126439, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 2, "selected": false, "text": "<p>I don't see why a static code analysis couldn't give a good enough figure for this.</p>\n\n<p>It's trivial to find all the local variables in any given function, and the size for each variable can be found either through the C standard (for built in types) or by calculating it (for complex types like structs and unions). </p>\n\n<p>Sure, the answer can't be guaranteed to be 100% accurate, since the compiler can do various sorts of optimizations like padding, putting variables in registers or completely remove unnecessary variables. But any answer it gives should be a good estimate at least.</p>\n\n<p>I did a quick google search and found <a href=\"http://www.absint.com/stackanalyzer/\" rel=\"nofollow noreferrer\">StackAnalyzer</a> but my guess is that other static code analysis tools have similar capabilities.</p>\n\n<p>If you want a 100% accurate figure, then you'd have to look at the output from the compiler or check it during runtime (like Ralph suggested in <a href=\"https://stackoverflow.com/questions/126036/checking-stack-usage-at-compile-time#126246\">his reply</a>)</p>\n" }, { "answer_id": 126490, "author": "shodanex", "author_id": 11589, "author_profile": "https://Stackoverflow.com/users/11589", "pm_score": 3, "selected": false, "text": "<p>StackAnlyser seems to examinate the executable code itself plus some debugging info.\nWhat is described by <a href=\"https://stackoverflow.com/questions/126036/checking-stack-usage-at-compile-time#126439\">this reply</a>, is what I am looking for, stack analyzer looks like overkill to me.</p>\n\n<p>Something similar to what exists for ADA would be fine. Look at this manual page from the gnat manual :</p>\n\n<p>22.2 Static Stack Usage Analysis</p>\n\n<p>A unit compiled with -fstack-usage will generate an extra file that specifies the maximum amount of stack used, on a per-function basis. The file has the same basename as the target object file with a .su extension. Each line of this file is made up of three fields:</p>\n\n<pre><code>* The name of the function.\n* A number of bytes.\n* One or more qualifiers: static, dynamic, bounded. \n</code></pre>\n\n<p>The second field corresponds to the size of the known part of the function frame.</p>\n\n<p>The qualifier static means that the function frame size is purely static. It usually means that all local variables have a static size. In this case, the second field is a reliable measure of the function stack utilization.</p>\n\n<p>The qualifier dynamic means that the function frame size is not static. It happens mainly when some local variables have a dynamic size. When this qualifier appears alone, the second field is not a reliable measure of the function stack analysis. When it is qualified with bounded, it means that the second field is a reliable maximum of the function stack utilization. </p>\n" }, { "answer_id": 126505, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 1, "selected": false, "text": "<p>Assuming you're on an embedded platform, you might find that your toolchain has a go at this. Good commercial embedded compilers (like, for example the Arm/Keil compiler) often produce reports of stack usage. </p>\n\n<p>Of course, interrupts and recursion are usually a bit beyond them, but it gives you a rough idea if someone has committed some terrible screw-up with a multi megabyte buffer on the stack somewhere.</p>\n" }, { "answer_id": 126640, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 1, "selected": false, "text": "<p>Not exactly \"compile time\", but I would do this as a post-build step:</p>\n\n<ul>\n<li>let the linker create a map file for you</li>\n<li>for each function in the map file read the corresponding part of the executable, and analyse the function prologue.</li>\n</ul>\n\n<p>This is similar to what StackAnalyzer does, but a lot simpler. I think analysing the executable or the disassembly is the easiest way you can get to the compiler output. While the compiler knows those things internally, I am afraid you will not be able to get it from it (you might ask the compiler vendor to implement the functionality, or if using open source compiler, you could do it yourself or let someone do it for you).</p>\n\n<p>To implement this you need to:</p>\n\n<ul>\n<li>be able to parse map file</li>\n<li>understand format of the executable</li>\n<li>know what a function prologue can look like and be able to \"decode\" it</li>\n</ul>\n\n<p>How easy or difficult this would be depends on your target platform. (Embedded? Which CPU architecture? What compiler?)</p>\n\n<p>All of this definitely can be done in x86/Win32, but if you never did anything like this and have to create all of this from the scratch, it can take a few days before you are done and have something working.</p>\n" }, { "answer_id": 434848, "author": "Blaisorblade", "author_id": 53974, "author_profile": "https://Stackoverflow.com/users/53974", "pm_score": 5, "selected": true, "text": "<p>Linux kernel code runs on a 4K stack on x86. Hence they care. What they use to check that, is a perl script they wrote, which you may find as scripts/checkstack.pl in a recent kernel tarball (2.6.25 has got it). It runs on the output of objdump, usage documentation is in the initial comment.</p>\n\n<p>I think I already used it for user-space binaries ages ago, and if you know a bit of perl programming, it's easy to fix that if it is broken.</p>\n\n<p>Anyway, what it basically does is to look automatically at GCC's output. And the fact that kernel hackers wrote such a tool means that there is no static way to do it with GCC (or maybe that it was added very recently, but I doubt so).</p>\n\n<p>Btw, with objdump from the mingw project and ActivePerl, or with Cygwin, you should be able to do that also on Windows and also on binaries obtained with other compilers.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11589/" ]
Is there a way to know and output the stack size needed by a function at compile time in C ? Here is what I would like to know : Let's take some function : ``` void foo(int a) { char c[5]; char * s; //do something return; } ``` When compiling this function, I would like to know how much stack space it will consume whent it is called. This might be useful to detect the on stack declaration of a structure hiding a big buffer. I am looking for something that would print something like this : file foo.c : function foo stack usage is `n` bytes Is there a way not to look at the generated assembly to know that ? Or a limit that can be set for the compiler ? Update : I am not trying to avoid runtime stack overflow for a given process, I am looking for a way to find before runtime, if a function stack usage, as determined by the compiler, is available as an output of the compilation process. Let's put it another way : is it possible to know the size of all the objects local to a function ? I guess compiler optimization won't be my friend, because some variable will disappear but a superior limit is fine.
Linux kernel code runs on a 4K stack on x86. Hence they care. What they use to check that, is a perl script they wrote, which you may find as scripts/checkstack.pl in a recent kernel tarball (2.6.25 has got it). It runs on the output of objdump, usage documentation is in the initial comment. I think I already used it for user-space binaries ages ago, and if you know a bit of perl programming, it's easy to fix that if it is broken. Anyway, what it basically does is to look automatically at GCC's output. And the fact that kernel hackers wrote such a tool means that there is no static way to do it with GCC (or maybe that it was added very recently, but I doubt so). Btw, with objdump from the mingw project and ActivePerl, or with Cygwin, you should be able to do that also on Windows and also on binaries obtained with other compilers.
126,048
<p>I have a problem where a Web Application needs to (after interaction from the user via Javascript)<br> &nbsp;&nbsp; 1) open a Windows Forms Application<br> &nbsp;&nbsp; 2) send a parameter to the app (e.g. an ID)</p> <p>Correspondingly, the Windows Forms Application should be able to<br> &nbsp;&nbsp; 1) send parameters back to the Web Application (updating the URL is ok)<br> &nbsp;&nbsp; 2) open the Web App in a new brower, if it does not exist<br> If many browser windows are open it's important that the correct one is updated.</p> <p>Windows Forms Application is in ASP.NET<br> Browser is IE6+<br> The applications are controlled and internal for a specific organisation so it's not a question of launching a custom app. </p> <p>Question A) Is this possible?<br> Question B) How do I send parameters to an open Windows Forms Application from a Web App?<br> Question C) If updating the Web App, how do I make sure the right browser is targeted? </p>
[ { "answer_id": 126057, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>No I don't think it's possible.<br>\nThink of viruses/trojans/spyware. If it were possible to launch an application from a mere HTML page, it would be very easy to install malware.<br>\nBrowsers are designed to prevent you from doing that.</p>\n" }, { "answer_id": 126059, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>You could use clickonce to deploy and start the forms app - this should take care of sending the parameter to the app.</p>\n" }, { "answer_id": 126067, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 3, "selected": false, "text": "<p>What you're asking for is possible but seems awkward.</p>\n\n<p>Trying to call an application from a web page is not something you could do due to security considerations. You could however make a desktop application which would be associated with a certain type of files and then use content-type on the web page to make sure that your app is called when a URL with this type is opened. It would be similar to the way MS Office handles .doc or .xls documents or the Media Player opens the .mp3 or .wmv files.</p>\n\n<p>The second part (opening a particular web page from your application) is easier.\nAs you should know the address of your web page create a URL string with the parameters you want and open it in default browser (there are plenty of examples on how to do that, a sample is below).</p>\n\n<pre><code>System.Diagnostics.Process.Start(\"http://example.com?key=value\");\n</code></pre>\n\n<p>If you want to update the page in the already opened browser or use a browser of your choice (i.e. always IE6 instead of Opera or Chrome) then you'll have to do some homework but it's still quite easy.</p>\n" }, { "answer_id": 126092, "author": "user17060", "author_id": 17060, "author_profile": "https://Stackoverflow.com/users/17060", "pm_score": 1, "selected": false, "text": "<p>Check out \n<a href=\"http://msdn.microsoft.com/en-us/library/8c6yea83(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/8c6yea83(VS.85).aspx</a></p>\n\n<p>Using VBScript in your Web Page you can call an open Windows Forms application and send keys to it. </p>\n\n<p>This only works on IE though and you need to adjust the security settings to allow ActiveX. </p>\n" }, { "answer_id": 127969, "author": "Dejan", "author_id": 11471, "author_profile": "https://Stackoverflow.com/users/11471", "pm_score": 1, "selected": false, "text": "<p>Have a look into \"registered protocols\" (for example <a href=\"http://kb.mozillazine.org/Register_protocol\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://en.wikipedia.org/wiki/Protocol_(computing)\" rel=\"nofollow noreferrer\">here</a>). I know Skype does this to make outward phone calls from a web page. But probably some changes will be needed in the win application to intercept the parameters from the url.<br>\nI haven't tried this but it should be possible</p>\n" }, { "answer_id": 136740, "author": "Kevin Lamb", "author_id": 3149, "author_profile": "https://Stackoverflow.com/users/3149", "pm_score": 0, "selected": false, "text": "<p>While this may not perfectly fit with your application, what about using a web service and the form?</p>\n\n<p>Also, you can pass parameters to ensure IE6, not Firefox opens.</p>\n\n<pre><code>System.Diagnostics.Process.Start(\"c:\\ie6\\ie6.exe http://www.example.com/mypage\");\n</code></pre>\n" }, { "answer_id": 152839, "author": "Bruce", "author_id": 21552, "author_profile": "https://Stackoverflow.com/users/21552", "pm_score": 0, "selected": false, "text": "<p>Ok, so I actually found a clue to the web -> winform part.</p>\n\n<p>The following code was handed to me from an web application that sends a parameter to a winform app. I assume this solution has some security factors in play (such as allowing running VBScript (and ActiveX?) in the webpage. That's ok for me though.</p>\n\n<p>The code:</p>\n\n<p><code>&lt;script type=\"text/vbscript\" language=\"vbscript\"&gt;<br>\n &lt;!--<br>\n Function OpenWinformApp(chSocialSecurityNumber)<br>\n Dim oWinformAppWebStart<br>\n Set oWinformAppWebStart = CreateObject(\"WinformAppWebStart.CWinformAppWebStart\")<br>\n oWinformAppWebStart.OpenPersonForm CStr(chSocialSecurityNumber)<br>\n End Function<br>\n --&gt;<br>\n &lt;/script&gt;</code></p>\n" }, { "answer_id": 10289225, "author": "Zuuum", "author_id": 452198, "author_profile": "https://Stackoverflow.com/users/452198", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://pokein.com\" rel=\"nofollow\">PokeIn</a> library connects you desktop application to your web application in real time/per user. Moreover, due to its reverse ajax state management, you could consider both of your applications as one.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21552/" ]
I have a problem where a Web Application needs to (after interaction from the user via Javascript)    1) open a Windows Forms Application    2) send a parameter to the app (e.g. an ID) Correspondingly, the Windows Forms Application should be able to    1) send parameters back to the Web Application (updating the URL is ok)    2) open the Web App in a new brower, if it does not exist If many browser windows are open it's important that the correct one is updated. Windows Forms Application is in ASP.NET Browser is IE6+ The applications are controlled and internal for a specific organisation so it's not a question of launching a custom app. Question A) Is this possible? Question B) How do I send parameters to an open Windows Forms Application from a Web App? Question C) If updating the Web App, how do I make sure the right browser is targeted?
What you're asking for is possible but seems awkward. Trying to call an application from a web page is not something you could do due to security considerations. You could however make a desktop application which would be associated with a certain type of files and then use content-type on the web page to make sure that your app is called when a URL with this type is opened. It would be similar to the way MS Office handles .doc or .xls documents or the Media Player opens the .mp3 or .wmv files. The second part (opening a particular web page from your application) is easier. As you should know the address of your web page create a URL string with the parameters you want and open it in default browser (there are plenty of examples on how to do that, a sample is below). ``` System.Diagnostics.Process.Start("http://example.com?key=value"); ``` If you want to update the page in the already opened browser or use a browser of your choice (i.e. always IE6 instead of Opera or Chrome) then you'll have to do some homework but it's still quite easy.
126,070
<p>I have an email subject of the form:</p> <pre><code>=?utf-8?B?T3.....?= </code></pre> <p>The body of the email is utf-8 base64 encoded - and has decoded fine. I am current using Perl's Email::MIME module to decode the email.</p> <p>What is the meaning of the =?utf-8 delimiter and how do I extract information from this string?</p>
[ { "answer_id": 126087, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 6, "selected": true, "text": "<p>The <a href=\"http://en.wikipedia.org/wiki/MIME#Encoded-Word\" rel=\"noreferrer\"><code>encoded-word</code></a> tokens (as per <a href=\"http://www.faqs.org/rfcs/rfc2047.html\" rel=\"noreferrer\">RFC 2047</a>) can occur in values of some headers. They are parsed as follows:</p>\n\n\n\n<pre><code>=?&lt;charset&gt;?&lt;encoding&gt;?&lt;data&gt;?=\n</code></pre>\n\n<p>Charset is UTF-8 in this case, the encoding is <code>B</code> which means base64 (the other option is <code>Q</code> which means Quoted Printable).</p>\n\n<p>To read it, first decode the base64, then treat it as UTF-8 characters.</p>\n\n<p>Also read the various Internet Mail RFCs for more detail, mainly <a href=\"http://www.faqs.org/rfcs/rfc2047.html\" rel=\"noreferrer\">RFC 2047</a>.</p>\n\n<p>Since you are using Perl, <a href=\"https://metacpan.org/pod/Encode::MIME::Header\" rel=\"noreferrer\">Encode::MIME::Header</a> could be of use:</p>\n\n<blockquote>\n <p>SYNOPSIS</p>\n\n<pre><code>use Encode qw/encode decode/;\n$utf8 = decode('MIME-Header', $header);\n$header = encode('MIME-Header', $utf8);\n</code></pre>\n \n <p>ABSTRACT</p>\n \n <p>This module implements RFC 2047 Mime\n Header Encoding. There are 3 variant\n encoding names; MIME-Header, MIME-B\n and MIME-Q. The difference is\n described below</p>\n \n \n\n<pre><code> decode() encode() \nMIME-Header Both B and Q =?UTF-8?B?....?= \nMIME-B B only; Q croaks =?UTF-8?B?....?= \nMIME-Q Q only; B croaks =?UTF-8?Q?....?=\n</code></pre>\n</blockquote>\n" }, { "answer_id": 126098, "author": "marijne", "author_id": 7038, "author_profile": "https://Stackoverflow.com/users/7038", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"http://www.faqs.org/rfcs/rfc2047.html\" rel=\"nofollow noreferrer\">RFC2047</a>. The 'B' means that the part between the last two '?'s is base64-encoded. The 'utf-8' naturally means that the decoded data should be interpreted as UTF-8.</p>\n" }, { "answer_id": 126099, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 1, "selected": false, "text": "<p>This is a standard extension for charset labeling of headers, specified in <a href=\"http://www.rfc-archive.org/getrfc.php?rfc=2047\" rel=\"nofollow noreferrer\">RFC2047</a>.</p>\n" }, { "answer_id": 126103, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 4, "selected": false, "text": "<p>I think that the Encode module handles that with the <code>MIME-Header</code> encoding, so try this:</p>\n\n<pre><code>use Encode qw(decode);\nmy $decoded = decode(\"MIME-Header\", $encoded);\n</code></pre>\n" }, { "answer_id": 21923828, "author": "Philonious", "author_id": 3335339, "author_profile": "https://Stackoverflow.com/users/3335339", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://metacpan.org/pod/MIME::Words\" rel=\"nofollow\">MIME::Words</a> from MIME-tools work well too for this. I ran into some issue with Encode and found MIME::Words succeeded on some strings where Encode did not.</p>\n\n<pre><code>use MIME::Words qw(:all);\n$decoded = decode_mimewords(\n 'To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= &lt;[email protected]&gt;',\n);\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21553/" ]
I have an email subject of the form: ``` =?utf-8?B?T3.....?= ``` The body of the email is utf-8 base64 encoded - and has decoded fine. I am current using Perl's Email::MIME module to decode the email. What is the meaning of the =?utf-8 delimiter and how do I extract information from this string?
The [`encoded-word`](http://en.wikipedia.org/wiki/MIME#Encoded-Word) tokens (as per [RFC 2047](http://www.faqs.org/rfcs/rfc2047.html)) can occur in values of some headers. They are parsed as follows: ``` =?<charset>?<encoding>?<data>?= ``` Charset is UTF-8 in this case, the encoding is `B` which means base64 (the other option is `Q` which means Quoted Printable). To read it, first decode the base64, then treat it as UTF-8 characters. Also read the various Internet Mail RFCs for more detail, mainly [RFC 2047](http://www.faqs.org/rfcs/rfc2047.html). Since you are using Perl, [Encode::MIME::Header](https://metacpan.org/pod/Encode::MIME::Header) could be of use: > > SYNOPSIS > > > > ``` > use Encode qw/encode decode/; > $utf8 = decode('MIME-Header', $header); > $header = encode('MIME-Header', $utf8); > > ``` > > ABSTRACT > > > This module implements RFC 2047 Mime > Header Encoding. There are 3 variant > encoding names; MIME-Header, MIME-B > and MIME-Q. The difference is > described below > > > > ``` > decode() encode() > MIME-Header Both B and Q =?UTF-8?B?....?= > MIME-B B only; Q croaks =?UTF-8?B?....?= > MIME-Q Q only; B croaks =?UTF-8?Q?....?= > > ``` > >
126,094
<p>Considering that the debug data file is available (PDB) and by using either <strong>System.Reflection</strong> or another similar framework such as <strong>Mono.Cecil</strong>, how to retrieve programmatically the source file name and the line number where a type or a member of a type is declared.</p> <p>For example, let's say you have compiled this file into an assembly:</p> <p><em>C:\MyProject\Foo.cs</em></p> <pre><code>1: public class Foo 2: { 3: public string SayHello() 4: { 5: return "Hello"; 6: } 7: } </code></pre> <p>How to do something like:</p> <pre><code>MethodInfo methodInfo = typeof(Foo).GetMethod("SayHello"); string sourceFileName = methodInfo.GetSourceFile(); // ?? Does not exist! int sourceLineNumber = methodInfo.GetLineNumber(); // ?? Does not exist! </code></pre> <p>sourceFileName would contain "C:\MyProject\Foo.cs" and sourceLineNumber be equal to 3.</p> <p><em>Update: <code>System.Diagnostics.StackFrame</code> is indeed able to get that information, but only in the scope of current executing call stack. It means that the method must be invoked first. I would like to get the same info, but without invoking the type member.</em></p>
[ { "answer_id": 126132, "author": "Richard", "author_id": 20038, "author_profile": "https://Stackoverflow.com/users/20038", "pm_score": -1, "selected": false, "text": "<p>you might find some help with these links:</p>\n\n<p><a href=\"http://www.busycode.com/news/index.php/article/news-about-adobe-flex/2008-09-09/1570.html\" rel=\"nofollow noreferrer\">Getting file and line numbers without deploying the PDB files</a>\n also found this following <a href=\"http://bytes.com/forum/thread348765.html\" rel=\"nofollow noreferrer\">post</a> </p>\n\n<p>\"Hi Mark,</p>\n\n<p>The following will give you the line number of your code (in the\nsource file):</p>\n\n<pre><code>Dim CurrentStack As System.Diagnostics.StackTrace\nMsgBox (CurrentStack.GetFrame(0).GetFileLineNumber)\n</code></pre>\n\n<p>In case you're interested, you can find out about the routine that you're\nin, as well as all its callers.</p>\n\n<pre><code>Public Function MeAndMyCaller As String\n Dim CurrentStack As New System.Diagnostics.StackTrace\n Dim Myself As String = CurrentStack.GetFrame(0).GetMethod.Name\n Dim MyCaller As String = CurrentStack.GetFrame(1).GetMethod.Name\n Return \"In \" &amp; Myself &amp; vbCrLf &amp; \"Called by \" &amp; MyCaller\nEnd Function\n</code></pre>\n\n<p>This can be very handy if you want a generalised error routine because it\ncan get the name of the caller (which would be where the error occurred).</p>\n\n<p>Regards,\nFergus\nMVP [Windows Start button, Shutdown dialogue]\n\"</p>\n" }, { "answer_id": 16295971, "author": "illegal-immigrant", "author_id": 407443, "author_profile": "https://Stackoverflow.com/users/407443", "pm_score": 3, "selected": false, "text": "<p>Up to date method:</p>\n\n<pre><code>private static void Log(string text,\n [CallerFilePath] string file = \"\",\n [CallerMemberName] string member = \"\",\n [CallerLineNumber] int line = 0)\n{\n Console.WriteLine(\"{0}_{1}({2}): {3}\", Path.GetFileName(file), member, line, text);\n}\n</code></pre>\n\n<p>New <code>Framework API</code> which populates arguments (marked with special attributes) at runtime,\nsee more in <a href=\"https://stackoverflow.com/questions/6369184/print-the-source-filename-and-linenumber-in-c-sharp/16295702#16295702\">my answer to this SO question</a></p>\n" }, { "answer_id": 26431841, "author": "Harald Hoyer", "author_id": 805390, "author_profile": "https://Stackoverflow.com/users/805390", "pm_score": 2, "selected": false, "text": "<p>Using one of the methods explained above, inside the constructor of an attribute, you can provide the source location of everything, that may have an attribute - for instance a class. See the following attribute class:</p>\n\n<pre><code>sealed class ProvideSourceLocation : Attribute\n {\n public readonly string File;\n public readonly string Member;\n public readonly int Line;\n public ProvideSourceLocation\n (\n [CallerFilePath] string file = \"\",\n [CallerMemberName] string member = \"\",\n [CallerLineNumber] int line = 0)\n {\n File = file;\n Member = member;\n Line = line;\n }\n\n public override string ToString() { return File + \"(\" + Line + \"):\" + Member; }\n }\n\n\n[ProvideSourceLocation]\nclass Test\n{\n ...\n}\n</code></pre>\n\n<p>The you can write for instance: </p>\n\n<pre><code>Console.WriteLine(typeof(Test).GetCustomAttribute&lt;ProvideSourceLocation&gt;(true));\n</code></pre>\n\n<p>Output will be: </p>\n\n<pre><code>a:\\develop\\HWClassLibrary.cs\\src\\Tester\\Program.cs(65):\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563/" ]
Considering that the debug data file is available (PDB) and by using either **System.Reflection** or another similar framework such as **Mono.Cecil**, how to retrieve programmatically the source file name and the line number where a type or a member of a type is declared. For example, let's say you have compiled this file into an assembly: *C:\MyProject\Foo.cs* ``` 1: public class Foo 2: { 3: public string SayHello() 4: { 5: return "Hello"; 6: } 7: } ``` How to do something like: ``` MethodInfo methodInfo = typeof(Foo).GetMethod("SayHello"); string sourceFileName = methodInfo.GetSourceFile(); // ?? Does not exist! int sourceLineNumber = methodInfo.GetLineNumber(); // ?? Does not exist! ``` sourceFileName would contain "C:\MyProject\Foo.cs" and sourceLineNumber be equal to 3. *Update: `System.Diagnostics.StackFrame` is indeed able to get that information, but only in the scope of current executing call stack. It means that the method must be invoked first. I would like to get the same info, but without invoking the type member.*
Up to date method: ``` private static void Log(string text, [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = 0) { Console.WriteLine("{0}_{1}({2}): {3}", Path.GetFileName(file), member, line, text); } ``` New `Framework API` which populates arguments (marked with special attributes) at runtime, see more in [my answer to this SO question](https://stackoverflow.com/questions/6369184/print-the-source-filename-and-linenumber-in-c-sharp/16295702#16295702)
126,100
<p>What's the fastest way to count the number of keys/properties of an object? Is it possible to do this without iterating over the object? I.e., without doing:</p> <pre><code>var count = 0; for (k in myobj) if (myobj.hasOwnProperty(k)) ++count; </code></pre> <p>(Firefox did provide a magic <code>__count__</code> property, but this was removed somewhere around version 4.)</p>
[ { "answer_id": 126151, "author": "Confusion", "author_id": 16784, "author_profile": "https://Stackoverflow.com/users/16784", "pm_score": 5, "selected": false, "text": "<p>If you are actually running into a performance problem I would suggest wrapping the calls that add/remove properties to/from the object with a function that also increments/decrements an appropriately named (size?) property.</p>\n\n<p>You only need to calculate the initial number of properties once and move on from there. If there isn't an actual performance problem, don't bother. Just wrap that bit of code in a function <code>getNumberOfProperties(object)</code> and be done with it.</p>\n" }, { "answer_id": 126157, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 4, "selected": false, "text": "<p>I'm not aware of any way to do this. However, to keep the iterations to a minimum, you could try checking for the existence of <code>__count__</code> and if it doesn't exist (i.e., not Firefox) then you could iterate over the object and define it for later use, e.g.:</p>\n<pre><code>if (myobj.__count__ === undefined) {\n myobj.__count__ = ...\n}\n</code></pre>\n<p>This way, any browser supporting <code>__count__</code> would use that, and iterations would only be carried out for those which don't. If the count changes and you can't do this, you could always make it a function:</p>\n<pre><code>if (myobj.__count__ === undefined) {\n myobj.__count__ = function() { return ... }\n myobj.__count__.toString = function() { return this(); }\n}\n</code></pre>\n<p>This way, any time you reference myobj.<code>__count__</code> the function will fire and recalculate.</p>\n" }, { "answer_id": 4889658, "author": "Avi Flax", "author_id": 7012, "author_profile": "https://Stackoverflow.com/users/7012", "pm_score": 13, "selected": true, "text": "<p>To do this in any <em><a href=\"https://en.wikipedia.org/wiki/ECMAScript#5th_Edition\" rel=\"noreferrer\">ES5</a>-compatible environment</em>, such as <a href=\"http://nodejs.org\" rel=\"noreferrer\">Node.js</a>, Chrome, <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_9\" rel=\"noreferrer\">Internet Explorer 9+</a>, Firefox 4+, or Safari 5+:</p>\n<pre class=\"lang-js prettyprint-override\"><code>Object.keys(obj).length\n</code></pre>\n<ul>\n<li><a href=\"http://kangax.github.com/es5-compat-table/\" rel=\"noreferrer\">Browser compatibility</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"noreferrer\">Object.keys documentation</a> (includes a method you can add to non-ES5 browsers)</li>\n</ul>\n" }, { "answer_id": 5675579, "author": "Renaat De Muynck", "author_id": 288264, "author_profile": "https://Stackoverflow.com/users/288264", "pm_score": 7, "selected": false, "text": "<p>You could use this code:</p>\n\n<pre><code>if (!Object.keys) {\n Object.keys = function (obj) {\n var keys = [],\n k;\n for (k in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, k)) {\n keys.push(k);\n }\n }\n return keys;\n };\n}\n</code></pre>\n\n<p>Then you can use this in older browsers as well:</p>\n\n<pre><code>var len = Object.keys(obj).length;\n</code></pre>\n" }, { "answer_id": 6019605, "author": "studgeek", "author_id": 255961, "author_profile": "https://Stackoverflow.com/users/255961", "pm_score": 7, "selected": false, "text": "<p>If you are using <a href=\"http://underscorejs.org/\" rel=\"nofollow noreferrer\">Underscore.js</a> you can use <a href=\"http://underscorejs.org/#size\" rel=\"nofollow noreferrer\">_.size</a> (<a href=\"https://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip#comment7517359_6019605\">thanks douwe</a>):</p>\n<pre><code>_.size(obj)\n</code></pre>\n<p>Alternatively you can also use <a href=\"http://underscorejs.org/#keys\" rel=\"nofollow noreferrer\">_.keys</a> which might be clearer for some:</p>\n<pre><code>_.keys(obj).length\n</code></pre>\n<p>I highly recommend Underscore.js. It's a tight library for doing lots of basic things. Whenever possible, they match <a href=\"https://en.wikipedia.org/wiki/ECMAScript#5th_Edition\" rel=\"nofollow noreferrer\">ECMAScript 5</a> and defer to the native implementation.</p>\n<p>Otherwise I support <a href=\"https://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip/4889658#4889658\">Avi Flax' answer</a>. I edited it to add a link to the <a href=\"https://en.wikipedia.org/wiki/MDN_Web_Docs\" rel=\"nofollow noreferrer\">MDC</a> documentation which includes the keys() method you can add to non-ECMAScript 5 browsers.</p>\n" }, { "answer_id": 6504767, "author": "Ali", "author_id": 49153, "author_profile": "https://Stackoverflow.com/users/49153", "pm_score": 3, "selected": false, "text": "<p>How I've solved this problem is to build my own implementation of a basic list which keeps a record of how many items are stored in the object. It’s very simple. Something like this:</p>\n<pre><code>function BasicList()\n{\n var items = {};\n this.count = 0;\n\n this.add = function(index, item)\n {\n items[index] = item;\n this.count++;\n }\n\n this.remove = function (index)\n {\n delete items[index];\n this.count--;\n }\n\n this.get = function(index)\n {\n if (undefined === index)\n return items;\n else\n return items[index];\n }\n}\n</code></pre>\n" }, { "answer_id": 8724297, "author": "hakunin", "author_id": 517529, "author_profile": "https://Stackoverflow.com/users/517529", "pm_score": 3, "selected": false, "text": "<p>For those who have Underscore.js included in their project you can do:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>_({a:'', b:''}).size() // =&gt; 2\n</code></pre>\n\n<p>or functional style:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>_.size({a:'', b:''}) // =&gt; 2\n</code></pre>\n" }, { "answer_id": 10119408, "author": "Mark Rhodes", "author_id": 509619, "author_profile": "https://Stackoverflow.com/users/509619", "pm_score": 2, "selected": false, "text": "<p>For those that have <a href=\"https://en.wikipedia.org/wiki/Ext_JS\" rel=\"nofollow noreferrer\">Ext JS</a> 4 in their project, you can do:</p>\n<pre><code>Ext.Object.getSize(myobj);\n</code></pre>\n<p>The advantage of this is that it'll work on all Ext JS compatible browsers (<a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_6\" rel=\"nofollow noreferrer\">Internet Explorer 6</a> - <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_8\" rel=\"nofollow noreferrer\">Internet Explorer 8</a> included). However, I believe the running time is no better than O(n) though, as with other suggested solutions.</p>\n" }, { "answer_id": 12232776, "author": "codejoecode", "author_id": 1641237, "author_profile": "https://Stackoverflow.com/users/1641237", "pm_score": -1, "selected": false, "text": "<p>If jQuery in previous answers does not work, then try</p>\n<pre><code>$(Object.Item).length\n</code></pre>\n" }, { "answer_id": 14377849, "author": "BenderTheOffender", "author_id": 1047014, "author_profile": "https://Stackoverflow.com/users/1047014", "pm_score": 4, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip/4889658#4889658\">stated by Avi Flax</a>,</p>\n<pre><code>Object.keys(obj).length\n</code></pre>\n<p>will do the trick for all enumerable properties on your object, but to also include the non-enumerable properties, you can instead use the <code>Object.getOwnPropertyNames</code>. Here's the difference:</p>\n<pre><code>var myObject = new Object();\n\nObject.defineProperty(myObject, &quot;nonEnumerableProp&quot;, {\n enumerable: false\n});\nObject.defineProperty(myObject, &quot;enumerableProp&quot;, {\n enumerable: true\n});\n\nconsole.log(Object.getOwnPropertyNames(myObject).length); //outputs 2\nconsole.log(Object.keys(myObject).length); //outputs 1\n\nconsole.log(myObject.hasOwnProperty(&quot;nonEnumerableProp&quot;)); //outputs true\nconsole.log(myObject.hasOwnProperty(&quot;enumerableProp&quot;)); //outputs true\n\nconsole.log(&quot;nonEnumerableProp&quot; in myObject); //outputs true\nconsole.log(&quot;enumerableProp&quot; in myObject); //outputs true\n</code></pre>\n<p>As <a href=\"http://kangax.github.com/es5-compat-table/\" rel=\"nofollow noreferrer\">stated here</a>, this has the same browser support as <code>Object.keys</code>.</p>\n<p>However, in most cases, you might not want to include the nonenumerables in these type of operations, but it's always good to know the difference ;)</p>\n" }, { "answer_id": 16763915, "author": "Luc125", "author_id": 746757, "author_profile": "https://Stackoverflow.com/users/746757", "pm_score": 7, "selected": false, "text": "<p>The standard Object implementation (<a href=\"http://www.ecma-international.org/ecma-262/5.1/#sec-8.6.2\" rel=\"noreferrer\">ES5.1 Object Internal Properties and Methods</a>) does not require an <code>Object</code> to track its number of keys/properties, so there should be no standard way to determine the size of an <code>Object</code> without explicitly or implicitly iterating over its keys.</p>\n\n<p>So here are the most commonly used alternatives:</p>\n\n\n\n<h3>1. ECMAScript's Object.keys()</h3>\n\n<p><code>Object.keys(obj).length;</code> Works by <em>internally</em> iterating over the keys to compute a temporary array and returns its length.</p>\n\n<ul>\n<li><strong>Pros</strong> - Readable and clean syntax. No library or custom code required except a shim if native support is unavailable</li>\n<li><strong>Cons</strong> - Memory overhead due to the creation of the array.</li>\n</ul>\n\n<h3>2. Library-based solutions</h3>\n\n<p>Many library-based examples elsewhere in this topic are useful idioms in the context of their library. From a performance viewpoint, however, there is nothing to gain compared to a perfect no-library code since all those library methods actually encapsulate either a for-loop or ES5 <code>Object.keys</code> (native or shimmed).</p>\n\n<h3>3. Optimizing a for-loop</h3>\n\n<p>The <strong>slowest part</strong> of such a for-loop is generally the <code>.hasOwnProperty()</code> call, because of the function call overhead. So when I just want the number of entries of a JSON object, I just skip the <code>.hasOwnProperty()</code> call if I know that no code did nor will extend <code>Object.prototype</code>.</p>\n\n<p>Otherwise, your code could be very slightly optimized by making <code>k</code> local (<code>var k</code>) and by using prefix-increment operator (<code>++count</code>) instead of postfix.</p>\n\n<pre><code>var count = 0;\nfor (var k in myobj) if (myobj.hasOwnProperty(k)) ++count;\n</code></pre>\n\n<p>Another idea relies on caching the <code>hasOwnProperty</code> method:</p>\n\n<pre><code>var hasOwn = Object.prototype.hasOwnProperty;\nvar count = 0;\nfor (var k in myobj) if (hasOwn.call(myobj, k)) ++count;\n</code></pre>\n\n<p>Whether this is faster or not on a given environment is a question of benchmarking. Very limited performance gain can be expected anyway.</p>\n" }, { "answer_id": 22739088, "author": "Belldandu", "author_id": 3271268, "author_profile": "https://Stackoverflow.com/users/3271268", "pm_score": 4, "selected": false, "text": "<p>To iterate on <a href=\"https://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip/4889658#4889658\">Avi Flax' answer</a>, <em>Object.keys(obj).length</em> is correct for an object that doesn’t have functions tied to it.</p>\n<p>Example:</p>\n<pre><code>obj = {&quot;lol&quot;: &quot;what&quot;, owo: &quot;pfft&quot;};\nObject.keys(obj).length; // should be 2\n</code></pre>\n<p>versus</p>\n<pre><code>arr = [];\nobj = {&quot;lol&quot;: &quot;what&quot;, owo: &quot;pfft&quot;};\nobj.omg = function(){\n _.each(obj, function(a){\n arr.push(a);\n });\n};\nObject.keys(obj).length; // should be 3 because it looks like this\n/* obj === {&quot;lol&quot;: &quot;what&quot;, owo: &quot;pfft&quot;, omg: function(){_.each(obj, function(a){arr.push(a);});}} */\n</code></pre>\n<p>Steps to avoid this:</p>\n<ol>\n<li><p>do not put functions in an object that you want to count the number of keys in</p>\n</li>\n<li><p>use a separate object or make a new object specifically for functions (if you want to count how many functions there are in the file using <code>Object.keys(obj).length</code>)</p>\n</li>\n</ol>\n<p>Also, yes, I used the <code>_</code> or <a href=\"https://en.wikipedia.org/wiki/Underscore.js\" rel=\"nofollow noreferrer\">Underscore.js</a> module from Node.js in my example.</p>\n<p>Documentation can be found <a href=\"http://underscorejs.org/\" rel=\"nofollow noreferrer\">here</a> as well as its source on GitHub and various other information.</p>\n<p>And finally a lodash implementation <a href=\"https://lodash.com/docs#size\" rel=\"nofollow noreferrer\">https://lodash.com/docs#size</a></p>\n<p><code>_.size(obj)</code></p>\n" }, { "answer_id": 32131981, "author": "lepe", "author_id": 196507, "author_profile": "https://Stackoverflow.com/users/196507", "pm_score": 3, "selected": false, "text": "<p>From <em><a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow noreferrer\">Object.defineProperty()</a></em>:</p>\n<blockquote>\n<p>Object.defineProperty(obj, prop, descriptor)</p>\n</blockquote>\n<p>You can either add it to all your objects:</p>\n<pre><code>Object.defineProperty(Object.prototype, &quot;length&quot;, {\n enumerable: false,\n get: function() {\n return Object.keys(this).length;\n }\n});\n</code></pre>\n<p>Or a single object:</p>\n<pre><code>var myObj = {};\nObject.defineProperty(myObj, &quot;length&quot;, {\n enumerable: false,\n get: function() {\n return Object.keys(this).length;\n }\n});\n</code></pre>\n<p>Example:</p>\n<pre><code>var myObj = {};\nmyObj.name = &quot;John Doe&quot;;\nmyObj.email = &quot;[email protected]&quot;;\nmyObj.length; // Output: 2\n</code></pre>\n<p>Added that way, it won't be displayed in <em>for..in</em> loops:</p>\n<pre><code>for(var i in myObj) {\n console.log(i + &quot;: &quot; + myObj[i]);\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>name: John Doe\nemail: [email protected]\n</code></pre>\n<p>Note: it does not work in browsers before <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_9\" rel=\"nofollow noreferrer\">Internet Explorer 9</a>.</p>\n" }, { "answer_id": 48337446, "author": "Flavien Volken", "author_id": 532695, "author_profile": "https://Stackoverflow.com/users/532695", "pm_score": 5, "selected": false, "text": "<p>As answered in a previous answer: <code>Object.keys(obj).length</code></p>\n<p>But: as we have now a real <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"noreferrer\">Map</a> class in ES6, I would <a href=\"https://stackoverflow.com/questions/32600157/maps-vs-objects-in-es6-when-to-use\">suggest</a> to use it instead of using the properties of an object.</p>\n<pre><code>const map = new Map();\nmap.set(&quot;key&quot;, &quot;value&quot;);\nmap.size; // THE fastest way\n</code></pre>\n" }, { "answer_id": 49023825, "author": "Fayaz", "author_id": 8301207, "author_profile": "https://Stackoverflow.com/users/8301207", "pm_score": 2, "selected": false, "text": "<p><strong>You can use:</strong></p>\n\n<pre><code>Object.keys(objectName).length; \n</code></pre>\n\n<p>and </p>\n\n<pre><code>Object.values(objectName).length;\n</code></pre>\n" }, { "answer_id": 49831635, "author": "Taquatech", "author_id": 9540188, "author_profile": "https://Stackoverflow.com/users/9540188", "pm_score": -1, "selected": false, "text": "<p>I try to make it available to all objects like this:</p>\n<pre><code>Object.defineProperty(Object.prototype,\n &quot;length&quot;,\n {\n get() {\n if (!Object.keys) {\n Object.keys = function (obj) {\n var keys = [],k;\n for (k in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, k)) {\n keys.push(k);\n }\n }\n return keys;\n };\n }\n return Object.keys(this).length;\n },});\n\nconsole.log({&quot;Name&quot;:&quot;Joe&quot;, &quot;Age&quot;:26}.length) // Returns 2\n</code></pre>\n" }, { "answer_id": 56712818, "author": "Robert Sinclair", "author_id": 1907888, "author_profile": "https://Stackoverflow.com/users/1907888", "pm_score": 1, "selected": false, "text": "<p>The OP didn't specify if the object is a nodeList. If it is, then you can just use the <strong>length</strong> method on it directly. Example:</p>\n<pre><code>buttons = document.querySelectorAll('[id=button)) {\nconsole.log('Found ' + buttons.length + ' on the screen');\n</code></pre>\n" }, { "answer_id": 58492580, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 6, "selected": false, "text": "<p>Here are some performance tests for three methods;</p>\n<p><a href=\"https://jsperf.com/get-the-number-of-keys-in-an-object\" rel=\"noreferrer\">https://jsperf.com/get-the-number-of-keys-in-an-object</a></p>\n<h2 id=\"object.keys.length-omt4\">Object.keys().length</h2>\n<p><strong>20,735</strong> operations per second</p>\n<p>It is very simple and compatible and runs fast <em>but</em> expensive, because it creates a new array of keys, which then gets thrown away.</p>\n<pre><code>return Object.keys(objectToRead).length;\n</code></pre>\n<h2 id=\"loop-through-the-keys-md5f\">Loop through the keys</h2>\n<p><strong>15,734</strong> operations per second</p>\n<pre><code>let size=0;\nfor(let k in objectToRead) {\n size++\n}\nreturn size;\n</code></pre>\n<p>It is slightly slower, but nowhere near the memory usage, so it is probably better if you're interested in optimising for mobile or other small machines.</p>\n<h2 id=\"using-map-instead-of-object-q9b2\">Using Map instead of Object</h2>\n<p><strong>953,839,338</strong> operations per second</p>\n<pre><code>return mapToRead.size;\n</code></pre>\n<p>Basically, Map tracks its own size, so we're just returning a number field. It is far, far faster than any other method. If you have control of the object, convert them to maps instead.</p>\n" }, { "answer_id": 70914677, "author": "dazzafact", "author_id": 1163485, "author_profile": "https://Stackoverflow.com/users/1163485", "pm_score": 4, "selected": false, "text": "<p><strong>this works for both, Arrays and Objects</strong></p>\n<pre><code>//count objects/arrays\nfunction count(obj){\n return Object.keys(obj).length\n }\n</code></pre>\n<p><strong>count objects/arrays with a Loop</strong></p>\n<pre><code>function count(obj){\n var x=0;\n for(k in obj){\n x++;\n }\n return x;\n }\n</code></pre>\n<p><strong>count objects/arrays and also the length of a String</strong></p>\n<pre><code>function count(obj){\n if (typeof (obj) === 'string' || obj instanceof String)\n {\n return obj.length; \n }\n return Object.keys(obj).length\n }\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11543/" ]
What's the fastest way to count the number of keys/properties of an object? Is it possible to do this without iterating over the object? I.e., without doing: ``` var count = 0; for (k in myobj) if (myobj.hasOwnProperty(k)) ++count; ``` (Firefox did provide a magic `__count__` property, but this was removed somewhere around version 4.)
To do this in any *[ES5](https://en.wikipedia.org/wiki/ECMAScript#5th_Edition)-compatible environment*, such as [Node.js](http://nodejs.org), Chrome, [Internet Explorer 9+](https://en.wikipedia.org/wiki/Internet_Explorer_9), Firefox 4+, or Safari 5+: ```js Object.keys(obj).length ``` * [Browser compatibility](http://kangax.github.com/es5-compat-table/) * [Object.keys documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) (includes a method you can add to non-ES5 browsers)
126,109
<p>I defined a record named <code>log</code>. I want to create an mnesia table with name <code>log_table</code>. When I try to write a record to table, I get <code>bad_type</code> error as follows:</p> <pre><code>(node1@kitt)4&gt; mnesia:create_table(log_table, [{ram_copies, [node()]}, {attributes, record_info(fields, log)}]). {atomic,ok} (node1@kitt)5&gt; mnesia:dirty_write(log_table, #log{id="hebelek"}). ** exception exit: {aborted,{bad_type,#log{id = "hebelek"}}} in function mnesia:abort/1 </code></pre> <p>What am I missing?</p>
[ { "answer_id": 126185, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 0, "selected": false, "text": "<p>How does your definition of the log-records look? Do you get the same error if you create a new table from scratch (i.e. remove the Mnesia@ directory first).</p>\n" }, { "answer_id": 126223, "author": "Haldun", "author_id": 21000, "author_profile": "https://Stackoverflow.com/users/21000", "pm_score": 2, "selected": false, "text": "<p>I've found it. When I changed <code>mnesia:create_table</code> call to this</p>\n\n<pre><code>mnesia:create_table(log_table, [{ram_copies, [node()]},\n {record_name, log},\n {attributes, record_info(fields, log)}]).\n</code></pre>\n\n<p>everything works OK.</p>\n" }, { "answer_id": 126930, "author": "Adam Lindberg", "author_id": 2457, "author_profile": "https://Stackoverflow.com/users/2457", "pm_score": 4, "selected": true, "text": "<p>By default the record name is assumed to be the same as the table name.</p>\n\n<p>To fix this you should either name your table just <code>log</code> or append the option <code>{record_name, log}</code> in your table options (as you've done in your fix).</p>\n\n<p>It is usually good practice to let your record and table be named the same thing, it makes the code easier to read and debug. You can also then use the <code>mnesia:write/1</code> function with just your record as only argument. Mnesia then figures out which table to put the record in by looking at the name.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21000/" ]
I defined a record named `log`. I want to create an mnesia table with name `log_table`. When I try to write a record to table, I get `bad_type` error as follows: ``` (node1@kitt)4> mnesia:create_table(log_table, [{ram_copies, [node()]}, {attributes, record_info(fields, log)}]). {atomic,ok} (node1@kitt)5> mnesia:dirty_write(log_table, #log{id="hebelek"}). ** exception exit: {aborted,{bad_type,#log{id = "hebelek"}}} in function mnesia:abort/1 ``` What am I missing?
By default the record name is assumed to be the same as the table name. To fix this you should either name your table just `log` or append the option `{record_name, log}` in your table options (as you've done in your fix). It is usually good practice to let your record and table be named the same thing, it makes the code easier to read and debug. You can also then use the `mnesia:write/1` function with just your record as only argument. Mnesia then figures out which table to put the record in by looking at the name.
126,114
<p><strong>Problem</strong>. I need a way to find Starteam server time through Starteam Java SDK 8.0. Version of server is 8.0.172 so method <code>Server.getCurrentTime()</code> is not available since it was added only in server version 9.0.</p> <p><strong>Motivation</strong>. My application needs to use views at specific dates. So if there's some difference in system time between client (where the app is running) and server then obtained views are not accurate. In the worst case the client's requested date is in the future for server so the operation results in exception.</p>
[ { "answer_id": 126516, "author": "Ioannis", "author_id": 20428, "author_profile": "https://Stackoverflow.com/users/20428", "pm_score": -1, "selected": false, "text": "<p><code>&lt;stab_in_the_dark&gt;</code>\nI'm not familiar with that SDK but from looking at the API if the server is in a known timezone why not create and an OLEDate object whose date is going to be the client's time rolled appropriately according to the server's timezone?\n<code>&lt;/stab_in_the_dark&gt;</code></p>\n" }, { "answer_id": 127671, "author": "wheleph", "author_id": 15647, "author_profile": "https://Stackoverflow.com/users/15647", "pm_score": 3, "selected": true, "text": "<p>After some investigation I haven't found any cleaner solution than using a temporary item. My app requests the item's time of creation and compares it with local time. Here's the method I use to get server time: </p>\n\n<pre><code>public Date getCurrentServerTime() {\n Folder rootFolder = project.getDefaultView().getRootFolder();\n\n Topic newItem = (Topic) Item.createItem(project.getTypeNames().TOPIC, rootFolder);\n newItem.update();\n newItem.remove();\n newItem.update();\n return newItem.getCreatedTime().createDate();\n}\n</code></pre>\n" }, { "answer_id": 244496, "author": "Doug Porter", "author_id": 4311, "author_profile": "https://Stackoverflow.com/users/4311", "pm_score": 1, "selected": false, "text": "<p>If your StarTeam server is on a Windows box and your code will be executing on a Windows box, you could shell out and execute the <strong>NET time</strong> command to fetch the time on that machine and then compare it to the local time.</p>\n\n<pre><code>net time \\\\my_starteam_server_machine_name\n</code></pre>\n\n<p>which should return:</p>\n\n<pre><code>\"Current time at \\\\my_starteam_server_machine_name is 10/28/2008 2:19 PM\"\n\n\"The command completed successfully.\"\n</code></pre>\n" }, { "answer_id": 732149, "author": "Jeremy Murray", "author_id": 88834, "author_profile": "https://Stackoverflow.com/users/88834", "pm_score": 1, "selected": false, "text": "<p>We needed to come up with a way of finding the server time for use with CodeCollab. Here is a (longish) C# code sample of how to do it without creating a temporary file. Resolution is 1 second.</p>\n\n<pre><code> static void Main(string[] args)\n {\n // ServerTime replacement for pre-2006 StarTeam servers.\n // Picks a date in the future.\n // Gets a view, sets the configuration to the date, and tries to get a property from the root folder.\n // If it cannot retrieve the property, the date is too far in the future. Roll back the date to an earlier time.\n\n DateTime StartTime = DateTime.Now;\n\n Server s = new Server(\"serverAddress\", 49201);\n s.LogOn(\"User\", \"Password\");\n\n // Getting a view - doesn't matter which, as long as it is not deleted.\n Project p = s.Projects[0];\n View v = p.AccessibleViews[0]; // AccessibleViews saves checking permissions.\n\n // Timestep to use when searching. One hour is fairly quick for resolution.\n TimeSpan deltaTime = new TimeSpan(1, 0, 0);\n deltaTime = new TimeSpan(24 * 365, 0, 0);\n\n // Invalid calls return faster - start a ways in the future.\n TimeSpan offset = new TimeSpan(24, 0, 0);\n\n // Times before the view was created are invalid.\n DateTime minTime = v.CreatedTime;\n DateTime localTime = DateTime.Now;\n\n if (localTime &lt; minTime)\n {\n System.Console.WriteLine(\"Current time is older than view creation time: \" + minTime);\n\n // If the dates are so dissimilar that the current date is before the creation date,\n // it is probably a good idea to use a bigger delta.\n deltaTime = new TimeSpan(24 * 365, 0, 0);\n\n // Set the offset to the minimum time and work up from there.\n offset = minTime - localTime;\n }\n\n // Storage for calculated date.\n DateTime testTime;\n\n // Larger divisors converge quicker, but might take longer depending on offset.\n const float stepDivisor = 10.0f;\n\n bool foundValid = false;\n\n while (true)\n {\n localTime = DateTime.Now;\n\n testTime = localTime.Add(offset);\n\n ViewConfiguration vc = ViewConfiguration.CreateFromTime(testTime);\n\n View tempView = new View(v, vc);\n\n System.Console.Write(\"Testing \" + testTime + \" (Offset \" + (int)offset.TotalSeconds + \") (Delta \" + deltaTime.TotalSeconds + \"): \");\n\n // Unfortunately, there is no isValid operation. Attempting to\n // read a property from an invalid date configuration will\n // throw an exception.\n // An alternate to this would be proferred.\n bool valid = true;\n try\n {\n string testname = tempView.RootFolder.Name;\n }\n catch (ServerException)\n {\n System.Console.WriteLine(\" InValid\");\n valid = false;\n }\n\n if (valid)\n {\n System.Console.WriteLine(\" Valid\");\n\n // If the last check was invalid, the current check is valid, and \n // If the change is this small, the time is very close to the server time.\n if (foundValid == false &amp;&amp; deltaTime.TotalSeconds &lt;= 1)\n {\n break;\n }\n\n foundValid = true;\n offset = offset.Add(deltaTime);\n }\n else\n {\n offset = offset.Subtract(deltaTime);\n\n // Once a valid time is found, start reducing the timestep.\n if (foundValid)\n {\n foundValid = false;\n deltaTime = new TimeSpan(0,0,Math.Max((int)(deltaTime.TotalSeconds / stepDivisor), 1));\n }\n }\n\n }\n\n System.Console.WriteLine(\"Run time: \" + (DateTime.Now - StartTime).TotalSeconds + \" seconds.\");\n System.Console.WriteLine(\"The local time is \" + localTime);\n System.Console.WriteLine(\"The server time is \" + testTime);\n System.Console.WriteLine(\"The server time is offset from the local time by \" + offset.TotalSeconds + \" seconds.\");\n }\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Testing 4/9/2009 3:05:40 PM (Offset 86400) (Delta 31536000): InValid\nTesting 4/9/2008 3:05:40 PM (Offset -31449600) (Delta 31536000): Valid\n...\nTesting 4/8/2009 10:05:41 PM (Offset 25200) (Delta 3): InValid\nTesting 4/8/2009 10:05:38 PM (Offset 25197) (Delta 1): Valid\nRun time: 9.0933426 seconds.\nThe local time is 4/8/2009 3:05:41 PM\nThe server time is 4/8/2009 10:05:38 PM\nThe server time is offset from the local time by 25197 seconds.\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15647/" ]
**Problem**. I need a way to find Starteam server time through Starteam Java SDK 8.0. Version of server is 8.0.172 so method `Server.getCurrentTime()` is not available since it was added only in server version 9.0. **Motivation**. My application needs to use views at specific dates. So if there's some difference in system time between client (where the app is running) and server then obtained views are not accurate. In the worst case the client's requested date is in the future for server so the operation results in exception.
After some investigation I haven't found any cleaner solution than using a temporary item. My app requests the item's time of creation and compares it with local time. Here's the method I use to get server time: ``` public Date getCurrentServerTime() { Folder rootFolder = project.getDefaultView().getRootFolder(); Topic newItem = (Topic) Item.createItem(project.getTypeNames().TOPIC, rootFolder); newItem.update(); newItem.remove(); newItem.update(); return newItem.getCreatedTime().createDate(); } ```
126,116
<p>Is it possbile to execute linux commands with java? I am trying to create a web servlet to allow ftp users to change their passwords without ssh login access. I would like to execute the next commands: </p> <pre><code># adduser -s /sbin/nologin clientA -d /home/mainclient/clientA # passwd clientA # cd /home/mainclient; chgrp -R mainclient clientA # cd /home/mainclient/clientA; chmod 770 . </code></pre>
[ { "answer_id": 126121, "author": "Craig Day", "author_id": 5193, "author_profile": "https://Stackoverflow.com/users/5193", "pm_score": 4, "selected": true, "text": "<p>Check out <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html\" rel=\"nofollow noreferrer\">this</a>.</p>\n\n<p>However, doing what you are talking about is way outside spec, and I wouldnt reccommend it. To get it to work you are going to either run your app server as root, or use some other mechanism to give the user the app server is running as permission to execute these privileged commands. One small screw-up somewhere and you are \"owned\".</p>\n" }, { "answer_id": 126124, "author": "Josh Moore", "author_id": 5004, "author_profile": "https://Stackoverflow.com/users/5004", "pm_score": 3, "selected": false, "text": "<p>Use: </p>\n\n<pre><code>Runtime.getRuntim().exec(\"Command\");\n</code></pre>\n\n<p>where Command is the command string you want to execute.</p>\n" }, { "answer_id": 126130, "author": "Chris", "author_id": 18793, "author_profile": "https://Stackoverflow.com/users/18793", "pm_score": 0, "selected": false, "text": "<p>The java <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html\" rel=\"nofollow noreferrer\">RunTime</a> object has exec methods to run commands in a separate process</p>\n" }, { "answer_id": 126139, "author": "Andreas Kraft", "author_id": 4799, "author_profile": "https://Stackoverflow.com/users/4799", "pm_score": 0, "selected": false, "text": "<p>have a look at <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html#exec(java.lang.String)\" rel=\"nofollow noreferrer\">java.lang.Runtime</a></p>\n" }, { "answer_id": 126410, "author": "Vilmantas Baranauskas", "author_id": 11662, "author_profile": "https://Stackoverflow.com/users/11662", "pm_score": 1, "selected": false, "text": "<p>If you invoke those commands from Java, make sure to pack multiple commands to a single shell-script. This will make invocation much easier.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
Is it possbile to execute linux commands with java? I am trying to create a web servlet to allow ftp users to change their passwords without ssh login access. I would like to execute the next commands: ``` # adduser -s /sbin/nologin clientA -d /home/mainclient/clientA # passwd clientA # cd /home/mainclient; chgrp -R mainclient clientA # cd /home/mainclient/clientA; chmod 770 . ```
Check out [this](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html). However, doing what you are talking about is way outside spec, and I wouldnt reccommend it. To get it to work you are going to either run your app server as root, or use some other mechanism to give the user the app server is running as permission to execute these privileged commands. One small screw-up somewhere and you are "owned".
126,138
<p>I'm trying to run a process and do stuff with its input, output and error streams. The obvious way to do this is to use something like <code>select()</code>, but the only thing I can find in Java that does that is <code>Selector.select()</code>, which takes a <code>Channel</code>. It doesn't appear to be possible to get a <code>Channel</code> from an <code>InputStream</code> or <code>OutputStream</code> (<code>FileStream</code> has a <code>getChannel()</code> method but that doesn't help here)</p> <p>So, instead I wrote some code to poll all the streams:</p> <pre><code>while( !out_eof || !err_eof ) { while( out_str.available() ) { if( (bytes = out_str.read(buf)) != -1 ) { // Do something with output stream } else out_eof = true; } while( err_str.available() ) { if( (bytes = err_str.read(buf)) != -1 ) { // Do something with error stream } else err_eof = true; } sleep(100); } </code></pre> <p>which works, except that it never terminates. When one of the streams reaches end of file, <code>available()</code> returns zero so <code>read()</code> isn't called and we never get the -1 return that would indicate EOF.</p> <p>One solution would be a non-blocking way to detect EOF. I can't see one in the docs anywhere. Alternatively is there a better way of doing what I want to do?</p> <p>I see this question here: <a href="https://stackoverflow.com/questions/60302/starting-a-process-with-inherited-stdinstdoutstderr-in-java-6#60578" title="Processes with inherited stdin/stdout/stderr in Java">link text</a> and although it doesn't exactly do what I want, I can probably use that idea, of spawning separate threads for each stream, for the particular problem I have now. But surely that isn't the only way to do it? Surely there must be a way to read from multiple streams without using a thread for each?</p>
[ { "answer_id": 126366, "author": "Matt Quail", "author_id": 15790, "author_profile": "https://Stackoverflow.com/users/15790", "pm_score": 3, "selected": true, "text": "<p>As you said, the solution <a href=\"https://stackoverflow.com/questions/60302/starting-a-process-with-inherited-stdinstdoutstderr-in-java-6#60578\">outlined in this Answer</a> is the traditional way of reading both stdout and stderr from a Process. A thread-per-stream is the way to go, even though it is slightly annoying.</p>\n" }, { "answer_id": 126423, "author": "Daniel Schneller", "author_id": 1252368, "author_profile": "https://Stackoverflow.com/users/1252368", "pm_score": 2, "selected": false, "text": "<p>You will indeed have to go the route of spawning a Thread for each stream you want to monitor. If your use case allows for combining both stdout and stderr of the process in question you need only one thread, otherwise two are needed.</p>\n\n<p>It took me quite some time to get it right in one of our projects where I have to launch an external process, take its output and do something with it while at the same time looking for errors and process termination and also being able to terminate it when the java app's user cancels the operation.</p>\n\n<p>I created a rather simple class to encapsulate the watching part whose run() method looks something like this:</p>\n\n<pre><code>public void run() {\n BufferedReader tStreamReader = null;\n try {\n while (externalCommand == null &amp;&amp; !shouldHalt) {\n logger.warning(\"ExtProcMonitor(\"\n + (watchStdErr ? \"err\" : \"out\")\n + \") Sleeping until external command is found\");\n Thread.sleep(500);\n }\n if (externalCommand == null) {\n return;\n }\n tStreamReader =\n new BufferedReader(new InputStreamReader(watchStdErr ? externalCommand.getErrorStream()\n : externalCommand.getInputStream()));\n String tLine;\n while ((tLine = tStreamReader.readLine()) != null) {\n logger.severe(tLine);\n if (filter != null) {\n if (filter.matches(tLine)) {\n informFilterListeners(tLine);\n return;\n }\n }\n }\n } catch (IOException e) {\n logger.logExceptionMessage(e, \"IOException stderr\");\n } catch (InterruptedException e) {\n logger.logExceptionMessage(e, \"InterruptedException waiting for external process\");\n } finally {\n if (tStreamReader != null) {\n try {\n tStreamReader.close();\n } catch (IOException e) {\n // ignore\n }\n }\n }\n}\n</code></pre>\n\n<p>On the calling side it looks like this:</p>\n\n<pre><code> Thread tExtMonitorThread = new Thread(new Runnable() {\n\n public void run() {\n try {\n while (externalCommand == null) {\n getLogger().warning(\"Monitor: Sleeping until external command is found\");\n Thread.sleep(500);\n if (isStopRequested()) {\n getLogger()\n .warning(\"Terminating external process on user request\");\n if (externalCommand != null) {\n externalCommand.destroy();\n }\n return;\n }\n }\n int tReturnCode = externalCommand.waitFor();\n getLogger().warning(\"External command exited with code \" + tReturnCode);\n } catch (InterruptedException e) {\n getLogger().logExceptionMessage(e, \"Interrupted while waiting for external command to exit\");\n }\n }\n }, \"ExtCommandWaiter\");\n\n ExternalProcessOutputHandlerThread tExtErrThread =\n new ExternalProcessOutputHandlerThread(\"ExtCommandStdErr\", getLogger(), true);\n ExternalProcessOutputHandlerThread tExtOutThread =\n new ExternalProcessOutputHandlerThread(\"ExtCommandStdOut\", getLogger(), true);\n tExtMonitorThread.start();\n tExtOutThread.start();\n tExtErrThread.start();\n tExtErrThread.setFilter(new FilterFunctor() {\n\n public boolean matches(Object o) {\n String tLine = (String)o;\n return tLine.indexOf(\"Error\") &gt; -1;\n }\n });\n\n FilterListener tListener = new FilterListener() {\n private boolean abortFlag = false;\n\n public boolean shouldAbort() {\n return abortFlag;\n }\n\n public void matched(String aLine) {\n abortFlag = abortFlag || (aLine.indexOf(\"Error\") &gt; -1);\n }\n\n };\n\n tExtErrThread.addFilterListener(tListener);\n externalCommand = new ProcessBuilder(aCommand).start();\n tExtErrThread.setProcess(externalCommand);\n try {\n tExtMonitorThread.join();\n tExtErrThread.join();\n tExtOutThread.join();\n } catch (InterruptedException e) {\n // when this happens try to bring the external process down \n getLogger().severe(\"Aborted because auf InterruptedException.\");\n getLogger().severe(\"Killing external command...\");\n externalCommand.destroy();\n getLogger().severe(\"External command killed.\");\n externalCommand = null;\n return -42;\n }\n int tRetVal = tListener.shouldAbort() ? -44 : externalCommand.exitValue();\n\n externalCommand = null;\n try {\n getLogger().warning(\"command exit code: \" + tRetVal);\n } catch (IllegalThreadStateException ex) {\n getLogger().warning(\"command exit code: unknown\");\n }\n return tRetVal;\n</code></pre>\n\n<p>Unfortunately I don't have to for a self-contained runnable example, but maybe this helps.\nIf I had to do it again I would have another look at using the Thread.interrupt() method instead of a self-made stop flag (mind to declare it volatile!), but I leave that for another time. :)</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11815/" ]
I'm trying to run a process and do stuff with its input, output and error streams. The obvious way to do this is to use something like `select()`, but the only thing I can find in Java that does that is `Selector.select()`, which takes a `Channel`. It doesn't appear to be possible to get a `Channel` from an `InputStream` or `OutputStream` (`FileStream` has a `getChannel()` method but that doesn't help here) So, instead I wrote some code to poll all the streams: ``` while( !out_eof || !err_eof ) { while( out_str.available() ) { if( (bytes = out_str.read(buf)) != -1 ) { // Do something with output stream } else out_eof = true; } while( err_str.available() ) { if( (bytes = err_str.read(buf)) != -1 ) { // Do something with error stream } else err_eof = true; } sleep(100); } ``` which works, except that it never terminates. When one of the streams reaches end of file, `available()` returns zero so `read()` isn't called and we never get the -1 return that would indicate EOF. One solution would be a non-blocking way to detect EOF. I can't see one in the docs anywhere. Alternatively is there a better way of doing what I want to do? I see this question here: [link text](https://stackoverflow.com/questions/60302/starting-a-process-with-inherited-stdinstdoutstderr-in-java-6#60578 "Processes with inherited stdin/stdout/stderr in Java") and although it doesn't exactly do what I want, I can probably use that idea, of spawning separate threads for each stream, for the particular problem I have now. But surely that isn't the only way to do it? Surely there must be a way to read from multiple streams without using a thread for each?
As you said, the solution [outlined in this Answer](https://stackoverflow.com/questions/60302/starting-a-process-with-inherited-stdinstdoutstderr-in-java-6#60578) is the traditional way of reading both stdout and stderr from a Process. A thread-per-stream is the way to go, even though it is slightly annoying.
126,141
<p>I need to determine which version of GTK+ is installed on Ubuntu</p> <p>Man does not seem to help</p>
[ { "answer_id": 126145, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 5, "selected": false, "text": "<p>You can use this command:</p>\n<pre><code>$ dpkg -s libgtk2.0-0|grep '^Version'\n</code></pre>\n" }, { "answer_id": 126193, "author": "Mark Baker", "author_id": 11815, "author_profile": "https://Stackoverflow.com/users/11815", "pm_score": 7, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/a/126145/\">This suggestion</a> will tell you which minor version of 2.0 is installed. Different major versions will have different package names because they can co-exist on the system (in order to support applications built with older versions).</p>\n\n<p>Even for development files, which normally would only let you have one version on the system, you can have a version of gtk 1.x and a version of gtk 2.0 on the same system (the include files are in directories called gtk-1.2 or gtk-2.0).</p>\n\n<p>So in short there isn't a simple answer to \"what version of GTK is on the system\". But...</p>\n\n<p>Try something like:</p>\n\n<pre><code>dpkg -l libgtk* | grep -e '^i' | grep -e 'libgtk-*[0-9]'\n</code></pre>\n\n<p>to list all the libgtk packages, including -dev ones, that are on your system. <code>dpkg -l</code> will list all the packages that dpkg knows about, including ones that aren't currently installed, so I've used grep to list only ones that are installed (line starts with i).</p>\n\n<p>Alternatively, and probably better if it's the version of the headers etc that you're interested in, use pkg-config:</p>\n\n<pre><code>pkg-config --modversion gtk+\n</code></pre>\n\n<p>will tell you what version of GTK 1.x development files are installed, and</p>\n\n<pre><code>pkg-config --modversion gtk+-2.0\n</code></pre>\n\n<p>will tell you what version of GTK 2.0. The old 1.x version also has its own gtk-config program that does the same thing. Similarly, for GTK+ 3:</p>\n\n<pre><code>pkg-config --modversion gtk+-3.0\n</code></pre>\n" }, { "answer_id": 126395, "author": "Xqj37", "author_id": 14688, "author_profile": "https://Stackoverflow.com/users/14688", "pm_score": 2, "selected": false, "text": "<p>I think a distribution-independent way is:</p>\n\n<p><code>gtk-config --version</code></p>\n" }, { "answer_id": 174254, "author": "Luka Marinko", "author_id": 19814, "author_profile": "https://Stackoverflow.com/users/19814", "pm_score": 2, "selected": false, "text": "<p>You can also just open synaptic and search for libgtk, it will show you exactly which lib is installed.</p>\n" }, { "answer_id": 13098607, "author": "Dr Casper Black", "author_id": 229901, "author_profile": "https://Stackoverflow.com/users/229901", "pm_score": 5, "selected": false, "text": "<p><strong>get GTK3 version:</strong> </p>\n\n<pre><code>dpkg -s libgtk-3-0|grep '^Version'\n</code></pre>\n\n<p>or just version number</p>\n\n<pre><code>dpkg -s libgtk-3-0|grep '^Version' | cut -d' ' -f2-\n</code></pre>\n" }, { "answer_id": 16231467, "author": "Helge", "author_id": 180954, "author_profile": "https://Stackoverflow.com/users/180954", "pm_score": 1, "selected": false, "text": "<p>To make the answer more general than Ubuntu (I have Redhat):</p>\n\n<p>gtk is usually installed under /usr, but possibly in other locations. This should be visible in environment variables. Check with </p>\n\n<pre><code>env | grep gtk\n</code></pre>\n\n<p>Then try to find where your gtk files are stored. For example, use <code>locate</code> and grep.</p>\n\n<pre><code>locate gtk | grep /usr/lib\n</code></pre>\n\n<p>In this way, I found <code>/usr/lib64/gtk-2.0</code>, which contains the subdirectory <code>2.10.0</code>, which contains many .so library files. My conclusion is that I have gtk+ version 2.10. This is rather consistent with the rpm command on Redhat: <code>rpm -qa | grep gtk2</code>, so I think my conclusion is right.</p>\n" }, { "answer_id": 16402135, "author": "Chimera", "author_id": 1076451, "author_profile": "https://Stackoverflow.com/users/1076451", "pm_score": 3, "selected": false, "text": "<p>You could also just compile the following program and run it on your machine.</p>\n\n<pre><code>#include &lt;gtk/gtk.h&gt;\n#include &lt;glib/gprintf.h&gt;\n\nint main(int argc, char *argv[])\n{\n /* Initialize GTK */\n gtk_init (&amp;argc, &amp;argv);\n\n g_printf(\"%d.%d.%d\\n\", gtk_major_version, gtk_minor_version, gtk_micro_version);\n return(0);\n}\n</code></pre>\n\n<p>compile with ( assuming above source file is named version.c):</p>\n\n<pre><code>gcc version.c -o version `pkg-config --cflags --libs gtk+-2.0`\n</code></pre>\n\n<p>When you run this you will get some output. On my old embedded device I get the following:</p>\n\n<pre><code>[root@n00E04B3730DF n2]# ./version \n2.10.4\n[root@n00E04B3730DF n2]#\n</code></pre>\n" }, { "answer_id": 27871238, "author": "Максим Шатов", "author_id": 1737151, "author_profile": "https://Stackoverflow.com/users/1737151", "pm_score": 3, "selected": false, "text": "<p>Try, </p>\n\n<pre><code>apt-cache policy libgtk2.0-0 libgtk-3-0 \n</code></pre>\n\n<p>or, </p>\n\n<pre><code>dpkg -l libgtk2.0-0 libgtk-3-0\n</code></pre>\n" }, { "answer_id": 32215303, "author": "ThorSummoner", "author_id": 1695680, "author_profile": "https://Stackoverflow.com/users/1695680", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre><code> dpkg-query -W libgtk-3-bin\n</code></pre>\n" }, { "answer_id": 47659005, "author": "liberforce", "author_id": 518853, "author_profile": "https://Stackoverflow.com/users/518853", "pm_score": 2, "selected": false, "text": "<p>This will get the version of the GTK libraries for GTK 2, 3, and 4.</p>\n<pre><code>dpkg -l | egrep &quot;libgtk(2.0-0|-3-0|-4)&quot;\n</code></pre>\n<p>As major versions are parallel installable, you may have both on your system, which is my case, so the above command returns this on my Ubuntu Trusty system:</p>\n<pre><code>ii libgtk-3-0:amd64 3.10.8-0ubuntu1.6 amd64 GTK+ graphical user interface library\nii libgtk2.0-0:amd64 2.24.23-0ubuntu1.4 amd64 GTK+ graphical user interface library\n</code></pre>\n<p>This means I have GTK+ 2.24.23 and 3.10.8 installed.</p>\n<p>If what you want is the version of the development files, use:</p>\n<ul>\n<li><code>pkg-config --modversion gtk+-2.0</code> for GTK 2</li>\n<li><code>pkg-config --modversion gtk+-3.0</code> for GTK 3</li>\n<li><code>pkg-config --modversion gtk4</code> for GTK 4</li>\n</ul>\n<p>(This change because the <code>+</code> from <code>GTK+</code> was dropped a while ago.)</p>\n" }, { "answer_id": 63590934, "author": "stragu", "author_id": 1494531, "author_profile": "https://Stackoverflow.com/users/1494531", "pm_score": 2, "selected": false, "text": "<p>Because <code>apt-cache policy</code> will list all the matches available, even if not installed, I would suggest using this command for a more manageable shortlist of GTK-related packages installed on your system:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>apt list --installed libgtk*\n</code></pre>\n" }, { "answer_id": 63867633, "author": "survivor303", "author_id": 5584567, "author_profile": "https://Stackoverflow.com/users/5584567", "pm_score": 5, "selected": false, "text": "<p>This isn't so difficult.</p>\n<p>Just check your gtk+ toolkit utilities version from terminal:</p>\n<pre><code>gtk-launch --version\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15352/" ]
I need to determine which version of GTK+ is installed on Ubuntu Man does not seem to help
[This suggestion](https://stackoverflow.com/a/126145/) will tell you which minor version of 2.0 is installed. Different major versions will have different package names because they can co-exist on the system (in order to support applications built with older versions). Even for development files, which normally would only let you have one version on the system, you can have a version of gtk 1.x and a version of gtk 2.0 on the same system (the include files are in directories called gtk-1.2 or gtk-2.0). So in short there isn't a simple answer to "what version of GTK is on the system". But... Try something like: ``` dpkg -l libgtk* | grep -e '^i' | grep -e 'libgtk-*[0-9]' ``` to list all the libgtk packages, including -dev ones, that are on your system. `dpkg -l` will list all the packages that dpkg knows about, including ones that aren't currently installed, so I've used grep to list only ones that are installed (line starts with i). Alternatively, and probably better if it's the version of the headers etc that you're interested in, use pkg-config: ``` pkg-config --modversion gtk+ ``` will tell you what version of GTK 1.x development files are installed, and ``` pkg-config --modversion gtk+-2.0 ``` will tell you what version of GTK 2.0. The old 1.x version also has its own gtk-config program that does the same thing. Similarly, for GTK+ 3: ``` pkg-config --modversion gtk+-3.0 ```
126,148
<p>How is the salt generated in HashProvider in Microsoft Enterprise Library when we set SaltEnabled?</p> <p>Is it random to new machines? Is it some magic number?</p> <p>(I know what is a salt, the question is what's the actual value of a/the salt in Enterprise Library HashProvider)</p>
[ { "answer_id": 128481, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "<p>Edit:</p>\n\n<p>See Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.HashAlgorithmProvider for an example implementation. Hashing steps are:</p>\n\n<ol>\n<li>If SaltEnabled, generate random bytes for the salt length using RNGCryptoServiceProvider.</li>\n<li>Append the salt to the plaintext.</li>\n<li>Hash the salted plaintext.</li>\n<li>Then (this is the important step), append the salt again to the <strong>hash</strong>.</li>\n</ol>\n\n<p>To compare against hashed text, you must use: </p>\n\n<pre><code>public bool CompareHash(byte[] plaintext, byte[] hashedtext)\n</code></pre>\n\n<p>versus rehashing and comparing. If you rehash, a new random salt is generated and you're lost.</p>\n\n<p>CompareHash does the following:</p>\n\n<ol>\n<li>Pulls the non-hashed salt off the hashtext. Remember, it was appended at step 4 above.</li>\n<li>Uses that salt to compute a hash for the plaintext.</li>\n<li>Compares the new hash with the hashedtext minus salt. If they're the same - true, else false.</li>\n</ol>\n\n<p>Original:</p>\n\n<p>\"if salt is enabled on a HashProvider, the provider will generate a random sequence of bytes, that will be added to the hash. If you compare a hashed value with a unhashed value, the salt will be extracted from the hashed value and used to hash the unhashed value, prior to comparison.\"</p>\n\n<p>and</p>\n\n<p>\"As for decoding as hash-value. this cannot be done. after creating a hash there should be no way to reverse this into the original value.\nHowever, what you can do is compare an unhashed-value with a hashed-value by putting it through the same algorithm and comparing the output.\"</p>\n\n<p>From <a href=\"http://www.codeplex.com/entlib/Thread/View.aspx?ThreadId=10284\" rel=\"nofollow noreferrer\">http://www.codeplex.com/entlib/Thread/View.aspx?ThreadId=10284</a></p>\n" }, { "answer_id": 172826, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 0, "selected": false, "text": "<p>Slightly offtopic : </p>\n\n<p>This salt is used to prevent Rainbow attacks. A rainbow attack is a type of attempt to find out what was the string for which this hash has been computed based on a very large (exhaustive / several gigabytes usually) dictionary of precomputed hashes.</p>\n\n<p><a href=\"http://www.codinghorror.com/blog\" rel=\"nofollow noreferrer\">'Uncle' Jeff</a> has a <a href=\"http://www.codinghorror.com/blog/archives/000949.html\" rel=\"nofollow noreferrer\">blog entry about this</a>.</p>\n\n<p>Additionally you could look up Wikipedia : </p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Rainbow_table\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Rainbow_table</a></p>\n" }, { "answer_id": 4454468, "author": "xr280xr", "author_id": 263832, "author_profile": "https://Stackoverflow.com/users/263832", "pm_score": 0, "selected": false, "text": "<p>So I'm a couple years too late, I guess, but my understanding is that a new random salt value is created every time you create a hash.</p>\n" }, { "answer_id": 27247664, "author": "Gareth Stephenson", "author_id": 869376, "author_profile": "https://Stackoverflow.com/users/869376", "pm_score": 0, "selected": false, "text": "<p>I replied to a similar question regarding the Enterprise Library and the salt value it uses for hashing.</p>\n\n<p>You can view it here: <a href=\"https://stackoverflow.com/a/27247012/869376\">https://stackoverflow.com/a/27247012/869376</a></p>\n\n<p>The highlights:</p>\n\n<ol>\n<li>The salt is a randomly generated 16 byte array.</li>\n<li>It is generated via the <code>CryptographyUtility.GetRandomBytes(16);</code> method in the <code>Microsoft.Practices.EnterpriseLibrary.Security.Cryptography</code> namespace. This eventually calls a C library method called <code>[DllImport(\"QCall\", CharSet = CharSet.Unicode)]\nprivate static extern void GetBytes(SafeProvHandle hProv, byte[] randomBytes, int count);</code></li>\n<li>The first 16 bytes of the Base64 encoded string is the salt that was used to hash the original value</li>\n</ol>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How is the salt generated in HashProvider in Microsoft Enterprise Library when we set SaltEnabled? Is it random to new machines? Is it some magic number? (I know what is a salt, the question is what's the actual value of a/the salt in Enterprise Library HashProvider)
Edit: See Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.HashAlgorithmProvider for an example implementation. Hashing steps are: 1. If SaltEnabled, generate random bytes for the salt length using RNGCryptoServiceProvider. 2. Append the salt to the plaintext. 3. Hash the salted plaintext. 4. Then (this is the important step), append the salt again to the **hash**. To compare against hashed text, you must use: ``` public bool CompareHash(byte[] plaintext, byte[] hashedtext) ``` versus rehashing and comparing. If you rehash, a new random salt is generated and you're lost. CompareHash does the following: 1. Pulls the non-hashed salt off the hashtext. Remember, it was appended at step 4 above. 2. Uses that salt to compute a hash for the plaintext. 3. Compares the new hash with the hashedtext minus salt. If they're the same - true, else false. Original: "if salt is enabled on a HashProvider, the provider will generate a random sequence of bytes, that will be added to the hash. If you compare a hashed value with a unhashed value, the salt will be extracted from the hashed value and used to hash the unhashed value, prior to comparison." and "As for decoding as hash-value. this cannot be done. after creating a hash there should be no way to reverse this into the original value. However, what you can do is compare an unhashed-value with a hashed-value by putting it through the same algorithm and comparing the output." From <http://www.codeplex.com/entlib/Thread/View.aspx?ThreadId=10284>
126,154
<p>I am designing a page to Add/Edit users - I used a repeater control and a table to display users. In users view the individual columns of the table row have labels to display a record values and when users click on edit button, the labels are hidden and text boxes are displayed for users to edit values - The problem is - as soon as the text boxes are visible, the table size increases - the row height and cells size becomes large. Is there a way to display the text boxes so that they take the same size as the labels</p>
[ { "answer_id": 126254, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "<p>I'd use JS+CSS... You'll have to get your hands dirty for this one though. Visual Studio isn't going to help you much. </p>\n\n<p>Here's how I'd do it:</p>\n\n<ol>\n<li>Get the <code>&lt;td&gt;</code> clientWidth and clientHeight.</li>\n<li><em>Set</em> the <code>&lt;td&gt;</code>'s width and height to those px values (so they're no longer relative)</li>\n<li>Swap the text for the input</li>\n<li>In your CSS, make sure the input has no padding/margin/border and set width:100%, line-height:1em, and height:1em</li>\n</ol>\n\n<p>When you switch back, make sure you un-set the <code>&lt;td&gt;</code> width and height so they return to automatic values.</p>\n\n<p>You'll need to tweak this all slightly. I'm sure you'll have to play around with the padding on the <code>&lt;td&gt;</code> and perhaps set overflow:hidden but you should be able to do what you want.</p>\n" }, { "answer_id": 126311, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 1, "selected": false, "text": "<p>Dealing with tables, the question is: can your labels span on multiple text rows (ie: can you have long texts)? If yes, you may encounter layout problems any way. If no, a simple approach can be creating a CSS Class:</p>\n\n<pre><code>\n.CellContent { display:block; width: ...; height: ...; }\n</code></pre>\n\n<p>with your preferred cell width/height. Just stay a bit \"large\" with your height.</p>\n\n<p>Assign the class to both your label and textbox, and you should not get width/height changes when switching control (thanks to the display:block property). </p>\n\n<p>Again, if you have long texts, you will still encounter issues, and may want to use multilines. In that case, I would suggest ignoring height problems: just set the width to be consistent, and always show a 3-4 lines textbox for editing. Users will not be bothered to see a row height change, if they are ready to type long texts.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17296/" ]
I am designing a page to Add/Edit users - I used a repeater control and a table to display users. In users view the individual columns of the table row have labels to display a record values and when users click on edit button, the labels are hidden and text boxes are displayed for users to edit values - The problem is - as soon as the text boxes are visible, the table size increases - the row height and cells size becomes large. Is there a way to display the text boxes so that they take the same size as the labels
Dealing with tables, the question is: can your labels span on multiple text rows (ie: can you have long texts)? If yes, you may encounter layout problems any way. If no, a simple approach can be creating a CSS Class: ``` .CellContent { display:block; width: ...; height: ...; } ``` with your preferred cell width/height. Just stay a bit "large" with your height. Assign the class to both your label and textbox, and you should not get width/height changes when switching control (thanks to the display:block property). Again, if you have long texts, you will still encounter issues, and may want to use multilines. In that case, I would suggest ignoring height problems: just set the width to be consistent, and always show a 3-4 lines textbox for editing. Users will not be bothered to see a row height change, if they are ready to type long texts.
126,164
<p>Assume the following class:</p> <pre><code>public class MyEnum: IEnumerator { private List&lt;SomeObject&gt; _myList = new List&lt;SomeObject&gt;(); ... } </code></pre> <p>It is necessary to implement the IEnumerator methods in MyEnum. But is it possible to 'delegate' or redirect the implementation for IEnumerator directly to _myList without needing to implement the IEnumerator methods?</p>
[ { "answer_id": 126171, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": -1, "selected": false, "text": "<p>Not unless you derive from List&lt;T>.</p>\n\n<pre><code>public class MyEnum : List&lt;SomeObject&gt;, IEnumerable&lt;SomeObject&gt;{}\n</code></pre>\n" }, { "answer_id": 126191, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "<p>You can do this:</p>\n\n<pre><code>public class MyEnum : IEnumerator {\n private List&lt;SomeObject&gt; _myList = new List&lt;SomeObject&gt;();\n public IEnumerator GetEnumerator() { return this._myList.GetEnumerator(); }\n}\n</code></pre>\n\n<p>The reason is simple. Your class can contains several fields which are collections, so compiler/enviroment can't know which field should be used for implementing \"IEnumerator\".</p>\n\n<p><strong>EIDT:</strong> I agree with @pb - you should implements IEnumerator&lt;SomeObject&gt; interface.</p>\n" }, { "answer_id": 126197, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 0, "selected": false, "text": "<p>If you want return a collection in a way where the caller is unable to modify the collection, you might want to wrap the List into a ReadOnlyCollection&lt;> and return IEnumerable&lt;> of the ReadOnlyCollection&lt;>.</p>\n\n<p>This way you can be sure your collection will not be changed.</p>\n" }, { "answer_id": 126198, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": true, "text": "<p><strong>Method 1:</strong>\nContinue to use encapsulation and forward calls to the List implementation.</p>\n\n<pre><code>class SomeObject\n{\n}\n\nclass MyEnum : IEnumerable&lt;SomeObject&gt;\n{\n private List&lt;SomeObject&gt; _myList = new List&lt;SomeObject&gt;();\n\n public void Add(SomeObject o)\n {\n _myList.Add(o);\n }\n\n public IEnumerator&lt;SomeObject&gt; GetEnumerator()\n {\n return _myList.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return this.GetEnumerator();\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n MyEnum a = new MyEnum();\n a.Add(new SomeObject());\n\n foreach (SomeObject o in a)\n {\n Console.WriteLine(o.GetType().ToString());\n }\n\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p><strong>Method 2:</strong>\nInherit from List implementation you get that behavior for free.</p>\n\n<pre><code>class SomeObject\n{\n}\n\nclass MyEnum : List&lt;SomeObject&gt;\n{\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n MyEnum a = new MyEnum();\n a.Add(new SomeObject());\n\n foreach (SomeObject o in a)\n {\n Console.WriteLine(o.GetType().ToString());\n }\n\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p><strong>Method 1</strong> allows for better sandboxing as there is no method that will be called in List without MyEnum knowledge. For least effort <strong>Method 2</strong> is preferred.</p>\n" }, { "answer_id": 126201, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>Apart from using pb's method, this isn't possible for a “simple” reason: the interface method needs to get passed a <code>this</code> pointer as the first argument. When you call <code>GetEnumerator</code> on your object, this pointer will be your object. However, in order for the invocation to work on the nested list, the pointer would have to be a reference to that list, not your class.</p>\n\n<p>Therefore you explicitly have to delegate the method to the other object.</p>\n\n<p>(And by the way, the advice in the other reply was right: use <code>IEnumerator&lt;T&gt;</code>, <em>not</em> <code>IEnumerable</code>!)</p>\n" }, { "answer_id": 126287, "author": "Willem", "author_id": 21568, "author_profile": "https://Stackoverflow.com/users/21568", "pm_score": -1, "selected": false, "text": "<p>Thank you all for your input and explanations. \nEventually I have combined some of your answers to the following:</p>\n\n<pre><code> class MyEnum : IEnumerable&lt;SomeObject&gt;\n{\n private List&lt;SomeObject&gt; _myList = new List&lt;SomeObject&gt;();\n public IEnumerator&lt;SomeObject&gt; GetEnumerator()\n {\n // Create a read-only copy of the list.\n ReadOnlyCollection&lt;CustomDevice&gt; items = new ReadOnlyCollection&lt;CustomDevice&gt;(_myList);\n return items.GetEnumerator();\n }\n}\n</code></pre>\n\n<p>This solution is to ensure the calling code is incapable of modifying the list and each enumerator is independant of the others in every way (e.g. with sorting).\nThanks again.</p>\n" }, { "answer_id": 44422396, "author": "yoyo", "author_id": 503688, "author_profile": "https://Stackoverflow.com/users/503688", "pm_score": -1, "selected": false, "text": "<p>Note that thanks to <a href=\"https://blogs.msdn.microsoft.com/kcwalina/2007/07/18/duck-notation/\" rel=\"nofollow noreferrer\">duck-typing</a>, you can use <code>foreach</code> on any object that has a <code>GetEnumerator</code> method - the object type need not actually implement <code>IEnumerable</code>.</p>\n\n<p>So if you do this:</p>\n\n<pre><code>class SomeObject\n{\n}\n\n class MyEnum\n {\n private List&lt;SomeObject&gt; _myList = new List&lt;SomeObject&gt;();\n\n public IEnumerator&lt;SomeObject&gt; GetEnumerator()\n {\n return _myList.GetEnumerator();\n }\n }\n</code></pre>\n\n<p>Then this works just fine:</p>\n\n<pre><code>MyEnum objects = new MyEnum();\n// ... add some objects\nforeach (SomeObject obj in objects)\n{\n Console.WriteLine(obj.ToString());\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21568/" ]
Assume the following class: ``` public class MyEnum: IEnumerator { private List<SomeObject> _myList = new List<SomeObject>(); ... } ``` It is necessary to implement the IEnumerator methods in MyEnum. But is it possible to 'delegate' or redirect the implementation for IEnumerator directly to \_myList without needing to implement the IEnumerator methods?
**Method 1:** Continue to use encapsulation and forward calls to the List implementation. ``` class SomeObject { } class MyEnum : IEnumerable<SomeObject> { private List<SomeObject> _myList = new List<SomeObject>(); public void Add(SomeObject o) { _myList.Add(o); } public IEnumerator<SomeObject> GetEnumerator() { return _myList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } class Program { static void Main(string[] args) { MyEnum a = new MyEnum(); a.Add(new SomeObject()); foreach (SomeObject o in a) { Console.WriteLine(o.GetType().ToString()); } Console.ReadLine(); } } ``` **Method 2:** Inherit from List implementation you get that behavior for free. ``` class SomeObject { } class MyEnum : List<SomeObject> { } class Program { static void Main(string[] args) { MyEnum a = new MyEnum(); a.Add(new SomeObject()); foreach (SomeObject o in a) { Console.WriteLine(o.GetType().ToString()); } Console.ReadLine(); } } ``` **Method 1** allows for better sandboxing as there is no method that will be called in List without MyEnum knowledge. For least effort **Method 2** is preferred.
126,167
<p>Application able to record error in OnError, but we are not able to do any redirect or so to show something meaningfull to user. Any ideas? I know that we can set maxRequestLength in web.config, but anyway user can exceed this limit and some normal error need to be displayed.</p>
[ { "answer_id": 126200, "author": "Adam Vigh", "author_id": 1613872, "author_profile": "https://Stackoverflow.com/users/1613872", "pm_score": -1, "selected": false, "text": "<p>You could check the length of the postedfile (FileUpload.PostedFile.ContentLength), to see if it's below the limit or not and simply showing a friendly error message if necessary.</p>\n" }, { "answer_id": 126303, "author": "ljubomir", "author_id": 11506, "author_profile": "https://Stackoverflow.com/users/11506", "pm_score": 0, "selected": false, "text": "<p>You should be able to catch the error in Global.asax - OnError() handler. \nBut unfortunately, your initial request will be finished and you will not be able to render the same upload page with some error notification to the user. </p>\n\n<p>What you can do at most is to display a friendly error page with simple redirect clause from within OnError() handler and on that page to have some back link or similar functionality to return the user to the page where he triggered the error in the first place.</p>\n\n<p>Update: </p>\n\n<p>I had to implement exact check upon file upload recently and what i came up with is <a href=\"http://swfupload.org/\" rel=\"nofollow noreferrer\">SWFUpload</a> library which totally met my requirements and also has a lot of additional features. I used it along with jquery wrapper provided by Steve Sanderson. More details can be found <a href=\"http://blog.codeville.net/2008/11/24/jquery-ajax-uploader-plugin-with-progress-bar/\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>The point is, that flash is able to detect the file size on client side and react properly if this case is met. And i think this is exactly what you need.</p>\n\n<p>Further more, you can implement flash detection check if you want to gracefully degerade to native upload button0 in case client does not have flash installed.</p>\n" }, { "answer_id": 126312, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, you probably will require IIS7 and catch this with a custom handler, since IIS6 will never get to the stage where it can see the size of the file. It can only know the size when it's done uploading or has got an error.</p>\n\n<p>This is a known problem in ASP.NET. Another (lame) alternative is to handle this earlier in the request and maybe use a flash-based uploader. <strong>John links to several in below link</strong>.</p>\n\n<p><strong>Update</strong>: Jon Galloway seemed to have <a href=\"http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx\" rel=\"nofollow noreferrer\">looked deeper into this problem</a> and it seems like a RIA-uploader is the only sensible alternative, since IIS seems to always have to swallow the file AND THEN tell you that it's to large.</p>\n" }, { "answer_id": 126376, "author": "JohnIdol", "author_id": 1311500, "author_profile": "https://Stackoverflow.com/users/1311500", "pm_score": 4, "selected": true, "text": "<p>As you say you can setup maxRequestLength in your web.config (overriding the default 4MB of your machine.config) and if this limits is exceeded you usually get a HTTP 401.1 error.</p>\n\n<p>In order to handle a generic HTTP error at application level you can setup a CustomError section in your web.config within the system.web section:</p>\n\n<pre><code>&lt;system.web&gt;\n &lt;customErrors mode=On defaultRedirect=yourCustomErrorPage.aspx /&gt;\n&lt;/system.web&gt;\n</code></pre>\n\n<p>Everytime the error is showed the user will be redirected to your custom error page.</p>\n\n<p>If you want a specialized page for each error you can do something like:</p>\n\n<pre><code>&lt;system.web&gt; \n &lt;customErrors mode=\"On\" defaultRedirect=\"yourCustomErrorPage.aspx\"&gt;\n &lt;error statusCode=\"404\" redirect=\"PageNotFound.aspx\" /&gt;\n &lt;/customErrors&gt;\n&lt;/system.web&gt;\n</code></pre>\n\n<p>And so on.</p>\n\n<p>Alternatively you could edit the CustomErrors tab of your virtual directory properties from IIS to point to your error handling pages of choice.</p>\n\n<p>The above doesn't seem to work for 401.x errors - this code-project article explains a workaround for a what seems to be a very similar problem: <a href=\"http://www.codeproject.com/KB/aspnet/Custon401Page.aspx\" rel=\"nofollow noreferrer\">Redirecting to custom 401 page</a> </p>\n" }, { "answer_id": 839909, "author": "Mike Strother", "author_id": 21320, "author_profile": "https://Stackoverflow.com/users/21320", "pm_score": 1, "selected": false, "text": "<p>Sergei,</p>\n\n<p>Per JohnIdol's answer, you need to set up a custom error page for the <em>413</em> statuscode. e.g.:</p>\n\n<pre><code> &lt;customErrors mode=\"On\" defaultRedirect=\"~/Errors/Error.aspx\"&gt;\n &lt;error statusCode=\"413\" redirect=\"~/Errors/UploadError.aspx\"/&gt;\n &lt;/customErrors&gt;\n</code></pre>\n\n<p>I know because I had to solve the same problem on a client project, and this was the solution that worked for me. Unfortunately it was the only solution I found... it wasn't possible to catch this particular problem in code; for instance, checking the length of the posted file as snomag has suggested, or catching an error in global.asax. Like you, I also had tried these other approaches before I came up with a working solution. (actually I eventually found this somewhere on the web when I was working on my problem).</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 7196929, "author": "joelmdev", "author_id": 663246, "author_profile": "https://Stackoverflow.com/users/663246", "pm_score": 0, "selected": false, "text": "<p>The best way to handle large uploads is to use a solution that implements an HttpModule that will break the file up into chunks. Any of the pre-rolled solutions out there should allow you to limit file size. Plenty of others have posted links to those on this page so I won't bother. \nHowever, if you don't want to bother with that you <em>can</em> handle this in your app's Global.asax Application_Error event. If your application is .NET 4.0, stick this block of code in there:</p>\n\n<pre><code> if (ex.InnerException != null &amp;&amp; ex.InnerException.GetType() == typeof(HttpException) &amp;&amp; ((HttpException)ex.InnerException).WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)\n {\n //Handle and redirect here, you can use Server.ClearError() and Response.Redirect(\"FileTooBig.aspx\") or whatever you choose\n }\n</code></pre>\n\n<p>Source: <a href=\"http://justinyue.wordpress.com/2010/10/29/handle-the-maximum-request-length-exceeded-error-for-asyncfileupload-control/\" rel=\"nofollow\">http://justinyue.wordpress.com/2010/10/29/handle-the-maximum-request-length-exceeded-error-for-asyncfileupload-control/</a></p>\n\n<p>If you're running on an earlier framework, try the code here (it's in VB, but it's easy to translate): <a href=\"http://www.webdeveloper.com/forum/showthread.php?t=52132\" rel=\"nofollow\">http://www.webdeveloper.com/forum/showthread.php?t=52132</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11768/" ]
Application able to record error in OnError, but we are not able to do any redirect or so to show something meaningfull to user. Any ideas? I know that we can set maxRequestLength in web.config, but anyway user can exceed this limit and some normal error need to be displayed.
As you say you can setup maxRequestLength in your web.config (overriding the default 4MB of your machine.config) and if this limits is exceeded you usually get a HTTP 401.1 error. In order to handle a generic HTTP error at application level you can setup a CustomError section in your web.config within the system.web section: ``` <system.web> <customErrors mode=On defaultRedirect=yourCustomErrorPage.aspx /> </system.web> ``` Everytime the error is showed the user will be redirected to your custom error page. If you want a specialized page for each error you can do something like: ``` <system.web> <customErrors mode="On" defaultRedirect="yourCustomErrorPage.aspx"> <error statusCode="404" redirect="PageNotFound.aspx" /> </customErrors> </system.web> ``` And so on. Alternatively you could edit the CustomErrors tab of your virtual directory properties from IIS to point to your error handling pages of choice. The above doesn't seem to work for 401.x errors - this code-project article explains a workaround for a what seems to be a very similar problem: [Redirecting to custom 401 page](http://www.codeproject.com/KB/aspnet/Custon401Page.aspx)
126,179
<p>If I have a query like, </p> <pre><code>DELETE FROM table WHERE datetime_field &lt; '2008-01-01 00:00:00' </code></pre> <p>does having the <code>datetime_field</code> column indexed help? i.e. is the index only useful when using equality (or inequality) testing, or is it useful when doing an ordered comparison as well?</p> <blockquote> <p>(Suggestions for better executing this query, without recreating the table, would also be ok!)</p> </blockquote>
[ { "answer_id": 126183, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 1, "selected": false, "text": "<p>It does, check with a DESCRIBE SELECT FROM table ...</p>\n" }, { "answer_id": 126190, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 2, "selected": false, "text": "<p>An index on the datetime field will definitely help with date range based searches. We use them all the time in our databases and the queries are rediculously slow without the indexes.</p>\n" }, { "answer_id": 126215, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 5, "selected": true, "text": "<p>Maybe. In general, if there is such an index, it will use a range scan on that index if there is no \"better\" index on the query. However, if the optimiser decides that the range would end up being too big (i.e. include more than, say 1/3 of the rows), it probably won't use the index at all, as a table scan would be likely to be faster.</p>\n\n<p>Use EXPLAIN (on a SELECT; you can't EXPLAIN a delete) to determine its decision in a specific case. This is likely to depend upon</p>\n\n<ul>\n<li>How many rows there are in the table</li>\n<li>What the range is that you're specifying</li>\n<li>What else is specified in the WHERE clause. It won't use a range scan of one index if there is another index which \"looks better\".</li>\n</ul>\n" }, { "answer_id": 126461, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html\" rel=\"nofollow noreferrer\">MySQL Reference manual</a>:</p>\n\n<blockquote>\n <p>A B-tree index can be used for column comparisons in expressions that use the =, >, >=, &lt;, &lt;=, or BETWEEN operators.</p>\n</blockquote>\n\n<p>For a large number of rows, it can be much faster to lookup the rows through a tree index than through a table scan. But as the other answers point out, use <code>EXPLAIN</code> to find out MySQL's decision.</p>\n" }, { "answer_id": 22039326, "author": "Razvan Tudorica", "author_id": 1526119, "author_profile": "https://Stackoverflow.com/users/1526119", "pm_score": 0, "selected": false, "text": "<p>Except you don't have this bug in mysql <a href=\"http://bugs.mysql.com/bug.php?id=58190\" rel=\"nofollow\">http://bugs.mysql.com/bug.php?id=58190</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4966/" ]
If I have a query like, ``` DELETE FROM table WHERE datetime_field < '2008-01-01 00:00:00' ``` does having the `datetime_field` column indexed help? i.e. is the index only useful when using equality (or inequality) testing, or is it useful when doing an ordered comparison as well? > > (Suggestions for better executing this query, without recreating the table, would also be ok!) > > >
Maybe. In general, if there is such an index, it will use a range scan on that index if there is no "better" index on the query. However, if the optimiser decides that the range would end up being too big (i.e. include more than, say 1/3 of the rows), it probably won't use the index at all, as a table scan would be likely to be faster. Use EXPLAIN (on a SELECT; you can't EXPLAIN a delete) to determine its decision in a specific case. This is likely to depend upon * How many rows there are in the table * What the range is that you're specifying * What else is specified in the WHERE clause. It won't use a range scan of one index if there is another index which "looks better".
126,238
<p>Imagine to have two RESTful controllers (UsersController, OffersController) and a PagesController (used for static content such as index, about and so on) in your application.</p> <p>You have the following routes defined:</p> <pre><code>map.with_options :controller =&gt; 'pages' do |pages| pages.root :action =&gt; 'index' # static home page pages.about :action =&gt; 'about' # static about page # maybe more static pages... end map.resources :users # RESTful UsersController map.resources :posts # RESTful PostsController </code></pre> <p>Your application layout looks like this:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Demo Application&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;ul id="menu"&gt; &lt;li&gt; &lt;%= link_to 'Home', root_path %&gt; &lt;/li&gt; &lt;li&gt; &lt;%= link_to 'Offers', offers_path %&gt; &lt;ul id="submenu&gt; &lt;li&gt;&lt;%= link_to 'Search', 'path/to/search' %&gt;&lt;/li&gt; &lt;li&gt;maybe more links...&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;%= link_to 'About', about_path %&gt; &lt;/li&gt; &lt;li&gt; &lt;%= link_to 'Admin', users_path %&gt; &lt;ul id="submenu"&gt; &lt;li&gt;&lt;%= link_to 'New User', new_user_path %&gt;&lt;/li&gt; &lt;li&gt;&lt;%= link_to 'New Offer', new_offer_path %&gt;&lt;/li&gt; &lt;li&gt;maybe more links&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/li&gt; &lt;%= yield %&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The problem with the layout is that I want only one <code>#submenu</code> to be visible at any time. All other submenus can be completely skipped (don't need to rendered at all).</p> <p>Take the Admin menu for example: This menu should be active for all RESTful paths in the application except for <code>offers_path</code>. Active means that the submenu is visible.</p> <p>The only solution I can think of to achieve this is to build a lot complicated if conditions and that sucks (really complicated to write and to maintain). I'm looking for an elegant solution?</p> <p>I hope someone understands my question - if there's something unclear just comment the question and I'm going to explain it in more detail.</p>
[ { "answer_id": 126849, "author": "Jeremiah Peschka", "author_id": 11780, "author_profile": "https://Stackoverflow.com/users/11780", "pm_score": 1, "selected": false, "text": "<p>Typically, I would abstract out the menuing functionality so that I have a helper method for rendering the Admin menu. This way, it's possible to throw as much logic in the helper as you want without clouding up your view logic. </p>\n\n<p>So, your helper would look like (forgive the ruby/rails pseudo-code, it's been a month or two since I touched it):</p>\n\n<pre><code>def render_admin_menu()\n if !current_path.contains('offer')\n render :partial =&gt; 'shared/admin_menu'\n end\nend\n</code></pre>\n" }, { "answer_id": 127619, "author": "PJ.", "author_id": 3230, "author_profile": "https://Stackoverflow.com/users/3230", "pm_score": 4, "selected": true, "text": "<p>One thing you could play with is yield and content_for, used with a few partials for the menus. For example you could put each section of the menu in a partial and then modify your layout to something like:</p>\n\n<pre><code>&lt;%= yield(:menu) %&gt;\n</code></pre>\n\n<p>You then can then specify in your views content_for and put whatever partials you want into the menu. If it's not specified it won't get rendered.</p>\n\n<pre><code>&lt;% content_for(:menu) do %&gt;\n &lt;%= render :partial =&gt; 'layouts/menu' %&gt;\n &lt;%= render :partial =&gt; 'layouts/search_menu' %&gt;\n etc...\n &lt;% end %&gt;\n</code></pre>\n\n<p>If you're using a lot of the same menus in most pages, specify a default in your layout if no yield(:menu) is found.</p>\n\n<pre><code>&lt;%= yield(:menu) || render :partial =&gt; 'layouts/menu_default' %&gt;\n</code></pre>\n\n<p>Saves you a lot of typing. :) I've found this to be a nice clean way of handling things.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20467/" ]
Imagine to have two RESTful controllers (UsersController, OffersController) and a PagesController (used for static content such as index, about and so on) in your application. You have the following routes defined: ``` map.with_options :controller => 'pages' do |pages| pages.root :action => 'index' # static home page pages.about :action => 'about' # static about page # maybe more static pages... end map.resources :users # RESTful UsersController map.resources :posts # RESTful PostsController ``` Your application layout looks like this: ``` <html> <head> <title>Demo Application</title> </head> <body> <ul id="menu"> <li> <%= link_to 'Home', root_path %> </li> <li> <%= link_to 'Offers', offers_path %> <ul id="submenu> <li><%= link_to 'Search', 'path/to/search' %></li> <li>maybe more links...</li> </ul> </li> <li> <%= link_to 'About', about_path %> </li> <li> <%= link_to 'Admin', users_path %> <ul id="submenu"> <li><%= link_to 'New User', new_user_path %></li> <li><%= link_to 'New Offer', new_offer_path %></li> <li>maybe more links</li> </ul> </li> </li> <%= yield %> </body> </html> ``` The problem with the layout is that I want only one `#submenu` to be visible at any time. All other submenus can be completely skipped (don't need to rendered at all). Take the Admin menu for example: This menu should be active for all RESTful paths in the application except for `offers_path`. Active means that the submenu is visible. The only solution I can think of to achieve this is to build a lot complicated if conditions and that sucks (really complicated to write and to maintain). I'm looking for an elegant solution? I hope someone understands my question - if there's something unclear just comment the question and I'm going to explain it in more detail.
One thing you could play with is yield and content\_for, used with a few partials for the menus. For example you could put each section of the menu in a partial and then modify your layout to something like: ``` <%= yield(:menu) %> ``` You then can then specify in your views content\_for and put whatever partials you want into the menu. If it's not specified it won't get rendered. ``` <% content_for(:menu) do %> <%= render :partial => 'layouts/menu' %> <%= render :partial => 'layouts/search_menu' %> etc... <% end %> ``` If you're using a lot of the same menus in most pages, specify a default in your layout if no yield(:menu) is found. ``` <%= yield(:menu) || render :partial => 'layouts/menu_default' %> ``` Saves you a lot of typing. :) I've found this to be a nice clean way of handling things.
126,242
<p>This is probably explained more easily with an example. I'm trying to find a way of turning a relative URL, e.g. "/Foo.aspx" or "~/Foo.aspx" into a full URL, e.g. <a href="http://localhost/Foo.aspx" rel="noreferrer">http://localhost/Foo.aspx</a>. That way when I deploy to test or stage, where the domain under which the site runs is different, I will get <a href="http://test/Foo.aspx" rel="noreferrer">http://test/Foo.aspx</a> and <a href="http://stage/Foo.aspx" rel="noreferrer">http://stage/Foo.aspx</a>.</p> <p>Any ideas?</p>
[ { "answer_id": 126258, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 7, "selected": true, "text": "<p>Have a play with this (modified <a href=\"http://web.archive.org/web/20130730034405/http://www.aspdotnetfaq.com/Faq/how-to-convert-relative-url-to-absolute-url-in-asp-net-page.aspx\" rel=\"noreferrer\">from here</a>)</p>\n\n<pre><code>public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl) {\n return string.Format(\"http{0}://{1}{2}\",\n (Request.IsSecureConnection) ? \"s\" : \"\", \n Request.Url.Host,\n Page.ResolveUrl(relativeUrl)\n );\n}\n</code></pre>\n" }, { "answer_id": 126263, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 2, "selected": false, "text": "<p>Use the .NET Uri class to combine your relative path and the hostname.<br/>\n<a href=\"http://msdn.microsoft.com/en-us/library/system.uri.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.uri.aspx</a></p>\n" }, { "answer_id": 2788568, "author": "StocksR", "author_id": 6892, "author_profile": "https://Stackoverflow.com/users/6892", "pm_score": 3, "selected": false, "text": "<p>This is my helper function to do this</p>\n\n<pre><code>public string GetFullUrl(string relativeUrl) {\n string root = Request.Url.GetLeftPart(UriPartial.Authority);\n return root + Page.ResolveUrl(\"~/\" + relativeUrl) ;\n}\n</code></pre>\n" }, { "answer_id": 4146744, "author": "Joshua Grippo", "author_id": 503496, "author_profile": "https://Stackoverflow.com/users/503496", "pm_score": 2, "selected": false, "text": "<p>This is the helper function that I created to do the conversion.</p>\n\n<pre><code>//\"~/SomeFolder/SomePage.aspx\"\npublic static string GetFullURL(string relativePath)\n{\n string sRelative=Page.ResolveUrl(relativePath);\n string sAbsolute=Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,sRelative);\n return sAbsolute;\n}\n</code></pre>\n" }, { "answer_id": 7427598, "author": "Marcus", "author_id": 946286, "author_profile": "https://Stackoverflow.com/users/946286", "pm_score": 5, "selected": false, "text": "<p>You just need to create a new URI using the <code>page.request.url</code> and then get the <code>AbsoluteUri</code> of that:</p>\n<pre><code>New System.Uri(Page.Request.Url, &quot;Foo.aspx&quot;).AbsoluteUri\n</code></pre>\n" }, { "answer_id": 9020514, "author": "Josh M.", "author_id": 374198, "author_profile": "https://Stackoverflow.com/users/374198", "pm_score": 5, "selected": false, "text": "<p>This one's been beat to death but I thought I'd post my own solution which I think is cleaner than many of the other answers.</p>\n\n<pre><code>public static string AbsoluteAction(this UrlHelper url, string actionName, string controllerName, object routeValues)\n{\n return url.Action(actionName, controllerName, routeValues, url.RequestContext.HttpContext.Request.Url.Scheme);\n}\n\npublic static string AbsoluteContent(this UrlHelper url, string path)\n{\n Uri uri = new Uri(path, UriKind.RelativeOrAbsolute);\n\n //If the URI is not already absolute, rebuild it based on the current request.\n if (!uri.IsAbsoluteUri)\n {\n Uri requestUrl = url.RequestContext.HttpContext.Request.Url;\n UriBuilder builder = new UriBuilder(requestUrl.Scheme, requestUrl.Host, requestUrl.Port);\n\n builder.Path = VirtualPathUtility.ToAbsolute(path);\n uri = builder.Uri;\n }\n\n return uri.ToString();\n}\n</code></pre>\n" }, { "answer_id": 12461030, "author": "Menelaos Vergis", "author_id": 1503307, "author_profile": "https://Stackoverflow.com/users/1503307", "pm_score": 1, "selected": false, "text": "<p>Simply:</p>\n\n<pre><code>url = new Uri(baseUri, url);\n</code></pre>\n" }, { "answer_id": 14440359, "author": "stucampbell", "author_id": 21379, "author_profile": "https://Stackoverflow.com/users/21379", "pm_score": 2, "selected": false, "text": "<p>I thought I'd share my approach to doing this in ASP.NET MVC using the <code>Uri</code> class and some extension magic.</p>\n\n<pre><code>public static class UrlHelperExtensions\n{\n public static string AbsolutePath(this UrlHelper urlHelper, \n string relativePath)\n {\n return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,\n relativePath).ToString();\n }\n}\n</code></pre>\n\n<p>You can then output an absolute path using:</p>\n\n<pre><code>// gives absolute path, e.g. https://example.com/customers\nUrl.AbsolutePath(Url.Action(\"Index\", \"Customers\"));\n</code></pre>\n\n<p>It looks a little ugly having the nested method calls so I prefer to further extend <code>UrlHelper</code> with common action methods so that I can do:</p>\n\n<pre><code>// gives absolute path, e.g. https://example.com/customers\nUrl.AbsoluteAction(\"Index\", \"Customers\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Url.AbsoluteAction(\"Details\", \"Customers\", new{id = 123});\n</code></pre>\n\n<p>The full extension class is as follows:</p>\n\n<pre><code>public static class UrlHelperExtensions\n{\n public static string AbsolutePath(this UrlHelper urlHelper, \n string relativePath)\n {\n return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,\n relativePath).ToString();\n }\n\n public static string AbsoluteAction(this UrlHelper urlHelper, \n string actionName, \n string controllerName)\n {\n return AbsolutePath(urlHelper, \n urlHelper.Action(actionName, controllerName));\n }\n\n public static string AbsoluteAction(this UrlHelper urlHelper, \n string actionName, \n string controllerName, \n object routeValues)\n {\n return AbsolutePath(urlHelper, \n urlHelper.Action(actionName, \n controllerName, routeValues));\n }\n}\n</code></pre>\n" }, { "answer_id": 14950535, "author": "Carl G", "author_id": 39396, "author_profile": "https://Stackoverflow.com/users/39396", "pm_score": 1, "selected": false, "text": "<p>In ASP.NET MVC you can use the overloads of <a href=\"http://msdn.microsoft.com/en-us/library/dd492619%28v=vs.108%29.aspx\" rel=\"nofollow\"><code>HtmlHelper</code></a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper%28v=vs.108%29.aspx\" rel=\"nofollow\"><code>UrlHelper</code></a> that take the <code>protocol</code> or <code>host</code> parameters. When either of these paramters are non-empty, the helpers generate an absolute URL. This is an extension method I'm using:</p>\n\n<pre><code>public static MvcHtmlString ActionLinkAbsolute&lt;TViewModel&gt;(\n this HtmlHelper&lt;TViewModel&gt; html, \n string linkText, \n string actionName, \n string controllerName, \n object routeValues = null,\n object htmlAttributes = null)\n{\n var request = html.ViewContext.HttpContext.Request;\n var url = new UriBuilder(request.Url);\n return html.ActionLink(linkText, actionName, controllerName, url.Scheme, url.Host, null, routeValues, htmlAttributes);\n}\n</code></pre>\n\n<p>And use it from a Razor view, e.g.:</p>\n\n<pre><code> @Html.ActionLinkAbsolute(\"Click here\", \"Action\", \"Controller\", new { id = Model.Id }) \n</code></pre>\n" }, { "answer_id": 37122000, "author": "Robert McKee", "author_id": 856353, "author_profile": "https://Stackoverflow.com/users/856353", "pm_score": 0, "selected": false, "text": "<p>Ancient question, but I thought I'd answer it since many of the answers are incomplete.</p>\n\n<pre><code>public static string ResolveFullUrl(this System.Web.UI.Page page, string relativeUrl)\n{\n if (string.IsNullOrEmpty(relativeUrl))\n return relativeUrl;\n\n if (relativeUrl.StartsWith(\"/\"))\n relativeUrl = relativeUrl.Insert(0, \"~\");\n if (!relativeUrl.StartsWith(\"~/\"))\n relativeUrl = relativeUrl.Insert(0, \"~/\");\n\n return $\"{page.Request.Url.Scheme}{Uri.SchemeDelimiter}{page.Request.Url.Authority}{VirtualPathUtility.ToAbsolute(relativeUrl)}\";\n}\n</code></pre>\n\n<p>This works as an extension of off Page, just like ResolveUrl and ResolveClientUrl for webforms. Feel free to convert it to a HttpResponse extension if you want or need to use it in a non-webforms environment. It correctly handles both http and https, on standard and non-standard ports, and if there is a username/password component. It also doesn't use any hard coded strings (namely ://).</p>\n" }, { "answer_id": 37884172, "author": "Xavier J", "author_id": 3167751, "author_profile": "https://Stackoverflow.com/users/3167751", "pm_score": 0, "selected": false, "text": "<p>Here's an approach. This doesn't care if the string is relative or absolute, but you must provide a baseUri for it to use.</p>\n\n<pre><code> /// &lt;summary&gt;\n /// This function turns arbitrary strings containing a \n /// URI into an appropriate absolute URI. \n /// &lt;/summary&gt;\n /// &lt;param name=\"input\"&gt;A relative or absolute URI (as a string)&lt;/param&gt;\n /// &lt;param name=\"baseUri\"&gt;The base URI to use if the input parameter is relative.&lt;/param&gt;\n /// &lt;returns&gt;An absolute URI&lt;/returns&gt;\n public static Uri MakeFullUri(string input, Uri baseUri)\n {\n var tmp = new Uri(input, UriKind.RelativeOrAbsolute);\n //if it's absolute, return that\n if (tmp.IsAbsoluteUri)\n {\n return tmp;\n }\n // build relative on top of the base one instead\n return new Uri(baseUri, tmp);\n }\n</code></pre>\n\n<p>In an ASP.NET context, you could do this:</p>\n\n<pre><code>Uri baseUri = new Uri(\"http://yahoo.com/folder\");\nUri newUri = MakeFullUri(\"/some/path?abcd=123\", baseUri);\n//\n//newUri will contain http://yahoo.com/some/path?abcd=123\n//\nUri newUri2 = MakeFullUri(\"some/path?abcd=123\", baseUri);\n//\n//newUri2 will contain http://yahoo.com/folder/some/path?abcd=123\n//\nUri newUri3 = MakeFullUri(\"http://google.com\", baseUri);\n//\n//newUri3 will contain http://google.com, and baseUri is not used at all.\n//\n</code></pre>\n" }, { "answer_id": 43555252, "author": "Softcanon Development", "author_id": 7852940, "author_profile": "https://Stackoverflow.com/users/7852940", "pm_score": 0, "selected": false, "text": "<p>Modified from other answer for work with localhost and other ports... im using for ex. email links. You can call from any part of app, not only in a page or usercontrol, i put this in Global for not need to pass HttpContext.Current.Request as parameter</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Return full URL from virtual relative path like ~/dir/subir/file.html\n /// usefull in ex. external links\n /// &lt;/summary&gt;\n /// &lt;param name=\"rootVirtualPath\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static string GetAbsoluteFullURLFromRootVirtualPath(string rootVirtualPath)\n {\n\n return string.Format(\"http{0}://{1}{2}{3}\",\n (HttpContext.Current.Request.IsSecureConnection) ? \"s\" : \"\"\n , HttpContext.Current.Request.Url.Host\n , (HttpContext.Current.Request.Url.IsDefaultPort) ? \"\" : \":\" + HttpContext.Current.Request.Url.Port\n , VirtualPathUtility.ToAbsolute(rootVirtualPath)\n );\n\n }\n</code></pre>\n" }, { "answer_id": 60466798, "author": "Aftab Ahmed Kalhoro", "author_id": 1767839, "author_profile": "https://Stackoverflow.com/users/1767839", "pm_score": 0, "selected": false, "text": "<p>In ASP.NET MVC, you can use <code>Url.Content(relativePath)</code> to convert into absolute Url</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277/" ]
This is probably explained more easily with an example. I'm trying to find a way of turning a relative URL, e.g. "/Foo.aspx" or "~/Foo.aspx" into a full URL, e.g. <http://localhost/Foo.aspx>. That way when I deploy to test or stage, where the domain under which the site runs is different, I will get <http://test/Foo.aspx> and <http://stage/Foo.aspx>. Any ideas?
Have a play with this (modified [from here](http://web.archive.org/web/20130730034405/http://www.aspdotnetfaq.com/Faq/how-to-convert-relative-url-to-absolute-url-in-asp-net-page.aspx)) ``` public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl) { return string.Format("http{0}://{1}{2}", (Request.IsSecureConnection) ? "s" : "", Request.Url.Host, Page.ResolveUrl(relativeUrl) ); } ```
126,271
<p>Does someone have experience with storing key-value pairs in a database?</p> <p>I've been using this type of table:</p> <pre><code>CREATE TABLE key_value_pairs ( itemid varchar(32) NOT NULL, itemkey varchar(32) NOT NULL, itemvalue varchar(32) NOT NULL, CONSTRAINT ct_primarykey PRIMARY KEY(itemid,itemkey) ) </code></pre> <p>Then for example the following rows could exist:</p> <pre><code> itemid itemkey itemvalue ---------------- ------------- ------------ 123 Colour Red 123 Size Medium 123 Fabric Cotton </code></pre> <p>The trouble with this scheme is the SQL syntax required to extract data is quite complex. Would it be better to just create a series of key/value columns?</p> <pre><code>CREATE TABLE key_value_pairs ( itemid varchar(32) NOT NULL, itemkey1 varchar(32) NOT NULL, itemvalue1 varchar(32) NOT NULL, itemkey2 varchar(32) NOT NULL, itemvalue2 varchar(32) NOT NULL, . . .etc . . . ) </code></pre> <p>This will be easier and faster to query but lacks the extensibility of the first approach. Any advice?</p>
[ { "answer_id": 126282, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 1, "selected": false, "text": "<p>the first method is quite ok. you can create a UDF that extracts the desired data and just call that.</p>\n" }, { "answer_id": 126295, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 3, "selected": false, "text": "<p>From experience, i have found that certain keys will be more widely used or queried more often. We have usually then slightly de-normalized the design to include a specific field back in the main \"item\" table.</p>\n\n<p>eg. if every Item has a Colour, you might add the Colour column to your item table. Fabric and Size may be used less often and can be kept separate in the key-value pair table. You may even keep the colour in the key-value pair table, but duplicate the data in the item table to get the performance benefits.</p>\n\n<p>Obviously this varies depending on the data and how flexible you need the key-value pairs to be. It can also result in your attribute data not being located consistantly. However, de-normalizing does greatly simplify the queries and improves their performance as well. </p>\n\n<p>I would usually only consider de-normalizing when performance becomes and issue, not just to simplify a query.</p>\n" }, { "answer_id": 126302, "author": "Valerion", "author_id": 16156, "author_profile": "https://Stackoverflow.com/users/16156", "pm_score": 0, "selected": false, "text": "<p>The second table is badly de-normalised. I would stick with the first approach.</p>\n" }, { "answer_id": 126307, "author": "Hannes Ovrén", "author_id": 13565, "author_profile": "https://Stackoverflow.com/users/13565", "pm_score": 2, "selected": false, "text": "<p>If you have very few possible keys, then I would just store them as columns. But if the set of possible keys is large then your first approach is good (and the second approach would be impossible).</p>\n\n<p>Or is it so that each item can only have a finite number of keys, but the keys could be something from a large set?</p>\n\n<p>You could also consider using an Object Relational Mapper to make querying easier.</p>\n" }, { "answer_id": 126308, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>The first method is a lot more flexible at the cost you mention. </p>\n\n<p>And the second approach is never viable as you showed. Instead you'd do (as per your first example) </p>\n\n<pre><code>create table item_config (item_id int, colour varchar, size varchar, fabric varchar)\n</code></pre>\n\n<p>of course this will only work when the amount of data is known and doesn't change a lot.</p>\n\n<p>As a general rule any application that demands changing DDL of tables to do normal work should be given a second and third thoughts.</p>\n" }, { "answer_id": 126379, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 0, "selected": false, "text": "<p>I think you're doing the right thing, as long as the keys/values for a given type of item change frequently.<br>\nIf they are rather static, then simply making the item table wider makes more sense. </p>\n\n<p>We use a similar (but rather more complex) approach, with a lot of logic around the keys/values, as well as tables for the types of values permitted for each key.<br>\nThis allows us to define items as just another instance of a key, and our central table maps arbitrary key types to other arbitrary key types. It can rapidly tie your brain in knots, but once you've written and encapsulated the logic to handle it all, you have a lot of flexibility. </p>\n\n<p>I can write more details of what we do if required.</p>\n" }, { "answer_id": 126383, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "<p>I don't understand why the SQL to extract data should be complex for your first design. Surely to get all values for an item, you just do this:</p>\n\n<pre><code>SELECT itemkey,itemvalue FROM key_value_pairs WHERE itemid='123';\n</code></pre>\n\n<p>or if you just want one particular key for that item:</p>\n\n<pre><code>SELECT itemvalue FROM key_value_pairs WHERE itemid='123' AND itemkey='Fabric';\n</code></pre>\n\n<p>The first design also gives you the flexibility to easily add new keys whenever you like.</p>\n" }, { "answer_id": 126392, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 0, "selected": false, "text": "<p>If the keys are dynamic, or there are loads of them, then use the mapping table that you have as your first example. In addition this is the most general solution, it scales best in the future as you add more keys, it is easy to code the SQL to get the data out, and the database will be able to optimise the query better than you would imagine (i.e., I wouldn't put effort into prematurely optimising this case unless it was proven to be a bottleneck in testing later on, in which case you could consider the next two options below).</p>\n\n<p>If the keys are a known set, and there aren't many of them (&lt;10, maybe &lt;5), then I don't see the problem in having them as value columns on the item.</p>\n\n<p>If there are a medium number of known fixed keys (10 - 30) then maybe have another table to hold the item_details.</p>\n\n<p>However I don't ever see a need to use your second example structure, it looks cumbersome.</p>\n" }, { "answer_id": 126397, "author": "Peter Marshall", "author_id": 4692, "author_profile": "https://Stackoverflow.com/users/4692", "pm_score": 4, "selected": false, "text": "<p>There is another solution that falls somewhere between the two. You can use an xml type column for the keys and values. So you keep the itemid field, then have an xml field that contains the xml defined for some key value pairs like <code>&lt;items&gt; &lt;item key=\"colour\" value=\"red\"/&gt;&lt;item key=\"xxx\" value=\"blah\"/&gt;&lt;/items&gt;</code>\nThen when you extract your data fro the database you can process the xml in a number of different ways. Depending on your usage. This is an extend able solution. </p>\n" }, { "answer_id": 126467, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 1, "selected": false, "text": "<p>Violating normalization rules is fine as long as the business requirement can still be fulfilled. Having <code>key_1, value_1, key_2, value_2, ... key_n, value_n</code> can be OK, right up until the point that you need <code>key_n+1, value_n+1</code>.</p>\n\n<p>My solution has been a table of data for shared attributes and XML for unique attributes. That means I use both. If everything (or most things) have a size, then size is a column in the table. If only object A have attribute Z, then Z is stored as XML similar Peter Marshall's answer already given.</p>\n" }, { "answer_id": 126735, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 4, "selected": false, "text": "<p>In most cases that you would use the first method, it's because you haven't really sat down and thought out your model. \"Well, we don't know what the keys will be yet\". Generally, this is pretty poor design. It's going to be slower than actually having your keys as columns, which they should be.</p>\n\n<p>I'd also question why your id is a varchar.</p>\n\n<p>In the rare case that you really must implement a key/value table, the first solution is fine, although, I'd generally want to have the keys in a separate table so you aren't storing varchars as the keys in your key/value table.</p>\n\n<p>eg,</p>\n\n<pre><code>CREATE TABLE valid_keys ( \n id NUMBER(10) NOT NULL,\n description varchar(32) NOT NULL,\n CONSTRAINT pk_valid_keys PRIMARY KEY(id)\n);\n\nCREATE TABLE item_values ( \n item_id NUMBER(10) NOT NULL,\n key_id NUMBER(10) NOT NULL,\n item_value VARCHAR2(32) NOT NULL,\n CONSTRAINT pk_item_values PRIMARY KEY(item_id),\n CONSTRAINT fk_item_values_iv FOREIGN KEY (key_id) REFERENCES valid_keys (id)\n);\n</code></pre>\n\n<p>You can then even go nuts and add a \"TYPE\" to the keys, allowing some type checking.</p>\n" }, { "answer_id": 127172, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 8, "selected": true, "text": "<p>Before you continue on your approach, I would humbly suggest you step back and consider if you really want to store this data in a \"Key-Value Pair\"table. I don't know your application but my experience has shown that every time I have done what you are doing, later on I wish I had created a color table, a fabric table and a size table.</p>\n\n<p>Think about referential integrity constraints, if you take the key-value pair approach, the database can't tell you when you are trying to store a color id in a size field</p>\n\n<p>Think about the performance benefits of joining on a table with 10 values versus a generic value that may have thousands of values across multiple domains. How useful is an index on Key Value really going to be?</p>\n\n<p>Usually the reasoning behind doing what you are doing is because the domains need to be \"user definable\". If that is the case then even I am not going to push you towards creating tables on the fly (although that is a feasible approach).</p>\n\n<p>However, if your reasoning is because you think it will be easier to manage than multiple tables, or because you are envisioning a maintenance user interface that is generic for all domains, then stop and think really hard before you continue.</p>\n" }, { "answer_id": 131349, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "<p>If you go the route of a KVP table, and I have to say that I do not like that technique at all myself as it is indeed difficult to query, then you should consider clustering the values for a single item id together using an appropriate technique for whatever platform you're on.</p>\n\n<p>RDBMS's have a tendency to scatter rows around to avoid block contention on inserts and if you have 8 rowes to retrieve you could easily find yourself accessing 8 blocks of the table to read them. On Oracle you'd do well to consider a hash cluster for storing these, which would vastly improve performance on accessing the values for a given item id.</p>\n" }, { "answer_id": 325260, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Your example is not a very good example of the use of key value pairs. A better example would be the use of something like a Fee table a Customer table and a Customer_Fee table in a billing application. The Fee table would consist of fields like:\n fee_id, fee_name, fee_description \nThe Customer_Fee table would consist of fields like:\n customer_id, fee_id, fee_value</p>\n" }, { "answer_id": 916828, "author": "mansu", "author_id": 105735, "author_profile": "https://Stackoverflow.com/users/105735", "pm_score": 2, "selected": false, "text": "<p>I think the best way to design such tables is as follows:</p>\n\n<ul>\n<li>Make the frequently used fields as columns in the database.</li>\n<li>Provide a Misc column which contains a dictionary(in JSON/XML/other string formeat) which will contain the fields as key-value pairs. </li>\n</ul>\n\n<p>Salient points:</p>\n\n<ul>\n<li>You can write your normal SQL queries to query for SQL in most situations.</li>\n<li>You can do a FullTextSearch on the key-value pairs. MySQL has a full text search engine, else you can use \"like\" queries which are a little slower. While full text search is bad, we assume that such queries are fewer, so that should not cause too many issues.</li>\n<li>If your key-value pairs are simple boolean flags, this technique has the same power as having a separate column for the key. Any more complex operation on the key value pairs should be done outside the database.</li>\n<li>Looking at the frequency of queries over a period of time will give tell you which key-value pairs need to be converted in columns.</li>\n<li>This technique also makes it easy to force integrity constraints on the database.</li>\n<li>It provides a more natural path for developers to re-factor their schema and code.</li>\n</ul>\n" }, { "answer_id": 1556295, "author": "Mario", "author_id": 25358, "author_profile": "https://Stackoverflow.com/users/25358", "pm_score": 4, "selected": false, "text": "<p>I once used key-value pairs in a database for the purpose of creating a spreadsheet (used for data entry) in which a teller would summarize his activity from working a cash drawer. Each k/v pair represented a named cell into which the user entered a monetary amount. The primary reason for this approach is that the spreadsheet was highly subject to change. New products and services were added routinely (thus new cells appeared). Also, certain cells were not needed in certain situations and could be dropped.</p>\n\n<p>The app I wrote was a rewrite of an application that did break the teller sheet into separate sections each represented in a different table. The trouble here was that as products and services were added, schema modifications were required. As with all design choices there are pros and cons to taking a certain direction as compared to another. My redesign certainly performed slower and more quickly consumed disk space; however, it was highly agile and allowed for new products and services to be added in minutes. The only issue of note, however, was disk consumption; there were no other headaches I can recall.</p>\n\n<p>As already mentioned, the reason I usually consider a key-value pair approach is when users—this could be a the business owner—want to create their own types having a user-specific set of attributes. In such situations I have come to the following determination.</p>\n\n<p>If there is either no need to retrieve data by these attributes or searching can be deferred to the application once a chunk of data has been retrieved, I recommend storing all the attributes in a single text field (using JSON, YAML, XML, etc.). If there is a strong need to retrieve data by these attributes, it gets messy.</p>\n\n<p>You can create a single \"attributes\" table (id, item_id, key, value, data_type, sort_value) where the sort column coverts the actual value into a string-sortable representation. (e.g. date: “2010-12-25 12:00:00”, number: “0000000001”) Or you can create separate attribute tables by data-type (e.g. string_attributes, date_attributes, number_attributes). Among numerous pros and cons to both approaches: the first is simpler, the second is faster. Both will cause you to write ugly, complex queries.</p>\n" }, { "answer_id": 28909443, "author": "Trevy Burgess", "author_id": 3538246, "author_profile": "https://Stackoverflow.com/users/3538246", "pm_score": -1, "selected": false, "text": "<p>Times have changed. Now you have other database types you can use beside relational databases. NOSQL choices now include, Column Stores, Document Stores, Graph, and Multi-model (See: <a href=\"http://en.wikipedia.org/wiki/NoSQL\" rel=\"nofollow\">http://en.wikipedia.org/wiki/NoSQL</a>).</p>\n\n<p>For Key-Value databases, your choices include (but not limited to) CouchDb, Redis, and MongoDB.</p>\n" }, { "answer_id": 32714379, "author": "Amar", "author_id": 2206412, "author_profile": "https://Stackoverflow.com/users/2206412", "pm_score": 3, "selected": false, "text": "<p>PostgreSQL 8.4 supports hstore data type for storing sets of (key,value) pairs within a single PostgreSQL data field.\nPlease refer <a href=\"http://www.postgresql.org/docs/8.4/static/hstore.html\" rel=\"noreferrer\">http://www.postgresql.org/docs/8.4/static/hstore.html</a> for its usage information. Though it's very old question but thought to pass on this info thinking it might help someone.</p>\n" }, { "answer_id": 72413084, "author": "nomadus", "author_id": 2480869, "author_profile": "https://Stackoverflow.com/users/2480869", "pm_score": 0, "selected": false, "text": "<p>I've been thinking about the same challenge and this is what I came up with.\nThe task is a relational table, where I store common attributes:</p>\n<pre><code>CREATE TABLE `tasks` (\n `task_id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,\n `account_id` BIGINT(20) UNSIGNED NOT NULL,\n `type` VARCHAR(128) COLLATE UTF8MB4_UNICODE_CI DEFAULT NULL,\n `title` VARCHAR(256) COLLATE UTF8MB4_UNICODE_CI NOT NULL,\n `description` TEXT COLLATE UTF8MB4_UNICODE_CI NOT NULL,\n `priority` VARCHAR(40) COLLATE UTF8MB4_UNICODE_CI DEFAULT NULL,\n `created_by` VARCHAR(40) COLLATE UTF8MB4_UNICODE_CI DEFAULT NULL,\n `creation_date` TIMESTAMP NULL DEFAULT NULL,\n `last_updated_by` VARCHAR(40) COLLATE UTF8MB4_UNICODE_CI DEFAULT NULL,\n `last_updated_date` TIMESTAMP NULL DEFAULT NULL,\n PRIMARY KEY (`task_id`),\n KEY `tasks_fk_1` (`account_id`),\n CONSTRAINT `tasks_fk_1` FOREIGN KEY (`account_id`)\n REFERENCES `accounts` (`account_id`)\n ON DELETE CASCADE ON UPDATE NO ACTION\n) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=UTF8MB4 COLLATE = UTF8MB4_UNICODE_CI ROW_FORMAT=DYNAMIC;\n</code></pre>\n<p>And here is the KV table to store additional task info. I prefer storing values with their types to handle the data in a proper way. Feel free to comment.</p>\n<pre><code>CREATE TABLE `task_variables` (\n `row_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n `task_id` bigint(20) unsigned NOT NULL,\n `name` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,\n `type` varchar(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,\n `variable_text_value` varchar(256) COLLATE utf8mb4_unicode_ci DEFAULT NULL,\n `variable_number_value` double DEFAULT NULL,\n `variable_date_value` datetime DEFAULT NULL,\n `created_by` varchar(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,\n `creation_date` timestamp NULL DEFAULT NULL,\n `last_updated_by` varchar(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,\n `last_updated_date` timestamp NULL DEFAULT NULL,\n PRIMARY KEY (`row_id`),\n KEY `task_variables_fk` (`task_id`),\n CONSTRAINT `task_variables_fk` FOREIGN KEY (`task_id`) REFERENCES `tasks` (`task_id`) ON DELETE CASCADE\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2887/" ]
Does someone have experience with storing key-value pairs in a database? I've been using this type of table: ``` CREATE TABLE key_value_pairs ( itemid varchar(32) NOT NULL, itemkey varchar(32) NOT NULL, itemvalue varchar(32) NOT NULL, CONSTRAINT ct_primarykey PRIMARY KEY(itemid,itemkey) ) ``` Then for example the following rows could exist: ``` itemid itemkey itemvalue ---------------- ------------- ------------ 123 Colour Red 123 Size Medium 123 Fabric Cotton ``` The trouble with this scheme is the SQL syntax required to extract data is quite complex. Would it be better to just create a series of key/value columns? ``` CREATE TABLE key_value_pairs ( itemid varchar(32) NOT NULL, itemkey1 varchar(32) NOT NULL, itemvalue1 varchar(32) NOT NULL, itemkey2 varchar(32) NOT NULL, itemvalue2 varchar(32) NOT NULL, . . .etc . . . ) ``` This will be easier and faster to query but lacks the extensibility of the first approach. Any advice?
Before you continue on your approach, I would humbly suggest you step back and consider if you really want to store this data in a "Key-Value Pair"table. I don't know your application but my experience has shown that every time I have done what you are doing, later on I wish I had created a color table, a fabric table and a size table. Think about referential integrity constraints, if you take the key-value pair approach, the database can't tell you when you are trying to store a color id in a size field Think about the performance benefits of joining on a table with 10 values versus a generic value that may have thousands of values across multiple domains. How useful is an index on Key Value really going to be? Usually the reasoning behind doing what you are doing is because the domains need to be "user definable". If that is the case then even I am not going to push you towards creating tables on the fly (although that is a feasible approach). However, if your reasoning is because you think it will be easier to manage than multiple tables, or because you are envisioning a maintenance user interface that is generic for all domains, then stop and think really hard before you continue.
126,277
<p>Say you want to generate a matched list of identifiers and strings</p> <pre><code>enum { NAME_ONE, NAME_TWO, NAME_THREE }; myFunction(NAME_ONE, "NAME_ONE"); myFunction(NAME_TWO, "NAME_TWO"); myFunction(NAME_THREE, "NAME_THREE"); </code></pre> <p>..without repeating yourself, and without auto-generating the code, using C/C++ macros</p> <p><b>Initial guess:</b></p> <p>You could add an #include file containing</p> <pre><code>myDefine(NAME_ONE) myDefine(NAME_TWO) myDefine(NAME_THREE) </code></pre> <p>Then use it twice like:</p> <pre><code>#define myDefine(a) a, enum { #include "definitions" } #undef myDefine #define myDefine(a) myFunc(a, "a"); #include "definitions" #undef myDefine </code></pre> <p>but #define doesn't let you put parameters within a string?</p>
[ { "answer_id": 126291, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 6, "selected": true, "text": "<p>For your second #define, you need to use the # preprocessor operator, like this:</p>\n\n<pre><code>#define myDefine(a) myFunc(a, #a);\n</code></pre>\n\n<p>That converts the argument to a string.</p>\n" }, { "answer_id": 126511, "author": "AareP", "author_id": 11741, "author_profile": "https://Stackoverflow.com/users/11741", "pm_score": 2, "selected": false, "text": "<p>Here's a good way to declare name-list:</p>\n\n<pre><code>#define FOR_ALL_FUNCTIONS(F)\\\n F(NameOne)\\\n F(NameTwo)\\\n F(NameThree)\\\n\n#define DECLARE_FUNCTION(N)\\\n void N();\n\n#define IMPLEMENT_FUNCTION(N)\\\n void N(){}\n\nFOR_ALL_FUNCTIONS(DECLARE_FUNCTION);\nFOR_ALL_FUNCTIONS(IMPLEMENT_FUNCTION);\n</code></pre>\n\n<p>This way this name-list can be re-used multiple times. I have used it for prototyping new language features, although never ended up using them. So, if nothing else, they were a great way to find dead-ends in own inventions. I wonder if it's because what they say: \"macros are bad\"... :)</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46478/" ]
Say you want to generate a matched list of identifiers and strings ``` enum { NAME_ONE, NAME_TWO, NAME_THREE }; myFunction(NAME_ONE, "NAME_ONE"); myFunction(NAME_TWO, "NAME_TWO"); myFunction(NAME_THREE, "NAME_THREE"); ``` ..without repeating yourself, and without auto-generating the code, using C/C++ macros **Initial guess:** You could add an #include file containing ``` myDefine(NAME_ONE) myDefine(NAME_TWO) myDefine(NAME_THREE) ``` Then use it twice like: ``` #define myDefine(a) a, enum { #include "definitions" } #undef myDefine #define myDefine(a) myFunc(a, "a"); #include "definitions" #undef myDefine ``` but #define doesn't let you put parameters within a string?
For your second #define, you need to use the # preprocessor operator, like this: ``` #define myDefine(a) myFunc(a, #a); ``` That converts the argument to a string.
126,297
<p>After I <a href="https://stackoverflow.com/questions/121922/automatic-casts">messed up the description of my previous post</a> on this I have sat down and tried to convey my exact intent.</p> <p>I have a class called P which performs some distinct purpose. I also have PW which perform some distinct purpose on P. PW has no member variables, just member functions.</p> <p>From this description you would assume that the code would follow like this:</p> <pre><code>class P { public: void a( ); }; class PW { public: PW( const P&amp; p ) : p( p ) { } void b( ); P&amp; p; }; class C { public: P GetP( ) const { return p; } private: P p; }; // ... PW&amp; p = c.GetP( ); // valid // ... </code></pre> <p>However that brings up a problem. I can't call the functions of P without indirection everywhere.</p> <pre><code>// ... p-&gt;p-&gt;a( ) // ... </code></pre> <p><strong>What I would like to do is call p->a( ) and have it automatically determine that I would like to call the member function of P.</strong></p> <p>Also having a member of PW called <em>a</em> doesn't really scale - what if I add (or remove) another function to P - this will need to be added (or removed) to PW.</p>
[ { "answer_id": 126321, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 1, "selected": false, "text": "<p>If you make P a superclass to PW, like you did in your previous question, you could call p->a() and it would direct to class P. It seems like you've already considered and rejected this though, judging from this question. If so, would you care to elaborate why this wont work for you? </p>\n" }, { "answer_id": 126446, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 3, "selected": true, "text": "<p>You could try overriding operator* and operator-> to return access to the embedded p.\nSomething like this might do the trick :</p>\n\n<pre><code>class P\n{\n public:\n void a( ) { std::cout &lt;&lt; \"a\" &lt;&lt; std::endl; }\n};\n\nclass PW\n{\n public:\n PW(P&amp; p) : p(p) { }\n\n void b( ) { std::cout &lt;&lt; \"b\" &lt;&lt; std::endl; }\n\n P &amp; operator*() { return p; }\n P * operator-&gt;() { return &amp;p; }\n\n private:\n P &amp; p;\n};\n\nclass C\n{\n public:\n P &amp; getP() { return p; }\n\n private:\n P p;\n};\n\n\nint main()\n{\n C c;\n PW pw(c.getP());\n\n (*pw).a();\n pw-&gt;a();\n pw.b();\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>This code prints</p>\n\n<pre><code>a\na\nb\n</code></pre>\n\n<p>However, this method may confuse the user since the semantic of operator* and operator-> becomes a little messed up.</p>\n" }, { "answer_id": 127697, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 0, "selected": false, "text": "<p>I think you need to think through what kind of relationship exists between PW and P.</p>\n\n<p>Is it an is-a relationship? Are instances of PW instances of P? Then it would make sense to have PW inherit from P.</p>\n\n<p>Is it a has-a relationship? Then you should stick with containment, and put up with the syntactic inconvenience.</p>\n\n<p>Incidentally, it's generally not a good idea to expose a non-const reference to a member variable in a class's public interface.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ]
After I [messed up the description of my previous post](https://stackoverflow.com/questions/121922/automatic-casts) on this I have sat down and tried to convey my exact intent. I have a class called P which performs some distinct purpose. I also have PW which perform some distinct purpose on P. PW has no member variables, just member functions. From this description you would assume that the code would follow like this: ``` class P { public: void a( ); }; class PW { public: PW( const P& p ) : p( p ) { } void b( ); P& p; }; class C { public: P GetP( ) const { return p; } private: P p; }; // ... PW& p = c.GetP( ); // valid // ... ``` However that brings up a problem. I can't call the functions of P without indirection everywhere. ``` // ... p->p->a( ) // ... ``` **What I would like to do is call p->a( ) and have it automatically determine that I would like to call the member function of P.** Also having a member of PW called *a* doesn't really scale - what if I add (or remove) another function to P - this will need to be added (or removed) to PW.
You could try overriding operator\* and operator-> to return access to the embedded p. Something like this might do the trick : ``` class P { public: void a( ) { std::cout << "a" << std::endl; } }; class PW { public: PW(P& p) : p(p) { } void b( ) { std::cout << "b" << std::endl; } P & operator*() { return p; } P * operator->() { return &p; } private: P & p; }; class C { public: P & getP() { return p; } private: P p; }; int main() { C c; PW pw(c.getP()); (*pw).a(); pw->a(); pw.b(); return EXIT_SUCCESS; } ``` This code prints ``` a a b ``` However, this method may confuse the user since the semantic of operator\* and operator-> becomes a little messed up.
126,320
<p>Suppose I have a set of commits in a repository folder...</p> <pre><code>123 (250 new files, 137 changed files, 14 deleted files) 122 (150 changed files) 121 (renamed folder) 120 (90 changed files) 119 (115 changed files, 14 deleted files, 12 added files) 118 (113 changed files) 117 (10 changed files) </code></pre> <p>I want to get a working copy that includes all changes from revision 117 onward but does NOT include the changes for revisions 118 and 120.</p> <p>EDIT: To perhaps make the problem clearer, I want to undo the changes that were made in 118 and 120 while retaining all other changes. The folder contains thousands of files in hundreds of subfolders.</p> <p>What is the best way to achieve this?</p> <p><strong>The answer</strong>, thanks to Bruno and Bert, is the command (in this case, for removing 120 after the full merge was performed)</p> <pre><code>svn merge -c -120 . </code></pre> <p>Note that the revision number must be specified with a leading minus. '-120' not '120'</p>
[ { "answer_id": 126357, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": -1, "selected": false, "text": "<p>I suppose you could create a branch from revision 117, then merge everything except 118 and 120.</p>\n\n<pre><code>svn copy -r 117 source destination\n</code></pre>\n\n<p>Then checkout this branch and from there do <code>svnmerge.py merge -r119,120-123</code></p>\n\n<p><strong>EDIT:</strong> This doesn't undo the revisions in the branch/trunk. Use <code>svn merge</code> instead.</p>\n" }, { "answer_id": 126411, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 6, "selected": true, "text": "<p>To undo revisions 118 and 120:</p>\n\n<pre><code>svn up -r HEAD # get latest revision\nsvn merge -c -120 . # undo revision 120\nsvn merge -c -118 . # undo revision 118\nsvn commit # after solving problems (if any)\n</code></pre>\n\n<p>Also see the description in <a href=\"http://svnbook.red-bean.com/en/1.5/svn.branchmerge.basicmerging.html#svn.branchmerge.basicmerging.undo\" rel=\"noreferrer\">Undoing changes</a>.</p>\n\n<p>Note the minus in the <code>-c -120</code> argument. The <code>-c</code> (or <code>--change</code>) switch is supported since Subversion 1.4, older versions can use <code>-r 120:119</code>.</p>\n" }, { "answer_id": 143137, "author": "neves", "author_id": 10335, "author_profile": "https://Stackoverflow.com/users/10335", "pm_score": 3, "selected": false, "text": "<p>There's a more straightforward way if you use TortoiseSVN, a Windows client for Subversion. You just click to view the log in your updated work copy, select the revisions you want to undo, right click, and select \"Revert changes from these revisions\".</p>\n\n<p>It is a safe operation because the changes are applied just in your workspace. You still have to commit to modify your repository.</p>\n\n<p>It is one of the best features of TortoiseSVN. I've always been a command line guy, but Tortoise changed my mind. </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4200/" ]
Suppose I have a set of commits in a repository folder... ``` 123 (250 new files, 137 changed files, 14 deleted files) 122 (150 changed files) 121 (renamed folder) 120 (90 changed files) 119 (115 changed files, 14 deleted files, 12 added files) 118 (113 changed files) 117 (10 changed files) ``` I want to get a working copy that includes all changes from revision 117 onward but does NOT include the changes for revisions 118 and 120. EDIT: To perhaps make the problem clearer, I want to undo the changes that were made in 118 and 120 while retaining all other changes. The folder contains thousands of files in hundreds of subfolders. What is the best way to achieve this? **The answer**, thanks to Bruno and Bert, is the command (in this case, for removing 120 after the full merge was performed) ``` svn merge -c -120 . ``` Note that the revision number must be specified with a leading minus. '-120' not '120'
To undo revisions 118 and 120: ``` svn up -r HEAD # get latest revision svn merge -c -120 . # undo revision 120 svn merge -c -118 . # undo revision 118 svn commit # after solving problems (if any) ``` Also see the description in [Undoing changes](http://svnbook.red-bean.com/en/1.5/svn.branchmerge.basicmerging.html#svn.branchmerge.basicmerging.undo). Note the minus in the `-c -120` argument. The `-c` (or `--change`) switch is supported since Subversion 1.4, older versions can use `-r 120:119`.
126,332
<p>I'm wanting a method called same_url? that will return true if the passed in URLs are equal. The passed in URLs might be either params options hash or strings.</p> <pre><code>same_url?({:controller =&gt; :foo, :action =&gt; :bar}, "http://www.example.com/foo/bar") # =&gt; true </code></pre> <p>The Rails Framework helper <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001607" rel="nofollow noreferrer">current_page?</a> seems like a good starting point but I'd like to pass in an arbitrary number of URLs.</p> <p>As an added bonus It would be good if a hash of params to exclude from the comparison could be passed in. So a method call might look like:</p> <pre><code>same_url?(projects_path(:page =&gt; 2), "projects?page=3", :excluding =&gt; :page) # =&gt; true </code></pre>
[ { "answer_id": 126693, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 1, "selected": false, "text": "<p>Is this the sort of thing you're after?</p>\n\n<pre><code>def same_url?(one, two)\n url_for(one) == url_for(two)\nend\n</code></pre>\n" }, { "answer_id": 126816, "author": "Dave Nolan", "author_id": 9474, "author_profile": "https://Stackoverflow.com/users/9474", "pm_score": 3, "selected": false, "text": "<p>Here's the method (bung it in /lib and require it in environment.rb):</p>\n\n<pre><code>def same_page?(a, b, params_to_exclude = {})\n if a.respond_to?(:except) &amp;&amp; b.respond_to?(:except)\n url_for(a.except(params_to_exclude)) == url_for(b.except(params_to_exclude))\n else\n url_for(a) == url_for(b)\n end\nend\n</code></pre>\n\n<p><strong>If you are on Rails pre-2.0.1</strong>, you also need to add the <code>except</code> helper method to Hash:</p>\n\n<pre><code>class Hash\n # Usage { :a =&gt; 1, :b =&gt; 2, :c =&gt; 3}.except(:a) -&gt; { :b =&gt; 2, :c =&gt; 3}\n def except(*keys)\n self.reject { |k,v|\n keys.include? k.to_sym\n }\n end\nend\n</code></pre>\n\n<p>Later version of Rails (well, ActiveSupport) include <code>except</code> already (credit: <a href=\"https://stackoverflow.com/users/77859/brian-guthrie\">Brian Guthrie</a>)</p>\n" }, { "answer_id": 648828, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 0, "selected": false, "text": "<pre><code>def all_urls_same_as_current? *params_for_urls\n params_for_urls.map do |a_url_hash| \n url_for a_url_hash.except(*exclude_keys)\n end.all? do |a_url_str|\n a_url_str == request.request_uri\n end\nend\n</code></pre>\n\n<p>Wherein:</p>\n\n<ul>\n<li><code>params_for_urls</code> is an array of hashes of url parameters (each array entry are params to build a url)</li>\n<li><code>exclude_keys</code> is an array of symbols for keys you want to ignore</li>\n<li><code>request.request_uri</code> may not be exactly what you should use, see below.</li>\n</ul>\n\n<hr>\n\n<p>Then there are all sorts of things you'll want to consider when implementing your version:</p>\n\n<ul>\n<li>do you want to compare the full uri with domain, port and all, or just the path?</li>\n<li>if just the path, do you want to still compare arguments passed after the question mark or just those that compose the actual path path?</li>\n</ul>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19588/" ]
I'm wanting a method called same\_url? that will return true if the passed in URLs are equal. The passed in URLs might be either params options hash or strings. ``` same_url?({:controller => :foo, :action => :bar}, "http://www.example.com/foo/bar") # => true ``` The Rails Framework helper [current\_page?](http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001607) seems like a good starting point but I'd like to pass in an arbitrary number of URLs. As an added bonus It would be good if a hash of params to exclude from the comparison could be passed in. So a method call might look like: ``` same_url?(projects_path(:page => 2), "projects?page=3", :excluding => :page) # => true ```
Here's the method (bung it in /lib and require it in environment.rb): ``` def same_page?(a, b, params_to_exclude = {}) if a.respond_to?(:except) && b.respond_to?(:except) url_for(a.except(params_to_exclude)) == url_for(b.except(params_to_exclude)) else url_for(a) == url_for(b) end end ``` **If you are on Rails pre-2.0.1**, you also need to add the `except` helper method to Hash: ``` class Hash # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3} def except(*keys) self.reject { |k,v| keys.include? k.to_sym } end end ``` Later version of Rails (well, ActiveSupport) include `except` already (credit: [Brian Guthrie](https://stackoverflow.com/users/77859/brian-guthrie))
126,337
<p>I have a 2.4 MB XML file, an export from Microsoft Project (hey I'm the victim here!) from which I am requested to extract certain details for re-presentation. Ignoring the intelligence or otherwise of the request, which library should I try first from a Ruby perspective?</p> <p>I'm aware of the following (in no particular order):</p> <ul> <li><a href="http://www.germane-software.com/software/rexml/" rel="noreferrer">REXML</a></li> <li><a href="http://www.chilkatsoft.com/ruby-xml.asp" rel="noreferrer">Chilkat Ruby XML library</a></li> <li><a href="http://code.whytheluckystiff.net/hpricot/wiki/HpricotXML" rel="noreferrer">hpricot XML</a></li> <li><a href="http://libxml.rubyforge.org/" rel="noreferrer">libXML</a></li> </ul> <p>I'd prefer something packaged as a Ruby gem, which I suspect the Chilkat library is not.</p> <p>Performance isn't a major issue - I don't expect the thing to need to run more than once a day (once a week is more likely). I'm more interested in something that's as easy to use as anything XML-related is able to get.</p> <p>EDIT: I tried the gemified ones:</p> <p>hpricot is, by a country mile, easiest. For example, to extract the content of the SaveVersion tag in this XML (saved in a file called, say 'test.xml')</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;Project xmlns="http://schemas.microsoft.com/project"&gt; &lt;SaveVersion&gt;12&lt;/SaveVersion&gt; &lt;/Project&gt; </code></pre> <p>takes something like this: </p> <pre><code>doc = Hpricot.XML(open('test.xml')) version = (doc/:Project/:SaveVersion).first.inner_html </code></pre> <p>hpricot seems to be relatively unconcerned with namespaces, which in this example is fine: there's only one, but would potentially be a problem with a complex document. Since hpricot is also very slow, I rather imagine this would be a problem that solves itself.</p> <p>libxml-ruby is an order of magnitude faster, understands namespaces (it took me a good couple of hours to figure this out) and is altogether much closer to the XML metal - XPath queries and all the other stuff are in there. This is not necessarily a Good Thing if, like me, you open up an XML document only under conditions of extreme duress. The helper module was mostly helpful in providing examples of how to handle a default namespace effectively. This is roughly what I ended up with (I'm not in any way asserting its beauty, correctness or other value, it's just where I am right now):</p> <pre><code>xml_parser = XML::Parser.new xml_parser.string = File.read(path) doc = xml_parser.parse @root = doc.root @scopes = { :in_node =&gt; '', :in_root =&gt; '/', :in_doc =&gt; '//' } @ns_prefix = 'p' @ns = "#{@ns_prefix}:#{@root.namespace[0].href}" version = @root.find_first(xpath_qry("Project/SaveVersion", :in_root), @ns).content.to_i def xpath_qry(tags, scope = :in_node) "#{@scopes[scope]}" + tags.split(/\//).collect{ |tag| "#{@ns_prefix}:#{tag}"}.join('/') end </code></pre> <p>I'm still debating the pros and cons: libxml for its extra rigour, hpricot for the sheer style of _why's code.</p> <p>EDIT again, somewhat later: I discovered HappyMapper ('gem install happymapper') which is hugely promising, if still at an early stage. It's declarative and mostly works, although I have spotted a couple of edge cases that I don't have fixes for yet. It lets you do stuff like this, which parses my Google Reader OPML:</p> <pre><code>module OPML class Outline include HappyMapper tag 'outline' attribute :title, String attribute :text, String attribute :type, String attribute :xmlUrl, String attribute :htmlUrl, String has_many :outlines, Outline end end xml_string = File.read("google-reader-subscriptions.xml") sections = OPML::Outline.parse(xml_string) </code></pre> <p>I already love it, even though it's not perfect yet.</p>
[ { "answer_id": 146733, "author": "dimus", "author_id": 23080, "author_profile": "https://Stackoverflow.com/users/23080", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://code.whytheluckystiff.net/hpricot/wiki/HpricotBasics\" rel=\"nofollow noreferrer\">Hpricot</a> is probably the best tool for you -- it is easy to use and should handle 2mg file with no problem.</p>\n\n<p>Speedwise libxml should be the best. I used libxml2 binding for python few months ago (at that moment rb-libxml was stale). Streaming interface worked the best for me\n(LibXML::XML::Reader in ruby gem). It allows to process file while it is downloading, is a bit more userfriendly than SAX and allowed me to load data from 30mb xml file from internet to a MySQL database in a little more than a minute.</p>\n" }, { "answer_id": 1444018, "author": "Thomas", "author_id": 175484, "author_profile": "https://Stackoverflow.com/users/175484", "pm_score": 2, "selected": false, "text": "<p>Nokogiri wraps libxml2 and libxslt with a clean, Rubyish API that supports namespaces, XPath and CSS3 queries. Fast, too.\n<a href=\"http://nokogiri.org/\" rel=\"nofollow noreferrer\">http://nokogiri.org/</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1060/" ]
I have a 2.4 MB XML file, an export from Microsoft Project (hey I'm the victim here!) from which I am requested to extract certain details for re-presentation. Ignoring the intelligence or otherwise of the request, which library should I try first from a Ruby perspective? I'm aware of the following (in no particular order): * [REXML](http://www.germane-software.com/software/rexml/) * [Chilkat Ruby XML library](http://www.chilkatsoft.com/ruby-xml.asp) * [hpricot XML](http://code.whytheluckystiff.net/hpricot/wiki/HpricotXML) * [libXML](http://libxml.rubyforge.org/) I'd prefer something packaged as a Ruby gem, which I suspect the Chilkat library is not. Performance isn't a major issue - I don't expect the thing to need to run more than once a day (once a week is more likely). I'm more interested in something that's as easy to use as anything XML-related is able to get. EDIT: I tried the gemified ones: hpricot is, by a country mile, easiest. For example, to extract the content of the SaveVersion tag in this XML (saved in a file called, say 'test.xml') ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Project xmlns="http://schemas.microsoft.com/project"> <SaveVersion>12</SaveVersion> </Project> ``` takes something like this: ``` doc = Hpricot.XML(open('test.xml')) version = (doc/:Project/:SaveVersion).first.inner_html ``` hpricot seems to be relatively unconcerned with namespaces, which in this example is fine: there's only one, but would potentially be a problem with a complex document. Since hpricot is also very slow, I rather imagine this would be a problem that solves itself. libxml-ruby is an order of magnitude faster, understands namespaces (it took me a good couple of hours to figure this out) and is altogether much closer to the XML metal - XPath queries and all the other stuff are in there. This is not necessarily a Good Thing if, like me, you open up an XML document only under conditions of extreme duress. The helper module was mostly helpful in providing examples of how to handle a default namespace effectively. This is roughly what I ended up with (I'm not in any way asserting its beauty, correctness or other value, it's just where I am right now): ``` xml_parser = XML::Parser.new xml_parser.string = File.read(path) doc = xml_parser.parse @root = doc.root @scopes = { :in_node => '', :in_root => '/', :in_doc => '//' } @ns_prefix = 'p' @ns = "#{@ns_prefix}:#{@root.namespace[0].href}" version = @root.find_first(xpath_qry("Project/SaveVersion", :in_root), @ns).content.to_i def xpath_qry(tags, scope = :in_node) "#{@scopes[scope]}" + tags.split(/\//).collect{ |tag| "#{@ns_prefix}:#{tag}"}.join('/') end ``` I'm still debating the pros and cons: libxml for its extra rigour, hpricot for the sheer style of \_why's code. EDIT again, somewhat later: I discovered HappyMapper ('gem install happymapper') which is hugely promising, if still at an early stage. It's declarative and mostly works, although I have spotted a couple of edge cases that I don't have fixes for yet. It lets you do stuff like this, which parses my Google Reader OPML: ``` module OPML class Outline include HappyMapper tag 'outline' attribute :title, String attribute :text, String attribute :type, String attribute :xmlUrl, String attribute :htmlUrl, String has_many :outlines, Outline end end xml_string = File.read("google-reader-subscriptions.xml") sections = OPML::Outline.parse(xml_string) ``` I already love it, even though it's not perfect yet.
[Hpricot](http://code.whytheluckystiff.net/hpricot/wiki/HpricotBasics) is probably the best tool for you -- it is easy to use and should handle 2mg file with no problem. Speedwise libxml should be the best. I used libxml2 binding for python few months ago (at that moment rb-libxml was stale). Streaming interface worked the best for me (LibXML::XML::Reader in ruby gem). It allows to process file while it is downloading, is a bit more userfriendly than SAX and allowed me to load data from 30mb xml file from internet to a MySQL database in a little more than a minute.
126,364
<p><strong>Intro</strong>: I'm trying to migrate our Trac SQLite to a PostgreSQL backend, to do that I need psycopg2. After clicking past the embarrassing rant on www.initd.org I downloaded the latest version and tried running <code>setup.py install</code>. This didn't work, telling me I needed mingw. So I downloaded and installed mingw.</p> <p><strong>Problem</strong>: I now get the following error when running <code>setup.py build_ext --compiler=mingw32 install</code>:</p> <pre><code>running build_ext building 'psycopg2._psycopg' extension writing build\temp.win32-2.4\Release\psycopg\_psycopg.def C:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.4\Release\psycopg \psycopgmodule.o build\temp.win32-2.4\Release\psycopg\pqpath.o build\temp.win32- 2.4\Release\psycopg\typecast.o build\temp.win32-2.4\Release\psycopg\microprotoco ls.o build\temp.win32-2.4\Release\psycopg\microprotocols_proto.o build\temp.win3 2-2.4\Release\psycopg\connection_type.o build\temp.win32-2.4\Release\psycopg\con nection_int.o build\temp.win32-2.4\Release\psycopg\cursor_type.o build\temp.win3 2-2.4\Release\psycopg\cursor_int.o build\temp.win32-2.4\Release\psycopg\lobject_ type.o build\temp.win32-2.4\Release\psycopg\lobject_int.o build\temp.win32-2.4\R elease\psycopg\adapter_qstring.o build\temp.win32-2.4\Release\psycopg\adapter_pb oolean.o build\temp.win32-2.4\Release\psycopg\adapter_binary.o build\temp.win32- 2.4\Release\psycopg\adapter_asis.o build\temp.win32-2.4\Release\psycopg\adapter_ list.o build\temp.win32-2.4\Release\psycopg\adapter_datetime.o build\temp.win32- 2.4\Release\psycopg\_psycopg.def -LC:\Python24\libs -LC:\Python24\PCBuild -Lc:/P ROGRA~1/POSTGR~1/8.3/lib -lpython24 -lmsvcr71 -lpq -lmsvcr71 -lws2_32 -ladvapi32 -o build\lib.win32-2.4\psycopg2\_psycopg.pyd C:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot fin d -lpq collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 </code></pre> <p><strong>What I've tried</strong> - I noticed the forward slashes in the -L option, so I manually entered my PostgreSQL lib directory in the library_dirs option in the setup.cfg, to no avail (the call then had a -L option with backslashes, but the error message stayed the same).</p>
[ { "answer_id": 126494, "author": "Michael Twomey", "author_id": 995, "author_profile": "https://Stackoverflow.com/users/995", "pm_score": 3, "selected": true, "text": "<p>Have you tried the <a href=\"http://www.stickpeople.com/projects/python/win-psycopg/\" rel=\"nofollow noreferrer\">binary build</a> of psycopg2 for windows? If that works with your python then it mitigates the need to build by hand.</p>\n\n<p>I've seen random people ask this question on various lists and it seems one recommendation is to build postgresql by hand to work around this problem.</p>\n" }, { "answer_id": 126495, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 1, "selected": false, "text": "<p>Compiling extensions on windows can be tricky. There are precompiled libraries available however: <a href=\"http://www.stickpeople.com/projects/python/win-psycopg/\" rel=\"nofollow noreferrer\">http://www.stickpeople.com/projects/python/win-psycopg/</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
**Intro**: I'm trying to migrate our Trac SQLite to a PostgreSQL backend, to do that I need psycopg2. After clicking past the embarrassing rant on www.initd.org I downloaded the latest version and tried running `setup.py install`. This didn't work, telling me I needed mingw. So I downloaded and installed mingw. **Problem**: I now get the following error when running `setup.py build_ext --compiler=mingw32 install`: ``` running build_ext building 'psycopg2._psycopg' extension writing build\temp.win32-2.4\Release\psycopg\_psycopg.def C:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.4\Release\psycopg \psycopgmodule.o build\temp.win32-2.4\Release\psycopg\pqpath.o build\temp.win32- 2.4\Release\psycopg\typecast.o build\temp.win32-2.4\Release\psycopg\microprotoco ls.o build\temp.win32-2.4\Release\psycopg\microprotocols_proto.o build\temp.win3 2-2.4\Release\psycopg\connection_type.o build\temp.win32-2.4\Release\psycopg\con nection_int.o build\temp.win32-2.4\Release\psycopg\cursor_type.o build\temp.win3 2-2.4\Release\psycopg\cursor_int.o build\temp.win32-2.4\Release\psycopg\lobject_ type.o build\temp.win32-2.4\Release\psycopg\lobject_int.o build\temp.win32-2.4\R elease\psycopg\adapter_qstring.o build\temp.win32-2.4\Release\psycopg\adapter_pb oolean.o build\temp.win32-2.4\Release\psycopg\adapter_binary.o build\temp.win32- 2.4\Release\psycopg\adapter_asis.o build\temp.win32-2.4\Release\psycopg\adapter_ list.o build\temp.win32-2.4\Release\psycopg\adapter_datetime.o build\temp.win32- 2.4\Release\psycopg\_psycopg.def -LC:\Python24\libs -LC:\Python24\PCBuild -Lc:/P ROGRA~1/POSTGR~1/8.3/lib -lpython24 -lmsvcr71 -lpq -lmsvcr71 -lws2_32 -ladvapi32 -o build\lib.win32-2.4\psycopg2\_psycopg.pyd C:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot fin d -lpq collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 ``` **What I've tried** - I noticed the forward slashes in the -L option, so I manually entered my PostgreSQL lib directory in the library\_dirs option in the setup.cfg, to no avail (the call then had a -L option with backslashes, but the error message stayed the same).
Have you tried the [binary build](http://www.stickpeople.com/projects/python/win-psycopg/) of psycopg2 for windows? If that works with your python then it mitigates the need to build by hand. I've seen random people ask this question on various lists and it seems one recommendation is to build postgresql by hand to work around this problem.
126,373
<p>I write a lot of dynamically generated content (developing under PHP) and I use jQuery to add extra flexibility and functionality to my projects.</p> <p>Thing is that it's rather hard to add JavaScript in an unobtrusive manner. Here's an example:</p> <p>You have to generate a random number of <code>div</code> elements each with different functionality triggered <code>onClick</code>. I can use the <code>onclick</code> attribute on my <code>div</code> elements to call a JS function with a parameter but that is just a bad solution. Also I could generate some jQuery code along with each div in my PHP <code>for</code> loop, but then again this won't be entirely unobtrusive.</p> <p>So what's the solution in situations like this?</p>
[ { "answer_id": 126398, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 3, "selected": false, "text": "<p>You need to add something to the divs that defines what type of behaviour they have, then use jQuery to select those divs and add the behaviour. One option is to use the class attribute, although arguably this should be used for presentation rather than behaviour. An alternative would be the rel attribute, but I usually find that you also want to specify different CSS for each behaviour, so class is probably ok in this instance.</p>\n\n<p>So for instance, lets assume you want odd and even behaviour:</p>\n\n<pre><code>&lt;div class=\"odd\"&gt;...&lt;/div&gt;\n&lt;div class=\"even\"&gt;...&lt;/div&gt;\n&lt;div class=\"odd\"&gt;...&lt;/div&gt;\n&lt;div class=\"even\"&gt;...&lt;/div&gt;\n</code></pre>\n\n<p>Then in jQuery:</p>\n\n<pre><code>$(document).load(function() {\n$('.odd').click(function(el) {\n// do stuff\n});\n$('.even').click(function(el) {\n// dostuff\n});\n});\n</code></pre>\n\n<p>jQuery has a very powerful selector engine that can find based on any CSS based selector, and also support some XPath and its own selectors. Get to know them! <a href=\"http://docs.jquery.com/Selectors\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Selectors</a></p>\n" }, { "answer_id": 126404, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "<p>It's a bit hard to tell from your question, but perhaps you can use different jQuery selectors to set up different click behaviours? For example, say you have the following:</p>\n\n<pre><code>&lt;div class=\"section-1\"&gt;\n &lt;div&gt;&lt;/div&gt;\n&lt;/div&gt;\n&lt;div class=\"section-2\"&gt;\n &lt;div&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Perhaps you could do the following in jQuery:</p>\n\n<pre><code>$('.section-1 div').onclick(...one set of functionality...);\n$('.section-2 div').onclick(...another set of functionality...);\n</code></pre>\n\n<p>Basically, decide based on context what needs to happen. You could also select all of the divs and test for some parent or child element to determine what functionality they get.</p>\n\n<p>I'd have to know more about the specifics of your situation to give more focused advice, but maybe this will get you started.</p>\n" }, { "answer_id": 126464, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 1, "selected": false, "text": "<p>I would recommend disregarding the W3C standards and writing out HTML-properties on the elements that need handlers attached to them:</p>\n\n<p><em>Note: this will <strong>not</strong> break the rendering of the page!</em></p>\n\n<pre><code>&lt;ul&gt;\n &lt;li handler=\"doAlertOne\"&gt;&lt;/li&gt;\n &lt;li handler=\"doAlertTwo\"&gt;&lt;/li&gt;\n &lt;li handler=\"doAlertThree\"&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>Declare a few functions:</p>\n\n<pre><code>function doAlertOne() { }\nfunction doAlertTwo() { }\nfunction doAlertThree() { }\n</code></pre>\n\n<p>And then using jQuery like so:</p>\n\n<pre><code>$(\"ul li\").each(function ()\n{\n switch($(this).attr(\"handler\"))\n {\n case \"doAlertOne\":\n doAlertOne();\n break;\n\n case ... etc.\n }\n});\n</code></pre>\n\n<p>Be pragmatic.</p>\n" }, { "answer_id": 126486, "author": "Ged Byrne", "author_id": 10167, "author_profile": "https://Stackoverflow.com/users/10167", "pm_score": 0, "selected": false, "text": "<p>I haven't don't really know about JQuery, but I do know that the DOJO toolkit does make highly unobtrusive Javascript possible.</p>\n\n<p>Take a look at the example here: <a href=\"http://dojocampus.org/explorer/#Dojo_Query_Adding%20Events\" rel=\"nofollow noreferrer\">http://dojocampus.org/explorer/#Dojo_Query_Adding%20Events</a></p>\n\n<p>The demo dynamically adds events to a purely html table based on classes.</p>\n\n<p>Another example is the behaviour features, described here:<a href=\"http://dojocampus.org/content/2008/03/26/cleaning-your-markup-with-dojobehavior/\" rel=\"nofollow noreferrer\">http://dojocampus.org/content/2008/03/26/cleaning-your-markup-with-dojobehavior/</a></p>\n" }, { "answer_id": 126595, "author": "Rakesh Pai", "author_id": 20089, "author_profile": "https://Stackoverflow.com/users/20089", "pm_score": 2, "selected": false, "text": "<p>I would recommend that you use this thing called \"<a href=\"http://icant.co.uk/sandbox/eventdelegation/\" rel=\"nofollow noreferrer\">Event delegation</a>\". This is how it works.</p>\n\n<p>So, if you want to update an area, say a div, and you want to handle events unobtrusively, you attach an event handler to the div itself. Use any framework you prefer to do this. The event attachment can happen at any time, regardless of if you've updated the div or not.</p>\n\n<p>The event handler attached to this div will receive the event object as one of it's arguments. Using this event object, you can then figure which element triggered the event. You could update the div any number of times: events generated by the children of the div will bubble up to the div where you can catch and handle them.</p>\n\n<p>This also turns out to be a huge performance optimization if you are thinking about attaching multiple handlers to many elements inside the div.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20603/" ]
I write a lot of dynamically generated content (developing under PHP) and I use jQuery to add extra flexibility and functionality to my projects. Thing is that it's rather hard to add JavaScript in an unobtrusive manner. Here's an example: You have to generate a random number of `div` elements each with different functionality triggered `onClick`. I can use the `onclick` attribute on my `div` elements to call a JS function with a parameter but that is just a bad solution. Also I could generate some jQuery code along with each div in my PHP `for` loop, but then again this won't be entirely unobtrusive. So what's the solution in situations like this?
You need to add something to the divs that defines what type of behaviour they have, then use jQuery to select those divs and add the behaviour. One option is to use the class attribute, although arguably this should be used for presentation rather than behaviour. An alternative would be the rel attribute, but I usually find that you also want to specify different CSS for each behaviour, so class is probably ok in this instance. So for instance, lets assume you want odd and even behaviour: ``` <div class="odd">...</div> <div class="even">...</div> <div class="odd">...</div> <div class="even">...</div> ``` Then in jQuery: ``` $(document).load(function() { $('.odd').click(function(el) { // do stuff }); $('.even').click(function(el) { // dostuff }); }); ``` jQuery has a very powerful selector engine that can find based on any CSS based selector, and also support some XPath and its own selectors. Get to know them! <http://docs.jquery.com/Selectors>
126,401
<p>Debugging some finance-related SQL code found a strange issue with numeric(24,8) mathematics precision.</p> <p>Running the following query on your MSSQL you would get A + B * C expression result to be 0.123457</p> <p>SELECT A, B, C, A + B * C FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C ) T</p> <p>So we have lost 2 significant symbols. Trying to get this fixed in different ways i got that conversion of the intermediate multiplication result (which is Zero!) to numeric (24,8) would work fine.</p> <p>And finally a have a solution. But still I hace a question - why MSSQL behaves in this way and which type conversions actually occured in my sample?</p>
[ { "answer_id": 126473, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 4, "selected": true, "text": "<p>Just as addition of the float type is inaccurate, multiplication of the decimal types can be inaccurate (or cause inaccuracy) if you exceed the precision. See <a href=\"http://msdn.microsoft.com/en-us/library/ms191530%28SQL.90%29.aspx#_decimal\" rel=\"noreferrer\">Data Type Conversion</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms187746%28SQL.90%29.aspx\" rel=\"noreferrer\">decimal and numeric</a>.</p>\n\n<p>Since you multiplied <code>NUMERIC(24,8)</code> and <code>NUMERIC(24,8)</code>, and SQL Server will only check the type not the content, it probably will try to save the potential 16 non-decimal digits (24 - 8) when it can't save all 48 digits of precision (max is 38). Combine two of them, you get 32 non-decimal digits, which leaves you with only 6 decimal digits (38 - 32).</p>\n\n<p>Thus the original query </p>\n\n<pre><code>SELECT A, B, C, A + B * C\nFROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A,\n CAST(0 AS NUMERIC(24,8)) AS B,\n CAST(500 AS NUMERIC(24,8)) AS C ) T\n</code></pre>\n\n<p>reduces to</p>\n\n<pre><code>SELECT A, B, C, A + D\nFROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A,\n CAST(0 AS NUMERIC(24,8)) AS B,\n CAST(500 AS NUMERIC(24,8)) AS C,\n CAST(0 AS NUMERIC(38,6)) AS D ) T\n</code></pre>\n\n<p>Again, between <code>NUMERIC(24,8)</code> and <code>NUMERIC(38,6)</code>, SQL Server will try to save the potential 32 digits of non-decimals, so <code>A + D</code> reduces to </p>\n\n<pre><code>SELECT CAST(0.12345678 AS NUMERIC(38,6))\n</code></pre>\n\n<p>which gives you <code>0.123457</code> after rounding.</p>\n" }, { "answer_id": 126713, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 0, "selected": false, "text": "<p>Following the logic pointed out by <a href=\"https://stackoverflow.com/questions/126401/sql-server-2005-numeric-precision-loss#126473\">eed3si9n</a> and what you said in your question it seems that the best approach when doing mathematics operations is to extract them into a function and additionally to specify precision after each operation,</p>\n\n<p>It this case the function could look something like:</p>\n\n<pre><code>create function dbo.myMath(@a as numeric(24,8), @b as numeric(24,8), @c as numeric(24,8))\nreturns numeric(24,8)\nas\nbegin \n declare @d as numeric(24,8)\n set @d = @b* @c\n return @a + @d\nend\n</code></pre>\n" }, { "answer_id": 16914553, "author": "phoenix10k", "author_id": 1097516, "author_profile": "https://Stackoverflow.com/users/1097516", "pm_score": 0, "selected": false, "text": "<p>Despite what it says on <a href=\"http://msdn.microsoft.com/en-us/library/ms190476%28v=sql.110%29.aspx\" rel=\"nofollow\">Precision, Scale, and Length (Transact-SQL)</a>. I believe it is also applying a minimum 'scale' (number of decimal places) of 6 to the resulting NUMERIC type for multiplication the same as it does for division etc.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21603/" ]
Debugging some finance-related SQL code found a strange issue with numeric(24,8) mathematics precision. Running the following query on your MSSQL you would get A + B \* C expression result to be 0.123457 SELECT A, B, C, A + B \* C FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C ) T So we have lost 2 significant symbols. Trying to get this fixed in different ways i got that conversion of the intermediate multiplication result (which is Zero!) to numeric (24,8) would work fine. And finally a have a solution. But still I hace a question - why MSSQL behaves in this way and which type conversions actually occured in my sample?
Just as addition of the float type is inaccurate, multiplication of the decimal types can be inaccurate (or cause inaccuracy) if you exceed the precision. See [Data Type Conversion](http://msdn.microsoft.com/en-us/library/ms191530%28SQL.90%29.aspx#_decimal) and [decimal and numeric](http://msdn.microsoft.com/en-us/library/ms187746%28SQL.90%29.aspx). Since you multiplied `NUMERIC(24,8)` and `NUMERIC(24,8)`, and SQL Server will only check the type not the content, it probably will try to save the potential 16 non-decimal digits (24 - 8) when it can't save all 48 digits of precision (max is 38). Combine two of them, you get 32 non-decimal digits, which leaves you with only 6 decimal digits (38 - 32). Thus the original query ``` SELECT A, B, C, A + B * C FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C ) T ``` reduces to ``` SELECT A, B, C, A + D FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C, CAST(0 AS NUMERIC(38,6)) AS D ) T ``` Again, between `NUMERIC(24,8)` and `NUMERIC(38,6)`, SQL Server will try to save the potential 32 digits of non-decimals, so `A + D` reduces to ``` SELECT CAST(0.12345678 AS NUMERIC(38,6)) ``` which gives you `0.123457` after rounding.
126,406
<p>I would like to change the database files location of MySQL administrator to another drive of my computer. (I run Windows XP SP2 and MySQL Administrator 1.2.8.)</p> <p>--Under the startup variable --> General Parameters --> I changed <code>Data directory:</code> from <code>C:/Program Files/MySQL/MySQL Server 5.0/data</code> to <code>D:/.....</code>, but after I stopped the service and restarted it, the following error appeared: </p> <pre><code>Could not re-connect to the MySQL Server. Server could not be started. Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist </code></pre> <p>Has anyone else had this problem? </p>
[ { "answer_id": 126420, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 5, "selected": true, "text": "<p>Normally it works like this:</p>\n\n<ol>\n<li>shut down MySQL</li>\n<li>change the <code>[mysqld]</code> and <code>[mysqld_safe]</code> <code>datadir</code> variable in the MySQL configuration</li>\n<li>change the <code>basedir</code> variable in the same section.</li>\n<li>move the location over</li>\n<li>restart MySQL</li>\n</ol>\n\n<p>If that doesn't work I have no idea. On linux you can try to move the socket to a new location too, but that shouldn't affect windows. Alternatively you can use a symbolic link on *nix what most people do I guess.</p>\n" }, { "answer_id": 126422, "author": "Silver Dragon", "author_id": 9440, "author_profile": "https://Stackoverflow.com/users/9440", "pm_score": 0, "selected": false, "text": "<p>You also have to manually modify mysql's configuration (usually my.conf)</p>\n" }, { "answer_id": 126433, "author": "Daniel Schneller", "author_id": 1252368, "author_profile": "https://Stackoverflow.com/users/1252368", "pm_score": 0, "selected": false, "text": "<p>MySQL Administrator cannot be used for tasks like this. It is merely a tool for looking at MySQL servers, despite its name. Relocating data is described in many MySQL tutorials and in the manual IIRC. But basically it's just moving the data to a new location while the server is shut down and then correcting the paths in the servers config file.\nAfter that you should be able to restart the server and connect MySQL Administrator to it.</p>\n" }, { "answer_id": 13462057, "author": "ajcw", "author_id": 310174, "author_profile": "https://Stackoverflow.com/users/310174", "pm_score": 3, "selected": false, "text": "<p>In Windows</p>\n\n<ol>\n<li>Navigate to <code>C:\\Program Files\\MySQL\\MySQL Server 5.4\\</code> and locate the <code>my.ini</code> file</li>\n<li>Find the SERVER SECTION and go to approx line 76 and modify the <strong>datadir</strong> line to where you want your MySQL application data to be stored</li>\n<li>Now navigate to <code>C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.4\\data\\</code> and copy and paste the mysql folder into your new location.</li>\n<li>Restart the MySQL Server in <em>Control Panel > Administrative Tools > Service</em></li>\n</ol>\n" }, { "answer_id": 15142635, "author": "BMZ", "author_id": 2120787, "author_profile": "https://Stackoverflow.com/users/2120787", "pm_score": 0, "selected": false, "text": "<p>Make sure you give the Network Service Full permissions in the security tab of Windows Explorer options. If the server can't read/write etc. to the selected folder the service will either not start or it will attempt a start and shut right down.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21608/" ]
I would like to change the database files location of MySQL administrator to another drive of my computer. (I run Windows XP SP2 and MySQL Administrator 1.2.8.) --Under the startup variable --> General Parameters --> I changed `Data directory:` from `C:/Program Files/MySQL/MySQL Server 5.0/data` to `D:/.....`, but after I stopped the service and restarted it, the following error appeared: ``` Could not re-connect to the MySQL Server. Server could not be started. Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist ``` Has anyone else had this problem?
Normally it works like this: 1. shut down MySQL 2. change the `[mysqld]` and `[mysqld_safe]` `datadir` variable in the MySQL configuration 3. change the `basedir` variable in the same section. 4. move the location over 5. restart MySQL If that doesn't work I have no idea. On linux you can try to move the socket to a new location too, but that shouldn't affect windows. Alternatively you can use a symbolic link on \*nix what most people do I guess.
126,409
<p>What are the ways to eliminate the use of switch in code?</p>
[ { "answer_id": 126415, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 4, "selected": false, "text": "<p>Everybody loves HUGE <code>if else</code> blocks. So easy to read! I am curious as to why you would want to remove switch statements, though. If you need a switch statement, you probably need a switch statement. Seriously though, I'd say it depends on what the code's doing. If all the switch is doing is calling functions (say) you could pass function pointers. Whether it's a <em>better</em> solution is debatable.</p>\n\n<p>Language is an important factor here also, I think.</p>\n" }, { "answer_id": 126417, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 5, "selected": false, "text": "<p>I think the best way is to use a good Map. Using a dictionary you can map almost any input to some other value/object/function.</p>\n\n<p>your code would look something(psuedo) like this:</p>\n\n<pre><code>void InitMap(){\n Map[key1] = Object/Action;\n Map[key2] = Object/Action;\n}\n\nObject/Action DoStuff(Object key){\n return Map[key];\n}\n</code></pre>\n" }, { "answer_id": 126418, "author": "Iain Holder", "author_id": 1122, "author_profile": "https://Stackoverflow.com/users/1122", "pm_score": 2, "selected": false, "text": "<p>if-else</p>\n\n<p>I refute the premise that switch is inherently bad though.</p>\n" }, { "answer_id": 126419, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 2, "selected": false, "text": "<p>Well, for one, I didn't know using switch was an anti pattern.</p>\n\n<p>Secondly, switch can always be replaced with if / else if statements.</p>\n" }, { "answer_id": 126427, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 0, "selected": false, "text": "<p>The most obvious, language independent, answer is to use a series of 'if'. </p>\n\n<p>If the language you are using has function pointers (C) or has functions that are 1st class values (Lua) you may achieve results similar to a \"switch\" using an array (or a list) of (pointers to) functions.</p>\n\n<p>You should be more specific on the language if you want better answers.</p>\n" }, { "answer_id": 126428, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 2, "selected": false, "text": "<p>Why do you want to? In the hands of a good compiler, a switch statement can be far more efficient than if/else blocks (as well as being easier to read), and only the largest switches are likely to be sped up if they're replaced by any sort of indirect-lookup data structure.</p>\n" }, { "answer_id": 126436, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 5, "selected": false, "text": "<p>Switch in itself isn't that bad, but if you have lots of \"switch\" or \"if/else\" on objects in your methods it may be a sign that your design is a bit \"procedural\" and that your objects are just value buckets. Move the logic to your objects, invoke a method on your objects and let them decide how to respond instead.</p>\n" }, { "answer_id": 126443, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 3, "selected": false, "text": "<p>'switch' is just a language construct and all language constructs can be thought of as tools to get a job done. As with real tools, some tools are better suited to one task than another (you wouldn't use a sledge hammer to put up a picture hook). The important part is how 'getting the job done' is defined. Does it need to be maintainable, does it need to be fast, does it need to scale, does it need to be extendable and so on.</p>\n\n<p>At each point in the programming process there are usually a range of constructs and patterns that can be used: a switch, an if-else-if sequence, virtual functions, jump tables, maps with function pointers and so on. With experience a programmer will instinctively know the right tool to use for a given situation.</p>\n\n<p>It must be assumed that anyone maintaining or reviewing code is at least as skilled as the original author so that any construct can be safely used.</p>\n" }, { "answer_id": 126444, "author": "Xavier Nodet", "author_id": 4177, "author_profile": "https://Stackoverflow.com/users/4177", "pm_score": 1, "selected": false, "text": "<p>If the switch is there to distinguish between various kinds of objects, you're probably missing some classes to precisely describe those objects, or some virtual methods...</p>\n" }, { "answer_id": 126453, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 6, "selected": false, "text": "<p>A switch is a pattern, whether implemented with a switch statement, if else chain, lookup table, oop polymorphism, pattern matching or something else.</p>\n\n<p>Do you want to eliminate the use of the \"<strong>switch statement</strong>\" or the \"<strong>switch pattern</strong>\"? The first one can be eliminated, the second one, only if another pattern/algorithm can be used, and most of the time that is not possible or it's not a better approach to do so.</p>\n\n<p>If you want to eliminate the <strong>switch statement</strong> from code, the first question to ask is <em>where does it make sense to eliminate the switch statement</em> and use some other technique. Unfortunately the answer to this question is domain specific. </p>\n\n<p>And remember that compilers can do various optimizations to switch statements. So for example if you want to do message processing efficiently, a switch statement is pretty much the way to go. But on the other hand running business rules based on a switch statement is probably not the best way to go and the application should be rearchitected.</p>\n\n<p>Here are some alternatives to switch statement :</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Lookup_table\" rel=\"noreferrer\">lookup table</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Type_polymorphism\" rel=\"noreferrer\">polymorphism</a> </li>\n<li><a href=\"http://en.wikipedia.org/wiki/Pattern_matching\" rel=\"noreferrer\">pattern matching</a> (especially used in functional programming, C++ templates) </li>\n</ul>\n" }, { "answer_id": 126454, "author": "jason", "author_id": 5045, "author_profile": "https://Stackoverflow.com/users/5045", "pm_score": 0, "selected": false, "text": "<p>Switch statements can often be replaced by a good OO design.</p>\n\n<p>For example, you have an Account class, and are using a switch statement to perform a different calculation based on the type of account.</p>\n\n<p>I would suggest that this should be replaced by a number of account classes, representing the different types of account, and all implementing an Account interface.</p>\n\n<p>The switch then becomes unnecessary, as you can treat all types of accounts the same and thanks to polymorphism, the appropriate calculation will be run for the account type.</p>\n" }, { "answer_id": 126455, "author": "mlarsen", "author_id": 17700, "author_profile": "https://Stackoverflow.com/users/17700", "pm_score": 9, "selected": true, "text": "<p>Switch-statements are not an antipattern per se, but if you're coding object oriented you should consider if the use of a switch is better solved with <a href=\"http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming\" rel=\"noreferrer\">polymorphism</a> instead of using a switch statement.</p>\n\n<p>With polymorphism, this:</p>\n\n<pre><code>foreach (var animal in zoo) {\n switch (typeof(animal)) {\n case \"dog\":\n echo animal.bark();\n break;\n\n case \"cat\":\n echo animal.meow();\n break;\n }\n}\n</code></pre>\n\n<p>becomes this:</p>\n\n<pre><code>foreach (var animal in zoo) {\n echo animal.speak();\n}\n</code></pre>\n" }, { "answer_id": 126462, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 3, "selected": false, "text": "<p>I think that what you are looking for is the Strategy Pattern. </p>\n\n<p>This can be implemented in a number of ways, which have been mentionned in other answers to this question, such as: </p>\n\n<ul>\n<li>A map of values -> functions</li>\n<li>Polymorphism. (the sub-type of an object will decide how it handles a specific process). </li>\n<li>First class functions. </li>\n</ul>\n" }, { "answer_id": 126466, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": -1, "selected": false, "text": "<p>Another vote for if/else. I'm not a huge fan of case or switch statements because there are some people that don't use them. The code is less readable if you use case or switch. Maybe not less readable to you, but to those that have never needed to use the command. </p>\n\n<p>The same goes for object factories.</p>\n\n<p>If/else blocks are a simple construct that everyone gets. There's a few things you can do to make sure that you don't cause problems. </p>\n\n<p>Firstly - Don't try and indent if statements more than a couple of times. If you're finding yourself indenting, then you're doing it wrong. </p>\n\n<pre><code> if a = 1 then \n do something else \n if a = 2 then \n do something else\n else \n if a = 3 then \n do the last thing\n endif\n endif \n endif\n</code></pre>\n\n<p>Is really bad - do this instead. </p>\n\n<pre><code>if a = 1 then \n do something\nendif \nif a = 2 then \n do something else\nendif \nif a = 3 then \n do something more\nendif \n</code></pre>\n\n<p>Optimisation be damned. It doesn't make that much of a difference to the speed of your code. </p>\n\n<p>Secondly, I'm not averse to breaking out of an If Block as long as there are enough breaks statements scattered through the particular code block to make it obvious</p>\n\n<pre><code>procedure processA(a:int)\n if a = 1 then \n do something\n procedure_return\n endif \n if a = 2 then \n do something else\n procedure_return\n endif \n if a = 3 then \n do something more\n procedure_return\n endif \nend_procedure\n</code></pre>\n\n<p><strong>EDIT</strong>: On Switch and why I think it's hard to grok: </p>\n\n<p>Here's an example of a switch statement...</p>\n\n<pre><code>private void doLog(LogLevel logLevel, String msg) {\n String prefix;\n switch (logLevel) {\n case INFO:\n prefix = \"INFO\";\n break;\n case WARN:\n prefix = \"WARN\";\n break;\n case ERROR:\n prefix = \"ERROR\";\n break;\n default:\n throw new RuntimeException(\"Oops, forgot to add stuff on new enum constant\");\n }\n System.out.println(String.format(\"%s: %s\", prefix, msg));\n }\n</code></pre>\n\n<p>For me the issue here is that the normal control structures which apply in C like languages have been completely broken. There's a general rule that if you want to place more than one line of code inside a control structure, you use braces or a begin/end statement. </p>\n\n<p>e.g. </p>\n\n<pre><code>for i from 1 to 1000 {statement1; statement2}\nif something=false then {statement1; statement2}\nwhile isOKtoLoop {statement1; statement2}\n</code></pre>\n\n<p>For me (and you can correct me if I'm wrong), the Case statement throws this rule out of the window. A conditionally executed block of code is not placed inside a begin/end structure. Because of this, I believe that Case is conceptually different enough to not be used. </p>\n\n<p>Hope that answers your questions.</p>\n" }, { "answer_id": 126475, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 8, "selected": false, "text": "<p>See the <a href=\"http://c2.com/cgi/wiki?SwitchStatementsSmell\" rel=\"noreferrer\">Switch Statements Smell</a>:</p>\n<blockquote>\n<p>Typically, similar switch statements are scattered throughout a program. If you add or remove a clause in one switch, you often have to find and repair the others too.</p>\n</blockquote>\n<p>Both <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201485672\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Refactoring</a> and <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321213351\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Refactoring to Patterns</a> have approaches to resolve this.</p>\n<p>If your (pseudo) code looks like:</p>\n<pre><code>class RequestHandler {\n\n public void handleRequest(int action) {\n switch(action) {\n case LOGIN:\n doLogin();\n break;\n case LOGOUT:\n doLogout();\n break;\n case QUERY:\n doQuery();\n break;\n }\n }\n}\n</code></pre>\n<p>This code violates the <a href=\"http://en.wikipedia.org/wiki/Open/closed_principle\" rel=\"noreferrer\">Open Closed Principle</a> and is fragile to every new type of action code that comes along.\nTo remedy this you could introduce a 'Command' object:</p>\n<pre><code>interface Command {\n public void execute();\n}\n\nclass LoginCommand implements Command {\n public void execute() {\n // do what doLogin() used to do\n }\n}\n\nclass RequestHandler {\n private Map&lt;Integer, Command&gt; commandMap; // injected in, or obtained from a factory\n public void handleRequest(int action) {\n Command command = commandMap.get(action);\n command.execute();\n }\n}\n</code></pre>\n<p>Hope this helps.</p>\n" }, { "answer_id": 126480, "author": "Will", "author_id": 15721, "author_profile": "https://Stackoverflow.com/users/15721", "pm_score": 0, "selected": false, "text": "<p>Depends why you want to replace it!</p>\n\n<p>Many interpreters use 'computed gotos' instead of switch statements for opcode execution.</p>\n\n<p>What I miss about C/C++ switch is the Pascal 'in' and ranges. I also wish I could switch on strings. But these, while trivial for a compiler to eat, are hard work when done using structures and iterators and things. So, on the contrary, there are plenty of things I wish I could replace with a switch, if only C's switch() was more flexible!</p>\n" }, { "answer_id": 126512, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 1, "selected": false, "text": "<p>For C++ </p>\n\n<p>If you are referring to ie an AbstractFactory I think that a <em>registerCreatorFunc(..)</em> method usually is better than requiring to add a case for each and every \"new\" statement that is needed. Then letting all classes create and register a <em>creatorFunction(..)</em> which can be easy implemented with a macro (if I dare to mention). I believe this is a common approach many framework do. I first saw it in ET++ and I think many frameworks that require a DECL and IMPL macro uses it.</p>\n" }, { "answer_id": 126575, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 3, "selected": false, "text": "<p><code>switch</code> statements would be good to replace if you find yourself adding new states or new behaviour to the statements:</p>\n\n<pre>\nint state;\n\nString getString() {\n switch (state) {\n case 0 : // behaviour for state 0\n return \"zero\";\n case 1 : // behaviour for state 1\n return \"one\";\n }\n throw new IllegalStateException();\n}\n\ndouble getDouble() {\n\n switch (this.state) {\n case 0 : // behaviour for state 0\n return 0d;\n case 1 : // behaviour for state 1\n return 1d;\n }\n throw new IllegalStateException();\n}\n</pre>\n\n<p>Adding new behaviour requires copying the <code>switch</code>, and adding new states means adding another <code>case</code> to <em>every</em> <code>switch</code> statement.</p>\n\n<p>In Java, you can only switch a very limited number of primitive types whose values you know at runtime. This presents a problem in and of itself: states are being represented as magic numbers or characters. </p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Conditional_statement\" rel=\"noreferrer\">Pattern matching</a>, and multiple <code>if - else</code> blocks can be used, though really have the same problems when adding new behaviours and new states.</p>\n\n<p>The solution which others have suggested as \"polymorphism\" is an instance of the <a href=\"http://www.vincehuston.org/dp/state.html\" rel=\"noreferrer\">State pattern</a>:</p>\n\n<p>Replace each of the states with its own class. Each behaviour has its own method on the class:</p>\n\n<pre>\nIState state;\n\nString getString() {\n return state.getString();\n}\n\ndouble getDouble() {\n return state.getDouble();\n}\n</pre>\n\n<p>Each time you add a new state, you have to add a new implementation of the <code>IState</code> interface. In a <code>switch</code> world, you'd be adding a <code>case</code> to each <code>switch</code>.</p>\n\n<p>Each time you add a new behaviour, you need to add a new method to the <code>IState</code> interface, and each of the implementations. This is the same burden as before, though now the compiler will check that you have implementations of the new behaviour on each pre-existing state.</p>\n\n<p>Others have said already, that this may be too heavyweight, so of course there is a point you reach where you move from one to another. Personally, the second time I write a switch is the point at which I refactor.</p>\n" }, { "answer_id": 126722, "author": "Bill Michell", "author_id": 7938, "author_profile": "https://Stackoverflow.com/users/7938", "pm_score": 1, "selected": false, "text": "<p>In a procedural language, like C, then switch will be better than any of the alternatives.</p>\n\n<p>In an object-oriented language, then there are almost always other alternatives available that better utilise the object structure, particularly polymorphism.</p>\n\n<p>The problem with switch statements arises when several very similar switch blocks occur at multiple places in the application, and support for a new value needs to be added. It is pretty common for a developer to forget to add support for the new value to one of the switch blocks scattered around the application.</p>\n\n<p>With polymorphism, then a new class replaces the new value, and the new behaviour is added as part of adding the new class. Behaviour at these switch points is then either inherited from the superclass, overridden to provide new behaviour, or implemented to avoid a compiler error when the super method is abstract.</p>\n\n<p>Where there is no obvious polymorphism going on, it can be well worth implementing the <a href=\"http://today.java.net/pub/a/today/2004/10/29/patterns.html\" rel=\"nofollow noreferrer\">Strategy pattern</a>.</p>\n\n<p>But if your alternative is a big IF ... THEN ... ELSE block, then forget it.</p>\n" }, { "answer_id": 126755, "author": "innaM", "author_id": 7498, "author_profile": "https://Stackoverflow.com/users/7498", "pm_score": 0, "selected": false, "text": "<p>Use a language that doesn't come with a built-in switch statement. Perl 5 comes to mind.</p>\n\n<p>Seriously though, why would you want to avoid it? And if you have good reason to avoid it, why not simply avoid it then?</p>\n" }, { "answer_id": 127933, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 1, "selected": false, "text": "<p>Function pointers are one way to replace a huge chunky switch statement, they are especially good in languages where you can capture functions by their names and make stuff with them.</p>\n\n<p>Of course, you ought not force switch statements out of your code, and there always is a chance you are doing it all wrong, which results with stupid redundant pieces of code. (This is unavoidable sometimes, but a good language should allow you to remove redundancy while staying clean.)</p>\n\n<p>This is a great divide&amp;conquer example:</p>\n\n<p>Say you have an interpreter of some sort.</p>\n\n<pre><code>switch(*IP) {\n case OPCODE_ADD:\n ...\n break;\n case OPCODE_NOT_ZERO:\n ...\n break;\n case OPCODE_JUMP:\n ...\n break;\n default:\n fixme(*IP);\n}\n</code></pre>\n\n<p>Instead, you can use this:</p>\n\n<pre><code>opcode_table[*IP](*IP, vm);\n\n... // in somewhere else:\nvoid opcode_add(byte_opcode op, Vm* vm) { ... };\nvoid opcode_not_zero(byte_opcode op, Vm* vm) { ... };\nvoid opcode_jump(byte_opcode op, Vm* vm) { ... };\nvoid opcode_default(byte_opcode op, Vm* vm) { /* fixme */ };\n\nOpcodeFuncPtr opcode_table[256] = {\n ...\n opcode_add,\n opcode_not_zero,\n opcode_jump,\n opcode_default,\n opcode_default,\n ... // etc.\n};\n</code></pre>\n\n<p>Note that I don't know how to remove the redundancy of the opcode_table in C. Perhaps I should make a question about it. :) </p>\n" }, { "answer_id": 318339, "author": "Sheraz", "author_id": 40723, "author_profile": "https://Stackoverflow.com/users/40723", "pm_score": 2, "selected": false, "text": "<p>Switch is not a good way to go as it breaks the Open Close Principal. This is how I do it.</p>\n\n<pre><code>public class Animal\n{\n public abstract void Speak();\n}\n\n\npublic class Dog : Animal\n{\n public virtual void Speak()\n {\n Console.WriteLine(\"Hao Hao\");\n }\n}\n\npublic class Cat : Animal\n{\n public virtual void Speak()\n {\n Console.WriteLine(\"Meauuuu\");\n }\n}\n</code></pre>\n\n<p>And here is how to use it (taking your code):</p>\n\n<pre><code>foreach (var animal in zoo) \n{\n echo animal.speak();\n}\n</code></pre>\n\n<p>Basically what we are doing is delegating the responsibility to the child class instead of having the parent decide what to do with children.</p>\n\n<p>You might also want to read up on \"Liskov Substitution Principle\".</p>\n" }, { "answer_id": 31155996, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 2, "selected": false, "text": "<p>In JavaScript using Associative array:<br>\n<strong>this:</strong> </p>\n\n<pre><code>function getItemPricing(customer, item) {\n switch (customer.type) {\n // VIPs are awesome. Give them 50% off.\n case 'VIP':\n return item.price * item.quantity * 0.50;\n\n // Preferred customers are no VIPs, but they still get 25% off.\n case 'Preferred':\n return item.price * item.quantity * 0.75;\n\n // No discount for other customers.\n case 'Regular':\n case\n default:\n return item.price * item.quantity;\n }\n}\n</code></pre>\n\n<p><strong>becomes this:</strong> </p>\n\n<pre><code>function getItemPricing(customer, item) {\nvar pricing = {\n 'VIP': function(item) {\n return item.price * item.quantity * 0.50;\n },\n 'Preferred': function(item) {\n if (item.price &lt;= 100.0)\n return item.price * item.quantity * 0.75;\n\n // Else\n return item.price * item.quantity;\n },\n 'Regular': function(item) {\n return item.price * item.quantity;\n }\n};\n\n if (pricing[customer.type])\n return pricing[customer.type](item);\n else\n return pricing.Regular(item);\n}\n</code></pre>\n\n<p><a href=\"http://encosia.com/first-class-functions-as-an-alternative-to-javascripts-switch-statement/\" rel=\"nofollow\">Courtesy</a> </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12514/" ]
What are the ways to eliminate the use of switch in code?
Switch-statements are not an antipattern per se, but if you're coding object oriented you should consider if the use of a switch is better solved with [polymorphism](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming) instead of using a switch statement. With polymorphism, this: ``` foreach (var animal in zoo) { switch (typeof(animal)) { case "dog": echo animal.bark(); break; case "cat": echo animal.meow(); break; } } ``` becomes this: ``` foreach (var animal in zoo) { echo animal.speak(); } ```
126,430
<p>Is it possible to change the natural order of columns in Postgres 8.1?</p> <p>I know that you shouldn't rely on column order - it's not <em>essential</em> to what I am doing - I only need it to make some auto-generated stuff come out in a way that is more pleasing, so that the field order matches all the way from pgadmin through the back end and out to the front end.</p>
[ { "answer_id": 126432, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, no, it's not. Column order is entirely up to Postgres.</p>\n" }, { "answer_id": 126437, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p><strong>Specifying the column order in the query is the only reliable (and sane) way</strong>. That said, you can usually get a different ordering by altering the table as shown in the example below as the columns are usually (not guaranteed to be) returned in the order they were added to the table.</p>\n\n<pre><code>postgres=# create table a(a int, b int, c int);\nCREATE TABLE\npostgres=# insert into a values (1,2,3);\nINSERT 0 1\npostgres=# select * from a;\n a | b | c\n---+---+---\n 1 | 2 | 3\n(1 row)\n\npostgres=# alter table a add column a2 int;\nALTER TABLE\npostgres=# select * from a;\n a | b | c | a2\n---+---+---+----\n 1 | 2 | 3 |\n(1 row)\n\npostgres=# update a set a2 = a;\nUPDATE 1\npostgres=# alter table a drop column a;\nALTER TABLE\npostgres=# alter table a rename column a2 to a;\nALTER TABLE\npostgres=# select * from a;\n b | c | a\n---+---+---\n 2 | 3 | 1\n(1 row)\n\npostgres=#\n</code></pre>\n" }, { "answer_id": 126749, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<h2>Reorder the columns in postgresql walkthrough</h2>\n<p>Warning: this approach deletes table properties such as unique indexes and other unintended consequences that come with doing a <code>drop your_table</code>. So you'll need to add those back on after.</p>\n<pre><code>--create a table where column bar comes before column baz:\nCREATE TABLE foo ( moo integer, bar character varying(10), baz date ); \n\n--insert some data\ninsert into foo (moo, bar, baz) values (34, 'yadz', now()); \ninsert into foo (moo, bar, baz) values (12, 'blerp', now()); \nselect * from foo; \n ┌─────┬───────┬────────────┐ \n │ moo │ bar │ baz │ \n ├─────┼───────┼────────────┤ \n │ 34 │ yadz │ 2021-04-07 │ \n │ 12 │ blerp │ 2021-04-07 │ \n └─────┴───────┴────────────┘ \n\n-- Define your reordered columns here, don't forget one, \n-- or it'll be missing from the replacement.\ndrop view if exists my_view;\ncreate view my_view as ( select moo, baz, bar from foo );\nselect * from my_view; \n\nDROP TABLE IF EXISTS foo2; \n--foo2 is your replacement table that has columns ordered correctly\ncreate table foo2 as select * from my_view; \nselect * from foo2;\n--finally drop the view and the original table and rename\nDROP VIEW my_view; \nDROP TABLE foo; \nALTER TABLE foo2 RENAME TO foo; \n\n--observe the reordered columns:\nselect * from foo;\n ┌─────┬────────────┬───────┐ \n │ moo │ baz │ bar │ \n ├─────┼────────────┼───────┤ \n │ 34 │ 2021-04-07 │ yadz │ \n │ 12 │ 2021-04-07 │ blerp │ \n └─────┴────────────┴───────┘ \n</code></pre>\n<h2>Get the prior order of column names for copying and pasting</h2>\n<p>If your table you want to reorder has hundreds of columns, you'll want to automate the getting of the given order of columns so you can copy, nudge, then paste into the above views.</p>\n<pre><code>SELECT string_agg(column_name, ',') from ( \n select * FROM INFORMATION_SCHEMA.COLUMNS \n WHERE table_name = 'your_big_table' \n order by ordinal_position asc \n) f1;\n</code></pre>\n<p>Which prints:</p>\n<pre><code>column_name_1,column_name_2, ..., column_name_n\n</code></pre>\n<p>You copy the above named ordering, you move them to where they belong then paste into the view up top.</p>\n" }, { "answer_id": 127507, "author": "Tometzky", "author_id": 15862, "author_profile": "https://Stackoverflow.com/users/15862", "pm_score": 4, "selected": false, "text": "<p>If your database is not very big and you can afford some downtime then you can:</p>\n\n<ol>\n<li>Disable write access to the database<br>\n<em>this is essential as otherwise any changes after starting the next point will be lost</em></li>\n<li><code>pg_dump --create --column-inserts databasename &gt; databasename.pgdump.sql</code></li>\n<li>Edit apropriate <code>CREATE TABLE</code> statement in databasename.pgdump.sql<br>\n<em>If the file is too big for your editor just split it using <code>split</code> command, edit, then assemble back using <code>cat</code></em></li>\n<li><code>drop database databasename</code><br>\n<em>You do have a recent backup, just in case, do you?</em></li>\n<li><code>psql --single-transaction -f databasename.pgdump.sql</code><br>\n<em>If you don't use <code>--single-transaction</code> it will be very slow</em></li>\n</ol>\n\n<p>If you use so called large objects make sure they are included in the dump. I'm not sure if they are by default in 8.1.</p>\n" }, { "answer_id": 656841, "author": "Russell", "author_id": 79282, "author_profile": "https://Stackoverflow.com/users/79282", "pm_score": 6, "selected": true, "text": "<p>You can actually just straight up change the column order, but I'd hardly recommend it, and you should be very careful if you decide to do it.</p>\n\n<p>eg.</p>\n\n<pre>\n# CREATE TABLE test (a int, b int, c int);\n# INSERT INTO test VALUES (1,2,3);\n# SELECT * FROM test;\n a | b | c \n---+---+---\n 1 | 2 | 3\n(1 row)\n</pre>\n\n<p>Now for the tricky bit, you need to connect to your database using the postgres user so you can modify the system tables.</p>\n\n<pre>\n# SELECT relname, relfilenode FROM pg_class WHERE relname='test';\n relname | relfilenode \n---------+-------------\n test_t | 27666\n(1 row)\n\n# SELECT attrelid, attname, attnum FROM pg_attribute WHERE attrelid=27666;\n attrelid | attname | attnum \n----------+----------+--------\n 27666 | tableoid | -7\n 27666 | cmax | -6\n 27666 | xmax | -5\n 27666 | cmin | -4\n 27666 | xmin | -3\n 27666 | ctid | -1\n 27666 | b | 1\n 27666 | a | 2\n 27666 | c | 3\n(9 rows)\n</pre>\n\n<p>attnum is a unique column, so you need to use a temporary value when you're modifying the column numbers as such:</p>\n\n<pre>\n# UPDATE pg_attribute SET attnum=4 WHERE attname='a' AND attrelid=27666;\nUPDATE 1\n# UPDATE pg_attribute SET attnum=1 WHERE attname='b' AND attrelid=27666;\nUPDATE 1\n# UPDATE pg_attribute SET attnum=2 WHERE attname='a' AND attrelid=27666;\nUPDATE 1\n\n# SELECT * FROM test;\n b | a | c \n---+---+---\n 1 | 2 | 3\n(1 row)\n</pre>\n\n<p>Again, because this is playing around with database system tables, use extreme caution if you feel you really need to do this.</p>\n\n<p>This is working as of postgres 8.3, with prior versions, your milage may vary.</p>\n" }, { "answer_id": 7439117, "author": "Erwin Brandstetter", "author_id": 939860, "author_profile": "https://Stackoverflow.com/users/939860", "pm_score": 4, "selected": false, "text": "<p>I have asked that question in pgsql-admin in 2007. Tom Lane himself declared it practically unfeasible to change the order in the catalogs. </p>\n\n<ul>\n<li><a href=\"https://archives.postgresql.org/pgsql-admin/2007-06/msg00037.php\" rel=\"nofollow noreferrer\">http://archives.postgresql.org/pgsql-admin/2007-06/msg00037.php</a></li>\n</ul>\n\n<p>Clarification: this applies for users with the present tools. Does not mean, it could not be implemented. IMO, it should be.<br>\nStill true for Postgres 12.</p>\n" }, { "answer_id": 40898553, "author": "Alex Willison", "author_id": 7221965, "author_profile": "https://Stackoverflow.com/users/7221965", "pm_score": 1, "selected": false, "text": "<p>You can get the column ordering that you want by creating a new table and selecting columns of the old table in the order that you want them to present:</p>\n\n<pre><code>CREATE TABLE test_new AS SELECT b, c, a FROM test;\nSELECT * from test_new;\n b | c | a \n---+---+---\n 2 | 3 | 1\n(1 row)\n</code></pre>\n\n<p>Note that this copies data only, not modifiers, constraints, indexes, etc..</p>\n\n<p>Once the new table is modified the way you want, drop the original and alter the name of the new one:</p>\n\n<pre><code>BEGIN;\nDROP TABLE test;\nALTER TABLE test_new RENAME TO test;\nCOMMIT;\n</code></pre>\n" }, { "answer_id": 48573607, "author": "Turgs", "author_id": 426935, "author_profile": "https://Stackoverflow.com/users/426935", "pm_score": 3, "selected": false, "text": "<p>I'm wanting the same. Yes, order isn't essential for my use-case, but it just rubs me the wrong way :)</p>\n\n<p>What I'm doing to resolve it is as follows.</p>\n\n<p><strong>This method will ensure you KEEP any existing data,</strong></p>\n\n<ol>\n<li>Create a new version of the table using the ordering I want, using a temporary name.</li>\n<li>Insert all data into that new table from the existing one.</li>\n<li>Drop the old table.</li>\n<li>Rename the new table to the \"proper name\" from \"temporary name\".</li>\n<li>Re-add any indexes you previously had.</li>\n<li>Reset ID sequence for primary key increments.</li>\n</ol>\n\n<p><strong>Current table order:</strong></p>\n\n<pre><code>id, name, email\n</code></pre>\n\n<p><strong>1. Create a new version of the table using the ordering I want, using a temporary name.</strong></p>\n\n<p>In this example, I want <code>email</code> to be before <code>name</code>.</p>\n\n<pre><code>CREATE TABLE mytable_tmp\n(\n id SERIAL PRIMARY KEY,\n email text,\n name text\n);\n</code></pre>\n\n<p><strong>2. Insert all data into that new table from the existing one.</strong></p>\n\n<pre><code>INSERT INTO mytable_tmp --- &lt;&lt; new tmp table\n(\n id\n, email\n, name\n)\nSELECT\n id\n, email\n, name\nFROM mytable; --- &lt;&lt; this is the existing table\n</code></pre>\n\n<p><strong>3. Drop the old table.</strong></p>\n\n<pre><code>DROP TABLE mytable;\n</code></pre>\n\n<p><strong>4. Rename the new table to the \"proper name\" from \"temporary name\".</strong></p>\n\n<pre><code>ALTER TABLE mytable_tmp RENAME TO mytable;\n</code></pre>\n\n<p><strong>5. Re-add any indexes you previously had.</strong></p>\n\n<pre><code>CREATE INDEX ...\n</code></pre>\n\n<p><strong>6. Reset ID sequence for primary key increments.</strong></p>\n\n<pre><code>SELECT setval('public.mytable_id_seq', max(id)) FROM mytable;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3408/" ]
Is it possible to change the natural order of columns in Postgres 8.1? I know that you shouldn't rely on column order - it's not *essential* to what I am doing - I only need it to make some auto-generated stuff come out in a way that is more pleasing, so that the field order matches all the way from pgadmin through the back end and out to the front end.
You can actually just straight up change the column order, but I'd hardly recommend it, and you should be very careful if you decide to do it. eg. ``` # CREATE TABLE test (a int, b int, c int); # INSERT INTO test VALUES (1,2,3); # SELECT * FROM test; a | b | c ---+---+--- 1 | 2 | 3 (1 row) ``` Now for the tricky bit, you need to connect to your database using the postgres user so you can modify the system tables. ``` # SELECT relname, relfilenode FROM pg_class WHERE relname='test'; relname | relfilenode ---------+------------- test_t | 27666 (1 row) # SELECT attrelid, attname, attnum FROM pg_attribute WHERE attrelid=27666; attrelid | attname | attnum ----------+----------+-------- 27666 | tableoid | -7 27666 | cmax | -6 27666 | xmax | -5 27666 | cmin | -4 27666 | xmin | -3 27666 | ctid | -1 27666 | b | 1 27666 | a | 2 27666 | c | 3 (9 rows) ``` attnum is a unique column, so you need to use a temporary value when you're modifying the column numbers as such: ``` # UPDATE pg_attribute SET attnum=4 WHERE attname='a' AND attrelid=27666; UPDATE 1 # UPDATE pg_attribute SET attnum=1 WHERE attname='b' AND attrelid=27666; UPDATE 1 # UPDATE pg_attribute SET attnum=2 WHERE attname='a' AND attrelid=27666; UPDATE 1 # SELECT * FROM test; b | a | c ---+---+--- 1 | 2 | 3 (1 row) ``` Again, because this is playing around with database system tables, use extreme caution if you feel you really need to do this. This is working as of postgres 8.3, with prior versions, your milage may vary.
126,445
<p>I am implementing a design that uses custom styled submit-buttons. They are quite simply light grey buttons with a slightly darker outer border:</p> <pre><code>input.button { background: #eee; border: 1px solid #ccc; } </code></pre> <p>This looks just right in Firefox, Safari and Opera. The problem is with Internet Explorer, both 6 and 7. </p> <p>Since the form is the first one on the page, it's counted as the main form - and thus active from the get go. The first submit button in the active form receives a solid black border in IE, to mark it as the main action.</p> <p>If I turn off borders, then the black extra border in IE goes away too. I am looking for a way to keep my normal borders, but remove the outline.</p>
[ { "answer_id": 126474, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "<p>Right, well here's an ugly fix for you to weigh up... Stick the button in a <code>&lt;span&gt;</code>, nuke the border on the button and give the border to the span instead.</p>\n\n<p>IE is a bit iffy about form element margins so this might not work precisely. Perhaps giving the span the same background as the button might help in that respect.</p>\n\n<pre><code>span.button {\n background: #eee;\n border: 1px solid #ccc;\n}\n\nspan.button input {\n background: #eee;\n border:0;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>&lt;span class=\"button\"&gt;&lt;input type=\"button\" name=\"...\" value=\"Button\"/&gt;&lt;/span&gt;\n</code></pre>\n" }, { "answer_id": 126476, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 0, "selected": false, "text": "<p>A hackish solution might be to use markup like this:</p>\n\n<pre><code>&lt;button&gt;&lt;span&gt;Go&lt;/span&gt;&lt;/button&gt;\n</code></pre>\n\n<p>and apply your border styles to the span element.</p>\n" }, { "answer_id": 126482, "author": "Magnar", "author_id": 1123, "author_profile": "https://Stackoverflow.com/users/1123", "pm_score": 1, "selected": false, "text": "<p>The best solution I have found, is to move the border to a wrapping element, like this:</p>\n\n<pre><code>&lt;div class='submit_button'&gt;&lt;input type=\"submit\" class=\"button\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>With this CSS:</p>\n\n<pre><code>.submit_button { width: 150px; border: 1px solid #ccc; }\n.submit_button .button { width: 150px; border: none; }\n</code></pre>\n\n<p>The main problem with this solution is that the button now is a block-element, and needs to be fixed-width. We could use inline-block, except that Firefox2 does not support it.</p>\n\n<p>Any better solutions are welcome.</p>\n" }, { "answer_id": 126517, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 6, "selected": true, "text": "<p>Well this works here:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;style type=\"text/css\"&gt;\n span.button {\n background: #eee;\n border: 1px solid #ccc;\n }\n\n span.button input {\n background:none;\n border:0;\n margin:0;\n padding:0;\n } \n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;span class=\"button\"&gt;&lt;input type=\"button\" name=\"...\" value=\"Button\"/&gt;&lt;/span&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 785748, "author": "nickmorss", "author_id": 91007, "author_profile": "https://Stackoverflow.com/users/91007", "pm_score": 5, "selected": false, "text": "<p>if you dont want to add a wrapper to the input / button then try doing this. As this is invalid CSS then make sre its for IE only. Have the border as per for other browsers but use the filter:chroma for IE...</p>\n\n<pre><code>&lt;!--[if IE]&gt;\n&lt;style type=\"text/css\"&gt;\ninput {\nfilter:chroma(color=#000000);\nborder:none;\n}\n&lt;/style&gt;\n&lt;![endif]--&gt;\n</code></pre>\n\n<p>worked for me.</p>\n" }, { "answer_id": 1152148, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I think \nfilter:chroma(color=#000000); as metnioned a wile ago is the best as you can apply in certain class. Otherwise you will have to go and apply an extra tag on every button you have that is if you are using classes of course.</p>\n\n<p>.buttonStyle {\nfilter:chroma(color=#000000);\nBACKGROUND-COLOR:#E5813C solid; \nBORDER-BOTTOM: #cccccc 1px solid; \nBORDER-LEFT: #cccccc 1px solid;\nBORDER-RIGHT: #cccccc 1px solid; \nBORDER-TOP: #cccccc 1px solid; COLOR:#FF9900; \nFONT-FAMILY: Verdana, Arial, Helvetica, sans-serif;\nFONT-SIZE: 10px; FONT-WEIGHT: bold; \nTEXT-DECORATION: none;\n}\nThat did it for me!</p>\n" }, { "answer_id": 2042927, "author": "Michael Torfs", "author_id": 189802, "author_profile": "https://Stackoverflow.com/users/189802", "pm_score": 0, "selected": false, "text": "<p>add *border:none\nthis removes the border for IE6 and IE7, but keeps it for the other browsers</p>\n" }, { "answer_id": 2210717, "author": "Benxamin", "author_id": 218119, "author_profile": "https://Stackoverflow.com/users/218119", "pm_score": 0, "selected": false, "text": "<p>With the sliding doors technique, use two <code>spans</code> inside of the <code>button</code>. And eliminate any formatting on the <code>button</code> in your IE override.</p>\n\n<pre><code>&lt;button&gt;&lt;span class=\"open\"&gt;Search&lt;span class=\"close\"&gt;&lt;/span&gt;&lt;/span&gt;&lt;/button&gt;\n</code></pre>\n" }, { "answer_id": 2726037, "author": "rexusdiablos", "author_id": 327374, "author_profile": "https://Stackoverflow.com/users/327374", "pm_score": 2, "selected": false, "text": "<p>I've found an answer that works for me on another forum. It removes the unwanted black border in ie6 and ie7. It's probable that some/many of you have not positioned your input=\"submit\" in form tags. Don't overlook this. It worked for me after trying <strong><em>everything</em></strong> else. </p>\n\n<p>If you are using a submit button, make sure it is within a form and not just a fieldset:</p>\n\n<pre><code>&lt;form&gt;&lt;fieldset&gt;&lt;input type=\"submit\"&gt;&lt;/fieldset&gt;&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 3365781, "author": "David Murdoch", "author_id": 160173, "author_profile": "https://Stackoverflow.com/users/160173", "pm_score": 3, "selected": false, "text": "<p>I know I'm almost 2 years late to the game, but I found another solution (at least for IE7).</p>\n\n<p>If you add another <code>input type=\"submit\"</code> to your form <em>before</em> any other submit button in the form the problem will go away. Now you just need to hide this new, black-border-absorbing-button. </p>\n\n<p>This works for me (overflow needs to be \"auto\"):</p>\n\n<pre><code>&lt;input type=\"submit\" value=\"\" style=\"height:0;overflow:auto;position:absolute;left:-9999px;\" /&gt;\n</code></pre>\n\n<p>Note: I am using an HTML5 doctype (<code>&lt;!doctype html&gt;</code>).</p>\n" }, { "answer_id": 4111318, "author": "ang", "author_id": 498955, "author_profile": "https://Stackoverflow.com/users/498955", "pm_score": 1, "selected": false, "text": "<p>I had this problem and solved it with a div around the button, displayed it as a block, and positioned it manually. the margins for buttons in IE and FF was just too unpredictable and there was no way for them both to be happy. My submit button had to be perfectly lined up against the input, so it just wouldnt work without positioning the items as blocks.</p>\n" }, { "answer_id": 8054579, "author": "Holf", "author_id": 169334, "author_profile": "https://Stackoverflow.com/users/169334", "pm_score": 2, "selected": false, "text": "<p>I was able to combine David Murdoch's suggestion with some JQuery such that the fix will automatically be applied for all 'input:submit' elements on the page:</p>\n\n<pre><code>// Test for IE7.\nif ($.browser.msie &amp;&amp; parseInt($.browser.version, 10) == 7) {\n $('&lt;input type=\"submit\" value=\"\" style=\"height:0;overflow:auto;position:absolute;left:-9999px;\" /&gt;')\n.insertBefore(\"input:submit\");\n }\n</code></pre>\n\n<p>You can include this in a Master Page or equivalent, so it gets applied to all pages in your site.</p>\n\n<p>It works, but it does feel a bit wrong, somehow.</p>\n" }, { "answer_id": 8130571, "author": "Tyler", "author_id": 539300, "author_profile": "https://Stackoverflow.com/users/539300", "pm_score": 0, "selected": false, "text": "<p>I can't comment (yet) so I have to add my comment this way. I thing Mr. David Murdoch's advice is the best for Opera ( <a href=\"https://stackoverflow.com/questions/126445/any-way-to-remove-ies-black-border-around-submit-button-in-active-forms/3365781#3365781\">here</a> ). OMG, what a lovely girl he's got btw.</p>\n\n<p>I've tried his approach in Opera and I succeeded basically doubling the input tags in this way:</p>\n\n<pre><code>&lt;input type=\"submit\" value=\"Go\" style=\"display:none;\" id=\"WorkaroundForOperaInputFocusBorderBug\" /&gt;\n&lt;input type=\"submit\" value=\"Go\" /&gt;\n</code></pre>\n\n<p>This way the 1st element is hidden but it CATCHES the display focus Opera would give to the 2nd input element instead. LOVE IT!</p>\n" }, { "answer_id": 8661062, "author": "Drew Chapin", "author_id": 1017257, "author_profile": "https://Stackoverflow.com/users/1017257", "pm_score": 2, "selected": false, "text": "<p>I'm building on @nickmorss's example of using filters which didn't really work out for my situation... Using the glow filter instead worked out much better for me.</p>\n\n<pre><code>&lt;!--[if IE]&gt;\n&lt;style type=\"text/css\"&gt;\n input[type=\"submit\"], input[type=\"button\"], button\n {\n border: none !important;\n filter: progid:DXImageTransform.Microsoft.glow(color=#d0d0d0,strength=1);\n height: 24px; /* I had to adjust the height from the original value */\n }\n&lt;/style&gt;\n&lt;![endif]--&gt;\n</code></pre>\n" }, { "answer_id": 8741469, "author": "Gregor", "author_id": 536082, "author_profile": "https://Stackoverflow.com/users/536082", "pm_score": 0, "selected": false, "text": "<p>At least in IE7 you can style the border althogh you can't remove it (set it to none).\nSo setting the color of the border to the same color that your background should do. </p>\n\n<pre><code>.submitbutton { \nbackground-color: #fff;\nborder: #fff dotted 1px; \n}\n</code></pre>\n\n<p>if your background is white. </p>\n" }, { "answer_id": 9291644, "author": "Luca Fagioli", "author_id": 636561, "author_profile": "https://Stackoverflow.com/users/636561", "pm_score": 1, "selected": false, "text": "<p>This is going to work:</p>\n\n<pre><code>input[type=button]\n{\n filter:chroma(color=#000000);\n}\n</code></pre>\n\n<p>This works even with <code>button</code> tag, and eventually you can safely use the <code>background-image</code> css property.</p>\n" }, { "answer_id": 12828931, "author": "curly_brackets", "author_id": 315200, "author_profile": "https://Stackoverflow.com/users/315200", "pm_score": 1, "selected": false, "text": "<p>The correct answer to this qustion is:</p>\n\n<pre><code>outline: none;\n</code></pre>\n\n<p>... works for IE and Chrome, in my knowledge.</p>\n" }, { "answer_id": 27618972, "author": "Shubh", "author_id": 769678, "author_profile": "https://Stackoverflow.com/users/769678", "pm_score": 0, "selected": false, "text": "<p>For me the below code actually worked.</p>\n\n<pre><code>&lt;!--[if IE]&gt;\n &lt;style type=\"text/css\"&gt;\n input[type=submit],input[type=reset],input[type=button]\n {\n filter:chroma(color=#000000);\n color:#010101;\n }\n &lt;/style&gt;\n&lt;![endif]--&gt;\n</code></pre>\n\n<p>Got it from <code>@Mark's</code> <a href=\"https://stackoverflow.com/a/9428298/769678\">answer</a> and loaded it only for IE.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1123/" ]
I am implementing a design that uses custom styled submit-buttons. They are quite simply light grey buttons with a slightly darker outer border: ``` input.button { background: #eee; border: 1px solid #ccc; } ``` This looks just right in Firefox, Safari and Opera. The problem is with Internet Explorer, both 6 and 7. Since the form is the first one on the page, it's counted as the main form - and thus active from the get go. The first submit button in the active form receives a solid black border in IE, to mark it as the main action. If I turn off borders, then the black extra border in IE goes away too. I am looking for a way to keep my normal borders, but remove the outline.
Well this works here: ``` <html> <head> <style type="text/css"> span.button { background: #eee; border: 1px solid #ccc; } span.button input { background:none; border:0; margin:0; padding:0; } </style> </head> <body> <span class="button"><input type="button" name="..." value="Button"/></span> </body> </html> ```
126,513
<p>I am running following <code>PHP</code> code to interact with a MS Access database.</p> <pre><code>$odbc_con = new COM("ADODB.Connection"); $constr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $db_path . ";"; $odbc_con -&gt; open($constr); $rs_select = $odbc_con -&gt; execute ("SELECT * FROM Main"); </code></pre> <p>Using <code>($rs_select -&gt; RecordCount)</code> gives -1 though the query is returning non-zero records.</p> <p>(a) What can be the reason? (b) Is there any way out?</p> <p>I have also tried using <code>count($rs_select -&gt; GetRows())</code>. This satisfies the need but looks inefficient as it will involve copying of all the records into an array first.</p>
[ { "answer_id": 126543, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "<p>Doesn't Access have its own COUNT operator? eg:</p>\n\n<pre><code>$rs_select = $odbc_con -&gt; execute (\"SELECT COUNT(*) FROM Main\");\n</code></pre>\n" }, { "answer_id": 126603, "author": "Otherside", "author_id": 18697, "author_profile": "https://Stackoverflow.com/users/18697", "pm_score": 1, "selected": false, "text": "<p>It is possible that ODBC doesn't know the recordcount yet. In that case it is possible to go to the last record and only then will recordcount reflect the true number of records. This will probably also not be very efficient since it will load all records from the query.</p>\n\n<p>As Oli said, using <code>SELECT COUNT(*)</code> will give you the result. I think that using 2 queries would still be more efficient than using my first method.</p>\n" }, { "answer_id": 128885, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 0, "selected": false, "text": "<p>Basically, Access is not going to show you the whole record set until it needs to (it's faster that way for much of the user experience anyway) - especially with larger recordsets.</p>\n\n<p>To get an accurate count, you must traverse the entire record set. In VBA I normally do that with a duo of foo.MoveLast and foo.MoveFirst - I don't know what the php equivalents are. It's expensive, but since it sounds like you are going to be processing the whole record set anyway, I guess it is OK.</p>\n\n<p>(a side note, this same traversal is also necessary if you are manipulating bookmarks in VBA, as you can get some wild results if you clone a recordset and don't traverse it before you copy the bookmark back to the form's recordset)</p>\n" }, { "answer_id": 130159, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 2, "selected": true, "text": "<p>ADODB has its own rules for what recordcount is returned depending on the type of recordset you've defined. See:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/194973\" rel=\"nofollow noreferrer\">MS Knowledge Base article 194973</a></p>\n\n<p><a href=\"http://www.w3schools.com/ADO/prop_rs_recordcount.asp\" rel=\"nofollow noreferrer\">W3C Schools article</a></p>\n\n<p>In the example above, the PHP COM() object is used to instantiate ADODB, a COM interface for generic database access. According to the <a href=\"http://us3.php.net/manual/en/class.com.php\" rel=\"nofollow noreferrer\">PHP documentation</a>, the object reference produced is overloaded, so you can just use the same properties/methods that the native ADODB object would have. This means that you need to use the ADODB methods to set the recordset type to one that will give an accurate recordcount (if you must have it). The alternative, as others have mentioned, is to use a second query to get the COUNT() of the records returned by the SELECT statement. This is easier, but may be inappropriate in the particular environment.</p>\n\n<p>I'm not an ADO guru, so can't provide you with the exact commands for setting your recordset type, but from the articles cited above, it is clear that you need a static or keyset cursor. It appears to me that the proper method of setting the CursorType is to use a parameter in the command that opens the recordset. <a href=\"http://www.w3schools.com/ADO/prop_rs_cursortype.asp\" rel=\"nofollow noreferrer\">This W3C Schools article on the CursorType property</a> gives the appropriate arguments for that command.</p>\n\n<p>Hopefully, this information will help the original poster accomplish his task, one way or the other.</p>\n" }, { "answer_id": 134357, "author": "Taptronic", "author_id": 14728, "author_profile": "https://Stackoverflow.com/users/14728", "pm_score": -1, "selected": false, "text": "<p>If you're using a dynamic cursor type of connection, then it could actually change. Someone may delete a record from that database while you're browsing through pages of records. To avoid, use a static sort of snapshot cursor. I have this bookmarked which will explain it well. This always got me and the bookmark always reminded me why.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/194973\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/194973</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6561/" ]
I am running following `PHP` code to interact with a MS Access database. ``` $odbc_con = new COM("ADODB.Connection"); $constr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $db_path . ";"; $odbc_con -> open($constr); $rs_select = $odbc_con -> execute ("SELECT * FROM Main"); ``` Using `($rs_select -> RecordCount)` gives -1 though the query is returning non-zero records. (a) What can be the reason? (b) Is there any way out? I have also tried using `count($rs_select -> GetRows())`. This satisfies the need but looks inefficient as it will involve copying of all the records into an array first.
ADODB has its own rules for what recordcount is returned depending on the type of recordset you've defined. See: [MS Knowledge Base article 194973](http://support.microsoft.com/kb/194973) [W3C Schools article](http://www.w3schools.com/ADO/prop_rs_recordcount.asp) In the example above, the PHP COM() object is used to instantiate ADODB, a COM interface for generic database access. According to the [PHP documentation](http://us3.php.net/manual/en/class.com.php), the object reference produced is overloaded, so you can just use the same properties/methods that the native ADODB object would have. This means that you need to use the ADODB methods to set the recordset type to one that will give an accurate recordcount (if you must have it). The alternative, as others have mentioned, is to use a second query to get the COUNT() of the records returned by the SELECT statement. This is easier, but may be inappropriate in the particular environment. I'm not an ADO guru, so can't provide you with the exact commands for setting your recordset type, but from the articles cited above, it is clear that you need a static or keyset cursor. It appears to me that the proper method of setting the CursorType is to use a parameter in the command that opens the recordset. [This W3C Schools article on the CursorType property](http://www.w3schools.com/ADO/prop_rs_cursortype.asp) gives the appropriate arguments for that command. Hopefully, this information will help the original poster accomplish his task, one way or the other.
126,524
<p>I could swear I've seen the function (or method) that takes a list, like this <code>[3, 7, 19]</code> and makes it into iterable list of tuples, like so: <code>[(0,3), (1,7), (2,19)]</code> to use it instead of:</p> <pre><code>for i in range(len(name_of_list)): name_of_list[i] = something </code></pre> <p>but I can't remember the name and googling "iterate list" gets nothing.</p>
[ { "answer_id": 126533, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 10, "selected": true, "text": "<pre><code>&gt;&gt;&gt; a = [3,4,5,6]\n&gt;&gt;&gt; for i, val in enumerate(a):\n... print i, val\n...\n0 3\n1 4\n2 5\n3 6\n&gt;&gt;&gt;\n</code></pre>\n" }, { "answer_id": 126535, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 7, "selected": false, "text": "<p>Yep, that would be the <a href=\"http://docs.python.org/library/functions.html#enumerate\" rel=\"noreferrer\"><code>enumerate</code></a> function! Or more to the point, you need to do:</p>\n\n<pre><code>list(enumerate([3,7,19]))\n\n[(0, 3), (1, 7), (2, 19)]\n</code></pre>\n" }, { "answer_id": 127375, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": false, "text": "<p>Here's another using the <code>zip</code> function.</p>\n\n<pre><code>&gt;&gt;&gt; a = [3, 7, 19]\n&gt;&gt;&gt; zip(range(len(a)), a)\n[(0, 3), (1, 7), (2, 19)]\n</code></pre>\n" }, { "answer_id": 18777094, "author": "Lucas Ribeiro", "author_id": 2055970, "author_profile": "https://Stackoverflow.com/users/2055970", "pm_score": 3, "selected": false, "text": "<p>Here it is a solution using map function:</p>\n\n<pre><code>&gt;&gt;&gt; a = [3, 7, 19]\n&gt;&gt;&gt; map(lambda x: (x, a[x]), range(len(a)))\n[(0, 3), (1, 7), (2, 19)]\n</code></pre>\n\n<p>And a solution using list comprehensions:</p>\n\n<pre><code>&gt;&gt;&gt; a = [3,7,19]\n&gt;&gt;&gt; [(x, a[x]) for x in range(len(a))]\n[(0, 3), (1, 7), (2, 19)]\n</code></pre>\n" }, { "answer_id": 35429590, "author": "Sнаđошƒаӽ", "author_id": 3375713, "author_profile": "https://Stackoverflow.com/users/3375713", "pm_score": 2, "selected": false, "text": "<p>If you have multiple lists, you can do this combining <code>enumerate</code> and <code>zip</code>:</p>\n\n<pre><code>list1 = [1, 2, 3, 4, 5]\nlist2 = [10, 20, 30, 40, 50]\nlist3 = [100, 200, 300, 400, 500]\nfor i, (l1, l2, l3) in enumerate(zip(list1, list2, list3)):\n print(i, l1, l2, l3)\n</code></pre>\n\nOutput:\n\n<pre><code>0 1 10 100\n1 2 20 200\n2 3 30 300\n3 4 40 400\n4 5 50 500\n</code></pre>\n\n<p>Note that parenthesis is required after <code>i</code>. Otherwise you get the error: <code>ValueError: need more than 2 values to unpack</code></p>\n" }, { "answer_id": 36571189, "author": "Harun ERGUL", "author_id": 4104008, "author_profile": "https://Stackoverflow.com/users/4104008", "pm_score": 3, "selected": false, "text": "<p>python <code>enumerate</code> function will be satisfied your requirements</p>\n\n<pre><code>result = list(enumerate([1,3,7,12]))\nprint result\n</code></pre>\n\n<p><strong>output</strong><br></p>\n\n<pre><code>[(0, 1), (1, 3), (2, 7),(3,12)]\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37141/" ]
I could swear I've seen the function (or method) that takes a list, like this `[3, 7, 19]` and makes it into iterable list of tuples, like so: `[(0,3), (1,7), (2,19)]` to use it instead of: ``` for i in range(len(name_of_list)): name_of_list[i] = something ``` but I can't remember the name and googling "iterate list" gets nothing.
``` >>> a = [3,4,5,6] >>> for i, val in enumerate(a): ... print i, val ... 0 3 1 4 2 5 3 6 >>> ```
126,526
<p>Has anyone got any suggestions for unit testing a Managed Application Add-In for Office? I'm using NUnit but I had the same issues with MSTest.</p> <p>The problem is that there is a .NET assembly loaded inside the Office application (in my case, Word) and I need a reference to that instance of the .NET assembly. I can't just instantiate the object because it wouldn't then have an instance of Word to do things to.</p> <p>Now, I can use the Application.COMAddIns("Name of addin").Object interface to get a reference, but that gets me a COM object that is returned through the RequestComAddInAutomationService. My solution so far is that for that object to have proxy methods for every method in the real .NET object that I want to test (all set under conditional-compilation so they disappear in the released version).</p> <p>The COM object (a VB.NET class) actually has a reference to the instance of the real add-in, but I tried just returning that to NUnit and I got a nice p/Invoke error:</p> <p>System.Runtime.Remoting.RemotingException : This remoting proxy has no channel sink which means either the server has no registered server channels that are listening, or this application has no suitable client channel to talk to the server. at System.Runtime.Remoting.Proxies.RemotingProxy.InternalInvoke(IMethodCallMessage reqMcmMsg, Boolean useDispatchMessage, Int32 callType) at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(IMessage reqMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type) </p> <p>I tried making the main add-in COM visible and the error changes:</p> <p>System.InvalidOperationException : Operation is not valid due to the current state of the object. at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData&amp; msgData) </p> <p>While I have a work-around, it's messy and puts lots of test code in the real project instead of the test project - which isn't really the way NUnit is meant to work.</p>
[ { "answer_id": 126560, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>Consider the various mocking frameworks <a href=\"http://www.nmock.org/\" rel=\"nofollow noreferrer\">NMock</a>, <a href=\"http://ayende.com/projects/rhino-mocks.aspx\" rel=\"nofollow noreferrer\">RhinoMocks</a>, etc. to fake the behavior of Office in your tests. </p>\n" }, { "answer_id": 713567, "author": "Richard Gadsden", "author_id": 20354, "author_profile": "https://Stackoverflow.com/users/20354", "pm_score": 3, "selected": true, "text": "<p>This is how I resolved it.</p>\n\n<ol>\n<li><p>Just about everything in my add-in runs from the Click method of a button in the UI. I have changed all those Click methods to consist only of a simple, parameterless call.</p></li>\n<li><p>I then created a new file (Partial Class) called EntryPoint that had lots of very short Friend Subs, each of which was usually one or two calls to parameterised worker functions, so that all the Click methods just called into this file. So, for example, there's a function that opens a standard document and calls a \"save as\" into our DMS. The function takes a parameter of which document to open, and there are a couple of dozen standard documents that we use.</p></li>\n</ol>\n\n<p>So I have </p>\n\n<pre><code>Private Sub btnMemo_Click(ByVal Ctrl As Microsoft.Office.Core.CommandBarButton, ByRef CancelDefault As Boolean) Handles btnMemo.Click\n DocMemo()\nEnd Sub\n</code></pre>\n\n<p>in the ThisAddin and then</p>\n\n<pre><code>Friend Sub DocMemo()\n OpenDocByNumber(\"Prec\", 8862, 1)\nEnd Sub\n</code></pre>\n\n<p>in my new EntryPoints file.</p>\n\n<ol start=\"3\">\n<li><p>I add a new AddInUtilities file which has</p>\n\n<p>Public Interface IAddInUtilities</p></li>\n</ol>\n\n<p><code>#If DEBUG Then</code></p>\n\n<pre><code>Sub DocMemo()\n</code></pre>\n\n<p><code>#End If</code></p>\n\n<pre><code>End Interface\n\n\nPublic Class AddInUtilities\n Implements IAddInUtilities\n Private Addin as ThisAddIn\n</code></pre>\n\n<p><code>#If DEBUG Then</code></p>\n\n<pre><code>Public Sub DocMemo() Implements IAddInUtilities.DocMemo\n Addin.DocMemo()\nEnd Sub\n</code></pre>\n\n<p><code>#End If</code></p>\n\n<pre><code> Friend Sub New(ByRef theAddin as ThisAddIn)\n Addin=theAddin\n End Sub\n End Class\n</code></pre>\n\n<ol start=\"4\">\n<li><p>I go to the ThisAddIn file and add in</p>\n\n<p>Private utilities As AddInUtilities</p>\n\n<p>Protected Overrides Function RequestComAddInAutomationService() As Object\n If utilities Is Nothing Then\n utilities = New AddInUtilities(Me)\n End If\n Return utilities\nEnd Function</p></li>\n</ol>\n\n<p>And now it's possible to test the DocMemo() function in EntryPoints using NUnit, something like this:</p>\n\n<pre><code>&lt;TestFixture()&gt; Public Class Numbering\n\nPrivate appWord As Word.Application\nPrivate objMacros As Object\n\n&lt;TestFixtureSetUp()&gt; Public Sub LaunchWord()\n appWord = New Word.Application\n appWord.Visible = True\n\n Dim AddIn As COMAddIn = Nothing\n Dim AddInUtilities As IAddInUtilities\n For Each tempAddin As COMAddIn In appWord.COMAddIns\n If tempAddin.Description = \"CobbettsMacrosVsto\" Then\n AddIn = tempAddin\n End If\n Next\n AddInUtilities = AddIn.Object\n objMacros = AddInUtilities.TestObject\n\n\nEnd Sub\n\n&lt;Test()&gt; Public Sub DocMemo()\n\n\n objMacros.DocMemo()\nEnd Sub\n\n&lt;TestFixtureTearDown()&gt; Public Sub TearDown()\n appWord.Quit(False)\nEnd Sub\n\nEnd Class\n</code></pre>\n\n<p>The only thing you can't then unit test are the actual Click events, because you're calling into EntryPoints in a different way, ie through the RequestComAddInAutomationService interface rather than through the event handlers.</p>\n\n<p>But it works!</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20354/" ]
Has anyone got any suggestions for unit testing a Managed Application Add-In for Office? I'm using NUnit but I had the same issues with MSTest. The problem is that there is a .NET assembly loaded inside the Office application (in my case, Word) and I need a reference to that instance of the .NET assembly. I can't just instantiate the object because it wouldn't then have an instance of Word to do things to. Now, I can use the Application.COMAddIns("Name of addin").Object interface to get a reference, but that gets me a COM object that is returned through the RequestComAddInAutomationService. My solution so far is that for that object to have proxy methods for every method in the real .NET object that I want to test (all set under conditional-compilation so they disappear in the released version). The COM object (a VB.NET class) actually has a reference to the instance of the real add-in, but I tried just returning that to NUnit and I got a nice p/Invoke error: System.Runtime.Remoting.RemotingException : This remoting proxy has no channel sink which means either the server has no registered server channels that are listening, or this application has no suitable client channel to talk to the server. at System.Runtime.Remoting.Proxies.RemotingProxy.InternalInvoke(IMethodCallMessage reqMcmMsg, Boolean useDispatchMessage, Int32 callType) at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(IMessage reqMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) I tried making the main add-in COM visible and the error changes: System.InvalidOperationException : Operation is not valid due to the current state of the object. at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData) While I have a work-around, it's messy and puts lots of test code in the real project instead of the test project - which isn't really the way NUnit is meant to work.
This is how I resolved it. 1. Just about everything in my add-in runs from the Click method of a button in the UI. I have changed all those Click methods to consist only of a simple, parameterless call. 2. I then created a new file (Partial Class) called EntryPoint that had lots of very short Friend Subs, each of which was usually one or two calls to parameterised worker functions, so that all the Click methods just called into this file. So, for example, there's a function that opens a standard document and calls a "save as" into our DMS. The function takes a parameter of which document to open, and there are a couple of dozen standard documents that we use. So I have ``` Private Sub btnMemo_Click(ByVal Ctrl As Microsoft.Office.Core.CommandBarButton, ByRef CancelDefault As Boolean) Handles btnMemo.Click DocMemo() End Sub ``` in the ThisAddin and then ``` Friend Sub DocMemo() OpenDocByNumber("Prec", 8862, 1) End Sub ``` in my new EntryPoints file. 3. I add a new AddInUtilities file which has Public Interface IAddInUtilities `#If DEBUG Then` ``` Sub DocMemo() ``` `#End If` ``` End Interface Public Class AddInUtilities Implements IAddInUtilities Private Addin as ThisAddIn ``` `#If DEBUG Then` ``` Public Sub DocMemo() Implements IAddInUtilities.DocMemo Addin.DocMemo() End Sub ``` `#End If` ``` Friend Sub New(ByRef theAddin as ThisAddIn) Addin=theAddin End Sub End Class ``` 4. I go to the ThisAddIn file and add in Private utilities As AddInUtilities Protected Overrides Function RequestComAddInAutomationService() As Object If utilities Is Nothing Then utilities = New AddInUtilities(Me) End If Return utilities End Function And now it's possible to test the DocMemo() function in EntryPoints using NUnit, something like this: ``` <TestFixture()> Public Class Numbering Private appWord As Word.Application Private objMacros As Object <TestFixtureSetUp()> Public Sub LaunchWord() appWord = New Word.Application appWord.Visible = True Dim AddIn As COMAddIn = Nothing Dim AddInUtilities As IAddInUtilities For Each tempAddin As COMAddIn In appWord.COMAddIns If tempAddin.Description = "CobbettsMacrosVsto" Then AddIn = tempAddin End If Next AddInUtilities = AddIn.Object objMacros = AddInUtilities.TestObject End Sub <Test()> Public Sub DocMemo() objMacros.DocMemo() End Sub <TestFixtureTearDown()> Public Sub TearDown() appWord.Quit(False) End Sub End Class ``` The only thing you can't then unit test are the actual Click events, because you're calling into EntryPoints in a different way, ie through the RequestComAddInAutomationService interface rather than through the event handlers. But it works!
126,528
<p>On the safari browser, the standard &lt;asp:Menu&gt; doesn't render well at all. How can this be fixed?</p>
[ { "answer_id": 126709, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>You can use ControlAdapters to alter the rendering of server controls.</p>\n\n<p>Here's an example:\n<a href=\"http://www.pluralsight.com/community/blogs/fritz/archive/2007/03/27/46598.aspx\" rel=\"nofollow noreferrer\">http://www.pluralsight.com/community/blogs/fritz/archive/2007/03/27/46598.aspx</a></p>\n\n<p>Though, in my opinion it might be equal amount of work to abandon the menu control for a pure css one (available on many sites).</p>\n" }, { "answer_id": 127128, "author": "deepcode.co.uk", "author_id": 20524, "author_profile": "https://Stackoverflow.com/users/20524", "pm_score": 0, "selected": false, "text": "<p>Oooof - was hoping it would be a simmple case of adding a browserCaps item in web.config with appropriate values or similar...</p>\n" }, { "answer_id": 127649, "author": "deepcode.co.uk", "author_id": 20524, "author_profile": "https://Stackoverflow.com/users/20524", "pm_score": 3, "selected": true, "text": "<p>Thanks for the advice, it led me into the following solution;</p>\n\n<p>I created a file named \"safari.browser\" and placed it in the App_Browsers directory. The content of this file is shown below;</p>\n\n<pre><code>&lt;browsers&gt;\n &lt;browser refID=\"safari1plus\"&gt;\n &lt;controlAdapters&gt;\n &lt;adapter controlType=\"System.Web.UI.WebControls.Menu\" adapterType=\"\" /&gt;\n &lt;/controlAdapters&gt;\n &lt;/browser&gt;\n&lt;/browsers&gt;\n</code></pre>\n\n<p>As I understand it, this tells ASP.NET not to use the adaptor it would normally use to render the control content and instead use uplevel rendering.</p>\n" }, { "answer_id": 977072, "author": "jonezy", "author_id": 2272, "author_profile": "https://Stackoverflow.com/users/2272", "pm_score": 0, "selected": false, "text": "<p>The best and simplest solution I've found for this problem is to include this bit of code in your page_load event.</p>\n\n<pre><code>if (Request.UserAgent.IndexOf(\"AppleWebKit\") &gt; 0)\n Request.Browser.Adapters.Clear();\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524/" ]
On the safari browser, the standard <asp:Menu> doesn't render well at all. How can this be fixed?
Thanks for the advice, it led me into the following solution; I created a file named "safari.browser" and placed it in the App\_Browsers directory. The content of this file is shown below; ``` <browsers> <browser refID="safari1plus"> <controlAdapters> <adapter controlType="System.Web.UI.WebControls.Menu" adapterType="" /> </controlAdapters> </browser> </browsers> ``` As I understand it, this tells ASP.NET not to use the adaptor it would normally use to render the control content and instead use uplevel rendering.
126,584
<p>I have a requirement to be be able to embed scanned tiff images into some SSRS reports.</p> <p>When I design a report in VS2005 and add an image control the tiff image displays perfectly however when I build it. I get the warning :</p> <p><code>Warning 2 [rsInvalidMIMEType] The value of the MIMEType property for the image ‘image1’ is “image/tiff”, which is not a valid MIMEType. c:\SSRSStuff\TestReport.rdl 0 0</code></p> <p>and instead of an image I get the little red x.</p> <p>Has anybody overcome this issue?</p>
[ { "answer_id": 130950, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 3, "selected": true, "text": "<p>Assuming you're delivering the image file via IIS, use an ASP.NET page to change image formats and mime type to something that you <em>can</em> use. </p>\n\n<pre><code>Response.ContentType = \"image/png\";\nResponse.Clear();\nusing (Bitmap bmp = new Bitmap(tifFilepath))\n bmp.Save(Response.OutputStream, ImageFormat.Png);\nResponse.End();\n</code></pre>\n" }, { "answer_id": 132873, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 0, "selected": false, "text": "<p>Thanks <a href=\"https://stackoverflow.com/users/19931/peter-wone\">Peter</a> your code didn't compile but the idea was sound.</p>\n\n<p>Here is my attempt that works for me.</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n Response.ContentType = \"image/jpeg\";\n Response.Clear(); \n Bitmap bmp = new Bitmap(tifFileLocation);\n bmp.Save(Response.OutputStream, ImageFormat.Jpeg);\n Response.End();\n\n}\n</code></pre>\n" }, { "answer_id": 2721462, "author": "Fulbert Fadri", "author_id": 326884, "author_profile": "https://Stackoverflow.com/users/326884", "pm_score": 2, "selected": false, "text": "<p>I have been goggling fora solution on how to display a TIFF image in a SSRS report but I couldn't find any and since SSRS doesn's support TIFF, I thought converting the TIFF to one of the suppported format will do the trick. And it did. I don't know if there are similar implementation like this out there, but I am just posting so others could benefit as well. \nNote this only applies if you have a TIFF image saved on database.</p>\n\n<pre><code>Public Shared Function ToImage(ByVal imageBytes As Byte()) As Byte()\n Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream(imageBytes)\n Dim os As System.IO.MemoryStream = New System.IO.MemoryStream()\n Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(ms)\n\n img.Save(os, System.Drawing.Imaging.ImageFormat.Jpeg)\n\n Return os.ToArray()\nEnd Function\n</code></pre>\n\n<p>Here’s how you can use the code:\n 1. In the Report Properties, Select Refereneces, click add and browse System.Drawing, Version=2.0.0.0 \n 2. Select the Code Property, Copy paste the function above \n 3. Click Ok \n 4. Drop an Image control from the toolbox \n 4.1. Right-Click the image and select Image Properties \n 4.2. Set the Image Source to Database \n 4.3. In the Use this field, Click expression and paste the code below \n =Code.ToImage(Fields!FormImage.Value)<br>\n 4.4. Set the appropriate Mime to Jpeg </p>\n\n<p>Regards,\nFulbert</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1116/" ]
I have a requirement to be be able to embed scanned tiff images into some SSRS reports. When I design a report in VS2005 and add an image control the tiff image displays perfectly however when I build it. I get the warning : `Warning 2 [rsInvalidMIMEType] The value of the MIMEType property for the image ‘image1’ is “image/tiff”, which is not a valid MIMEType. c:\SSRSStuff\TestReport.rdl 0 0` and instead of an image I get the little red x. Has anybody overcome this issue?
Assuming you're delivering the image file via IIS, use an ASP.NET page to change image formats and mime type to something that you *can* use. ``` Response.ContentType = "image/png"; Response.Clear(); using (Bitmap bmp = new Bitmap(tifFilepath)) bmp.Save(Response.OutputStream, ImageFormat.Png); Response.End(); ```
126,587
<p>I have an old server with a defunct evaluation version of SQL 2000 on it (from 2006), and two databases which were sitting on it.</p> <p>For some unknown reason, the LDF log files are missing. Presumed deleted.</p> <p>I have the mdf files (and in one case an ndf file too) for the databases which used to exist on that server, and I am trying to get them up and running on another SQL 2000 box I have sitting around.</p> <p><code>sp_attach_db</code> complains that the logfile is missing, and will not attach the database. Attempts to fool it by using a logfile from a database with the same name failed miserably. <code>sp_attach_single_file_db</code> will not work either. The mdf files have obviously not been cleanly detached.</p> <p>How do I get the databases attached and readable?</p>
[ { "answer_id": 126633, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 4, "selected": true, "text": "<p>I found this answer, which worked with my SQL 2000 machines:</p>\n\n<p><strong>How to attach a database with a non-cleanly detached MDF file.</strong></p>\n\n<p><strong>Step 1:</strong> Make a new database with same name, and which uses the same files as the old one on the new server.</p>\n\n<p><strong>Step 2:</strong> Stop SQL server, and move your mdf files (and any ndf files you have) over the top of the new ones you just created. Delete any log files.</p>\n\n<p><strong>Step 3:</strong> Start SQL and run this to put the DB in emergency mode.</p>\n\n<pre><code>sp_configure 'allow updates', 1\ngo\nreconfigure with override\nGO\nupdate sysdatabases set status = 32768 where name = 'TestDB'\ngo\nsp_configure 'allow updates', 0\ngo\nreconfigure with override\nGO\n</code></pre>\n\n<p><strong>Step 4:</strong> Restart SQL server and observe that the DB is successfully in emergency mode.</p>\n\n<p><strong>Step 5:</strong> Run this undocumented dbcc option to rebuild the log file (in the correct place)</p>\n\n<pre><code>DBCC REBUILD_LOG(TestDB,'D:\\SQL_Log\\TestDB_Log.LDF')\n</code></pre>\n\n<p><strong>Step 6:</strong> You might need to reset the status. Even if you don't, it won't do any harm to do so.</p>\n\n<pre><code>exec sp_resetstatus TestDB\n</code></pre>\n\n<p><strong>Step 7:</strong> Stop and start SQL to see your newly restored database.</p>\n" }, { "answer_id": 126638, "author": "Valerion", "author_id": 16156, "author_profile": "https://Stackoverflow.com/users/16156", "pm_score": 1, "selected": false, "text": "<p>In Enterprise Manager, right-click the server and choose Attach Database. Select the MDF file and click Ok. It will then ask you if you want to create a new log file or not. Say Yes.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/126587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6910/" ]
I have an old server with a defunct evaluation version of SQL 2000 on it (from 2006), and two databases which were sitting on it. For some unknown reason, the LDF log files are missing. Presumed deleted. I have the mdf files (and in one case an ndf file too) for the databases which used to exist on that server, and I am trying to get them up and running on another SQL 2000 box I have sitting around. `sp_attach_db` complains that the logfile is missing, and will not attach the database. Attempts to fool it by using a logfile from a database with the same name failed miserably. `sp_attach_single_file_db` will not work either. The mdf files have obviously not been cleanly detached. How do I get the databases attached and readable?
I found this answer, which worked with my SQL 2000 machines: **How to attach a database with a non-cleanly detached MDF file.** **Step 1:** Make a new database with same name, and which uses the same files as the old one on the new server. **Step 2:** Stop SQL server, and move your mdf files (and any ndf files you have) over the top of the new ones you just created. Delete any log files. **Step 3:** Start SQL and run this to put the DB in emergency mode. ``` sp_configure 'allow updates', 1 go reconfigure with override GO update sysdatabases set status = 32768 where name = 'TestDB' go sp_configure 'allow updates', 0 go reconfigure with override GO ``` **Step 4:** Restart SQL server and observe that the DB is successfully in emergency mode. **Step 5:** Run this undocumented dbcc option to rebuild the log file (in the correct place) ``` DBCC REBUILD_LOG(TestDB,'D:\SQL_Log\TestDB_Log.LDF') ``` **Step 6:** You might need to reset the status. Even if you don't, it won't do any harm to do so. ``` exec sp_resetstatus TestDB ``` **Step 7:** Stop and start SQL to see your newly restored database.