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
116,432
<p>Suppose we have a stylesheet which pulls in metadata using the key() function. In other words we have instance documents like this:</p> <pre><code>&lt;items&gt; &lt;item type="some_type"/&gt; &lt;item type="another_type"/&gt; &lt;/items&gt; </code></pre> <p>and a table of additional data we would like to associate with items during processing:</p> <pre><code>&lt;item-meta&gt; &lt;item type="some_type" meta="foo"/&gt; &lt;item type="another_type" meta="bar"/&gt; &lt;item type="yet_another_type" meta="baz"/&gt; &lt;/item-meta&gt; </code></pre> <p>Finally, suppose we want to do schema validation on the instance document, restricting the type attributes to the set of types which occur in item-meta. So in the schema we want to use key/keyref instead of restriction/enumeration. This is because using restriction/enumeration will require making a separate list of valid type attributes.</p> <p>However, it doesn't look like key/keyref will actually work. Having tried it (with MSXML 6.0) it appears the selector of a schema key won't accept the document() function in its xpath argument, so we can't examine the item-meta data, whether it appears in an external file or in the schema file itself. It looks like the only place we can look for keys is the instance document.</p> <p>So if we really don't want to have a separate list of valid types, we have to do a pre-validation transform, pulling in the item-meta stuff, then do the validation, then do our original transform. That seems overcomplicated for what ought to be a relatively straightforward use of XML schema and stylesheets.</p> <p>Is there a better way?</p>
[ { "answer_id": 117423, "author": "TToni", "author_id": 20703, "author_profile": "https://Stackoverflow.com/users/20703", "pm_score": 1, "selected": false, "text": "<p>Selectors in key/keyref allow only a very restricted xpath syntax. Short, but not completely accurate: The selector must point to a subnode of the element declared.</p>\n\n<p>The full definition of the restricted syntax is <a href=\"http://www.w3.org/TR/xmlschema-1/#coss-identity-constraint\" rel=\"nofollow noreferrer\">-> here</a>.</p>\n\n<p>So, no I don't see a better way, sorry.</p>\n\n<p>BTW: The W3C states that this restriction was made to make life easier on implementers of XML Schema processors. Keep in mind that one of the design goals of XML Schema was to make it possible to process a document in streaming mode. That explains really a lot of the sometimes seemingly random restrictions of XML Schema.</p>\n" }, { "answer_id": 117825, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Having thought about it a little more, I came up with the idea of having the stylesheet do that part of the validation. The schema would define the item type as a plain string, and the stylesheet would emit a message and stop processing if it couldn't look up the item type in the item-meta table.</p>\n\n<p>This solution fixes the original problem of having to write down the list of valid types more than once, but it introduces the problem that validation logic is now mixed in with the stylesheet logic. I don't have enough experience with XSD+XSLT to tell whether this new problem is less serious than the old one, but it seems to be more elegant than what I wrote earlier about pulling the item-meta table into each instance document in a pre-validation transform.</p>\n" }, { "answer_id": 117887, "author": "TToni", "author_id": 20703, "author_profile": "https://Stackoverflow.com/users/20703", "pm_score": 0, "selected": false, "text": "<p>You wouldn't need to stop the XSLT with some error. Just let it produce something that the schema won't validate and that points to the original problem like </p>\n\n<pre><code> &lt;error txt=\"Invalid-Item-Type 'invalid_type'\"/&gt;\n</code></pre>\n\n<p>Apart from that please keep in mind that there are no discussion threads here. The posts may go up and down, so it's better to edit your question accordingly.</p>\n\n<p>Remember, the philosophy here is \"One question, and the best answer wins\".</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Suppose we have a stylesheet which pulls in metadata using the key() function. In other words we have instance documents like this: ``` <items> <item type="some_type"/> <item type="another_type"/> </items> ``` and a table of additional data we would like to associate with items during processing: ``` <item-meta> <item type="some_type" meta="foo"/> <item type="another_type" meta="bar"/> <item type="yet_another_type" meta="baz"/> </item-meta> ``` Finally, suppose we want to do schema validation on the instance document, restricting the type attributes to the set of types which occur in item-meta. So in the schema we want to use key/keyref instead of restriction/enumeration. This is because using restriction/enumeration will require making a separate list of valid type attributes. However, it doesn't look like key/keyref will actually work. Having tried it (with MSXML 6.0) it appears the selector of a schema key won't accept the document() function in its xpath argument, so we can't examine the item-meta data, whether it appears in an external file or in the schema file itself. It looks like the only place we can look for keys is the instance document. So if we really don't want to have a separate list of valid types, we have to do a pre-validation transform, pulling in the item-meta stuff, then do the validation, then do our original transform. That seems overcomplicated for what ought to be a relatively straightforward use of XML schema and stylesheets. Is there a better way?
Selectors in key/keyref allow only a very restricted xpath syntax. Short, but not completely accurate: The selector must point to a subnode of the element declared. The full definition of the restricted syntax is [-> here](http://www.w3.org/TR/xmlschema-1/#coss-identity-constraint). So, no I don't see a better way, sorry. BTW: The W3C states that this restriction was made to make life easier on implementers of XML Schema processors. Keep in mind that one of the design goals of XML Schema was to make it possible to process a document in streaming mode. That explains really a lot of the sometimes seemingly random restrictions of XML Schema.
116,444
<p>By default netbeans stores it's settings in a directory called .netbeans under the user's home directory. Is it possible to change the location of this directory (especially under Windows)?</p> <p>Thanks to James Schek I now know the answer (change the path in netbeans.conf) but that leads me to another question: Is there a way to include the current username in the path to the netbeans setting directory? </p> <p>I want to do something like this:</p> <pre><code>netbeans_default_userdir="D:\etc\${USERNAME}\.netbeans\6.5beta" </code></pre> <p>but I can't figure out the name of the variable to use (if there's any). Of course I can achieve the same thing with the --userdir option, I'm just curious.</p>
[ { "answer_id": 116662, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 5, "selected": true, "text": "<p>yes, edit the netbeans.conf file under %NETBEANS_HOME%\\etc.</p>\n\n<p>Edit the line with:\nnetbeans_default_userdir=\"${HOME}/.netbeans/6.0\"</p>\n\n<p>If you need different \"profiles\"--i.e. want to run different copies of Netbeans with different home directories, you can pass a new home directory to the launcher. Run \"netbeans.exe --userdir /path/to/dir\" or \"nb.exe --userdir /path/to/dir\"</p>\n" }, { "answer_id": 117291, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 2, "selected": false, "text": "<p>\"HOME\" is the only variable supported by the IDE. When deploying a custom application using the Netbeans Platform, \"APPNAME\" is also supported out of the box.</p>\n" }, { "answer_id": 27975026, "author": "pipepiper", "author_id": 2080352, "author_profile": "https://Stackoverflow.com/users/2080352", "pm_score": 2, "selected": false, "text": "<p>For someone who lands up here hunting for an answer:</p>\n\n<p>If you are trying to setup a portable version in windows, Netbeans 7.2 and up wont start if userdir is at the same level or lower than the Netbeans root.</p>\n\n<p>So if you have:\n<code>c:\\Portable\\Netbeans</code> you can NOT do <code>netbeans_default_userdir=\"c:\\Portable\\Netbeans\\userdir\\8.0\"</code></p>\n\n<p>Use a folder OUTSIDE netbeans installation e.g.\n<code>netbeans_default_userdir=\"c:\\Portable\\NetbeansUserDir\\8.0\"</code></p>\n\n<p>for cache it does not matter.</p>\n\n<p>Tested in Windows 8.1 and 7.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4497/" ]
By default netbeans stores it's settings in a directory called .netbeans under the user's home directory. Is it possible to change the location of this directory (especially under Windows)? Thanks to James Schek I now know the answer (change the path in netbeans.conf) but that leads me to another question: Is there a way to include the current username in the path to the netbeans setting directory? I want to do something like this: ``` netbeans_default_userdir="D:\etc\${USERNAME}\.netbeans\6.5beta" ``` but I can't figure out the name of the variable to use (if there's any). Of course I can achieve the same thing with the --userdir option, I'm just curious.
yes, edit the netbeans.conf file under %NETBEANS\_HOME%\etc. Edit the line with: netbeans\_default\_userdir="${HOME}/.netbeans/6.0" If you need different "profiles"--i.e. want to run different copies of Netbeans with different home directories, you can pass a new home directory to the launcher. Run "netbeans.exe --userdir /path/to/dir" or "nb.exe --userdir /path/to/dir"
116,469
<p>Ok so before I even ask my question I want to make one thing clear. I am currently a student at NIU for Computer Science and this does relate to one of my assignments for a class there. So if anyone has a problem read no further and just go on about your business. </p> <p>Now for anyone who is willing to help heres the situation. For my current assignment we have to read a file that is just a block of text. For each word in the file we are to clear any punctuation in the word (ex : "can't" would end up as "can" and "that--to" would end up as "that" obviously with out the quotes, quotes were used just to specify what the example was).</p> <p>The problem I've run into is that I can clean the string fine and then insert it into the map that we are using but for some reason with the code I have written it is allowing an empty string to be inserted into the map. Now I've tried everything that I can come up with to stop this from happening and the only thing I've come up with is to use the erase method within the map structure itself.</p> <p>So what I am looking for is two things, any suggestions about how I could a) fix this with out simply just erasing it and b) any improvements that I could make on the code I already have written.</p> <p>Here are the functions I have written to read in from the file and then the one that cleans it. </p> <p>Note: the function that reads in from the file calls the clean_entry function to get rid of punctuation before anything is inserted into the map.</p> <p>Edit: Thank you Chris. Numbers are allowed :). If anyone has any improvements to the code I've written or any criticisms of something I did I'll listen. At school we really don't get feed back on the correct, proper, or most efficient way to do things.</p> <pre><code>int get_words(map&lt;string, int&gt;&amp; mapz) { int cnt = 0; //set out counter to zero map&lt;string, int&gt;::const_iterator mapzIter; ifstream input; //declare instream input.open( "prog2.d" ); //open instream assert( input ); //assure it is open string s; //temp strings to read into string not_s; input &gt;&gt; s; while(!input.eof()) //read in until EOF { not_s = ""; clean_entry(s, not_s); if((int)not_s.length() == 0) { input &gt;&gt; s; clean_entry(s, not_s); } mapz[not_s]++; //increment occurence input &gt;&gt;s; } input.close(); //close instream for(mapzIter = mapz.begin(); mapzIter != mapz.end(); mapzIter++) cnt = cnt + mapzIter-&gt;second; return cnt; //return number of words in instream } void clean_entry(const string&amp; non_clean, string&amp; clean) { int i, j, begin, end; for(i = 0; isalnum(non_clean[i]) == 0 &amp;&amp; non_clean[i] != '\0'; i++); begin = i; if(begin ==(int)non_clean.length()) return; for(j = begin; isalnum(non_clean[j]) != 0 &amp;&amp; non_clean[j] != '\0'; j++); end = j; clean = non_clean.substr(begin, (end-begin)); for(i = 0; i &lt; (int)clean.size(); i++) clean[i] = tolower(clean[i]); } </code></pre>
[ { "answer_id": 116510, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": true, "text": "<p>The problem with empty entries is in your while loop. If you get an empty string, you clean the next one, and add it without checking. Try changing: </p>\n\n<pre><code>not_s = \"\";\nclean_entry(s, not_s);\n\nif((int)not_s.length() == 0)\n {\n input &gt;&gt; s;\n clean_entry(s, not_s);\n } \n\nmapz[not_s]++; //increment occurence\ninput &gt;&gt;s;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>not_s = \"\";\nclean_entry(s, not_s);\n\nif((int)not_s.length() &gt; 0)\n{\n mapz[not_s]++; //increment occurence\n} \n\ninput &gt;&gt;s;\n</code></pre>\n\n<p>EDIT: I notice you are checking if the characters are alphanumeric. If numbers are not allowed, you may need to revisit that area as well.</p>\n" }, { "answer_id": 116555, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 1, "selected": false, "text": "<p>A blank string is a valid instance of the string class, so there's nothing special about adding it into the map. What you could do is first check if it's empty, and only increment in that case:</p>\n\n<pre><code>if (!not_s.empty())\n mapz[not_s]++;\n</code></pre>\n\n<p>Style-wise, there's a few things I'd change, one would be to return clean from clean_entry instead of modifying it:</p>\n\n<pre><code>string not_s = clean_entry(s);\n...\nstring clean_entry(const string &amp;non_clean)\n{\n string clean;\n ... // as before \n if(begin ==(int)non_clean.length())\n return clean;\n ... // as before\n return clean;\n }\n</code></pre>\n\n<p>This makes it clearer what the function is doing (taking a string, and returning something based on that string).</p>\n" }, { "answer_id": 116616, "author": "MP24", "author_id": 6206, "author_profile": "https://Stackoverflow.com/users/6206", "pm_score": 2, "selected": false, "text": "<p>Further improvements would be to</p>\n\n<ul>\n<li>declare variables only when you use them, and in the innermost scope</li>\n<li>use c++-style casts instead of the c-style (int) casts</li>\n<li>use empty() instead of length() == 0 comparisons</li>\n<li>use the prefix increment operator for the iterators (i.e. <code>++mapzIter</code>)</li>\n</ul>\n" }, { "answer_id": 116839, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 1, "selected": false, "text": "<p>The function 'getWords' is doing a lot of distinct actions that could be split out into other functions. There's a good chance that by splitting it up into it's individual parts, you would have found the bug yourself.</p>\n\n<p>From the basic structure, I think you could split the code into (at least):</p>\n\n<ul>\n<li>getNextWord: Return the next (non blank) word from the stream (returns false if none left)</li>\n<li>clean_entry: What you have now</li>\n<li>getNextCleanWord: Calls getNextWord, and if 'true' calls CleanWord. Returns 'false' if no words left.</li>\n</ul>\n\n<p>The signatures of 'getNextWord' and 'getNextCleanWord' might look something like:</p>\n\n<pre><code>bool getNextWord (std::ifstream &amp; input, std::string &amp; str);\nbool getNextCleanWord (std::ifstream &amp; input, std::string &amp; str);\n</code></pre>\n\n<p>The idea is that each function does a smaller more distinct part of the problem. For example, 'getNextWord' does nothing but get the next non blank word (if there is one). This smaller piece therefore becomes an easier part of the problem to solve and debug if necessary.</p>\n\n<p>The main component of 'getWords' then can be simplified down to:</p>\n\n<pre><code>std::string nextCleanWord;\nwhile (getNextCleanWord (input, nextCleanWord))\n{\n ++map[nextCleanWord];\n}\n</code></pre>\n\n<p>An important aspect to development, IMHO, is to try to Divide and Conquer the problem. Split it up into the individual tasks that need to take place. These sub-tasks will be easier to complete and should also be easier to maintain.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/924/" ]
Ok so before I even ask my question I want to make one thing clear. I am currently a student at NIU for Computer Science and this does relate to one of my assignments for a class there. So if anyone has a problem read no further and just go on about your business. Now for anyone who is willing to help heres the situation. For my current assignment we have to read a file that is just a block of text. For each word in the file we are to clear any punctuation in the word (ex : "can't" would end up as "can" and "that--to" would end up as "that" obviously with out the quotes, quotes were used just to specify what the example was). The problem I've run into is that I can clean the string fine and then insert it into the map that we are using but for some reason with the code I have written it is allowing an empty string to be inserted into the map. Now I've tried everything that I can come up with to stop this from happening and the only thing I've come up with is to use the erase method within the map structure itself. So what I am looking for is two things, any suggestions about how I could a) fix this with out simply just erasing it and b) any improvements that I could make on the code I already have written. Here are the functions I have written to read in from the file and then the one that cleans it. Note: the function that reads in from the file calls the clean\_entry function to get rid of punctuation before anything is inserted into the map. Edit: Thank you Chris. Numbers are allowed :). If anyone has any improvements to the code I've written or any criticisms of something I did I'll listen. At school we really don't get feed back on the correct, proper, or most efficient way to do things. ``` int get_words(map<string, int>& mapz) { int cnt = 0; //set out counter to zero map<string, int>::const_iterator mapzIter; ifstream input; //declare instream input.open( "prog2.d" ); //open instream assert( input ); //assure it is open string s; //temp strings to read into string not_s; input >> s; while(!input.eof()) //read in until EOF { not_s = ""; clean_entry(s, not_s); if((int)not_s.length() == 0) { input >> s; clean_entry(s, not_s); } mapz[not_s]++; //increment occurence input >>s; } input.close(); //close instream for(mapzIter = mapz.begin(); mapzIter != mapz.end(); mapzIter++) cnt = cnt + mapzIter->second; return cnt; //return number of words in instream } void clean_entry(const string& non_clean, string& clean) { int i, j, begin, end; for(i = 0; isalnum(non_clean[i]) == 0 && non_clean[i] != '\0'; i++); begin = i; if(begin ==(int)non_clean.length()) return; for(j = begin; isalnum(non_clean[j]) != 0 && non_clean[j] != '\0'; j++); end = j; clean = non_clean.substr(begin, (end-begin)); for(i = 0; i < (int)clean.size(); i++) clean[i] = tolower(clean[i]); } ```
The problem with empty entries is in your while loop. If you get an empty string, you clean the next one, and add it without checking. Try changing: ``` not_s = ""; clean_entry(s, not_s); if((int)not_s.length() == 0) { input >> s; clean_entry(s, not_s); } mapz[not_s]++; //increment occurence input >>s; ``` to ``` not_s = ""; clean_entry(s, not_s); if((int)not_s.length() > 0) { mapz[not_s]++; //increment occurence } input >>s; ``` EDIT: I notice you are checking if the characters are alphanumeric. If numbers are not allowed, you may need to revisit that area as well.
116,485
<p>I have 2 arrays of 16 elements (chars) that I need to "compare" and see how many elements are equal between the two.</p> <p>This routine is going to be used millions of times (a usual run is about 60 or 70 million times), so I need it to be as fast as possible. I'm working on C++ (C++Builder 2007, for the record)</p> <p>Right now, I have a simple:</p> <pre><code>matches += array1[0] == array2[0]; </code></pre> <p>repeated 16 times (as profiling it appears to be 30% faster than doing it with a for loop)</p> <p>Is there any other way that could work faster?</p> <p>Some data about the environment and the data itself:</p> <ul> <li>I'm using C++Builder, which doesn't have any speed optimizations to take into account. I will try eventually with another compiler, but right now I'm stuck with this one.</li> <li>The data will be different most of the times. 100% equal data is usually very very rare (maybe less than 1%)</li> </ul>
[ { "answer_id": 116504, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 0, "selected": false, "text": "<p>Is it faster as one statement?</p>\n\n<pre><code>matches += (array1[0] == array2[0]) + (array1[1] == array2[1]) + ...;\n</code></pre>\n" }, { "answer_id": 116512, "author": "Asaf R", "author_id": 6827, "author_profile": "https://Stackoverflow.com/users/6827", "pm_score": 2, "selected": false, "text": "<p>If you have the ability to control the location of the arrays, putting one right after the other in memory for instance, it might cause them to be loaded to the CPU's cache on the first access.</p>\n\n<p>It depends on the CPU and its cache structure and will vary from one machine to another.</p>\n\n<p>You can read about memory hierarchy and cache in <a href=\"https://rads.stackoverflow.com/amzn/click/com/0123704901\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Henessy &amp; Patterson's Computer Architecture: A Quantitative Approach</a></p>\n" }, { "answer_id": 116524, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "<p>If writing that 16 times is faster than a simple loop, then your compiler either sucks or you don't have optimization turned on.</p>\n\n<p>Short answer: there's no faster way, unless you do vector operations on parallel hardware.</p>\n" }, { "answer_id": 116529, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": false, "text": "<p>Magical compiler options will vary the time greatly. In particular making it generate SSE vectorization will likely get you a huge speedup.</p>\n" }, { "answer_id": 116530, "author": "Tomer Gabel", "author_id": 11558, "author_profile": "https://Stackoverflow.com/users/11558", "pm_score": 2, "selected": false, "text": "<p>If you need absolute lowest footprint, I'd go with assembly code. I haven't done this in a while but I'll bet MMX (or more likely SSE2/3) have instructions that can enable you to do exactly that in very few instructions.</p>\n" }, { "answer_id": 116558, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>If matches are the common case then try loading the values as 32 bit ints instead of 16 so you can compare 2 in one go (and count it as 2 matches).</p>\n\n<p>If the two 32 bit values are <strong>not</strong> the same then you will have to test them separately (AND out the top and bottom 16 bit values).</p>\n\n<p>The code will be more complex, but should be faster.</p>\n\n<p>If you are targeting a 64-bit system you could do the same trick with 64 bit ints, and if you really want to push the limit then look at dropping into assembler and using the various vector based instructions which would let you work with 128 bits at once.</p>\n" }, { "answer_id": 116563, "author": "Justsalt", "author_id": 13693, "author_profile": "https://Stackoverflow.com/users/13693", "pm_score": 0, "selected": false, "text": "<p>Try using pointers instead of arrays:</p>\n\n<pre><code>p1 = &amp;array1[0];\np2 = &amp;array2[0];\nmatch += (*p1++ == *p2++);\n// copy 15 times.\n</code></pre>\n\n<p>Of course you must measure this against other approaches to see which is fastest.</p>\n\n<p>And are you sure that this routine is a bottleneck in your processing? Do you actually speed up the performance of your application as a whole by optimizing this? Again, only measurement will tell.</p>\n" }, { "answer_id": 116582, "author": "Andrew Grant", "author_id": 1043, "author_profile": "https://Stackoverflow.com/users/1043", "pm_score": 3, "selected": false, "text": "<p>The key is to do the comparisons using the largest register your CPU supports, then fallback to bytes if necessary.</p>\n\n<p>The below code demonstrates with using 4-byte integers, but if you are running on a SIMD architecture (any modern Intel or AMD chip) you could compare both arrays in one instruction before falling back to an integer-based loop. Most compilers these days have intrinsic support for 128-bit types so will NOT require ASM.</p>\n\n<p>(Note that for the SIMD comparisions your arrays would have to be 16-byte aligned, and some processors (e.g MIPS) would require the arrays to be 4-byte aligned for the int-based comparisons.</p>\n\n<p>E.g.</p>\n\n<pre><code>int* array1 = (int*)byteArray[0];\nint* array2 = (int*)byteArray[1];\n\nint same = 0;\n\nfor (int i = 0; i &lt; 4; i++)\n{\n // test as an int\n if (array1[i] == array2[i])\n {\n same += 4;\n }\n else\n {\n // test individual bytes\n char* bytes1 = (char*)(array1+i);\n char* bytes2 = (char*)(array2+i);\n\n for (int j = 0; j &lt; 4; j++)\n {\n same += (bytes1[j] == bytes2[j];\n }\n }\n}\n</code></pre>\n\n<p>I can't remember what exactly the MSVC compiler supports for SIMD, but you could do something like;</p>\n\n<pre><code>// depending on compiler you may have to insert the words via an intrinsic\n__m128 qw1 = *(__m128*)byteArray[0];\n__m128 qw2 = *(__m128*)byteArray[1];\n\n// again, depending on the compiler the comparision may have to be done via an intrinsic\nif (qw1 == qw2)\n{\n same = 16;\n}\nelse\n{\n // do int/byte testing\n}\n</code></pre>\n" }, { "answer_id": 116600, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Is there any way you can modify the way the arrays are stored? Comparing 1 byte at a time is extremely slow considering you are probably using a 32-bit compiler. Instead if you stored your 16 bytes in 4 integers (32-bit) or 2 longs (64-bit), you would only need to perform 4 or 2 comparisons respectively.</p>\n\n<p>The question to ask yourself is how much is the cost of storing the data as 4-integer or 2-long arrays. How often do you need to access the data, etc.</p>\n" }, { "answer_id": 116608, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 0, "selected": false, "text": "<p>There's always the good old x86 REPNE CMPS instruction.</p>\n" }, { "answer_id": 116636, "author": "Kent Knox", "author_id": 17227, "author_profile": "https://Stackoverflow.com/users/17227", "pm_score": 5, "selected": true, "text": "<p>UPDATE: This answer has been modified to make my comments match the source code provided below.</p>\n\n<p>There is an optimization available if you have the capability to use SSE2 and popcnt instructions.</p>\n\n<p>16 bytes happens to fit nicely in an SSE register. Using c++ and assembly/intrinsics, load the two 16 byte arrays into xmm registers, and cmp them. This generates a bitmask representing the true/false condition of the compare. You then use a movmsk instruction to load a bit representation of the bitmask into an x86 register; this then becomes a bit field where you can count all the 1's to determine how many true values you had. A hardware popcnt instruction can be a fast way to count all the 1's in a register.</p>\n\n<p>This requires knowledge of assembly/intrinsics and SSE in particular. You should be able to find web resources for both.</p>\n\n<p>If you run this code on a machine that does not support either SSE2 or popcnt, you must then iterate through the arrays and count the differences with your unrolled loop approach.</p>\n\n<p>Good luck</p>\n\n<p>Edit:\nSince you indicated you did not know assembly, here's some sample code to illustrate my answer:</p>\n\n<pre><code>#include \"stdafx.h\"\n#include &lt;iostream&gt;\n#include \"intrin.h\"\n\ninline unsigned cmpArray16( char (&amp;arr1)[16], char (&amp;arr2)[16] )\n{\n __m128i first = _mm_loadu_si128( reinterpret_cast&lt;__m128i*&gt;( &amp;arr1 ) );\n __m128i second = _mm_loadu_si128( reinterpret_cast&lt;__m128i*&gt;( &amp;arr2 ) );\n\n return _mm_movemask_epi8( _mm_cmpeq_epi8( first, second ) );\n}\n\nint _tmain( int argc, _TCHAR* argv[] )\n{\n unsigned count = 0;\n char arr1[16] = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 };\n char arr2[16] = { 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 };\n\n count = __popcnt( cmpArray16( arr1, arr2 ) );\n\n std::cout &lt;&lt; \"The number of equivalent bytes = \" &lt;&lt; count &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n\n<p>Some notes: This function uses SSE2 instructions and a popcnt instruction introduced in the Phenom processor (that's the machine that I use). I believe the most recent Intel processors with SSE4 also have popcnt. This function does not check for instruction support with CPUID; the function is undefined if used on a processor that does not have SSE2 or popcnt (you will probably get an invalid opcode instruction). That detection code is a separate thread.</p>\n\n<p>I have not timed this code; the reason I think it's faster is because it compares 16 bytes at a time, branchless. You should modify this to fit your environment, and time it yourself to see if it works for you. I wrote and tested this on VS2008 SP1.</p>\n\n<p>SSE prefers data that is aligned on a natural 16-byte boundary; if you can guarantee that then you should get additional speed improvements, and you can change the _mm_loadu_si128 instructions to _mm_load_si128, which requires alignment.</p>\n" }, { "answer_id": 116642, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 1, "selected": false, "text": "<p>Does this have to be platform independent, or will this code always run on the same type of CPU? If you restrict yourself to modern x86 CPUs, you may be able to use <a href=\"http://en.wikipedia.org/wiki/MMX_(instruction_set)\" rel=\"nofollow noreferrer\">MMX</a> instructions, which should allow you to operate on an array of 8 bytes in one clock tick. AFAIK, gcc allows you to embed assembly in your C code, and the Intel's compiler (icc) supports intrinsics, which are wrappers that allow you to call specific assembly instructions directly. Other SIMD instruction sets, such as SSE, may also be useful for this.</p>\n" }, { "answer_id": 116845, "author": "Markus Schnell", "author_id": 20668, "author_profile": "https://Stackoverflow.com/users/20668", "pm_score": 1, "selected": false, "text": "<p>Is there any connection between the values in the arrays? Are some bytes more likely to be the same then others? Might there be some intrinsic order in the values? Then you could optimize for the most probable case.</p>\n" }, { "answer_id": 117787, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 0, "selected": false, "text": "<p>One extra possible optimization: if you are expecting that most of the time the arrays are identical then it might be slightly faster to do a memcmp() as the first step, setting '16' as the answer if the test returns true. If course if you are not expecting the arrays to be identical very often that would only slow things down.</p>\n" }, { "answer_id": 118525, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 1, "selected": false, "text": "<p>If you explain what the data actually represents then there might be a totally different way to represent the data in memory that would make this type of brute force compare unnecessary. Care to elaborate on what the data actually represents??</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16772/" ]
I have 2 arrays of 16 elements (chars) that I need to "compare" and see how many elements are equal between the two. This routine is going to be used millions of times (a usual run is about 60 or 70 million times), so I need it to be as fast as possible. I'm working on C++ (C++Builder 2007, for the record) Right now, I have a simple: ``` matches += array1[0] == array2[0]; ``` repeated 16 times (as profiling it appears to be 30% faster than doing it with a for loop) Is there any other way that could work faster? Some data about the environment and the data itself: * I'm using C++Builder, which doesn't have any speed optimizations to take into account. I will try eventually with another compiler, but right now I'm stuck with this one. * The data will be different most of the times. 100% equal data is usually very very rare (maybe less than 1%)
UPDATE: This answer has been modified to make my comments match the source code provided below. There is an optimization available if you have the capability to use SSE2 and popcnt instructions. 16 bytes happens to fit nicely in an SSE register. Using c++ and assembly/intrinsics, load the two 16 byte arrays into xmm registers, and cmp them. This generates a bitmask representing the true/false condition of the compare. You then use a movmsk instruction to load a bit representation of the bitmask into an x86 register; this then becomes a bit field where you can count all the 1's to determine how many true values you had. A hardware popcnt instruction can be a fast way to count all the 1's in a register. This requires knowledge of assembly/intrinsics and SSE in particular. You should be able to find web resources for both. If you run this code on a machine that does not support either SSE2 or popcnt, you must then iterate through the arrays and count the differences with your unrolled loop approach. Good luck Edit: Since you indicated you did not know assembly, here's some sample code to illustrate my answer: ``` #include "stdafx.h" #include <iostream> #include "intrin.h" inline unsigned cmpArray16( char (&arr1)[16], char (&arr2)[16] ) { __m128i first = _mm_loadu_si128( reinterpret_cast<__m128i*>( &arr1 ) ); __m128i second = _mm_loadu_si128( reinterpret_cast<__m128i*>( &arr2 ) ); return _mm_movemask_epi8( _mm_cmpeq_epi8( first, second ) ); } int _tmain( int argc, _TCHAR* argv[] ) { unsigned count = 0; char arr1[16] = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 }; char arr2[16] = { 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 }; count = __popcnt( cmpArray16( arr1, arr2 ) ); std::cout << "The number of equivalent bytes = " << count << std::endl; return 0; } ``` Some notes: This function uses SSE2 instructions and a popcnt instruction introduced in the Phenom processor (that's the machine that I use). I believe the most recent Intel processors with SSE4 also have popcnt. This function does not check for instruction support with CPUID; the function is undefined if used on a processor that does not have SSE2 or popcnt (you will probably get an invalid opcode instruction). That detection code is a separate thread. I have not timed this code; the reason I think it's faster is because it compares 16 bytes at a time, branchless. You should modify this to fit your environment, and time it yourself to see if it works for you. I wrote and tested this on VS2008 SP1. SSE prefers data that is aligned on a natural 16-byte boundary; if you can guarantee that then you should get additional speed improvements, and you can change the \_mm\_loadu\_si128 instructions to \_mm\_load\_si128, which requires alignment.
116,494
<p>How would one write a regular expression to use in Python to split paragraphs?</p> <p>A paragraph is defined by two line breaks (\n). But one can have any amount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph.</p> <p>I am using Python, so the solution can use Python's <a href="https://docs.python.org/2/library/re.html" rel="nofollow noreferrer">regular expression syntax</a> which is extended. (can make use of <code>(?P...)</code> stuff)</p> <h3>Examples:</h3> <pre><code>the_str = 'paragraph1\n\nparagraph2' # Splitting should yield ['paragraph1', 'paragraph2'] the_str = 'p1\n\t\np2\t\n\tstill p2\t \n \n\tp3' # Should yield ['p1', 'p2\t\n\tstill p2', 'p3'] the_str = 'p1\n\n\n\tp2' # Should yield ['p1', '\n\tp2'] </code></pre> <p>The best I could come with is: <code>r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*'</code>, i.e.</p> <pre><code>import re paragraphs = re.split(r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*', the_str) </code></pre> <p>But that is ugly. Is there anything better?</p> <h3>Suggestions rejected:</h3> <p><code>r'\s*?\n\s*?\n\s*?'</code> -&gt; That would make example 2 and 3 fail, since <code>\s</code> includes <code>\n</code>, so it would allow paragraph breaks with more than 2 <code>\n</code>s.</p>
[ { "answer_id": 116557, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 0, "selected": false, "text": "<p>Almost the same, but using non-greedy quantifiers and taking advantage of the whitespace sequence.</p>\n\n<pre><code>\\s*?\\n\\s*?\\n\\s*?\n</code></pre>\n" }, { "answer_id": 116621, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>You may be trying to deduce the structure of a document in plain test and doing what <a href=\"http://docutils.sourceforge.net/\" rel=\"nofollow noreferrer\">docutils</a> does.</p>\n<p>You might be able to simply use the <a href=\"http://docutils.sourceforge.net/docs/dev/hacking.html#parsing-the-document\" rel=\"nofollow noreferrer\">Docutils parser</a> rather than roll your own.</p>\n" }, { "answer_id": 116622, "author": "Eevee", "author_id": 17875, "author_profile": "https://Stackoverflow.com/users/17875", "pm_score": 4, "selected": true, "text": "<p>Unfortunately there's no nice way to write \"space but not a newline\".</p>\n\n<p>I think the best you can do is add some space with the <code>x</code> modifier and try to factor out the ugliness a bit, but that's questionable: <code>(?x) (?: [ \\t\\r\\f\\v]*? \\n ){2} [ \\t\\r\\f\\v]*?</code></p>\n\n<p>You could also try creating a subrule just for the character class and interpolating it three times.</p>\n" }, { "answer_id": 123806, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 2, "selected": false, "text": "<p>It is not a regexp, but it is really elegant:</p>\n<pre><code>from itertools import groupby\n\ndef paragraph(lines):\n for group_separator, line_iteration in groupby(lines.splitlines(True), key = str.isspace):\n if not group_separator:\n yield ''.join(line_iteration)\n\nfor p in paragraph('p1\\n\\t\\np2\\t\\n\\tstill p2\\t \\n \\n\\tp'):\n print repr(p)\n\n'p1\\n'\n'p2\\t\\n\\tstill p2\\t \\n'\n'\\tp3'\n</code></pre>\n<p>It's up to you to strip the output as you need it of course.</p>\n<p>It was inspired by the famous &quot;Python Cookbook&quot; ;-)</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17160/" ]
How would one write a regular expression to use in Python to split paragraphs? A paragraph is defined by two line breaks (\n). But one can have any amount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph. I am using Python, so the solution can use Python's [regular expression syntax](https://docs.python.org/2/library/re.html) which is extended. (can make use of `(?P...)` stuff) ### Examples: ``` the_str = 'paragraph1\n\nparagraph2' # Splitting should yield ['paragraph1', 'paragraph2'] the_str = 'p1\n\t\np2\t\n\tstill p2\t \n \n\tp3' # Should yield ['p1', 'p2\t\n\tstill p2', 'p3'] the_str = 'p1\n\n\n\tp2' # Should yield ['p1', '\n\tp2'] ``` The best I could come with is: `r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*'`, i.e. ``` import re paragraphs = re.split(r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*', the_str) ``` But that is ugly. Is there anything better? ### Suggestions rejected: `r'\s*?\n\s*?\n\s*?'` -> That would make example 2 and 3 fail, since `\s` includes `\n`, so it would allow paragraph breaks with more than 2 `\n`s.
Unfortunately there's no nice way to write "space but not a newline". I think the best you can do is add some space with the `x` modifier and try to factor out the ugliness a bit, but that's questionable: `(?x) (?: [ \t\r\f\v]*? \n ){2} [ \t\r\f\v]*?` You could also try creating a subrule just for the character class and interpolating it three times.
116,560
<p>I like to use Emacs' shell mode, but it has a few deficiencies. One of those is that it's not smart enough to open a new buffer when a shell command tries to invoke an editor. For example with the environment variable <code>VISUAL</code> set to <code>vim</code> I get the following from <code>svn propedit</code>:</p> <pre> $ svn propedit svn:externals . "svn-prop.tmp" 2L, 149C[1;1H ~ [4;1H~ [5;1H~ [6;1H~ [7;1H~ ... </pre> <p>(It may be hard to tell from the representation, but it's a horrible, ugly mess.)</p> <p>With <code>VISUAL</code> set to <code>"emacs -nw"</code>, I get</p> <pre> $ svn propedit svn:externals . emacs: Terminal type "dumb" is not powerful enough to run Emacs. It lacks the ability to position the cursor. If that is not the actual type of terminal you have, use the Bourne shell command `TERM=... export TERM' (C-shell: `setenv TERM ...') to specify the correct type. It may be necessary to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.svn: system('emacs -nw svn-prop.tmp') returned 256 </pre> <p>(It works with <code>VISUAL</code> set to just <code>emacs</code>, but only from inside an Emacs X window, not inside a terminal session.)</p> <p>Is there a way to get shell mode to do the right thing here and open up a new buffer on behalf of the command line process?</p>
[ { "answer_id": 116570, "author": "Rich", "author_id": 20640, "author_profile": "https://Stackoverflow.com/users/20640", "pm_score": 5, "selected": true, "text": "<p>You can attach to an Emacs session through <code>emacsclient</code>. First, start the emacs server with </p>\n\n<pre><code>M-x server-start\n</code></pre>\n\n<p>or add <code>(server-start)</code> to your <code>.emacs</code>. Then,</p>\n\n<pre><code>export VISUAL=emacsclient\n</code></pre>\n\n<p>Edit away.</p>\n\n<p>Note:</p>\n\n<ul>\n<li>The versions of <code>emacs</code> and <code>emacsclient</code> must agree. If you have multiple versions of Emacs installed, make sure you invoke the version of <code>emacsclient</code> corresponding to the version of Emacs running the server.</li>\n<li>If you start the server in multiple Emacs processes/frames (e.g., because <code>(server-start)</code> is in your <code>.emacs</code>), the buffer will be created in the last frame to start the server.</li>\n</ul>\n" }, { "answer_id": 122506, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 2, "selected": false, "text": "<p>There's emacsclient, gnuserv, and in Emacs 23, multi-tty that are all useful for this. Actually I think in Emacs 23, emacsclient has all of the interesting functionality of gnuserv.</p>\n" }, { "answer_id": 437748, "author": "jrockway", "author_id": 8457, "author_profile": "https://Stackoverflow.com/users/8457", "pm_score": 0, "selected": false, "text": "<p>Not entirely true. <code>ansi-term</code> can run an emacs fine (although I usually run mg for commit logs, in the rare event I don't commit from emacs directly). <code>eshell</code> can also run an emacs if you start a <code>screen</code> first and run it from within there.</p>\n" }, { "answer_id": 855170, "author": "killdash10", "author_id": 7621, "author_profile": "https://Stackoverflow.com/users/7621", "pm_score": 0, "selected": false, "text": "<p>Along with using emacs client/server, I am using this script to invoke emacs. </p>\n\n<p>This will start emacs if it is not running yet, or just open a new emacs buffer in the running emacs (using gnuclient). It runs in the background by default, but can be run in the foreground for processes that expect some input. For example, I am using this as my source control editor, when entering a change list description. I have \"SVN_EDITOR=emacs sync\", so I can do \"svn commit\" in an emacs shell, and it will open the svn editor in a new emacs buffer in the same emacs. When I close the buffer, \"svn commit\" continues. Pretty useful.</p>\n\n<pre>\n#!/bin/sh\n\nif [ -z $EMACS_CMD ]; then\n EMACS_CMD=\"/usr/bin/emacs\"\nfi\n\nif [ -z $GNUCLIENT_CMD ]; then\n GNUCLIENT_CMD=\"/usr/bin/gnuclient\"\nfi\n\nif [ \"$1\" = \"sync\" ]; then\n shift 1\n sync=true\nelse\n sync=false\nfi\n\ncmd=\"${EMACS_CMD} $*\"\nlsof $EMACS_CMD | grep $USER >/dev/null 2>&1\nif [ \"$?\" -ne \"1\" ]; then\n cmd=\"${GNUCLIENT_CMD} $*\"\nfi\n\nif [ $sync = \"true\" ]; then\n $cmd\nelse\n $cmd &\nfi\n\n</pre>\n" }, { "answer_id": 2677003, "author": "T Collins", "author_id": 321510, "author_profile": "https://Stackoverflow.com/users/321510", "pm_score": 0, "selected": false, "text": "<p>I wanted to do something similar for merging in an emacs shell via mercurial. Thanks to the posters here, i found the way. two steps:</p>\n\n<ol>\n<li><p>add: (start-server) in your .emacs file (remember to load-file after your change)</p></li>\n<li><p>in your hgrc:<pre>\n[merge-tools]\nemacs.executable = emacsclient\nemacs.premerge = False\nemacs.args = --eval \"(ediff-merge-with-ancestor \\\"$local\\\" \\\"$other\\\" \\\"$base\\\" nil \\\"$output\\\")\"\n</pre></p></li>\n</ol>\n" }, { "answer_id": 10133605, "author": "Bill", "author_id": 1330446, "author_profile": "https://Stackoverflow.com/users/1330446", "pm_score": 0, "selected": false, "text": "<p>When I have (start-server) in my .emacs I get this error....</p>\n<pre><code>Debugger entered--Lisp error: (void-function start-server)\n (start-server)\n eval-buffer(#&lt;buffer *load*&gt; nil &quot;/Users/jarrold/.emacs&quot; nil t) ; Reading at buffer position 22768\n load-with-code-conversion(&quot;/Users/jarrold/.emacs&quot; &quot;/Users/jarrold/.emacs&quot; t t)\n load(&quot;~/.emacs&quot; t t)\n #[nil &quot;^H\\205\\276^@ \\306=\\203^Q^@\\307^H\\310Q\\202A^@ \\311=\\2033^@\\312\\307\\313\\314#\\203#^@\\315\\202A^@\\312\\307\\$\n command-line()\n normal-top-level()\n</code></pre>\n<p>....I am using GNU Emacs 22.1.1</p>\n<p>And this is the version of Mac OS-X I am using:</p>\n<blockquote>\n<p>shandemo 511 $ uname -a Darwin Facilitys-MacBook-Pro.local 10.8.0</p>\n<p>Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011;</p>\n<p>root:xnu-1504.15.3~1/RELEASE_I386 i386</p>\n</blockquote>\n<p>Note that m-x ansi-term appears to allow me to successfully hg commit inside of its shell. However, that shell does not let me scroll through the buffer with e.g. c-p or c-n so I would prefer to us m-x shell.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
I like to use Emacs' shell mode, but it has a few deficiencies. One of those is that it's not smart enough to open a new buffer when a shell command tries to invoke an editor. For example with the environment variable `VISUAL` set to `vim` I get the following from `svn propedit`: ``` $ svn propedit svn:externals . "svn-prop.tmp" 2L, 149C[1;1H ~ [4;1H~ [5;1H~ [6;1H~ [7;1H~ ... ``` (It may be hard to tell from the representation, but it's a horrible, ugly mess.) With `VISUAL` set to `"emacs -nw"`, I get ``` $ svn propedit svn:externals . emacs: Terminal type "dumb" is not powerful enough to run Emacs. It lacks the ability to position the cursor. If that is not the actual type of terminal you have, use the Bourne shell command `TERM=... export TERM' (C-shell: `setenv TERM ...') to specify the correct type. It may be necessary to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.svn: system('emacs -nw svn-prop.tmp') returned 256 ``` (It works with `VISUAL` set to just `emacs`, but only from inside an Emacs X window, not inside a terminal session.) Is there a way to get shell mode to do the right thing here and open up a new buffer on behalf of the command line process?
You can attach to an Emacs session through `emacsclient`. First, start the emacs server with ``` M-x server-start ``` or add `(server-start)` to your `.emacs`. Then, ``` export VISUAL=emacsclient ``` Edit away. Note: * The versions of `emacs` and `emacsclient` must agree. If you have multiple versions of Emacs installed, make sure you invoke the version of `emacsclient` corresponding to the version of Emacs running the server. * If you start the server in multiple Emacs processes/frames (e.g., because `(server-start)` is in your `.emacs`), the buffer will be created in the last frame to start the server.
116,574
<p>While googling, I see that using <a href="http://docs.oracle.com/javase/6/docs/api/java/io/File.html#length%28%29" rel="noreferrer"><code>java.io.File#length()</code></a> can be slow. <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html" rel="noreferrer"><code>FileChannel</code></a> has a <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html#size%28%29" rel="noreferrer"><code>size()</code></a> method that is available as well.</p> <p>Is there an efficient way in java to get the file size?</p>
[ { "answer_id": 116916, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 8, "selected": true, "text": "<p>Well, I tried to measure it up with the code below:</p>\n\n<p>For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of:</p>\n\n<pre><code>LENGTH sum: 10626, per Iteration: 10626.0\n\nCHANNEL sum: 5535, per Iteration: 5535.0\n\nURL sum: 660, per Iteration: 660.0\n</code></pre>\n\n<p>For runs = 5 and iterations = 50 the picture draws different.</p>\n\n<pre><code>LENGTH sum: 39496, per Iteration: 157.984\n\nCHANNEL sum: 74261, per Iteration: 297.044\n\nURL sum: 95534, per Iteration: 382.136\n</code></pre>\n\n<p>File must be caching the calls to the filesystem, while channels and URL have some overhead.</p>\n\n<p>Code:</p>\n\n<pre><code>import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic enum FileSizeBench {\n\n LENGTH {\n @Override\n public long getResult() throws Exception {\n File me = new File(FileSizeBench.class.getResource(\n \"FileSizeBench.class\").getFile());\n return me.length();\n }\n },\n CHANNEL {\n @Override\n public long getResult() throws Exception {\n FileInputStream fis = null;\n try {\n File me = new File(FileSizeBench.class.getResource(\n \"FileSizeBench.class\").getFile());\n fis = new FileInputStream(me);\n return fis.getChannel().size();\n } finally {\n fis.close();\n }\n }\n },\n URL {\n @Override\n public long getResult() throws Exception {\n InputStream stream = null;\n try {\n URL url = FileSizeBench.class\n .getResource(\"FileSizeBench.class\");\n stream = url.openStream();\n return stream.available();\n } finally {\n stream.close();\n }\n }\n };\n\n public abstract long getResult() throws Exception;\n\n public static void main(String[] args) throws Exception {\n int runs = 5;\n int iterations = 50;\n\n EnumMap&lt;FileSizeBench, Long&gt; durations = new EnumMap&lt;FileSizeBench, Long&gt;(FileSizeBench.class);\n\n for (int i = 0; i &lt; runs; i++) {\n for (FileSizeBench test : values()) {\n if (!durations.containsKey(test)) {\n durations.put(test, 0l);\n }\n long duration = testNow(test, iterations);\n durations.put(test, durations.get(test) + duration);\n // System.out.println(test + \" took: \" + duration + \", per iteration: \" + ((double)duration / (double)iterations));\n }\n }\n\n for (Map.Entry&lt;FileSizeBench, Long&gt; entry : durations.entrySet()) {\n System.out.println();\n System.out.println(entry.getKey() + \" sum: \" + entry.getValue() + \", per Iteration: \" + ((double)entry.getValue() / (double)(runs * iterations)));\n }\n\n }\n\n private static long testNow(FileSizeBench test, int iterations)\n throws Exception {\n long result = -1;\n long before = System.nanoTime();\n for (int i = 0; i &lt; iterations; i++) {\n if (result == -1) {\n result = test.getResult();\n //System.out.println(result);\n } else if ((result = test.getResult()) != result) {\n throw new Exception(\"variance detected!\");\n }\n }\n return (System.nanoTime() - before) / 1000;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 118987, "author": "tgdavies", "author_id": 11002, "author_profile": "https://Stackoverflow.com/users/11002", "pm_score": 3, "selected": false, "text": "<p>When I modify your code to use a file accessed by an absolute path instead of a resource, I get a different result (for 1 run, 1 iteration, and a 100,000 byte file -- times for a 10 byte file are identical to 100,000 bytes)</p>\n\n<p>LENGTH sum: 33, per Iteration: 33.0</p>\n\n<p>CHANNEL sum: 3626, per Iteration: 3626.0</p>\n\n<p>URL sum: 294, per Iteration: 294.0</p>\n" }, { "answer_id": 119362, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>The benchmark given by GHad measures lots of other stuff (such as reflection, instantiating objects, etc.) besides getting the length. If we try to get rid of these things then for one call I get the following times in microseconds:</p>\n\n<pre>\n file sum___19.0, per Iteration___19.0\n raf sum___16.0, per Iteration___16.0\nchannel sum__273.0, per Iteration__273.0\n</pre>\n\n<p>For 100 runs and 10000 iterations I get:</p>\n\n<pre>\n file sum__1767629.0, per Iteration__1.7676290000000001\n raf sum___881284.0, per Iteration__0.8812840000000001\nchannel sum___414286.0, per Iteration__0.414286\n</pre>\n\n<p>I did run the following modified code giving as an argument the name of a 100MB file.</p>\n\n<pre><code>import java.io.*;\nimport java.nio.channels.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class FileSizeBench {\n\n private static File file;\n private static FileChannel channel;\n private static RandomAccessFile raf;\n\n public static void main(String[] args) throws Exception {\n int runs = 1;\n int iterations = 1;\n\n file = new File(args[0]);\n channel = new FileInputStream(args[0]).getChannel();\n raf = new RandomAccessFile(args[0], \"r\");\n\n HashMap&lt;String, Double&gt; times = new HashMap&lt;String, Double&gt;();\n times.put(\"file\", 0.0);\n times.put(\"channel\", 0.0);\n times.put(\"raf\", 0.0);\n\n long start;\n for (int i = 0; i &lt; runs; ++i) {\n long l = file.length();\n\n start = System.nanoTime();\n for (int j = 0; j &lt; iterations; ++j)\n if (l != file.length()) throw new Exception();\n times.put(\"file\", times.get(\"file\") + System.nanoTime() - start);\n\n start = System.nanoTime();\n for (int j = 0; j &lt; iterations; ++j)\n if (l != channel.size()) throw new Exception();\n times.put(\"channel\", times.get(\"channel\") + System.nanoTime() - start);\n\n start = System.nanoTime();\n for (int j = 0; j &lt; iterations; ++j)\n if (l != raf.length()) throw new Exception();\n times.put(\"raf\", times.get(\"raf\") + System.nanoTime() - start);\n }\n for (Map.Entry&lt;String, Double&gt; entry : times.entrySet()) {\n System.out.println(\n entry.getKey() + \" sum: \" + 1e-3 * entry.getValue() +\n \", per Iteration: \" + (1e-3 * entry.getValue() / runs / iterations));\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1803626, "author": "Karthikeyan", "author_id": 219105, "author_profile": "https://Stackoverflow.com/users/219105", "pm_score": 3, "selected": false, "text": "<p>In response to rgrig's benchmark, the time taken to open/close the FileChannel &amp; RandomAccessFile instances also needs to be taken into account, as these classes will open a stream for reading the file. </p>\n\n<p>After modifying the benchmark, I got these results for 1 iterations on a 85MB file:</p>\n\n<pre><code>file totalTime: 48000 (48 us)\nraf totalTime: 261000 (261 us)\nchannel totalTime: 7020000 (7 ms)\n</code></pre>\n\n<p>For 10000 iterations on same file:</p>\n\n<pre><code>file totalTime: 80074000 (80 ms)\nraf totalTime: 295417000 (295 ms)\nchannel totalTime: 368239000 (368 ms)\n</code></pre>\n\n<p>If all you need is the file size, file.length() is the fastest way to do it. If you plan to use the file for other purposes like reading/writing, then RAF seems to be a better bet. Just don't forget to close the file connection :-)</p>\n\n<pre><code>import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.RandomAccessFile;\nimport java.nio.channels.FileChannel;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class FileSizeBench\n{ \n public static void main(String[] args) throws Exception\n {\n int iterations = 1;\n String fileEntry = args[0];\n\n Map&lt;String, Long&gt; times = new HashMap&lt;String, Long&gt;();\n times.put(\"file\", 0L);\n times.put(\"channel\", 0L);\n times.put(\"raf\", 0L);\n\n long fileSize;\n long start;\n long end;\n File f1;\n FileChannel channel;\n RandomAccessFile raf;\n\n for (int i = 0; i &lt; iterations; i++)\n {\n // file.length()\n start = System.nanoTime();\n f1 = new File(fileEntry);\n fileSize = f1.length();\n end = System.nanoTime();\n times.put(\"file\", times.get(\"file\") + end - start);\n\n // channel.size()\n start = System.nanoTime();\n channel = new FileInputStream(fileEntry).getChannel();\n fileSize = channel.size();\n channel.close();\n end = System.nanoTime();\n times.put(\"channel\", times.get(\"channel\") + end - start);\n\n // raf.length()\n start = System.nanoTime();\n raf = new RandomAccessFile(fileEntry, \"r\");\n fileSize = raf.length();\n raf.close();\n end = System.nanoTime();\n times.put(\"raf\", times.get(\"raf\") + end - start);\n }\n\n for (Map.Entry&lt;String, Long&gt; entry : times.entrySet()) {\n System.out.println(entry.getKey() + \" totalTime: \" + entry.getValue() + \" (\" + getTime(entry.getValue()) + \")\");\n }\n }\n\n public static String getTime(Long timeTaken)\n {\n if (timeTaken &lt; 1000) {\n return timeTaken + \" ns\";\n } else if (timeTaken &lt; (1000*1000)) {\n return timeTaken/1000 + \" us\"; \n } else {\n return timeTaken/(1000*1000) + \" ms\";\n } \n }\n}\n</code></pre>\n" }, { "answer_id": 4202387, "author": "Ben Spink", "author_id": 510488, "author_profile": "https://Stackoverflow.com/users/510488", "pm_score": 2, "selected": false, "text": "<p>Actually, I think the \"ls\" may be faster. There are definitely some issues in Java dealing with getting File info. Unfortunately there is no equivalent safe method of recursive ls for Windows. (cmd.exe's DIR /S can get confused and generate errors in infinite loops)</p>\n\n<p>On XP, accessing a server on the LAN, it takes me 5 seconds in Windows to get the count of the files in a folder (33,000), and the total size.</p>\n\n<p>When I iterate recursively through this in Java, it takes me over 5 minutes. I started measuring the time it takes to do file.length(), file.lastModified(), and file.toURI() and what I found is that 99% of my time is taken by those 3 calls. The 3 calls I actually need to do...</p>\n\n<p>The difference for 1000 files is 15ms local versus 1800ms on server. The server path scanning in Java is ridiculously slow. If the native OS can be fast at scanning that same folder, why can't Java?</p>\n\n<p>As a more complete test, I used WineMerge on XP to compare the modified date, and size of the files on the server versus the files locally. This was iterating over the entire directory tree of 33,000 files in each folder. Total time, 7 seconds. java: over 5 minutes.</p>\n\n<p>So the original statement and question from the OP is true, and valid. Its less noticeable when dealing with a local file system. Doing a local compare of the folder with 33,000 items takes 3 seconds in WinMerge, and takes 32 seconds locally in Java. So again, java versus native is a 10x slowdown in these rudimentary tests.</p>\n\n<p>Java 1.6.0_22 (latest), Gigabit LAN, and network connections, ping is less than 1ms (both in the same switch)</p>\n\n<p>Java is slow.</p>\n" }, { "answer_id": 5385588, "author": "StuartH", "author_id": 670402, "author_profile": "https://Stackoverflow.com/users/670402", "pm_score": 4, "selected": false, "text": "<p>All the test cases in this post are flawed as they access the same file for each method tested. So disk caching kicks in which tests 2 and 3 benefit from. To prove my point I took test case provided by GHAD and changed the order of enumeration and below are the results. </p>\n\n<p>Looking at result I think File.length() is the winner really.</p>\n\n<p>Order of test is the order of output. You can even see the time taken on my machine varied between executions but File.Length() when not first, and incurring first disk access won.</p>\n\n<pre><code>---\nLENGTH sum: 1163351, per Iteration: 4653.404\nCHANNEL sum: 1094598, per Iteration: 4378.392\nURL sum: 739691, per Iteration: 2958.764\n\n---\nCHANNEL sum: 845804, per Iteration: 3383.216\nURL sum: 531334, per Iteration: 2125.336\nLENGTH sum: 318413, per Iteration: 1273.652\n\n--- \nURL sum: 137368, per Iteration: 549.472\nLENGTH sum: 18677, per Iteration: 74.708\nCHANNEL sum: 142125, per Iteration: 568.5\n</code></pre>\n" }, { "answer_id": 5520907, "author": "Ben Spink", "author_id": 688554, "author_profile": "https://Stackoverflow.com/users/688554", "pm_score": 3, "selected": false, "text": "<p>I ran into this same issue. I needed to get the file size and modified date of 90,000 files on a network share. Using Java, and being as minimalistic as possible, it would take a very long time. (I needed to get the URL from the file, and the path of the object as well. So its varied somewhat, but more than an hour.) I then used a native Win32 executable, and did the same task, just dumping the file path, modified, and size to the console, and executed that from Java. The speed was amazing. The native process, and my string handling to read the data could process over 1000 items a second.</p>\n\n<p>So even though people down ranked the above comment, this is a valid solution, and did solve my issue. In my case I knew the folders I needed the sizes of ahead of time, and I could pass that in the command line to my win32 app. I went from hours to process a directory to minutes.</p>\n\n<p>The issue did also seem to be Windows specific. OS X did not have the same issue and could access network file info as fast as the OS could do so.</p>\n\n<p>Java File handling on Windows is terrible. Local disk access for files is fine though. It was just network shares that caused the terrible performance. Windows could get info on the network share and calculate the total size in under a minute too.</p>\n\n<p>--Ben</p>\n" }, { "answer_id": 19430142, "author": "RoundPi", "author_id": 833538, "author_profile": "https://Stackoverflow.com/users/833538", "pm_score": 2, "selected": false, "text": "<p>From GHad's benchmark, there are a few issue people have mentioned:</p>\n\n<p>1>Like BalusC mentioned: stream.available() is flowed in this case. </p>\n\n<p>Because available() returns an <strong>estimate</strong> of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.</p>\n\n<p>So 1st to remove the URL this approach. </p>\n\n<p>2>As StuartH mentioned - the order the test run also make the cache difference, so take that out by run the test separately.</p>\n\n<hr>\n\n<p>Now start test:</p>\n\n<p>When CHANNEL one run alone:</p>\n\n<pre><code>CHANNEL sum: 59691, per Iteration: 238.764\n</code></pre>\n\n<p>When LENGTH one run alone:</p>\n\n<pre><code>LENGTH sum: 48268, per Iteration: 193.072\n</code></pre>\n\n<p>So looks like the LENGTH one is the winner here:</p>\n\n<pre><code>@Override\npublic long getResult() throws Exception {\n File me = new File(FileSizeBench.class.getResource(\n \"FileSizeBench.class\").getFile());\n return me.length();\n}\n</code></pre>\n" }, { "answer_id": 21307552, "author": "Scg", "author_id": 3227648, "author_profile": "https://Stackoverflow.com/users/3227648", "pm_score": 2, "selected": false, "text": "<p>If you want the file size of multiple files in a directory, use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#walkFileTree%28java.nio.file.Path,%20java.util.Set,%20int,%20java.nio.file.FileVisitor%29\" rel=\"nofollow\"><code>Files.walkFileTree</code></a>. You can obtain the size from the <code>BasicFileAttributes</code> that you'll receive. </p>\n\n<p>This is much faster then calling <code>.length()</code> on the result of <code>File.listFiles()</code> or using <code>Files.size()</code> on the result of <code>Files.newDirectoryStream()</code>. In my test cases it was about 100 times faster.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20641/" ]
While googling, I see that using [`java.io.File#length()`](http://docs.oracle.com/javase/6/docs/api/java/io/File.html#length%28%29) can be slow. [`FileChannel`](http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html) has a [`size()`](http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html#size%28%29) method that is available as well. Is there an efficient way in java to get the file size?
Well, I tried to measure it up with the code below: For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of: ``` LENGTH sum: 10626, per Iteration: 10626.0 CHANNEL sum: 5535, per Iteration: 5535.0 URL sum: 660, per Iteration: 660.0 ``` For runs = 5 and iterations = 50 the picture draws different. ``` LENGTH sum: 39496, per Iteration: 157.984 CHANNEL sum: 74261, per Iteration: 297.044 URL sum: 95534, per Iteration: 382.136 ``` File must be caching the calls to the filesystem, while channels and URL have some overhead. Code: ``` import java.io.*; import java.net.*; import java.util.*; public enum FileSizeBench { LENGTH { @Override public long getResult() throws Exception { File me = new File(FileSizeBench.class.getResource( "FileSizeBench.class").getFile()); return me.length(); } }, CHANNEL { @Override public long getResult() throws Exception { FileInputStream fis = null; try { File me = new File(FileSizeBench.class.getResource( "FileSizeBench.class").getFile()); fis = new FileInputStream(me); return fis.getChannel().size(); } finally { fis.close(); } } }, URL { @Override public long getResult() throws Exception { InputStream stream = null; try { URL url = FileSizeBench.class .getResource("FileSizeBench.class"); stream = url.openStream(); return stream.available(); } finally { stream.close(); } } }; public abstract long getResult() throws Exception; public static void main(String[] args) throws Exception { int runs = 5; int iterations = 50; EnumMap<FileSizeBench, Long> durations = new EnumMap<FileSizeBench, Long>(FileSizeBench.class); for (int i = 0; i < runs; i++) { for (FileSizeBench test : values()) { if (!durations.containsKey(test)) { durations.put(test, 0l); } long duration = testNow(test, iterations); durations.put(test, durations.get(test) + duration); // System.out.println(test + " took: " + duration + ", per iteration: " + ((double)duration / (double)iterations)); } } for (Map.Entry<FileSizeBench, Long> entry : durations.entrySet()) { System.out.println(); System.out.println(entry.getKey() + " sum: " + entry.getValue() + ", per Iteration: " + ((double)entry.getValue() / (double)(runs * iterations))); } } private static long testNow(FileSizeBench test, int iterations) throws Exception { long result = -1; long before = System.nanoTime(); for (int i = 0; i < iterations; i++) { if (result == -1) { result = test.getResult(); //System.out.println(result); } else if ((result = test.getResult()) != result) { throw new Exception("variance detected!"); } } return (System.nanoTime() - before) / 1000; } } ```
116,587
<p>I need to determine if a Class object representing an interface extends another interface, ie:</p> <pre><code> package a.b.c.d; public Interface IMyInterface extends a.b.d.c.ISomeOtherInterface{ } </code></pre> <p>according to <a href="http://web.archive.org/web/20100705124350/http://java.sun.com:80/j2se/1.4.2/docs/api/java/lang/Class.html" rel="nofollow noreferrer">the spec</a> Class.getSuperClass() will return null for an Interface. </p> <blockquote> <p>If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned.</p> </blockquote> <p>Therefore the following won't work.</p> <pre><code>Class interface = Class.ForName("a.b.c.d.IMyInterface") Class extendedInterface = interface.getSuperClass(); if(extendedInterface.getName().equals("a.b.d.c.ISomeOtherInterface")){ //do whatever here } </code></pre> <p>any ideas?</p>
[ { "answer_id": 116615, "author": "Andreas Holstenson", "author_id": 16351, "author_profile": "https://Stackoverflow.com/users/16351", "pm_score": 5, "selected": true, "text": "<p>Use Class.getInterfaces such as:</p>\n\n<pre><code>Class&lt;?&gt; c; // Your class\nfor(Class&lt;?&gt; i : c.getInterfaces()) {\n // test if i is your interface\n}\n</code></pre>\n\n<p>Also the following code might be of help, it will give you a set with all super-classes and interfaces of a certain class:</p>\n\n<pre><code>public static Set&lt;Class&lt;?&gt;&gt; getInheritance(Class&lt;?&gt; in)\n{\n LinkedHashSet&lt;Class&lt;?&gt;&gt; result = new LinkedHashSet&lt;Class&lt;?&gt;&gt;();\n\n result.add(in);\n getInheritance(in, result);\n\n return result;\n}\n\n/**\n * Get inheritance of type.\n * \n * @param in\n * @param result\n */\nprivate static void getInheritance(Class&lt;?&gt; in, Set&lt;Class&lt;?&gt;&gt; result)\n{\n Class&lt;?&gt; superclass = getSuperclass(in);\n\n if(superclass != null)\n {\n result.add(superclass);\n getInheritance(superclass, result);\n }\n\n getInterfaceInheritance(in, result);\n}\n\n/**\n * Get interfaces that the type inherits from.\n * \n * @param in\n * @param result\n */\nprivate static void getInterfaceInheritance(Class&lt;?&gt; in, Set&lt;Class&lt;?&gt;&gt; result)\n{\n for(Class&lt;?&gt; c : in.getInterfaces())\n {\n result.add(c);\n\n getInterfaceInheritance(c, result);\n }\n}\n\n/**\n * Get superclass of class.\n * \n * @param in\n * @return\n */\nprivate static Class&lt;?&gt; getSuperclass(Class&lt;?&gt; in)\n{\n if(in == null)\n {\n return null;\n }\n\n if(in.isArray() &amp;&amp; in != Object[].class)\n {\n Class&lt;?&gt; type = in.getComponentType();\n\n while(type.isArray())\n {\n type = type.getComponentType();\n }\n\n return type;\n }\n\n return in.getSuperclass();\n}\n</code></pre>\n\n<p>Edit: Added some code to get all super-classes and interfaces of a certain class.</p>\n" }, { "answer_id": 116619, "author": "user13664", "author_id": 13664, "author_profile": "https://Stackoverflow.com/users/13664", "pm_score": 0, "selected": false, "text": "<p>Take a look at Class.getInterfaces();</p>\n\n<pre><code>List&lt;Object&gt; list = new ArrayList&lt;Object&gt;();\nfor (Class c : list.getClass().getInterfaces()) {\n System.out.println(c.getName());\n}\n</code></pre>\n" }, { "answer_id": 116625, "author": "Dan Fleet", "author_id": 7470, "author_profile": "https://Stackoverflow.com/users/7470", "pm_score": 2, "selected": false, "text": "<p>Does Class.isAssignableFrom() do what you need?</p>\n\n<pre><code>Class baseInterface = Class.forName(\"a.b.c.d.IMyInterface\");\nClass extendedInterface = Class.forName(\"a.b.d.c.ISomeOtherInterface\");\n\nif ( baseInterface.isAssignableFrom(extendedInterface) )\n{\n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 116633, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 3, "selected": false, "text": "<pre><code>if (interface.isAssignableFrom(extendedInterface))\n</code></pre>\n\n<p>is what you want</p>\n\n<p>i always get the ordering backwards at first but recently realized that it's the exact opposite of using instanceof</p>\n\n<pre><code>if (extendedInterfaceA instanceof interfaceB) \n</code></pre>\n\n<p>is the same thing but you have to have instances of the classes rather than the classes themselves</p>\n" }, { "answer_id": 46471033, "author": "PhantomStr", "author_id": 8690096, "author_profile": "https://Stackoverflow.com/users/8690096", "pm_score": 0, "selected": false, "text": "<pre><code>Liast&lt;Class&gt; getAllInterfaces(Class&lt;?&gt; clazz){\n List&lt;Class&gt; interfaces = new ArrayList&lt;&gt;();\n Collections.addAll(interfaces,clazz.getInterfaces());\n if(!clazz.getSuperclass().equals(Object.class)){\n interfaces.addAll(getAllInterfaces(clazz.getSuperclass()));\n }\n return interfaces ;\n}\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
I need to determine if a Class object representing an interface extends another interface, ie: ``` package a.b.c.d; public Interface IMyInterface extends a.b.d.c.ISomeOtherInterface{ } ``` according to [the spec](http://web.archive.org/web/20100705124350/http://java.sun.com:80/j2se/1.4.2/docs/api/java/lang/Class.html) Class.getSuperClass() will return null for an Interface. > > If this Class represents either the > Object class, an interface, a > primitive type, or void, then null is > returned. > > > Therefore the following won't work. ``` Class interface = Class.ForName("a.b.c.d.IMyInterface") Class extendedInterface = interface.getSuperClass(); if(extendedInterface.getName().equals("a.b.d.c.ISomeOtherInterface")){ //do whatever here } ``` any ideas?
Use Class.getInterfaces such as: ``` Class<?> c; // Your class for(Class<?> i : c.getInterfaces()) { // test if i is your interface } ``` Also the following code might be of help, it will give you a set with all super-classes and interfaces of a certain class: ``` public static Set<Class<?>> getInheritance(Class<?> in) { LinkedHashSet<Class<?>> result = new LinkedHashSet<Class<?>>(); result.add(in); getInheritance(in, result); return result; } /** * Get inheritance of type. * * @param in * @param result */ private static void getInheritance(Class<?> in, Set<Class<?>> result) { Class<?> superclass = getSuperclass(in); if(superclass != null) { result.add(superclass); getInheritance(superclass, result); } getInterfaceInheritance(in, result); } /** * Get interfaces that the type inherits from. * * @param in * @param result */ private static void getInterfaceInheritance(Class<?> in, Set<Class<?>> result) { for(Class<?> c : in.getInterfaces()) { result.add(c); getInterfaceInheritance(c, result); } } /** * Get superclass of class. * * @param in * @return */ private static Class<?> getSuperclass(Class<?> in) { if(in == null) { return null; } if(in.isArray() && in != Object[].class) { Class<?> type = in.getComponentType(); while(type.isArray()) { type = type.getComponentType(); } return type; } return in.getSuperclass(); } ``` Edit: Added some code to get all super-classes and interfaces of a certain class.
116,626
<p>I'm trying to polish up my Ruby by re writing Kent Beck's xUnit Python example from "Test Driven Development: By Example". I've got quite far but now I get the following error when I run which I don't grok.</p> <pre><code>C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:21:in `test_running': wrong number of arguments (0 for 2) (ArgumentError) from C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:21:in `run' from C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:85 </code></pre> <p>My code looks like this:</p> <pre><code>class TestCase def initialize(name) puts "1. inside TestCase.initialise: @name: #{name}" @name = name end def set_up # No implementation (but present to be overridden in WasRun) end def run self.set_up self.send @name # &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;= ERROR HERE!!!!!! end end class WasRun &lt; TestCase attr_accessor :wasRun attr_accessor :wasSetUp def initialize(name) super(name) end def set_up @wasRun = false @wasSetUp = true end def test_method @wasRun = true end end class TestCaseTest &lt; TestCase def set_up @test = WasRun.new("test_method") end def test_running @test.run puts "test was run? (true expected): #{test.wasRun}" end def test_set_up @test.run puts "test was set up? (true expected): #{test.wasSetUp}" end end TestCaseTest.new("test_running").run </code></pre> <p>Can anyone point out my obvious mistake?</p>
[ { "answer_id": 116688, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 0, "selected": false, "text": "<p>One thing that leaps out is that the <code>send</code> method expects a symbol identifying the method name, but you're trying to use an instance variable.</p>\n\n<p><a href=\"http://www.ruby-doc.org/core/classes/Object.html#M000334\" rel=\"nofollow noreferrer\">Object.send documentation</a></p>\n\n<p>Also, shouldn't lines like this:</p>\n\n<pre><code>puts \"test was run? (true expected): #{test.wasRun}\"\n</code></pre>\n\n<p>be:</p>\n\n<pre><code>puts \"test was run? (true expected): #{@test.wasRun}\"\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 117053, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 5, "selected": true, "text": "<p>It's your print statement:</p>\n\n<pre><code> puts \"test was run? (true expected): #{test.wasRun}\"\n</code></pre>\n\n<p>should be</p>\n\n<pre><code> puts \"test was run? (true expected): #{@test.wasRun}\"\n</code></pre>\n\n<p>without the '@' you are calling Kernel#test, which expects 2 variables.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2455/" ]
I'm trying to polish up my Ruby by re writing Kent Beck's xUnit Python example from "Test Driven Development: By Example". I've got quite far but now I get the following error when I run which I don't grok. ``` C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:21:in `test_running': wrong number of arguments (0 for 2) (ArgumentError) from C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:21:in `run' from C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:85 ``` My code looks like this: ``` class TestCase def initialize(name) puts "1. inside TestCase.initialise: @name: #{name}" @name = name end def set_up # No implementation (but present to be overridden in WasRun) end def run self.set_up self.send @name # <<<<<<<<<<<<<<<<<<<<<<<<<= ERROR HERE!!!!!! end end class WasRun < TestCase attr_accessor :wasRun attr_accessor :wasSetUp def initialize(name) super(name) end def set_up @wasRun = false @wasSetUp = true end def test_method @wasRun = true end end class TestCaseTest < TestCase def set_up @test = WasRun.new("test_method") end def test_running @test.run puts "test was run? (true expected): #{test.wasRun}" end def test_set_up @test.run puts "test was set up? (true expected): #{test.wasSetUp}" end end TestCaseTest.new("test_running").run ``` Can anyone point out my obvious mistake?
It's your print statement: ``` puts "test was run? (true expected): #{test.wasRun}" ``` should be ``` puts "test was run? (true expected): #{@test.wasRun}" ``` without the '@' you are calling Kernel#test, which expects 2 variables.
116,635
<p>(I've asked the same question of the jmeter-user mailing list, but I wanted to try here as well - so at the least I can update this with the answer once I find it).</p> <p>I'm having trouble using <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">JMeter</a> to test a Tomcat webapp using a self-signed SSL cert. JMeter throws a SocketException with message <code>Unconnected sockets not implemented</code>. <a href="http://jakarta.apache.org/jmeter/usermanual/get-started.html#opt_ssl" rel="noreferrer">According to JMeter's docs</a>, the application is designed and written to accept any certificate, self-signed or CA signed or whatever.</p> <p>Has anyone run into this specific exception before?</p> <p>I've attempted to export this certificate from the server and import it into my local keystore (with <em>keytool -import -alias tomcat -file </em>), but the result is the same.</p> <p>I've also tried setting javax.net.debug=all as a JVM arg (<a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/ReadDebug.html" rel="noreferrer">the JSSE reference guide</a> lists this as a debugging step); however, I don't see any debugging output anywhere - should I expect this somewhere other than standard out/error?</p>
[ { "answer_id": 117424, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 2, "selected": false, "text": "<p>This is a hint rather than a proper answer: A cursory glance at Google results seems to suggest that the exception is usually caused by the code forcing the use of a default SSL socket factory that on purpose throws the exception when createSocket() is invoked on it. What some of the results seem to suggest is that the issue sometimes happens due to a bug in certain version in Java 6, or when the incorrect path or password is provided to the keystore.</p>\n\n<p>So, I'd say, try using Java 5. Also, try pointing JMeter to a well-known site that uses proper SSL certificates. This way you could test the self-signed certificate hypothesis.</p>\n" }, { "answer_id": 1375196, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 0, "selected": false, "text": "<p>I had Web Service problems similar to this with jdk 1.6.0_10.</p>\n\n<p>I upgraded to 1.6.0_16 and everything worked.</p>\n" }, { "answer_id": 1868392, "author": "Suppressingfire", "author_id": 49922, "author_profile": "https://Stackoverflow.com/users/49922", "pm_score": 0, "selected": false, "text": "<p>Try searching your classpath (in Eclipse, I do ctrl-shift-t to do this) for SSLSocketFactory*. If you find one, set it as a property on the Security class:</p>\n\n<p>In my environment, I've found the following two:</p>\n\n<pre><code>Security.setProperty(\"ssl.SocketFactory.provider\", \"com.ibm.jsse2.SSLSocketFactoryImpl\");\n</code></pre>\n\n<p>or </p>\n\n<pre><code>Security.setProperty(\"ssl.SocketFactory.provider\", \"com.ibm.websphere.ssl.protocol.SSLSocketFactory\");\n</code></pre>\n\n<p>(or for whatever other class you find)</p>\n\n<p>Similarly for <code>ServerSocketFactory</code>, if you need server sockets.</p>\n" }, { "answer_id": 6579665, "author": "Dikla", "author_id": 59241, "author_profile": "https://Stackoverflow.com/users/59241", "pm_score": 2, "selected": false, "text": "<p>I had the same problem in my code (not related to JMeter). </p>\n\n<p>My code uses a self-defined <code>SocketFactory</code>. What I found out is that the class <code>com.sun.jndi.ldap.Connection</code> calls some methods of the <code>SocketFactory</code> using <code>Method.invoke()</code>. One of the methods it tries to call is <code>createSocket()</code> - without parameters.</p>\n\n<p>When I added such method to my factory all worked fine.</p>\n" }, { "answer_id": 27764501, "author": "Flow", "author_id": 194894, "author_profile": "https://Stackoverflow.com/users/194894", "pm_score": 4, "selected": false, "text": "<p>Most <code>javax.net.SocketFactory</code> implementations define all <code>createSocket()</code> methods <strong>that have parameters</strong> as abstract. But have a <code>createSocket()</code> method without parameters that looks like this:</p>\n\n<pre><code>public Socket createSocket() throws IOException {\n throw new SocketException(\"Unconnected sockets not implemented\");\n}\n</code></pre>\n\n<p>So if you subclass the abstract <code>javax.net.SocketFactory</code> you will be force to override the methods with parameter, but it's easy to miss to override the <code>createSocket()</code> method without parameters. Thus the exception is thrown if your code calls <code>createSocket()</code>. Simply override the method and the be done. :)</p>\n" }, { "answer_id": 38694873, "author": "hoangthienan", "author_id": 359776, "author_profile": "https://Stackoverflow.com/users/359776", "pm_score": 0, "selected": false, "text": "<p>Here is my solution (java 1.6) removing TLS_DHE_ ciphers completely, force to override the methods createSocket()</p>\n\n<p>(<a href=\"https://gist.github.com/hoangthienan/735afb17ffd6955de95a49aa0138dbaa\" rel=\"nofollow\">https://gist.github.com/hoangthienan/735afb17ffd6955de95a49aa0138dbaa</a>)</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
(I've asked the same question of the jmeter-user mailing list, but I wanted to try here as well - so at the least I can update this with the answer once I find it). I'm having trouble using [JMeter](http://jakarta.apache.org/jmeter/) to test a Tomcat webapp using a self-signed SSL cert. JMeter throws a SocketException with message `Unconnected sockets not implemented`. [According to JMeter's docs](http://jakarta.apache.org/jmeter/usermanual/get-started.html#opt_ssl), the application is designed and written to accept any certificate, self-signed or CA signed or whatever. Has anyone run into this specific exception before? I've attempted to export this certificate from the server and import it into my local keystore (with *keytool -import -alias tomcat -file* ), but the result is the same. I've also tried setting javax.net.debug=all as a JVM arg ([the JSSE reference guide](http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/ReadDebug.html) lists this as a debugging step); however, I don't see any debugging output anywhere - should I expect this somewhere other than standard out/error?
Most `javax.net.SocketFactory` implementations define all `createSocket()` methods **that have parameters** as abstract. But have a `createSocket()` method without parameters that looks like this: ``` public Socket createSocket() throws IOException { throw new SocketException("Unconnected sockets not implemented"); } ``` So if you subclass the abstract `javax.net.SocketFactory` you will be force to override the methods with parameter, but it's easy to miss to override the `createSocket()` method without parameters. Thus the exception is thrown if your code calls `createSocket()`. Simply override the method and the be done. :)
116,640
<p>I'm experiencing an issue on a test machine running Red Hat Linux (kernel version is 2.4.21-37.ELsmp) using Java 1.6 (1.6.0_02 or 1.6.0_04). The problem is, once a certain number of threads are created in a single thread group, the operating system is unwilling or unable to create any more.</p> <p>This seems to be specific to Java creating threads, as the C thread-limit program was able to create about 1.5k threads. Additionally, this doesn't happen with a Java 1.4 JVM... it can create over 1.4k threads, though they are obviously being handled differently with respect to the OS.</p> <p>In this case, the number of threads it's cutting off at is a mere 29 threads. This is testable with a simple Java program that just creates threads until it gets an error and then prints the number of threads it created. The error is a <pre>java.lang.OutOfMemoryError: unable to create new native thread</pre></p> <p>This seems to be unaffected by things such as the number of threads in use by other processes or users or the total amount of memory the system is using at the time. JVM settings like Xms, Xmx, and Xss don't seem to change anything either (which is expected, considering the issue seems to be with native OS thread creation).</p> <p>The output of "ulimit -a" is as follows:</p> <pre> core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited file size (blocks, -f) unlimited max locked memory (kbytes, -l) 4 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 stack size (kbytes, -s) 10240 cpu time (seconds, -t) unlimited max user processes (-u) 7168 virtual memory (kbytes, -v) unlimited </pre> <p>The user process limit does not seem to be the issue. Searching for information on what could be wrong has not turned up much, but <a href="http://blogs.oracle.com/gverma/2008/03/redhat_linux_kernels_and_proce_1.html" rel="nofollow noreferrer">this post</a> seems to indicate that at least some Red Hat kernels limit a process to 300 MB of memory allocated for stack, and at 10 MB per thread for stack, it seems like the issue could be there (though it seems strange and unlikely as well).</p> <p>I've tried changing the stack size with "ulimit -s" to test this, but any value other than 10240 and the JVM does not start with an error of:</p> <pre>Error occurred during initialization of VM Cannot create VM thread. Out of system resources.</pre> <p>I can generally get around Linux, but I really don't know much about system configuration, and I haven't been able to find anything specifically addressing this kind of situation. Any ideas on what system or JVM settings could be causing this would be appreciated.</p> <p><strong>Edits</strong>: Running the thread-limit program mentioned by <a href="https://stackoverflow.com/questions/116640/low-single-process-thread-limit-in-red-hat-linux#116696">plinth</a>, there was no failure until it tried to create the 1529th thread.</p> <p>The issue also did not occur using a 1.4 JVM (does occur with 1.6.0_02 and 1.6.0_04 JVMs, can't test with a 1.5 JVM at the moment).</p> <p>The code for the thread test I'm using is as follows:</p> <pre><code>public class ThreadTest { public static void main(String[] pArgs) throws Exception { try { // keep spawning new threads forever while (true) { new TestThread().start(); } } // when out of memory error is reached, print out the number of // successful threads spawned and exit catch ( OutOfMemoryError e ) { System.out.println(TestThread.CREATE_COUNT); System.exit(-1); } } static class TestThread extends Thread { private static int CREATE_COUNT = 0; public TestThread() { CREATE_COUNT++; } // make the thread wait for eternity after being spawned public void run() { try { sleep(Integer.MAX_VALUE); } // even if there is an interruption, dont do anything catch (InterruptedException e) { } } } } </code></pre> <p>If you run this with a 1.4 JVM it will hang when it can't create any more threads and require a kill -9 (at least it did for me).</p> <p><strong>More Edit:</strong></p> <p>It turns out that the system that is having the problem is using the LinuxThreads threading model while another system that works fine is using the NPTL model. </p>
[ { "answer_id": 116696, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "<p>Have you looked at <a href=\"http://people.redhat.com/alikins/system_tuning.html#threads\" rel=\"nofollow noreferrer\">this resource</a>?\nIt states that you should be able run thread-limit to find the maximum number of threads and can tweak it by compiling glibc.</p>\n" }, { "answer_id": 117678, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 0, "selected": false, "text": "<p>This is with Ubuntu Linux (1GB RAM)</p>\n\n<pre><code>dsm@localhost:~$ javac ThreadTest.java \ndsm@localhost:~$ java ThreadTest \n8113\ndsm@localhost:~$ java -version\njava version \"1.6.0_07\"\nJava(TM) SE Runtime Environment (build 1.6.0_07-b06)\nJava HotSpot(TM) Client VM (build 10.0-b23, mixed mode, sharing)\ndsm@localhost:~$ \n</code></pre>\n" }, { "answer_id": 118429, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 0, "selected": false, "text": "<p>Can you try it with the JRockit JVM? IIRC, it had a different threading model than the stock Sun JVM.</p>\n" }, { "answer_id": 170865, "author": "ColinD", "author_id": 13792, "author_profile": "https://Stackoverflow.com/users/13792", "pm_score": 3, "selected": true, "text": "<p>Updating the kernel to a newer version (2.6.something) with NPTL threading fixed this.</p>\n" }, { "answer_id": 39077766, "author": "Umut Uzun", "author_id": 4374102, "author_profile": "https://Stackoverflow.com/users/4374102", "pm_score": 0, "selected": false, "text": "<p>The settings in <code>/etc/security/limits.d/90-nproc.conf</code> may be overriding your <code>/etc/security/limits.conf</code> settings. That may cause the system act in a different way shown in <code>ulimit -u</code>.</p>\n\n<p><a href=\"https://bugzilla.redhat.com/show_bug.cgi?id=823030\" rel=\"nofollow\">https://bugzilla.redhat.com/show_bug.cgi?id=823030</a></p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13792/" ]
I'm experiencing an issue on a test machine running Red Hat Linux (kernel version is 2.4.21-37.ELsmp) using Java 1.6 (1.6.0\_02 or 1.6.0\_04). The problem is, once a certain number of threads are created in a single thread group, the operating system is unwilling or unable to create any more. This seems to be specific to Java creating threads, as the C thread-limit program was able to create about 1.5k threads. Additionally, this doesn't happen with a Java 1.4 JVM... it can create over 1.4k threads, though they are obviously being handled differently with respect to the OS. In this case, the number of threads it's cutting off at is a mere 29 threads. This is testable with a simple Java program that just creates threads until it gets an error and then prints the number of threads it created. The error is a ``` java.lang.OutOfMemoryError: unable to create new native thread ``` This seems to be unaffected by things such as the number of threads in use by other processes or users or the total amount of memory the system is using at the time. JVM settings like Xms, Xmx, and Xss don't seem to change anything either (which is expected, considering the issue seems to be with native OS thread creation). The output of "ulimit -a" is as follows: ``` core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited file size (blocks, -f) unlimited max locked memory (kbytes, -l) 4 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 stack size (kbytes, -s) 10240 cpu time (seconds, -t) unlimited max user processes (-u) 7168 virtual memory (kbytes, -v) unlimited ``` The user process limit does not seem to be the issue. Searching for information on what could be wrong has not turned up much, but [this post](http://blogs.oracle.com/gverma/2008/03/redhat_linux_kernels_and_proce_1.html) seems to indicate that at least some Red Hat kernels limit a process to 300 MB of memory allocated for stack, and at 10 MB per thread for stack, it seems like the issue could be there (though it seems strange and unlikely as well). I've tried changing the stack size with "ulimit -s" to test this, but any value other than 10240 and the JVM does not start with an error of: ``` Error occurred during initialization of VM Cannot create VM thread. Out of system resources. ``` I can generally get around Linux, but I really don't know much about system configuration, and I haven't been able to find anything specifically addressing this kind of situation. Any ideas on what system or JVM settings could be causing this would be appreciated. **Edits**: Running the thread-limit program mentioned by [plinth](https://stackoverflow.com/questions/116640/low-single-process-thread-limit-in-red-hat-linux#116696), there was no failure until it tried to create the 1529th thread. The issue also did not occur using a 1.4 JVM (does occur with 1.6.0\_02 and 1.6.0\_04 JVMs, can't test with a 1.5 JVM at the moment). The code for the thread test I'm using is as follows: ``` public class ThreadTest { public static void main(String[] pArgs) throws Exception { try { // keep spawning new threads forever while (true) { new TestThread().start(); } } // when out of memory error is reached, print out the number of // successful threads spawned and exit catch ( OutOfMemoryError e ) { System.out.println(TestThread.CREATE_COUNT); System.exit(-1); } } static class TestThread extends Thread { private static int CREATE_COUNT = 0; public TestThread() { CREATE_COUNT++; } // make the thread wait for eternity after being spawned public void run() { try { sleep(Integer.MAX_VALUE); } // even if there is an interruption, dont do anything catch (InterruptedException e) { } } } } ``` If you run this with a 1.4 JVM it will hang when it can't create any more threads and require a kill -9 (at least it did for me). **More Edit:** It turns out that the system that is having the problem is using the LinuxThreads threading model while another system that works fine is using the NPTL model.
Updating the kernel to a newer version (2.6.something) with NPTL threading fixed this.
116,646
<p>I would like to implement a data access object pattern in C++, but preferably without using multiple inheritance and/or boost (which my client does not like). </p> <p>Do you have any suggestions?</p>
[ { "answer_id": 116714, "author": "JeffFoster", "author_id": 9853, "author_profile": "https://Stackoverflow.com/users/9853", "pm_score": 4, "selected": true, "text": "<p>OTL (otl.sourceforge.net) is an excellent C++ database library. It's a single include file so doesn't have all the complexity associated (rightly or wrongly!) with Boost.</p>\n\n<p>In terms of the DAO itself, you have many options. The simplest that hides the database implementation is just to use C++ style interfaces and implement the data access layer in a particular implementation.</p>\n\n<pre>\nclass MyDAO {\n // Pure virtual functions to access the data itself\n}\n\nclass MyDAOImpl : public MyDAO {\n // Implementations to get the data from the database\n}\n</pre>\n" }, { "answer_id": 118226, "author": "Odd", "author_id": 11908, "author_profile": "https://Stackoverflow.com/users/11908", "pm_score": 2, "selected": false, "text": "<p>A quick google search on data access object design patterns will return at least 10 results on the first page that will be useful. The most common of these is the abstract interface design as already shown by Jeff Foster. The only thing you may wish to add to this is a data access object factory to create your objects. </p>\n\n<p>Most of the examples I could find with decent code are in Java, it's a common design pattern in Java, but they're still very relevant to C++ and you could use them quite easily.</p>\n\n<p><a href=\"http://www.dofactory.com/patterns/PatternAbstract.aspx\" rel=\"nofollow noreferrer\">This is a good link</a>, it describes the abstract factory very well.</p>\n" }, { "answer_id": 135825, "author": "moffdub", "author_id": 10759, "author_profile": "https://Stackoverflow.com/users/10759", "pm_score": 1, "selected": false, "text": "<p>My preferred data access abstraction is the <a href=\"http://martinfowler.com/eaaCatalog/repository.html\" rel=\"nofollow noreferrer\">Repository Pattern</a>.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
I would like to implement a data access object pattern in C++, but preferably without using multiple inheritance and/or boost (which my client does not like). Do you have any suggestions?
OTL (otl.sourceforge.net) is an excellent C++ database library. It's a single include file so doesn't have all the complexity associated (rightly or wrongly!) with Boost. In terms of the DAO itself, you have many options. The simplest that hides the database implementation is just to use C++ style interfaces and implement the data access layer in a particular implementation. ``` class MyDAO { // Pure virtual functions to access the data itself } class MyDAOImpl : public MyDAO { // Implementations to get the data from the database } ```
116,650
<p>I am tasked with writing an authentication component for an open source <code>JAVA</code> app. We have an in-house authentication widget that uses <code>https</code>. I have some example <code>php</code> code that accesses the <code>widget</code> which uses <code>cURL</code> to handle the transfer. </p> <p>My question is whether or not there is a port of <code>cURL</code> to <code>JAVA</code>, or better yet, what base package will get me close enough to handle the task? </p> <p><strong>Update</strong>:</p> <p>This is in a nutshell, the code I would like to replicate in JAVA:</p> <pre><code>$cp = curl_init(); $my_url = "https://" . AUTH_SERVER . "/auth/authenticate.asp?pt1=$uname&amp;pt2=$pass&amp;pt4=full"; curl_setopt($cp, CURLOPT_URL, $my_url); curl_setopt($cp, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($cp); curl_close($cp); </code></pre> <p><a href="https://stackoverflow.com/questions/116650/curl-equivalent-in-java#116725">Heath</a>, I think you're on the right track, I think I'm going to end up using HttpsURLConnection and then picking out what I need from the response.</p>
[ { "answer_id": 116670, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 1, "selected": false, "text": "<p>Try <a href=\"http://commons.apache.org/net/\" rel=\"nofollow noreferrer\">Apache Commons Net</a> for network protocols. Free!</p>\n" }, { "answer_id": 116702, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 1, "selected": false, "text": "<p>You could also try [<a href=\"http://hc.apache.org/](HTTP\" rel=\"nofollow noreferrer\">http://hc.apache.org/](HTTP</a> Components) from the Apache Project if you need more features than the ones provided through Commons Net.</p>\n" }, { "answer_id": 116725, "author": "Heath Borders", "author_id": 9636, "author_profile": "https://Stackoverflow.com/users/9636", "pm_score": 7, "selected": true, "text": "<p>Exception handling omitted:</p>\n\n<pre><code>HttpURLConnection con = (HttpURLConnection) new URL(\"https://www.example.com\").openConnection();\ncon.setRequestMethod(\"POST\");\ncon.getOutputStream().write(\"LOGIN\".getBytes(\"UTF-8\"));\ncon.getInputStream();\n</code></pre>\n" }, { "answer_id": 116774, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 5, "selected": false, "text": "<p>I'd use the <a href=\"http://hc.apache.org/httpclient-3.x/\" rel=\"noreferrer\">Commons Http Client</a>. There is a contrib class in the project that allows you to use ssl.</p>\n\n<p>We're using it and it's working well.</p>\n\n<p>Edit: Here's the <a href=\"http://hc.apache.org/httpclient-3.x/sslguide.html\" rel=\"noreferrer\">SSL Guide</a></p>\n" }, { "answer_id": 22444271, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": "<h1>jsoup</h1>\n\n<p>The <a href=\"http://www.jsoup.org/\" rel=\"nofollow\">jsoup</a> library fetches a URL as the first step in its HTML scraping and parsing duties.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Document doc = Jsoup.connect(\"http://en.wikipedia.org/\").get();\n</code></pre>\n" }, { "answer_id": 57321671, "author": "jeffrey", "author_id": 10594630, "author_profile": "https://Stackoverflow.com/users/10594630", "pm_score": 0, "selected": false, "text": "<p>you can try curl-to-java lib to convert curl php code to java code <a href=\"https://github.com/jeffreyning/curl-to-java\" rel=\"nofollow noreferrer\">https://github.com/jeffreyning/curl-to-java</a> demo like this</p>\n\n<pre><code>public Object curl(String url, Object postData, String method) {\n\nCurlLib curl = CurlFactory.getInstance(\"default\");\nch = curl.curl_init();\ncurl.curl_setopt(ch, CurlOption.CURLOPT_CONNECTTIMEOUT, 1000);\ncurl.curl_setopt(ch, CurlOption.CURLOPT_TIMEOUT, 5000);\ncurl.curl_setopt(ch, CurlOption.CURLOPT_SSL_VERIFYPEER, false);\ncurl.curl_setopt(ch, CurlOption.CURLOPT_SSL_VERIFYHOST, false);\nString postDataStr = \"key1=v1\";\n\ncurl.curl_setopt(ch, CurlOption.CURLOPT_CUSTOMREQUEST, \"POST\");\ncurl.curl_setopt(ch, CurlOption.CURLOPT_POSTFIELDS, postDataStr);\ncurl.curl_setopt(ch, CurlOption.CURLOPT_URL, \"https://xxxx.com/yyy\");\nObject html = curl.curl_exec(ch);\nObject httpCode = curl.curl_getinfo(ch, CurlInfo.CURLINFO_HTTP_CODE);\nif (httpCode != null &amp;&amp; 200 == Integer.valueOf(httpCode.toString())) {\n return null;\n}\nreturn html;\n}\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16253/" ]
I am tasked with writing an authentication component for an open source `JAVA` app. We have an in-house authentication widget that uses `https`. I have some example `php` code that accesses the `widget` which uses `cURL` to handle the transfer. My question is whether or not there is a port of `cURL` to `JAVA`, or better yet, what base package will get me close enough to handle the task? **Update**: This is in a nutshell, the code I would like to replicate in JAVA: ``` $cp = curl_init(); $my_url = "https://" . AUTH_SERVER . "/auth/authenticate.asp?pt1=$uname&pt2=$pass&pt4=full"; curl_setopt($cp, CURLOPT_URL, $my_url); curl_setopt($cp, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($cp); curl_close($cp); ``` [Heath](https://stackoverflow.com/questions/116650/curl-equivalent-in-java#116725), I think you're on the right track, I think I'm going to end up using HttpsURLConnection and then picking out what I need from the response.
Exception handling omitted: ``` HttpURLConnection con = (HttpURLConnection) new URL("https://www.example.com").openConnection(); con.setRequestMethod("POST"); con.getOutputStream().write("LOGIN".getBytes("UTF-8")); con.getInputStream(); ```
116,682
<p>I have a URI here in which a simple document.cookie query through the console is resulting in three cookies being displayed. I verified this with trivial code such as the following as well:</p> <pre><code>var cookies = document.cookie.split(';'); console.log(cookies.length); </code></pre> <p>The variable cookies does indeed come out to the number 3. Web Developer on the other hand is indicating that a grand total of 8 cookies are in use.</p> <p>I'm slightly confused to believe which is inaccurate. I believe the best solution might involve just reiterating the code above without the influence of Firebug. However, I was wondering if someone might suggest a more clever alternative to decipher which tool is giving me the inaccurate information.</p>
[ { "answer_id": 116660, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 1, "selected": false, "text": "<p>Lisp supports a form of \"metaprogramming\", although not in the same sense as C++ template metaprogramming. Also, your term \"static\" could mean different things in this context, but Lisp also supports static typing, if that's what you mean.</p>\n" }, { "answer_id": 116661, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 6, "selected": true, "text": "<p>The alternative to template style meta-programming is Macro-style that you see in various Lisp implementations. I would suggest downloading <a href=\"http://www.paulgraham.com/onlisp.html\" rel=\"noreferrer\">Paul Graham's <em>On Lisp</em></a> and also taking a look at <a href=\"http://clojure.org\" rel=\"noreferrer\">Clojure</a> if you're interested in a Lisp with macros that runs on the JVM.</p>\n\n<p>Macros in Lisp are much more powerful than C/C++ style and constitute a language in their own right -- they are meant for meta-programming.</p>\n" }, { "answer_id": 116663, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://nemerle.org\" rel=\"nofollow noreferrer\" title=\"Nemerle\">Nemerle</a> and <a href=\"http://boo.codehaus.org\" rel=\"nofollow noreferrer\" title=\"Boo\">Boo</a> are my personal favorites for such things. Nemerle has a very elegant macro syntax, despite its poor documentation. Boo's documentation is excellent but its macros are a little less elegant. Both work incredibly well, however.</p>\n\n<p>Both target .NET, so they can easily interoperate with C# and other .NET languages -- even Java binaries, if you use IKVM.</p>\n\n<p>Edit: To clarify, I mean macros in the Lisp sense of the word, not C's preprocessor macros. These allow definition of new syntax and heavy metaprogramming at compiletime. For instance, Nemerle ships with macros that will validate your SQL queries against your SQL server at compiletime.</p>\n" }, { "answer_id": 116668, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 2, "selected": false, "text": "<p>I recommend <a href=\"http://www.haskell.org/\" rel=\"nofollow noreferrer\">Haskell</a>. Here is a <a href=\"http://research.microsoft.com/~simonpj/papers/meta-haskell/\" rel=\"nofollow noreferrer\">paper</a> describing its compile-time metaprogramming capabilities.</p>\n" }, { "answer_id": 116931, "author": "joeld", "author_id": 19104, "author_profile": "https://Stackoverflow.com/users/19104", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://d-programming-language.org/\" rel=\"nofollow noreferrer\" title=\"D programming language\">\"D\" programming language</a> is C++-like but has much better metaprogramming support. Here's an example of a ray-tracer written using only compile-time metaprogramming:</p>\n\n<p><a href=\"http://h3.team0xf.com/ctrace/\" rel=\"nofollow noreferrer\">Ctrace</a></p>\n\n<p>Additionally, there is a gcc branch called \"Concept GCC\" that supports metaprogramming contructs that C++ doesn't (at least not yet).</p>\n\n<p><a href=\"http://www.generic-programming.org/software/ConceptGCC/\" rel=\"nofollow noreferrer\" title=\"Concept GCC\">Concept GCC</a></p>\n" }, { "answer_id": 116969, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 2, "selected": false, "text": "<p>'metaprogramming' is really a bad name for this specific feature, at least when you're discussing more than one language, since this feature is only needed for a narrow slice of languages that are:</p>\n\n<ul>\n<li>static</li>\n<li>compiled to machine language</li>\n<li>heavily optimised for performance at compile time</li>\n<li>extensible with user-defined data types (OOP in C++'s case)</li>\n<li>hugely popular</li>\n</ul>\n\n<p>take out any one of these, and 'static metaprogramming', just doesn't make sense. therefore, i would be surprised if any remotely mainstream language had something like that, as understood on C++.</p>\n\n<p>of course, dynamic languages, and several functional languages support totally different concepts that could also be called metaprogramming.</p>\n" }, { "answer_id": 116994, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 1, "selected": false, "text": "<p>The Meta-Language (ML), of course: <a href=\"http://cs.anu.edu.au/student/comp8033/ml.html\" rel=\"nofollow noreferrer\">http://cs.anu.edu.au/student/comp8033/ml.html</a></p>\n" }, { "answer_id": 117097, "author": "simon", "author_id": 14143, "author_profile": "https://Stackoverflow.com/users/14143", "pm_score": 4, "selected": false, "text": "<p>Template metaprogramming is essentially abuse of the template mechanism. What I mean is that you get basically what you'd expect from a feature that was an unplanned side-effect --- it's a mess, and (although tools are getting better) a real pain in the ass because the language doesn't support you in doing it (I should note that my experience with state-of-the-art on this is out of date, since I essentially gave up on the approach. I've not heard of any great strides made, though)</p>\n\n<p>Messing around with this in about '98 was what drove me to look for better solutions. I could write useful systems that relied on it, but they were hellish. Poking around eventually led me to Common Lisp. Sure, the template mechanism is Turing complete, but then again so is intercal.</p>\n\n<p>Common Lisp does metaprogramming `right'. You have the full power of the language available while you do it, no special syntax, and because the language is very dynamic you can do more with it.</p>\n\n<p>There are other options of course. No other language I've used does metaprogramming better than Lisp does, which is why I use it for research code. There are lots of reasons you might want to try something else though, but it's all going to be tradeoffs. You can look at Haskell/ML/OCaml etc. Lots of functional languages have something approaching the power of Lisp macros. You can find some .NET targeted stuff, but they're all pretty marginal (in terms of user base etc.). None of the big players in industrially used languages have anything like this, really.</p>\n" }, { "answer_id": 120284, "author": "Attila Lendvai", "author_id": 14464, "author_profile": "https://Stackoverflow.com/users/14464", "pm_score": 5, "selected": false, "text": "<p>let me list a <strong>few important details</strong> about how <strong>metaprogramming</strong> works <strong>in lisp</strong> (or <a href=\"http://schemers.org/\" rel=\"nofollow noreferrer\">scheme</a>, or <a href=\"http://slate.tunes.org/documentation.html\" rel=\"nofollow noreferrer\">slate</a>, or pick your favorite \"dynamic\" language):</p>\n\n<ul>\n<li>when doing metaprogramming in lisp you <strong>don't have to deal with two languages</strong>. the meta level code is written in the same language as the object level code it generates. metaprogramming is not limited to two levels, and it's easier on the brain, too.</li>\n<li>in lisp you have the <strong>compiler available at runtime</strong>. in fact the compile-time/run-time distinction feels very artificial there and is very much subject to where you place your point of view. in lisp with a mere function call you can compile functions to machine instructions that you can use from then on as first class objects; i.e. they can be unnamed functions that you can keep in a local variable, or a global hashtable, etc...</li>\n<li><strong>macros</strong> in lisp are very simple: a bunch of functions stuffed in a hashtable and given to the compiler. for each form the compiler is about to compile, it consults that hashtable. if it finds a function then calls it at compile-time with the original form, and in place of the original form it compiles the form this function returns. (modulo some non-important details) so lisp macros <strong>are basically plugins for the compiler</strong>.</li>\n<li>writing a lisp function in lisp that evaluates lisp code is about two pages of code (this is usually called <strong>eval</strong>). in such a function you have all the power to introduce whatever new rules you want on the meta level. (making it run fast is going to take some effort though... about the same as bootstrapping a new language... :)</li>\n</ul>\n\n<p>random examples of what <strong>you can implement as a user library</strong> using lisp metaprogramming (these are actual examples of common lisp libraries):</p>\n\n<ul>\n<li>extend the language with <strong>delimited continuations</strong> (hu.dwim.delico)</li>\n<li>implement a <strong>js-to-lisp-rpc</strong> macro that you can use in javascript (which is generated from lisp). it expands into a mixture of js/lisp code that automatically posts (in the http request) all the referenced local variables, decodes them on the server side, runs the lisp code body on the server, and returns back the return value to the javascript side.</li>\n<li>add prolog like backtracking to the language that very seamlessly integrates with \"normal\" lisp code (see screamer)</li>\n<li>an <a href=\"https://stackoverflow.com/questions/106058/practical-example-of-lisps-flexibility#109131\">XML templating extension</a> to common lisp (includes an example of <strong>reader macros</strong> that are plugins for the lisp parser)</li>\n<li>a ton of small DSL's, like <a href=\"http://www.lispworks.com/reference/HyperSpec/Body/m_loop.htm\" rel=\"nofollow noreferrer\"><em>loop</em></a> or <a href=\"http://common-lisp.net/project/iterate/\" rel=\"nofollow noreferrer\"><em>iterate</em></a> for easy looping</li>\n</ul>\n" }, { "answer_id": 122596, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 3, "selected": false, "text": "<p>Common Lisp supports programs that write programs in several different ways.</p>\n\n<p>1) Program data and program \"abstract syntax tree\" are uniform (S-expressions!)</p>\n\n<p>2) <code>defmacro</code></p>\n\n<p>3) Reader macros.</p>\n\n<p>4) MOP</p>\n\n<p>Of these, the real mind-blower is MOP. Read \"The Art of the Metaobject Protocol.\" It will change things for you, I promise!</p>\n" }, { "answer_id": 216235, "author": "J D", "author_id": 13924, "author_profile": "https://Stackoverflow.com/users/13924", "pm_score": 2, "selected": false, "text": "<p>The ML family of languages were designed specifically for this purpose. One of OCaml's most famous success stories is the <a href=\"http://fftw.org\" rel=\"nofollow noreferrer\">FFTW</a> library for high-performance FFTs that is C code generated almost entirely by an OCaml program.</p>\n\n<p>Cheers,\nJon Harrop.</p>\n" }, { "answer_id": 301280, "author": "ja.", "author_id": 15467, "author_profile": "https://Stackoverflow.com/users/15467", "pm_score": 2, "selected": false, "text": "<p>Lots of work in Haskell: Domain Specific Languages (DSL's), Executable Specifications, Program Transformation, Partial Application, Staged Computation. Few links to get you started:</p>\n\n<ul>\n<li><a href=\"http://haskell.readscheme.org/appl.html\" rel=\"nofollow noreferrer\">http://haskell.readscheme.org/appl.html</a></li>\n<li><a href=\"http://www.cse.unsw.edu.au/~dons/papers/SCKCB07.html\" rel=\"nofollow noreferrer\">http://www.cse.unsw.edu.au/~dons/papers/SCKCB07.html</a></li>\n<li><a href=\"http://www.haskell.org/haskellwiki/Research_papers/Domain_specific_languages\" rel=\"nofollow noreferrer\">http://www.haskell.org/haskellwiki/Research_papers/Domain_specific_languages</a></li>\n</ul>\n" }, { "answer_id": 992197, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 2, "selected": false, "text": "<p>Most people try to find a language that has \"ultimate reflection\"\nfor self-inspection and something like \"eval\" for reifying new code.\nSuch languages are hard to find (LISP being a prime counterexample)\nand they certainly aren't mainstream.</p>\n\n<p>But another approach is to use a set of tools that can inspect,\ngenerate, and manipulate program code. Jackpot is such a tool\nfocused on Java. <a href=\"http://jackpot.netbeans.org/\" rel=\"nofollow noreferrer\">http://jackpot.netbeans.org/</a></p>\n\n<p>Our DMS software reengineering toolkit is\nsuch a tool, that works on C, C++, C#, Java, COBOL, PHP,\nJavascript, Ada, Verilog, VHDL and variety of other languages.\n(It uses production quality front ends to enable it to read\nall these langauges).\nBetter, it can do this with multiple languages at the same instant.\nSee <a href=\"http://www.semdesigns.com/Products/DMS/DMSToolkit.html\" rel=\"nofollow noreferrer\">http://www.semdesigns.com/Products/DMS/DMSToolkit.html</a></p>\n\n<p>DMS succeeds because it provides a regular method and support infrastructure for complete access to the program structure as ASTs, and in most cases additional data such a symbol tables, type information, control and data flow analysis, all necessary to do sophisticated program manipulation. </p>\n" }, { "answer_id": 31678589, "author": "zah", "author_id": 35511, "author_profile": "https://Stackoverflow.com/users/35511", "pm_score": 3, "selected": false, "text": "<p>Nim is a relatively new programming language that has extensive support for static meta-programming and produces efficient (C++ like) compiled code.</p>\n\n<p><a href=\"http://nim-lang.org/\" rel=\"noreferrer\">http://nim-lang.org/</a></p>\n\n<p>It supports compile-time function evaluation, lisp-like AST code transformations through macros, compile-time reflection, generic types that can be parametrized with arbitrary values, and term rewriting that can be used to create user-defined high-level type-aware peephole optimizations. It's even possible to execute external programs during the compilation process that can influence the code generation. As an example, consider talking to a locally running database server in order to verify that the ORM definition in your code (supplied through some DSL) matches the schema of the database.</p>\n" }, { "answer_id": 63435262, "author": "Dmitry Ponyatov", "author_id": 2134384, "author_profile": "https://Stackoverflow.com/users/2134384", "pm_score": 0, "selected": false, "text": "<p>It does not matter what language you are using -- any of them is able to do Heterogeneous Generative Metaprogramming. <strong>Take any dynamic language</strong> such as Python or Clojure, or Haskell if you are a type-fan, <strong>and write models</strong> in this host language that are <em>able to compile themself into some mainstream language</em> you want or forced to use by your team/employer.</p>\n<p>I found object graphs a good model for internal model representation. This graph can mix attributes and ordered subgraphs in a single node, which is native to attribute grammar and AST. So, object graph interpretation can be an effective layer between your host and target languages and can act itself as some sort of no-syntax language defined over data structures.</p>\n<p>The closest model is an AST: describe AST trees in Python (host language) targets to C++ syntax (target language):</p>\n<pre class=\"lang-py prettyprint-override\"><code># from metaL import *\nclass Object:\n def __init__(self, V):\n self.val = V\n self.slot = {}\n self.nest = []\n\n\nclass Module(Object):\n def cc(self):\n c = '// \\ %s\\n' % self.head(test=True)\n for i in self.nest:\n c += i.cc()\n c += '// / %s\\n' % self.head(test=True)\n return c\n\nhello = Module('hello')\n\n# &lt;module:hello&gt; #a04475a2\n\nclass Include(Object):\n def cc(self):\n return '#include &lt;%s.h&gt;\\n' % self.val\n\nstdlib = Include('stdlib')\nhello // stdlib\n\n# &lt;module:hello&gt; #b6efb657\n# 0: &lt;include:stdlib&gt; #f1af3e21\n\nclass Fn(Object):\n def cc(self):\n return '\\nvoid %s() {\\n}\\n\\n' % self.val\n\nmain = Fn('main')\nhello // main\n\nprint(hello.cc())\n</code></pre>\n<pre><code>// \\ &lt;module:hello&gt;\n#include &lt;stdlib.h&gt;\n\nvoid main() {\n}\n\n// / &lt;module:hello&gt;\n</code></pre>\n<p>But you are not limited with the level of abstraction of constructed object graph: you not only can freely add your own types but object graph can interpret itself, can thus can modify itself the same way as lists in a Lisp can do.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a URI here in which a simple document.cookie query through the console is resulting in three cookies being displayed. I verified this with trivial code such as the following as well: ``` var cookies = document.cookie.split(';'); console.log(cookies.length); ``` The variable cookies does indeed come out to the number 3. Web Developer on the other hand is indicating that a grand total of 8 cookies are in use. I'm slightly confused to believe which is inaccurate. I believe the best solution might involve just reiterating the code above without the influence of Firebug. However, I was wondering if someone might suggest a more clever alternative to decipher which tool is giving me the inaccurate information.
The alternative to template style meta-programming is Macro-style that you see in various Lisp implementations. I would suggest downloading [Paul Graham's *On Lisp*](http://www.paulgraham.com/onlisp.html) and also taking a look at [Clojure](http://clojure.org) if you're interested in a Lisp with macros that runs on the JVM. Macros in Lisp are much more powerful than C/C++ style and constitute a language in their own right -- they are meant for meta-programming.
116,687
<p>I want to call a few "static" methods of a CPP class defined in a different file but I'm having linking problems. I created a test-case that recreates my problem and the code for it is below.</p> <p>(I'm completely new to C++, I come from a Java background and I'm a little familiar with C.)</p> <pre><code>// CppClass.cpp #include &lt;iostream&gt; #include &lt;pthread.h&gt; static pthread_t thread; static pthread_mutex_t mutex; static pthread_cond_t cond; static int shutdown; using namespace std; class CppClass { public: static void Start() { cout &lt;&lt; "Testing start function." &lt;&lt; endl; shutdown = 0; pthread_attr_t attr; pthread_attr_init(&amp;attr); pthread_attr_setdetachstate(&amp;attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&amp;mutex, NULL); pthread_cond_init(&amp;cond, NULL); pthread_create(&amp;thread, &amp;attr, run_thread, NULL); } static void Stop() { pthread_mutex_lock(&amp;mutex); shutdown = 1; pthread_cond_broadcast(&amp;cond); pthread_mutex_unlock(&amp;mutex); } static void Join() { pthread_join(thread, NULL); } private: static void *run_thread(void *pthread_args) { CppClass *obj = new CppClass(); pthread_mutex_lock(&amp;mutex); while (shutdown == 0) { struct timespec ts; ts.tv_sec = time(NULL) + 3; pthread_cond_timedwait(&amp;cond, &amp;mutex, &amp;ts); if (shutdown) { break; } obj-&gt;display(); } pthread_mutex_unlock(&amp;mutex); pthread_mutex_destroy(&amp;mutex); pthread_cond_destroy(&amp;cond); pthread_exit(NULL); return NULL; } void display() { cout &lt;&lt; " Inside display() " &lt;&lt; endl; } }; // main.cpp #include &lt;iostream&gt; /* * If I remove the comment below and delete the * the class declaration part, it works. */ // #include "CppClass.cpp" using namespace std; class CppClass { public: static void Start(); static void Stop(); static void Join(); }; int main() { CppClass::Start(); while (1) { int quit; cout &lt;&lt; "Do you want to end?: (0 = stay, 1 = quit) "; cin &gt;&gt; quit; cout &lt;&lt; "Input: " &lt;&lt; quit &lt;&lt; endl; if (quit) { CppClass::Stop(); cout &lt;&lt; "Joining CppClass..." &lt;&lt; endl; CppClass::Join(); break; } } } </code></pre> <p>When I tried to compile, I get the following error:</p> <pre> $ g++ -o go main.cpp CppClass.cpp -l pthread /tmp/cclhBttM.o(.text+0x119): In function `main': : undefined reference to `CppClass::Start()' /tmp/cclhBttM.o(.text+0x182): In function `main': : undefined reference to `CppClass::Stop()' /tmp/cclhBttM.o(.text+0x1ad): In function `main': : undefined reference to `CppClass::Join()' collect2: ld returned 1 exit status </pre> <p>But if I remove the class declaration in main.cpp and replace it with #include "CppClass.cpp", it works fine. Basically, I want to put these declarations in a separate .h file and use it. Am I missing something?</p> <p>Thanks for the help.</p>
[ { "answer_id": 116708, "author": "Jon", "author_id": 12261, "author_profile": "https://Stackoverflow.com/users/12261", "pm_score": 2, "selected": false, "text": "<p>I think you want to do something like:</p>\n\n<p>g++ -c CppClass.cpp\ng++ -c main.cpp\ng++ -o go main.o CppClass.o</p>\n\n<p>That should resolve it.</p>\n" }, { "answer_id": 116733, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": false, "text": "<p>make a .h file with the class definition in it, and then #include that file into your 2 files.</p>\n" }, { "answer_id": 116740, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 0, "selected": false, "text": "<p>Sure looks like the linker is not picking up you second source file.</p>\n" }, { "answer_id": 116741, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 6, "selected": true, "text": "<p>It's obvious you come from a Java background because you haven't yet grasped the concept of header files. In Java the process of defining something is usually in one piece. You declare and define at the same time. In C/C++ it's a two-step process. <strong>Declaring</strong> something tells the compiler \"something exists with this type, but I'll tell you later how it is actually implemented\". <strong>Defining</strong> something is giving the compiler the actual implementation part. Header files are used mostly for declarations, .cpp files for definitions.</p>\n\n<p>Header files are there to describe the \"API\" of classes, but not their actual code. It is possible to include code in the header, that's called header-inlining. You have inlined everything in CppClass.cpp (not good, header-inlining should be the exception), and then you declare your class in main.cpp AGAIN which is a double declaration in C++. The inlining in the class body leads to code reduplication everytime you use a method (this only <em>sounds</em> insane. See the <a href=\"http://www.parashift.com/c++-faq-lite/inline-functions.html\" rel=\"noreferrer\">C++ faq section on inlining</a> for details.)</p>\n\n<p>Including the double declaration in your code gives you a compiler error. Leaving the class code out compiles but gives you a linker error because now you only have the header-like class declaration in main.cpp. The linker sees no code that implements your class methods, that's why the errors appear. Different to Java, the C++ linker will NOT automatically search for object files it wants to use. If you use class XYZ and don't give it object code for XYZ, it will simply fail.</p>\n\n<p>Please have a look at <a href=\"http://en.wikipedia.org/wiki/Header_files\" rel=\"noreferrer\">Wikipedia's header file article</a> and <a href=\"http://www.eventhelix.com/RealtimeMantra/HeaderFileIncludePatterns.htm\" rel=\"noreferrer\">Header File Include Patterns</a> (the link is also at the bottom of the Wikipedia article and contains more examples)</p>\n\n<p>In short:</p>\n\n<p>For each class, generate a NewClass.h and NewClass.cpp file.</p>\n\n<p>In the NewClass.h file, write:</p>\n\n<pre><code>class NewClass {\npublic:\n NewClass();\n int methodA();\n int methodB();\n}; &lt;- don't forget the semicolon\n</code></pre>\n\n<p>In the NewClass.cpp file, write:</p>\n\n<pre><code>#include \"NewClass.h\"\n\nNewClass::NewClass() {\n // constructor goes here\n}\n\nint NewClass::methodA() {\n // methodA goes here\n return 0;\n}\n\nint NewClass::methodB() {\n // methodB goes here\n return 1;\n}\n</code></pre>\n\n<p>In main.cpp, write:</p>\n\n<pre><code>#include \"NewClass.h\"\n\nint main() {\n NewClass nc;\n // do something with nc\n}\n</code></pre>\n\n<p>To link it all together, do a </p>\n\n<p>g++ -o NewClassExe NewClass.cpp main.cpp</p>\n\n<p>(just an example with gcc)</p>\n" }, { "answer_id": 116878, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 3, "selected": false, "text": "<p>You're defining the class twice, which I'm pretty sure doesn't work.</p>\n\n<p>Try something like this:</p>\n\n<p>First a header CppClass.h file:</p>\n\n<pre><code>// CppClass.h\nusing namespace std;\n\nclass CppClass\n{\npublic:\n static void Start();\n static void Stop();\n static void Join();\nprivate:\n void *run_thread(void *pthread_args);\n void display();\n};\n</code></pre>\n\n<p>Then a CppClass.cpp file implementing it:</p>\n\n<pre><code>// CppClass.cpp\n#include &lt;iostream&gt;\n#include &lt;pthread.h&gt;\n#include \"CppClass.h\"\n\nusing namespace std;\n\nvoid CppClass::Start()\n{\n /* method body goes here */\n}\nvoid CppClass::Stop()\n{\n /* method body goes here */\n}\nvoid CppClass::Join()\n{\n /* method body goes here */\n}\nvoid *CppClass::run_thread(void *pthread_args)\n{\n /* method body goes here */\n}\nvoid CppClass::display() {\n /* method body goes here */\n}\n</code></pre>\n\n<p>Then your main file:</p>\n\n<pre><code>// main.cpp\n#include \"CppClass.h\"\n\nint main()\n{\n /* main method body here */\n}\n</code></pre>\n\n<p>I believe the g++ call would be the same.</p>\n\n<p>Basically, you can't declare the same class twice. You should declare the class in the header file, then declare the implementation in the cpp file. You could also put all the code inline in a <em>single</em> declaration of the class in a header file. But declaring it twice like you did won't work.</p>\n\n<p>I hope that made sense...</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7205/" ]
I want to call a few "static" methods of a CPP class defined in a different file but I'm having linking problems. I created a test-case that recreates my problem and the code for it is below. (I'm completely new to C++, I come from a Java background and I'm a little familiar with C.) ``` // CppClass.cpp #include <iostream> #include <pthread.h> static pthread_t thread; static pthread_mutex_t mutex; static pthread_cond_t cond; static int shutdown; using namespace std; class CppClass { public: static void Start() { cout << "Testing start function." << endl; shutdown = 0; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_create(&thread, &attr, run_thread, NULL); } static void Stop() { pthread_mutex_lock(&mutex); shutdown = 1; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); } static void Join() { pthread_join(thread, NULL); } private: static void *run_thread(void *pthread_args) { CppClass *obj = new CppClass(); pthread_mutex_lock(&mutex); while (shutdown == 0) { struct timespec ts; ts.tv_sec = time(NULL) + 3; pthread_cond_timedwait(&cond, &mutex, &ts); if (shutdown) { break; } obj->display(); } pthread_mutex_unlock(&mutex); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); pthread_exit(NULL); return NULL; } void display() { cout << " Inside display() " << endl; } }; // main.cpp #include <iostream> /* * If I remove the comment below and delete the * the class declaration part, it works. */ // #include "CppClass.cpp" using namespace std; class CppClass { public: static void Start(); static void Stop(); static void Join(); }; int main() { CppClass::Start(); while (1) { int quit; cout << "Do you want to end?: (0 = stay, 1 = quit) "; cin >> quit; cout << "Input: " << quit << endl; if (quit) { CppClass::Stop(); cout << "Joining CppClass..." << endl; CppClass::Join(); break; } } } ``` When I tried to compile, I get the following error: ``` $ g++ -o go main.cpp CppClass.cpp -l pthread /tmp/cclhBttM.o(.text+0x119): In function `main': : undefined reference to `CppClass::Start()' /tmp/cclhBttM.o(.text+0x182): In function `main': : undefined reference to `CppClass::Stop()' /tmp/cclhBttM.o(.text+0x1ad): In function `main': : undefined reference to `CppClass::Join()' collect2: ld returned 1 exit status ``` But if I remove the class declaration in main.cpp and replace it with #include "CppClass.cpp", it works fine. Basically, I want to put these declarations in a separate .h file and use it. Am I missing something? Thanks for the help.
It's obvious you come from a Java background because you haven't yet grasped the concept of header files. In Java the process of defining something is usually in one piece. You declare and define at the same time. In C/C++ it's a two-step process. **Declaring** something tells the compiler "something exists with this type, but I'll tell you later how it is actually implemented". **Defining** something is giving the compiler the actual implementation part. Header files are used mostly for declarations, .cpp files for definitions. Header files are there to describe the "API" of classes, but not their actual code. It is possible to include code in the header, that's called header-inlining. You have inlined everything in CppClass.cpp (not good, header-inlining should be the exception), and then you declare your class in main.cpp AGAIN which is a double declaration in C++. The inlining in the class body leads to code reduplication everytime you use a method (this only *sounds* insane. See the [C++ faq section on inlining](http://www.parashift.com/c++-faq-lite/inline-functions.html) for details.) Including the double declaration in your code gives you a compiler error. Leaving the class code out compiles but gives you a linker error because now you only have the header-like class declaration in main.cpp. The linker sees no code that implements your class methods, that's why the errors appear. Different to Java, the C++ linker will NOT automatically search for object files it wants to use. If you use class XYZ and don't give it object code for XYZ, it will simply fail. Please have a look at [Wikipedia's header file article](http://en.wikipedia.org/wiki/Header_files) and [Header File Include Patterns](http://www.eventhelix.com/RealtimeMantra/HeaderFileIncludePatterns.htm) (the link is also at the bottom of the Wikipedia article and contains more examples) In short: For each class, generate a NewClass.h and NewClass.cpp file. In the NewClass.h file, write: ``` class NewClass { public: NewClass(); int methodA(); int methodB(); }; <- don't forget the semicolon ``` In the NewClass.cpp file, write: ``` #include "NewClass.h" NewClass::NewClass() { // constructor goes here } int NewClass::methodA() { // methodA goes here return 0; } int NewClass::methodB() { // methodB goes here return 1; } ``` In main.cpp, write: ``` #include "NewClass.h" int main() { NewClass nc; // do something with nc } ``` To link it all together, do a g++ -o NewClassExe NewClass.cpp main.cpp (just an example with gcc)
116,690
<p>SVN keyword substition gives is not pretty. E.g.,</p> <blockquote> <p>Last updated: $Date$ by $Author$</p> </blockquote> <p>yields</p> <blockquote> <p>Last updated: $Date: 2008-09-22 14:38:43 -0400 (Mon, 22 Sep 2008) $ by $Author: cconway $"</p> </blockquote> <p>Does anybody have a Javascript snippet that prettifies things and outputs some HTML? The result should be more like:</p> <blockquote> <p>Last update: 22 Sep 2008 by cconway</p> </blockquote> <p>P.S. Is there a way to replace "cconway" with a display name?</p>
[ { "answer_id": 116777, "author": "Chris MacDonald", "author_id": 18146, "author_profile": "https://Stackoverflow.com/users/18146", "pm_score": 0, "selected": false, "text": "<p>Some JavaScript libraries provide templating functionality.</p>\n\n<p>Prototype - <a href=\"http://www.prototypejs.org/api/template\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/api/template</a><br>\nExt JS - <a href=\"http://extjs.com/deploy/dev/docs/?class=Ext.DomHelper\" rel=\"nofollow noreferrer\">http://extjs.com/deploy/dev/docs/?class=Ext.DomHelper</a></p>\n\n<p>I'm sure you could find a plugin for JQuery.</p>\n" }, { "answer_id": 116804, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>Errr.. This feels a bit like me doing your job for you :), but here goes:</p>\n\n<pre><code>function formatSvnString(string){\n var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n\n var re = /\\$Date: (\\d{4})-(\\d\\d)-(\\d\\d).*?\\$Author: (\\S+) \\$/\n return string.replace(re, function(match, year, month, day, author){ \n var date = new Date([year, month, day].join('/'))\n return date.getDate()\n + ' ' + months[date.getMonth()]\n + ' ' + date.getFullYear()\n + ' by ' + author\n })\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>formatSvnString(\"$Date: 2008-09-22 14:38:43 -0400 (Mon, 22 Sep 2008) $ by $Author: cconway $\")\n// returns: 22 Sep 2008 by cconway\n</code></pre>\n\n<p>I'll leave it up to you to work out how to find these SVN string and apply the above code automatically :)</p>\n\n<p>To do the user's display name, you'll either have to convince SVN to insert it (I don't think it can do that, but I might be wrong), or somehow provide a means for JS to either fetch it, or to have access to a table full of usernames and associated display name (might be a bit too much like a security risk though. Hey kids, see if you can break into my server using one of these usernames!)</p>\n" }, { "answer_id": 127785, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 0, "selected": false, "text": "<p>Here's a little jQuery code to do the job:</p>\n\n<pre>\n $(document).ready(function() {\n var date = \"$Date: 2008-09-23 00:10:56 -0400 (Tue, 23 Sep 2008) $\"\n .replace(/\\$Date:.*\\((.*)\\)\\s*\\$/,\"$1\");\n $(\".timestamp\").text( \"Last updated: \" + date );\n });\n</pre>\n\n<p>where there is a <code>&lt;div class=\"timestamp\" /&gt;</code> in the HTML wherever you want the timestamp text to appear.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
SVN keyword substition gives is not pretty. E.g., > > Last updated: $Date$ by $Author$ > > > yields > > Last updated: $Date: 2008-09-22 > 14:38:43 -0400 (Mon, 22 Sep 2008) $ by > $Author: cconway $" > > > Does anybody have a Javascript snippet that prettifies things and outputs some HTML? The result should be more like: > > Last update: 22 Sep 2008 by cconway > > > P.S. Is there a way to replace "cconway" with a display name?
Errr.. This feels a bit like me doing your job for you :), but here goes: ``` function formatSvnString(string){ var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] var re = /\$Date: (\d{4})-(\d\d)-(\d\d).*?\$Author: (\S+) \$/ return string.replace(re, function(match, year, month, day, author){ var date = new Date([year, month, day].join('/')) return date.getDate() + ' ' + months[date.getMonth()] + ' ' + date.getFullYear() + ' by ' + author }) } ``` Usage: ``` formatSvnString("$Date: 2008-09-22 14:38:43 -0400 (Mon, 22 Sep 2008) $ by $Author: cconway $") // returns: 22 Sep 2008 by cconway ``` I'll leave it up to you to work out how to find these SVN string and apply the above code automatically :) To do the user's display name, you'll either have to convince SVN to insert it (I don't think it can do that, but I might be wrong), or somehow provide a means for JS to either fetch it, or to have access to a table full of usernames and associated display name (might be a bit too much like a security risk though. Hey kids, see if you can break into my server using one of these usernames!)
116,701
<p>What's the best way for a running C or C++ program that's been launched from the command line to put itself into the background, equivalent to if the user had launched from the unix shell with '&amp;' at the end of the command? (But the user didn't.) It's a GUI app and doesn't need any shell I/O, so there's no reason to tie up the shell after launch. But I want a shell command launch to be auto-backgrounded without the '&amp;' (or on Windows).</p> <p>Ideally, I want a solution that would work on any of Linux, OS X, and Windows. (Or separate solutions that I can select with #ifdef.) It's ok to assume that this should be done right at the beginning of execution, as opposed to somewhere in the middle.</p> <p>One solution is to have the main program be a script that launches the real binary, carefully putting it into the background. But it seems unsatisfying to need these coupled shell/binary pairs.</p> <p>Another solution is to immediately launch <em>another</em> executed version (with 'system' or CreateProcess), with the same command line arguments, but putting the child in the background and then having the parent exit. But this seems clunky compared to the process putting <em>itself</em> into background.</p> <p><strong>Edited after a few answers</strong>: Yes, a fork() (or system(), or CreateProcess on Windows) is one way to sort of do this, that I hinted at in my original question. But all of these solutions make a SECOND process that is backgrounded, and then terminate the original process. I was wondering if there was a way to put the EXISTING process into the background. One difference is that if the app was launched from a script that recorded its process id (perhaps for later killing or other purpose), the newly forked or created process will have a different id and so will not be controllable by any launching script, if you see what I'm getting at.</p> <p><strong>Edit #2</strong>: </p> <p>fork() isn't a good solution for OS X, where the man page for 'fork' says that it's unsafe if certain frameworks or libraries are being used. I tried it, and my app complains loudly at runtime: "The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec()." </p> <p>I was intrigued by daemon(), but when I tried it on OS X, it gave the same error message, so I assume that it's just a fancy wrapper for fork() and has the same restrictions.</p> <p>Excuse the OS X centrism, it just happens to be the system in front of me at the moment. But I am indeed looking for a solution to all three platforms.</p>
[ { "answer_id": 116709, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 3, "selected": false, "text": "<p>The way it's typically done on Unix-like OSes is to fork() at the beginning and exit from the parent. This won't work on Windows, but is much more elegant than launching another process where forking exists.</p>\n" }, { "answer_id": 116720, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 0, "selected": false, "text": "<p>The most common way of doing this under Linux is via <a href=\"http://en.wikipedia.org/wiki/Fork_(operating_system)\" rel=\"nofollow noreferrer\">forking</a>. The same should work on Mac, as for Windows I'm not 100% sure but I believe they have something similar. </p>\n\n<p>Basically what happens is the process splits itself into two processes, and then the original one exits (returning control to the shell or whatever), and the second process continues to run in the background.</p>\n" }, { "answer_id": 116752, "author": "Justin Rudd", "author_id": 12968, "author_profile": "https://Stackoverflow.com/users/12968", "pm_score": 1, "selected": false, "text": "<p>As others mentioned, fork() is how to do it on *nix. You can get fork() on Windows by using MingW or Cygwin libraries. But those will require you to switch to using GCC as your compiler.</p>\n\n<p>In pure Windows world, you'd use <a href=\"http://msdn.microsoft.com/en-us/library/ms682425.aspx\" rel=\"nofollow noreferrer\">CreateProcess</a> (or one of its derivatives CreateProcessAsUser, CreateProcessWithLogonW).</p>\n" }, { "answer_id": 116763, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>On UNIX, you need to fork twice in a row and let the parent die.</p>\n" }, { "answer_id": 116813, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 0, "selected": false, "text": "<p>I'm not sure about Windows, but on UNIX-like systems, you can <code>fork()</code> then <code>setsid()</code> the forked process to move it into a new process group that is not connected to a terminal.</p>\n" }, { "answer_id": 116814, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 3, "selected": false, "text": "<p>Three things need doing,</p>\n\n<pre><code>fork\nsetsid\nredirect STDIN, STDOUT and STDERR to /dev/null\n</code></pre>\n\n<p>This applies to POSIX systems (all the ones you mention claim to be POSIX (but Windows stops at the claiming bit))</p>\n" }, { "answer_id": 116833, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 0, "selected": false, "text": "<p>If you need a script to have the PID of the program, you can still get it after a fork.</p>\n\n<p>When you fork, save the PID of the child in the parent process. When you exit the parent process, either output the PID to <code>STD{OUT,ERR}</code> or simply have a <code>return pid;</code> statement at the end of <code>main()</code>. A calling script can then get the pid of the program, although it requires a certain knowledge of how the program works.</p>\n" }, { "answer_id": 116838, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 1, "selected": false, "text": "<p>The simplest form of backgrounding is:</p>\n\n<pre><code>if (fork() != 0) exit(0);\n</code></pre>\n\n<p>In Unix, if you want to background an disassociate from the tty completely, you would do:</p>\n\n<ol>\n<li>Close all descriptors which may access a tty (usually <code>0</code>, <code>1</code>, and <code>2</code>).</li>\n<li><code>if (fork() != 0) exit(0);</code></li>\n<li><code>setpgroup(0,getpid()); /* Might be necessary to prevent a SIGHUP on shell exit. */</code></li>\n<li><code>signal(SIGHUP,SIG_IGN); /* just in case, same as using nohup to launch program. */</code></li>\n<li><code>fd=open(\"/dev/tty\",O_RDWR);</code></li>\n<li><code>ioctl(fd,TIOCNOTTY,0); /* Disassociates from the terminal */</code></li>\n<li><code>close(fd);</code></li>\n<li><code>if (fork() != 0) exit(0); /* just for good measure */</code></li>\n</ol>\n\n<p>That should fully daemonize your program.</p>\n" }, { "answer_id": 116850, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 2, "selected": false, "text": "<p>To followup on your edited question:</p>\n\n<blockquote>\n <p>I was wondering if there was a way to put the EXISTING process into the background.</p>\n</blockquote>\n\n<p>In a Unix-like OS, there really is not a way to do this that I know of. The shell is blocked because it is executing one of the variants of a wait() call, waiting for the child process to exit. There is not a way for the child process to remain running but somehow cause the shell's wait() to return with a \"please stop watching me\" status. The reason you have the child fork and exit the original is so the shell will return from wait().</p>\n" }, { "answer_id": 116891, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 2, "selected": false, "text": "<p>Here is some pseudocode for Linux/UNIX:</p>\n\n<pre><code>initialization_code()\nif(failure) exit(1)\nif( fork() &gt; 0 ) exit(0)\nsetsid()\nsetup_signal_handlers()\nfor(fd=0; fd&lt;NOFILE; fd++) close(fd)\nopen(\"/dev/null\", O_RDONLY)\nopen(\"/dev/null\", O_WRONLY)\nopen(\"/dev/null\", o_WRONLY)\nchdir(\"/\")\n</code></pre>\n\n<p>And congratulations, your program continues as an independent \"daemonized\" process without a controlling TTY and without any standard input or output.</p>\n\n<p>Now, in Windows you simply build your program as a Win32 application with WinMain() instead of main(), and it runs without a console automatically. If you want to run as a service, you'll have to look that up because I've never written one and I don't really know how they work.</p>\n" }, { "answer_id": 116936, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 2, "selected": false, "text": "<p>A process cannot put itself into the background, because it isn't the one in charge of background vs. foreground. That would be the shell, which is waiting for process exit. If you launch a process with an ampersand \"&amp;\" at the end, then the shell does <em>not</em> wait for process exit.</p>\n\n<p>But the only way the process can escape the shell is to fork off another child and then let its original self exit back to the waiting shell.</p>\n\n<p>From the shell, you can background a process with Control-Z, then type \"bg\".</p>\n" }, { "answer_id": 116941, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "<p>Backgrounding a process is a shell function, not an OS function.</p>\n\n<p>If you want an app to start in the background, the typical trick is to write a shell script to launch it that launches it in the background.</p>\n\n<pre><code>#! /bin/sh\n/path/to/myGuiApplication &amp;\n</code></pre>\n" }, { "answer_id": 117105, "author": "Rob", "author_id": 18505, "author_profile": "https://Stackoverflow.com/users/18505", "pm_score": 0, "selected": false, "text": "<p>Under Windows, the closing thing you're going to get to fork() is loading your program as a Windows service, I think.</p>\n\n<p>Here is a link to an intro article on Windows services...\n<a href=\"http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx\" rel=\"nofollow noreferrer\">CodeProject: Simple Windows Service Sample</a></p>\n" }, { "answer_id": 117276, "author": "bstark", "author_id": 4056, "author_profile": "https://Stackoverflow.com/users/4056", "pm_score": 3, "selected": false, "text": "<p>On Linux, <a href=\"http://manpages.ubuntu.com/manpages/hardy/en/man3/daemon.html\" rel=\"noreferrer\">daemon()</a> is what you're looking for, if I understand you correctly.</p>\n" }, { "answer_id": 118081, "author": "Rodrigo Queiro", "author_id": 20330, "author_profile": "https://Stackoverflow.com/users/20330", "pm_score": 0, "selected": false, "text": "<p>So, as you say, just fork()ing will not do the trick. What you must do is fork() and then re-exec(), as this code sample does:</p>\n\n<pre><code>#include stdio.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;string.h&gt;\n\n#include &lt;CoreFoundation/CoreFoundation.h&gt;\n\nint main(int argc, char **argv)\n{\n int i, j;\n\n for (i=1; i&lt;argc; i++)\n if (strcmp(argv[i], \"--daemon\") == 0)\n {\n for (j = i+1; j&lt;argc; j++)\n argv[j-1] = argv[j];\n\n argv[argc - 1] = NULL;\n\n if (fork()) return 0;\n\n execv(argv[0], argv);\n\n return 0;\n }\n\n\n sleep(1);\n\n CFRunLoopRun();\n\n CFStringRef hello = CFSTR(\"Hello, world!\");\n\n printf(\"str: %s\\n\", CFStringGetCStringPtr(hello, CFStringGetFastestEncoding(hello)));\n\n return 0;\n}\n</code></pre>\n\n<p>The loop is to check for a --daemon argument, and if it is present, remove it before re-execing so an infinite loop is avoided.</p>\n\n<p>I don't think this will work if the binary is put into the path because argv[0] is not necessarily a full path, so it will need to be modified.</p>\n" }, { "answer_id": 118360, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 4, "selected": false, "text": "<p>My advice: <strong>don't do this</strong>, at least not under Linux/UNIX.</p>\n\n<p>GUI programs under Linux/UNIX traditionally do <em>not</em> auto-background themselves. While this may occasionally be annoying to newbies, it has a number of advantages:</p>\n\n<ul>\n<li><p>Makes it easy to capture standard error in case of core dumps / other problems that need debugging.</p></li>\n<li><p>Makes it easy for a shell script to run the program and wait until it's completed.</p></li>\n<li><p>Makes it easy for a shell script to run the program in the background and get its process id:</p>\n\n<pre><code>gui-program &amp;\npid=$!\n# do something with $pid later, such as check if the program is still running\n</code></pre>\n\n<p>If your program forks itself, this behavior will break.</p></li>\n</ul>\n\n<p>\"Scriptability\" is useful in so many unexpected circumstances, even with GUI programs, that I would hesitate to explicitly break these behaviors.</p>\n\n<p>Windows is another story. AFAIK, Windows programs automatically run in the background--even when invoked from a command shell--unless they explicitly request access to the command window.</p>\n" }, { "answer_id": 118701, "author": "andy", "author_id": 6152, "author_profile": "https://Stackoverflow.com/users/6152", "pm_score": 2, "selected": false, "text": "<p>You edited your question, but you may still be missing the point that your question is a syntax error of sorts -- if the process wasn't put in the background to begin with and you want the PID to stay the same, you can't ignore the fact that the program which started the process is waiting on that PID and that is pretty much the <b>definition</b> of being in the foreground.\n<p>\nI think you need to think about why you want to both put something in the background and keep the PID the same. I suggest you probably don't need both of those constraints.</p>\n" }, { "answer_id": 327579, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>/**Deamonize*/\n\npid_t pid;\npid = fork(); /**father makes a little deamon(son)*/\nif(pid&gt;0)\nexit(0); /**father dies*/\nwhile(1){\nprintf(\"Hello I'm your little deamon %d\\n\",pid); /**The child deamon goes on*/\nsleep(1)\n}\n\n/** try 'nohup' in linux(usage: nohup &lt;command&gt; &amp;) */\n</code></pre>\n" }, { "answer_id": 577482, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In Unix, I have learned to do that using <code>fork()</code>. \nIf you want to put a running process into the background, <code>fork</code> it twice.</p>\n" }, { "answer_id": 2506801, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I was trying the solution.</p>\n\n<p>Only one fork is needed from the parent process.</p>\n\n<p>The most important point is that, after fork, the parent process must die by calling <code>_exit(0);</code> and NOT by calling <code>exit(0);</code></p>\n\n<p>When <code>_exit(0);</code> is used, the command prompt immediately returns on the shell.</p>\n\n<p>This is the trick.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3832/" ]
What's the best way for a running C or C++ program that's been launched from the command line to put itself into the background, equivalent to if the user had launched from the unix shell with '&' at the end of the command? (But the user didn't.) It's a GUI app and doesn't need any shell I/O, so there's no reason to tie up the shell after launch. But I want a shell command launch to be auto-backgrounded without the '&' (or on Windows). Ideally, I want a solution that would work on any of Linux, OS X, and Windows. (Or separate solutions that I can select with #ifdef.) It's ok to assume that this should be done right at the beginning of execution, as opposed to somewhere in the middle. One solution is to have the main program be a script that launches the real binary, carefully putting it into the background. But it seems unsatisfying to need these coupled shell/binary pairs. Another solution is to immediately launch *another* executed version (with 'system' or CreateProcess), with the same command line arguments, but putting the child in the background and then having the parent exit. But this seems clunky compared to the process putting *itself* into background. **Edited after a few answers**: Yes, a fork() (or system(), or CreateProcess on Windows) is one way to sort of do this, that I hinted at in my original question. But all of these solutions make a SECOND process that is backgrounded, and then terminate the original process. I was wondering if there was a way to put the EXISTING process into the background. One difference is that if the app was launched from a script that recorded its process id (perhaps for later killing or other purpose), the newly forked or created process will have a different id and so will not be controllable by any launching script, if you see what I'm getting at. **Edit #2**: fork() isn't a good solution for OS X, where the man page for 'fork' says that it's unsafe if certain frameworks or libraries are being used. I tried it, and my app complains loudly at runtime: "The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec()." I was intrigued by daemon(), but when I tried it on OS X, it gave the same error message, so I assume that it's just a fancy wrapper for fork() and has the same restrictions. Excuse the OS X centrism, it just happens to be the system in front of me at the moment. But I am indeed looking for a solution to all three platforms.
My advice: **don't do this**, at least not under Linux/UNIX. GUI programs under Linux/UNIX traditionally do *not* auto-background themselves. While this may occasionally be annoying to newbies, it has a number of advantages: * Makes it easy to capture standard error in case of core dumps / other problems that need debugging. * Makes it easy for a shell script to run the program and wait until it's completed. * Makes it easy for a shell script to run the program in the background and get its process id: ``` gui-program & pid=$! # do something with $pid later, such as check if the program is still running ``` If your program forks itself, this behavior will break. "Scriptability" is useful in so many unexpected circumstances, even with GUI programs, that I would hesitate to explicitly break these behaviors. Windows is another story. AFAIK, Windows programs automatically run in the background--even when invoked from a command shell--unless they explicitly request access to the command window.
116,760
<p>I have a rather weak understanding of any of oracle's more advanced functionality but this should I think be possible.</p> <p>Say I have a table with the following schema:</p> <pre><code>MyTable Id INTEGER, Col1 VARCHAR2(100), Col2 VARCHAR2(100) </code></pre> <p>I would like to write an sproc with the following </p> <pre><code>PROCEDURE InsertOrUpdateMyTable(p_id in integer, p_col1 in varcahr2, p_col2 in varchar2) </code></pre> <p>Which, in the case of an update will, if the value in p_col1, p_col2 is null will not overwrite Col1, Col2 respectively</p> <p>So If I have a record:</p> <pre><code>id=123, Col1='ABC', Col2='DEF' exec InsertOrUpdateMyTable(123, 'XYZ', '098'); --results in id=123, Col1='XYZ', Col2='098' exec InsertOrUpdateMyTable(123, NULL, '098'); --results in id=123, Col1='ABC', Col2='098' exec InsertOrUpdateMyTable(123, NULL, NULL); --results in id=123, Col1='ABC', Col2='DEF' </code></pre> <p>Is there any simple way of doing this without having multiple SQL statements? </p> <p>I am thinking there might be a way to do this with the Merge statement though I am only mildly familiar with it.</p> <hr> <p><strong>EDIT:</strong> Cade Roux bellow suggests using COALESCE which works great! <a href="http://www.java2s.com/Code/Oracle/Conversion-Functions/COALESCEreturnsthefirstnonnullexpressionintheexpressionlist.htm" rel="nofollow noreferrer">Here are some examples of using the coalesce kewyord.</a> And here is the solution for my problem:</p> <pre><code>MERGE INTO MyTable mt USING (SELECT 1 FROM DUAL) a ON (mt.ID = p_id) WHEN MATCHED THEN UPDATE SET mt.Col1 = coalesce(p_col1, mt.Col1), mt.Col2 = coalesce(p_col2, mt.Col2) WHEN NOT MATCHED THEN INSERT (ID, Col1, Col2) VALUES (p_id, p_col1, p_col2); </code></pre>
[ { "answer_id": 116795, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": true, "text": "<p>Using MERGE and COALESCE? <a href=\"http://blogs.oracle.com/cmar/entry/using_merge_to_do_an\" rel=\"nofollow noreferrer\">Try this link for an example</a></p>\n\n<p>with</p>\n\n<pre><code>SET a.Col1 = COALESCE(incoming.Col1, a.Col1)\n ,a.Col2 = COALESCE(incoming.Col2, a.Col2)\n</code></pre>\n" }, { "answer_id": 116796, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 2, "selected": false, "text": "<p>Change the call or the update statement to use</p>\n\n<pre><code>nvl(newValue, oldValue)\n</code></pre>\n\n<p>for the new field value.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I have a rather weak understanding of any of oracle's more advanced functionality but this should I think be possible. Say I have a table with the following schema: ``` MyTable Id INTEGER, Col1 VARCHAR2(100), Col2 VARCHAR2(100) ``` I would like to write an sproc with the following ``` PROCEDURE InsertOrUpdateMyTable(p_id in integer, p_col1 in varcahr2, p_col2 in varchar2) ``` Which, in the case of an update will, if the value in p\_col1, p\_col2 is null will not overwrite Col1, Col2 respectively So If I have a record: ``` id=123, Col1='ABC', Col2='DEF' exec InsertOrUpdateMyTable(123, 'XYZ', '098'); --results in id=123, Col1='XYZ', Col2='098' exec InsertOrUpdateMyTable(123, NULL, '098'); --results in id=123, Col1='ABC', Col2='098' exec InsertOrUpdateMyTable(123, NULL, NULL); --results in id=123, Col1='ABC', Col2='DEF' ``` Is there any simple way of doing this without having multiple SQL statements? I am thinking there might be a way to do this with the Merge statement though I am only mildly familiar with it. --- **EDIT:** Cade Roux bellow suggests using COALESCE which works great! [Here are some examples of using the coalesce kewyord.](http://www.java2s.com/Code/Oracle/Conversion-Functions/COALESCEreturnsthefirstnonnullexpressionintheexpressionlist.htm) And here is the solution for my problem: ``` MERGE INTO MyTable mt USING (SELECT 1 FROM DUAL) a ON (mt.ID = p_id) WHEN MATCHED THEN UPDATE SET mt.Col1 = coalesce(p_col1, mt.Col1), mt.Col2 = coalesce(p_col2, mt.Col2) WHEN NOT MATCHED THEN INSERT (ID, Col1, Col2) VALUES (p_id, p_col1, p_col2); ```
Using MERGE and COALESCE? [Try this link for an example](http://blogs.oracle.com/cmar/entry/using_merge_to_do_an) with ``` SET a.Col1 = COALESCE(incoming.Col1, a.Col1) ,a.Col2 = COALESCE(incoming.Col2, a.Col2) ```
116,775
<p>I am adding custom controls to a FlowLayoutPanel. Each control has a date property. I would like to sort the controls in the flowlayoutpanel based on the date property. I can't presort the controls before I add them because it is possible for the user to add more.</p> <p>My current thought is when the ControlAdded event for the FlowLayoutPanel is triggered I loop through the controls and use the BringToFront function to order the controls based on the date. </p> <p>What is the best way to do this?</p>
[ { "answer_id": 117227, "author": "Andrew Queisser", "author_id": 18321, "author_profile": "https://Stackoverflow.com/users/18321", "pm_score": 0, "selected": false, "text": "<p>BringToFront affects the z-order not the x/y position, I suspect you want to sort the FlowLayoutPanel.Controls collection when someone adds or deletes controls in the panel. Probably use SuspendLayout and ResumeLayout around the sorting code.</p>\n" }, { "answer_id": 117766, "author": "wusher", "author_id": 1632, "author_profile": "https://Stackoverflow.com/users/1632", "pm_score": 3, "selected": true, "text": "<p>I doubt this is the best but is what I have so far:</p>\n\n<pre><code> SortedList&lt;DateTime,Control&gt; sl = new SortedList&lt;DateTime,Control&gt;();\n foreach (Control i in mainContent.Controls)\n {\n if (i.GetType().BaseType == typeof(MyBaseType))\n {\n MyBaseType iTyped = (MyBaseType)i;\n sl.Add(iTyped.Date, iTyped);\n }\n }\n\n\n foreach (MyBaseType j in sl.Values)\n {\n j.SendToBack();\n }\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
I am adding custom controls to a FlowLayoutPanel. Each control has a date property. I would like to sort the controls in the flowlayoutpanel based on the date property. I can't presort the controls before I add them because it is possible for the user to add more. My current thought is when the ControlAdded event for the FlowLayoutPanel is triggered I loop through the controls and use the BringToFront function to order the controls based on the date. What is the best way to do this?
I doubt this is the best but is what I have so far: ``` SortedList<DateTime,Control> sl = new SortedList<DateTime,Control>(); foreach (Control i in mainContent.Controls) { if (i.GetType().BaseType == typeof(MyBaseType)) { MyBaseType iTyped = (MyBaseType)i; sl.Add(iTyped.Date, iTyped); } } foreach (MyBaseType j in sl.Values) { j.SendToBack(); } ```
116,797
<p>I have an int array as a property of a Web User Control. I'd like to set that property inline if possible using the following syntax:</p> <pre><code>&lt;uc1:mycontrol runat="server" myintarray="1,2,3" /&gt; </code></pre> <p>This will fail at runtime because it will be expecting an actual int array, but a string is being passed instead. I can make <code>myintarray</code> a string and parse it in the setter, but I was wondering if there was a more elegant solution.</p>
[ { "answer_id": 116940, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 2, "selected": false, "text": "<p>Have you tried looking into Type Converters? This page looks worth a look: <a href=\"http://www.codeguru.com/columns/VB/article.php/c6529/\" rel=\"nofollow noreferrer\">http://www.codeguru.com/columns/VB/article.php/c6529/</a></p>\n\n<p>Also, Spring.Net seems to have a StringArrayConverter (<a href=\"http://www.springframework.net/doc-latest/reference/html/objects-misc.html\" rel=\"nofollow noreferrer\">http://www.springframework.net/doc-latest/reference/html/objects-misc.html</a> - section 6.4) which, if you can feed it to ASP.net by decorating the property with a TypeConverter attribute, might work..</p>\n" }, { "answer_id": 116953, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 3, "selected": false, "text": "<p>Seems to me that the logical&mdash;and more extensible&mdash;approach is to take a page from the <code>asp:</code> list controls:</p>\n\n<pre><code>&lt;uc1:mycontrol runat=\"server\"&gt;\n &lt;uc1:myintparam&gt;1&lt;/uc1:myintparam&gt;\n &lt;uc1:myintparam&gt;2&lt;/uc1:myintparam&gt;\n &lt;uc1:myintparam&gt;3&lt;/uc1:myintparam&gt;\n&lt;/uc1:mycontrol&gt;\n</code></pre>\n" }, { "answer_id": 116977, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 0, "selected": false, "text": "<p>Do do what Bill was talking about with the list you just need to create a List property on your user control. Then you can implement it as Bill described.</p>\n" }, { "answer_id": 117027, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 0, "selected": false, "text": "<p>You could add to the page events inside the aspx something like this:</p>\n\n<pre><code>&lt;script runat=\"server\"&gt;\nprotected void Page_Load(object sender, EventArgs e)\n{\n YourUserControlID.myintarray = new Int32[] { 1, 2, 3 };\n}\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 117054, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 1, "selected": false, "text": "<p>To add child elements that make your list you need to have your control setup a certain way:</p>\n\n<pre><code>[ParseChildren(true, \"Actions\")]\n[PersistChildren(false)]\n[ToolboxData(\"&lt;{0}:PageActionManager runat=\\\"server\\\" &gt;&lt;/PageActionManager&gt;\")]\n[NonVisualControl]\npublic class PageActionManager : Control\n{\n</code></pre>\n\n<p>The Actions above is the name of the cproperty the child elements will be in. I use an ArrayList, as I have not testing anything else with it.:</p>\n\n<pre><code> private ArrayList _actions = new ArrayList();\n public ArrayList Actions\n {\n get\n {\n return _actions;\n }\n }\n</code></pre>\n\n<p>when your contorl is initialized it will have the values of the child elements. Those you can make a mini class that just holds ints.</p>\n" }, { "answer_id": 117122, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 5, "selected": true, "text": "<p>Implement a type converter, here is one, warning : quick&amp;dirty, not for production use, etc :</p>\n\n<pre><code>public class IntArrayConverter : System.ComponentModel.TypeConverter\n{\n public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType)\n {\n return sourceType == typeof(string);\n }\n public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)\n {\n string val = value as string;\n string[] vals = val.Split(',');\n System.Collections.Generic.List&lt;int&gt; ints = new System.Collections.Generic.List&lt;int&gt;();\n foreach (string s in vals)\n ints.Add(Convert.ToInt32(s));\n return ints.ToArray();\n }\n}\n</code></pre>\n\n<p>and tag the property of your control :</p>\n\n<pre><code>private int[] ints;\n[TypeConverter(typeof(IntsConverter))]\npublic int[] Ints\n{\n get { return this.ints; }\n set { this.ints = value; }\n}\n</code></pre>\n" }, { "answer_id": 117254, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can implement a type converter class that converts between int array and string data types.\nThen decorate your int array property with the TypeConverterAttribute, specifying the class that you implemented. Visual Studio will then use your type converter for type conversions on your property.</p>\n" }, { "answer_id": 117522, "author": "ern", "author_id": 5609, "author_profile": "https://Stackoverflow.com/users/5609", "pm_score": 3, "selected": false, "text": "<p>@mathieu, thanks so much for your code. I modified it somewhat in order to compile:</p>\n\n<pre><code>public class IntArrayConverter : System.ComponentModel.TypeConverter\n{\n public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType)\n {\n return sourceType == typeof(string);\n }\n public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)\n {\n string val = value as string;\n string[] vals = val.Split(',');\n System.Collections.Generic.List&lt;int&gt; ints = new System.Collections.Generic.List&lt;int&gt;();\n foreach (string s in vals)\n ints.Add(Convert.ToInt32(s));\n return ints.ToArray();\n }\n}\n</code></pre>\n" }, { "answer_id": 1782648, "author": "Dgc", "author_id": 216960, "author_profile": "https://Stackoverflow.com/users/216960", "pm_score": 2, "selected": false, "text": "<p>You could also do something like this:</p>\n\n<pre><code>namespace InternalArray\n{\n /// &lt;summary&gt;\n /// Item for setting value specifically\n /// &lt;/summary&gt;\n\n public class ArrayItem\n {\n public int Value { get; set; }\n }\n\n public class CustomUserControl : UserControl\n {\n\n private List&lt;int&gt; Ints {get {return this.ItemsToList();}\n /// &lt;summary&gt;\n /// set our values explicitly\n /// &lt;/summary&gt;\n [PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(List&lt;ArrayItem&gt;))]\n public List&lt;ArrayItem&gt; Values { get; set; }\n\n /// &lt;summary&gt;\n /// Converts our ArrayItem into a List&lt;int&gt; \n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private List&lt;int&gt; ItemsToList()\n {\n return (from q in this.Values\n select q.Value).ToList&lt;int&gt;();\n }\n }\n}\n</code></pre>\n\n<p>which will result in:</p>\n\n<pre><code>&lt;xx:CustomUserControl runat=\"server\"&gt;\n &lt;Values&gt;\n &lt;xx:ArrayItem Value=\"1\" /&gt;\n &lt;/Values&gt;\n&lt;/xx:CustomUserControl&gt;\n</code></pre>\n" }, { "answer_id": 9399322, "author": "spleenboy", "author_id": 1226421, "author_profile": "https://Stackoverflow.com/users/1226421", "pm_score": 2, "selected": false, "text": "<p>Great snippet @mathieu. I needed to use this for converting longs, but rather than making a LongArrayConverter, I wrote up a version that uses Generics.</p>\n\n<pre><code>public class ArrayConverter&lt;T&gt; : TypeConverter\n{\n public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)\n {\n return sourceType == typeof(string);\n }\n\n public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)\n {\n string val = value as string;\n if (string.IsNullOrEmpty(val))\n return new T[0];\n\n string[] vals = val.Split(',');\n List&lt;T&gt; items = new List&lt;T&gt;();\n Type type = typeof(T);\n foreach (string s in vals)\n {\n T item = (T)Convert.ChangeType(s, type);\n items.Add(item);\n }\n return items.ToArray();\n }\n}\n</code></pre>\n\n<p>This version should work with any type that is convertible from string.</p>\n\n<pre><code>[TypeConverter(typeof(ArrayConverter&lt;int&gt;))]\npublic int[] Ints { get; set; }\n\n[TypeConverter(typeof(ArrayConverter&lt;long&gt;))]\npublic long[] Longs { get; set; }\n\n[TypeConverter(typeof(ArrayConverter&lt;DateTime))]\npublic DateTime[] DateTimes { get; set; }\n</code></pre>\n" }, { "answer_id": 63563015, "author": "Protector one", "author_id": 125938, "author_profile": "https://Stackoverflow.com/users/125938", "pm_score": 0, "selected": false, "text": "<p>If you use DataBinding on one of the parent Controls, you can use a DataBinding Expression:</p>\n<pre><code>&lt;uc1:mycontrol runat=&quot;server&quot; myintarray=&quot;&lt;%# new [] {1, 2, 3} %&gt;&quot; /&gt;\n</code></pre>\n<p>With a custom expression builder, you can do something similar. The expression builder:</p>\n<pre><code>[ExpressionPrefix(&quot;Code&quot;)]\npublic class CodeExpressionBuilder : ExpressionBuilder\n{\n public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)\n {\n return new CodeSnippetExpression(entry.Expression.Trim());\n }\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>&lt;uc1:mycontrol runat=&quot;server&quot; myintarray=&quot;&lt;%$ Code: new [] {1, 2, 3} %&gt;&quot; /&gt;\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5609/" ]
I have an int array as a property of a Web User Control. I'd like to set that property inline if possible using the following syntax: ``` <uc1:mycontrol runat="server" myintarray="1,2,3" /> ``` This will fail at runtime because it will be expecting an actual int array, but a string is being passed instead. I can make `myintarray` a string and parse it in the setter, but I was wondering if there was a more elegant solution.
Implement a type converter, here is one, warning : quick&dirty, not for production use, etc : ``` public class IntArrayConverter : System.ComponentModel.TypeConverter { public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { string val = value as string; string[] vals = val.Split(','); System.Collections.Generic.List<int> ints = new System.Collections.Generic.List<int>(); foreach (string s in vals) ints.Add(Convert.ToInt32(s)); return ints.ToArray(); } } ``` and tag the property of your control : ``` private int[] ints; [TypeConverter(typeof(IntsConverter))] public int[] Ints { get { return this.ints; } set { this.ints = value; } } ```
116,810
<p>I'm auditing our existing web application, which makes heavy use of <a href="http://www.w3schools.com/HTML/html_frames.asp" rel="nofollow noreferrer">HTML frames</a>. I would like to download all of the HTML in each frame, is there a method of doing this with <a href="http://www.gnu.org/software/wget/" rel="nofollow noreferrer">wget</a> or a little bit of scripting?</p>
[ { "answer_id": 116849, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 1, "selected": false, "text": "<pre><code>wget --recursive --domains=www.mysite.com http://www.mysite.com\n</code></pre>\n\n<p>Which indicates a recursive crawl should also traverse into frames and iframes. Be careful to limit the scope of recursion only to your web site since you probably don't want to crawl the whole web.</p>\n" }, { "answer_id": 116863, "author": "JustinD", "author_id": 12063, "author_profile": "https://Stackoverflow.com/users/12063", "pm_score": 4, "selected": true, "text": "<p>as an addition to Steve's answer:</p>\n\n<p>Span to any host—‘-H’</p>\n\n<p>The ‘-H’ option turns on host spanning, thus allowing Wget's recursive run to visit any host referenced by a link. Unless sufficient recursion-limiting criteria are applied depth, these foreign hosts will typically link to yet more hosts, and so on until Wget ends up sucking up much more data than you have intended. </p>\n\n<p>Limit spanning to certain domains—‘-D’</p>\n\n<p>The ‘-D’ option allows you to specify the domains that will be followed, thus limiting the recursion only to the hosts that belong to these domains. Obviously, this makes sense only in conjunction with ‘-H’. </p>\n\n<p>A typical example would be downloading the contents of ‘www.server.com’, but allowing downloads from ‘images.server.com’, etc.:</p>\n\n<pre><code> wget -rH -Dserver.com http://www.server.com/\n</code></pre>\n\n<p>You can specify more than one address by separating them with a comma, </p>\n\n<p>e.g. ‘-Ddomain1.com,domain2.com’. </p>\n\n<p>taken from: <a href=\"http://www.gnu.org/software/wget/manual/html_node/Spanning-Hosts.html#Spanning-Hosts\" rel=\"noreferrer\">wget manual</a></p>\n" }, { "answer_id": 116915, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 1, "selected": false, "text": "<p>wget has a -r option to make it recursive, try <strong>wget -r -l1</strong> (in case the font makes it hard to read: that last part is a lower case L followed by a number one)\nThe -l1 part tells it to recurse to a maximum depth of 1. Try playing with this number to scrape more.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302/" ]
I'm auditing our existing web application, which makes heavy use of [HTML frames](http://www.w3schools.com/HTML/html_frames.asp). I would like to download all of the HTML in each frame, is there a method of doing this with [wget](http://www.gnu.org/software/wget/) or a little bit of scripting?
as an addition to Steve's answer: Span to any host—‘-H’ The ‘-H’ option turns on host spanning, thus allowing Wget's recursive run to visit any host referenced by a link. Unless sufficient recursion-limiting criteria are applied depth, these foreign hosts will typically link to yet more hosts, and so on until Wget ends up sucking up much more data than you have intended. Limit spanning to certain domains—‘-D’ The ‘-D’ option allows you to specify the domains that will be followed, thus limiting the recursion only to the hosts that belong to these domains. Obviously, this makes sense only in conjunction with ‘-H’. A typical example would be downloading the contents of ‘www.server.com’, but allowing downloads from ‘images.server.com’, etc.: ``` wget -rH -Dserver.com http://www.server.com/ ``` You can specify more than one address by separating them with a comma, e.g. ‘-Ddomain1.com,domain2.com’. taken from: [wget manual](http://www.gnu.org/software/wget/manual/html_node/Spanning-Hosts.html#Spanning-Hosts)
116,819
<p>I want an expression that will fail when it encounters words such as "boon.ini" and "http". The goal would be to take this expression and be able to construct for any set of keywords.</p>
[ { "answer_id": 116862, "author": "Justin Poliey", "author_id": 6967, "author_profile": "https://Stackoverflow.com/users/6967", "pm_score": 4, "selected": false, "text": "<p>Rather than negating the result within the expression, you should do it in your code. That way, the expression becomes pretty simple.</p>\n\n<pre><code>\\b(boon\\.ini|http)\\b\n</code></pre>\n\n<p>Would return <code>true</code> if boon.ini or http was anywhere in your string. It won't match words like httpd or httpxyzzy because of the <code>\\b</code>, or word boundaries. If you want, you could just remove them and it will match those too. To add more keywords, just add more pipes.</p>\n\n<pre><code>\\b(boon\\.ini|http|foo|bar)\\b\n</code></pre>\n" }, { "answer_id": 116864, "author": "Tim Pietzcker", "author_id": 20670, "author_profile": "https://Stackoverflow.com/users/20670", "pm_score": 7, "selected": true, "text": "<pre><code>^(?:(?!boon\\.ini|http).)*$\\r?\\n?\n</code></pre>\n\n<p>(taken from <a href=\"http://www.regexbuddy.com\" rel=\"noreferrer\">RegexBuddy</a>'s library) will match any line that does not contain boon.ini and/or http. Is that what you wanted?</p>\n" }, { "answer_id": 116883, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 2, "selected": false, "text": "<p>you might be well served by writing a regex that will <em>succeed</em> when it encounters the words you're looking for, and then invert the condition.</p>\n\n<p>For instance, in perl you'd use:</p>\n\n<pre><code>if (!/boon\\.ini|http/) {\n # the string passed!\n}\n</code></pre>\n" }, { "answer_id": 116964, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 1, "selected": false, "text": "<p>Which language/regexp library? I thought you question was around ASP.NET in which case you can see the \"negative lookhead\" section of this article:\n<a href=\"http://msdn.microsoft.com/en-us/library/ms972966.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms972966.aspx</a></p>\n\n<p>Strictly speaking negation of a regular expression, still defines a regular language but there are very few libraries/languages/tool that allow to express it.</p>\n\n<p>Negative lookahed may serve you the same but the actual syntax depends on what you are using. Tim's answer is an example with <code>(?...)</code></p>\n" }, { "answer_id": 831989, "author": "Tim", "author_id": 102510, "author_profile": "https://Stackoverflow.com/users/102510", "pm_score": 4, "selected": false, "text": "<p>An alternative expression that could be used:</p>\n\n<pre><code>^(?!.*IgnoreMe).*$\n</code></pre>\n\n<p><code>^</code> = indicates start of line <br/>\n<code>$</code> = indicates the end of the line <br/>\n<code>(?! Expression)</code> = indicates zero width look ahead negative match on the expression</p>\n\n<p>The <code>^</code> at the front is needed, otherwise when evaluated the negative look ahead could start from somewhere within/beyond the 'IgnoreMe' text - and make a match where you don't want it too.</p>\n\n<p>e.g. If you use the regex: </p>\n\n<pre><code>(?!.*IgnoreMe).*$\n</code></pre>\n\n<p>With the input \"Hello IgnoreMe Please\", this will will result in something like: \"gnoreMe Please\" as the negative look ahead finds that there is no complete string 'IgnoreMe' after the 'I'.</p>\n" }, { "answer_id": 2798285, "author": "Manikandan", "author_id": 336704, "author_profile": "https://Stackoverflow.com/users/336704", "pm_score": 2, "selected": false, "text": "<pre><code>^[^£]*$\n</code></pre>\n\n<p>The above expression will restrict only the pound symbol from the string. This will allow all characters except string.</p>\n" }, { "answer_id": 19641987, "author": "Jon Kern", "author_id": 344720, "author_profile": "https://Stackoverflow.com/users/344720", "pm_score": 0, "selected": false, "text": "<p>I used this (based on Tim Pietzcker answer) to exclude non-production subdomain URLs for Google Analytics profile filters:</p>\n\n<pre><code>^\\w+-*\\w*\\.(?!(?:alpha(123)*\\.|beta(123)*\\.|preprod\\.)domain\\.com).*$\n</code></pre>\n\n<p>You can see the context here: <a href=\"http://technicaldebt.com/?p=1496\" rel=\"nofollow\">Regex to Exclude Multiple Words</a></p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19161/" ]
I want an expression that will fail when it encounters words such as "boon.ini" and "http". The goal would be to take this expression and be able to construct for any set of keywords.
``` ^(?:(?!boon\.ini|http).)*$\r?\n? ``` (taken from [RegexBuddy](http://www.regexbuddy.com)'s library) will match any line that does not contain boon.ini and/or http. Is that what you wanted?
116,824
<p>Whats the most efficient way of selecting total number of records from a large table? Currently, Im simply doing</p> <pre><code>$result = mysql_query("SELECT id FROM table"); $total = mysql_num_rows($result) </code></pre> <p>I was told this was not very efficient or fast, if you have a lot of records in the table. </p>
[ { "answer_id": 116829, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 3, "selected": false, "text": "<p>You should use <a href=\"http://dev.mysql.com/doc/refman/5.0/en/counting-rows.html\" rel=\"nofollow noreferrer\">SQL's built in COUNT function</a>:</p>\n\n<pre><code>$result = mysql_query(\"SELECT COUNT(id) FROM table\");\n</code></pre>\n" }, { "answer_id": 116840, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 6, "selected": true, "text": "<p>You were told correctly. mysql can do this count for you which is much more efficient.</p>\n\n<pre><code>$result = mysql_query( \"select count(id) as num_rows from table\" );\n$row = mysql_fetch_object( $result );\n$total = $row-&gt;num_rows;\n</code></pre>\n" }, { "answer_id": 116858, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>What about something like this:</p>\n\n<pre><code>$result = mysql_query(\"SELECT COUNT(id) AS total_things from table\");\n$row = mysql_fetch_array($result,MYSQL_ASSOC);\n$num_results = $row[\"total_things\"];\n</code></pre>\n" }, { "answer_id": 116867, "author": "VoxPelli", "author_id": 20667, "author_profile": "https://Stackoverflow.com/users/20667", "pm_score": 2, "selected": false, "text": "<p>According to the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_count\" rel=\"nofollow noreferrer\">MySQL documentation</a> this is most efficient if you're using a MyISAM table (which is the most usual type of tables used):</p>\n\n<pre><code>$result = mysql_query(\"SELECT COUNT(*) FROM table\");\n</code></pre>\n\n<p>Otherwise you should do as Wayne stated and be sure that the counted column is indexed.</p>\n" }, { "answer_id": 117024, "author": "Jonathan", "author_id": 19272, "author_profile": "https://Stackoverflow.com/users/19272", "pm_score": 2, "selected": false, "text": "<p>Can I just add, that the most \"efficient\" way of getting the total number of records, particularly in a large table, is to save the total amount as a number in another table.\nThat way, you don't have to query the entire table everytime you want to get the total.</p>\n\n<p>You will however, have to set up some code or Triggers in the database to increase or decrease that number when a row is added/deleted.</p>\n\n<p>So its not the easiest way, but if your website grows, you should definitely consider doing that.</p>\n" }, { "answer_id": 117315, "author": "skoob", "author_id": 20708, "author_profile": "https://Stackoverflow.com/users/20708", "pm_score": 2, "selected": false, "text": "<p><strong>MyISAM tables already store the row count</strong></p>\n\n<pre><code>SELECT COUNT(*) FROM table\n</code></pre>\n\n<p>on a MyISAM table simply reads that value. It doesn't scan the table or the index(es). So, it's just as fast or faster than reading the value from a different table.</p>\n" }, { "answer_id": 187759, "author": "Annika Backstrom", "author_id": 7675, "author_profile": "https://Stackoverflow.com/users/7675", "pm_score": 0, "selected": false, "text": "<p>Just wanted to note that <code>SHOW TABLE STATUS</code> returns a <code>Rows</code> column, though I can't speak to its efficiency. Some light Googling turns up reports of slowness in MySQL 4 over two years ago. Might make for interesting time trials.</p>\n\n<p>Also note the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/show-table-status.html\" rel=\"nofollow noreferrer\">InnoDB caveat</a> regarding inaccurate counts.</p>\n" }, { "answer_id": 10861793, "author": "Leon", "author_id": 1432316, "author_profile": "https://Stackoverflow.com/users/1432316", "pm_score": 2, "selected": false, "text": "<p>Even though I agree to use the built-in functions, I don't really see any performance difference between mysql_num_rows and count(id). For 25000 results, same performance (can say exact.) Just for the record.</p>\n" }, { "answer_id": 34766624, "author": "Divakarcool", "author_id": 3797574, "author_profile": "https://Stackoverflow.com/users/3797574", "pm_score": 0, "selected": false, "text": "<p>Use aggregate function. Try the below SQL Command</p>\n\n<pre><code>$num= mysql_query(\"SELECT COUNT(id) FROM $table\");\n</code></pre>\n" }, { "answer_id": 43727050, "author": "Apostolos", "author_id": 5615873, "author_profile": "https://Stackoverflow.com/users/5615873", "pm_score": 0, "selected": false, "text": "<p>mysqli_query() is deprecated. Better use this:</p>\n\n<pre><code>$result = $dbh-&gt;query(\"SELECT id FROM {table_name}\");\n$total = $result-&gt;num_rows;\n</code></pre>\n\n<p>Using PDO:</p>\n\n<pre><code>$result = $dbh-&gt;query(\"SELECT id FROM {table_name}\");\n$total = $result-&gt;rowCount();\n</code></pre>\n\n<p>(where '$dbh' = handle of the db connected to)</p>\n" }, { "answer_id": 68963111, "author": "kurdtpage", "author_id": 600852, "author_profile": "https://Stackoverflow.com/users/600852", "pm_score": 0, "selected": false, "text": "<p>I had a large table (&gt;50 million rows) and it took a long time to count the primary key, so I use the following:</p>\n<pre><code>SELECT TABLE_NAME, TABLE_ROWS\nFROM information_schema.tables\nWHERE TABLE_SCHEMA = &quot;database&quot;;\n</code></pre>\n<p>Replace database with the name of your schema.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Whats the most efficient way of selecting total number of records from a large table? Currently, Im simply doing ``` $result = mysql_query("SELECT id FROM table"); $total = mysql_num_rows($result) ``` I was told this was not very efficient or fast, if you have a lot of records in the table.
You were told correctly. mysql can do this count for you which is much more efficient. ``` $result = mysql_query( "select count(id) as num_rows from table" ); $row = mysql_fetch_object( $result ); $total = $row->num_rows; ```
116,830
<p>In Java, one can declare a variable parameterised by an "unknown" generic type, which looks like this:</p> <pre><code>Foo&lt;?&gt; x; </code></pre> <p>Is there an equivalent construct to this question-mark, in C#?</p>
[ { "answer_id": 116870, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 2, "selected": false, "text": "<p>No, there isn't really the same concept in C#. You would need to refer to a base class of Foo (maybe a non-generic Foo), or make the method you're working in generic itself (so that you can refer to Foo, and let the caller of your method determine what T is).</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 116877, "author": "Compile This", "author_id": 4048, "author_profile": "https://Stackoverflow.com/users/4048", "pm_score": 3, "selected": false, "text": "<p>There isn't an equivalent syntax in C#.</p>\n" }, { "answer_id": 116881, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": false, "text": "<p>AFAIK you can not do that in C#. What the BCL does and there are plenties of examples there is to create a class that is not generic and then create a generic class that inherits the base behavior from the previous one. See example below.</p>\n\n<pre><code>class Foo\n{\n}\n\nclass Foo&lt;T&gt; : Foo\n{\n}\n</code></pre>\n\n<p>The you can write something like this:</p>\n\n<pre><code>Foo t = new Foo&lt;int&gt;();\n</code></pre>\n" }, { "answer_id": 116948, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 6, "selected": true, "text": "<p>The short answer is no. There isn't an equivalent feature in C#.</p>\n\n<p>A workaround, from <a href=\"http://www.25hoursaday.com/CsharpVsJava.html#generics\" rel=\"noreferrer\">C# from a Java developer's perspective</a> by Dare Obasanjo:</p>\n\n<p>In certain cases, one may need create a method that can operate on data structures containing any type as opposed to those that contain a specific type (e.g. a method to print all the objects in a data structure) while still taking advantage of the benefits of strong typing in generics. The mechanism for specifying this in C# is via a feature called generic type inferencing while in Java this is done using wildcard types. The following code samples show how both approaches lead to the same result.</p>\n\n<p>C# Code</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic; \n\nclass Test{\n\n //Prints the contents of any generic Stack by \n //using generic type inference \n public static void PrintStackContents&lt;T&gt;(Stack&lt;T&gt; s){\n while(s.Count != 0){\n Console.WriteLine(s.Pop()); \n } \n }\n\n public static void Main(String[] args){\n\n Stack&lt;int&gt; s2 = new Stack&lt;int&gt;(); \n s2.Push(4); \n s2.Push(5); \n s2.Push(6); \n\n PrintStackContents(s2); \n\n Stack&lt;string&gt; s1 = new Stack&lt;string&gt;(); \n s1.Push(\"One\"); \n s1.Push(\"Two\"); \n s1.Push(\"Three\"); \n\n PrintStackContents(s1); \n }\n}\n</code></pre>\n\n<p>Java Code</p>\n\n<pre><code>import java.util.*; \n\nclass Test{\n\n //Prints the contents of any generic Stack by \n //specifying wildcard type \n public static void PrintStackContents(Stack&lt;?&gt; s){\n while(!s.empty()){\n System.out.println(s.pop()); \n }\n }\n\n public static void main(String[] args){\n\n Stack &lt;Integer&gt; s2 = new Stack &lt;Integer&gt;(); \n s2.push(4); \n s2.push(5); \n s2.push(6); \n\n PrintStackContents(s2); \n\n Stack&lt;String&gt; s1 = new Stack&lt;String&gt;(); \n s1.push(\"One\"); \n s1.push(\"Two\"); \n s1.push(\"Three\"); \n\n PrintStackContents(s1); \n }\n}\n</code></pre>\n" }, { "answer_id": 117000, "author": "Doug McClean", "author_id": 11173, "author_profile": "https://Stackoverflow.com/users/11173", "pm_score": 3, "selected": false, "text": "<p>It isn't (quite) true that there is no equivalent in C#. There is no static equivalent that you can use as a type, or call methods on, true enough. For that, use <a href=\"https://stackoverflow.com/questions/116830/is-there-an-anonymous-generic-tag-in-c-like-in-java#116881\">Jorge's answer</a>.</p>\n\n<p>On the other hand, sometimes you need the equivalent idea for reflection, and there is an equivalent there. If you have:</p>\n\n<pre><code>interface IFoo&lt;T&gt;\n{\n T Bar(T t, int n);\n}\n</code></pre>\n\n<p>you can get a <code>Type</code> that represents <code>IFoo&lt;int&gt;</code> using <code>typeof(IFoo&lt;int&gt;)</code>. Less well known, and a partial answer to your question, is that you can also get a <code>Type</code> that represents <code>IFoo&lt;T&gt;</code> using <code>typeof(IFoo&lt;&gt;)</code>.</p>\n\n<p>This is useful when you want to use <code>IFoo&lt;T&gt;</code> for some <code>T</code> through reflection and won't know <code>T</code> until runtime.</p>\n\n<pre><code>Type theInterface = typeof(IFoo&lt;&gt;);\nType theSpecificInterface = theInterface.MakeGenericType(typeof(string));\n\n// theSpecificInterface now holds IFoo&lt;string&gt; even though we may not have known we wanted to use string until runtime\n\n// proceed with reflection as normal, make late bound calls / constructions, emit DynamicMethod code, etc.\n</code></pre>\n" }, { "answer_id": 11358440, "author": "Dani", "author_id": 785529, "author_profile": "https://Stackoverflow.com/users/785529", "pm_score": 4, "selected": false, "text": "<p>While admittedly being not the clean approach, using <code>Foo&lt;object&gt; x</code> may also be suitable.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14113/" ]
In Java, one can declare a variable parameterised by an "unknown" generic type, which looks like this: ``` Foo<?> x; ``` Is there an equivalent construct to this question-mark, in C#?
The short answer is no. There isn't an equivalent feature in C#. A workaround, from [C# from a Java developer's perspective](http://www.25hoursaday.com/CsharpVsJava.html#generics) by Dare Obasanjo: In certain cases, one may need create a method that can operate on data structures containing any type as opposed to those that contain a specific type (e.g. a method to print all the objects in a data structure) while still taking advantage of the benefits of strong typing in generics. The mechanism for specifying this in C# is via a feature called generic type inferencing while in Java this is done using wildcard types. The following code samples show how both approaches lead to the same result. C# Code ``` using System; using System.Collections; using System.Collections.Generic; class Test{ //Prints the contents of any generic Stack by //using generic type inference public static void PrintStackContents<T>(Stack<T> s){ while(s.Count != 0){ Console.WriteLine(s.Pop()); } } public static void Main(String[] args){ Stack<int> s2 = new Stack<int>(); s2.Push(4); s2.Push(5); s2.Push(6); PrintStackContents(s2); Stack<string> s1 = new Stack<string>(); s1.Push("One"); s1.Push("Two"); s1.Push("Three"); PrintStackContents(s1); } } ``` Java Code ``` import java.util.*; class Test{ //Prints the contents of any generic Stack by //specifying wildcard type public static void PrintStackContents(Stack<?> s){ while(!s.empty()){ System.out.println(s.pop()); } } public static void main(String[] args){ Stack <Integer> s2 = new Stack <Integer>(); s2.push(4); s2.push(5); s2.push(6); PrintStackContents(s2); Stack<String> s1 = new Stack<String>(); s1.push("One"); s1.push("Two"); s1.push("Three"); PrintStackContents(s1); } } ```
116,869
<p>I know this is a dumb question. For some reason my mind is blank on this. Any ideas?</p> <p>Sorry should have been more clear. </p> <p>Using a <code>HtmlGenericControl</code> to pull in link description as well as image. </p> <pre><code> private void InternalCreateChildControls() { if (this.DataItem != null &amp;&amp; this.Relationships.Count &gt; 0) { HtmlGenericControl fieldset = new HtmlGenericControl("fieldset"); this.Controls.Add(fieldset); HtmlGenericControl legend = new HtmlGenericControl("legend"); legend.InnerText = this.Caption; fieldset.Controls.Add(legend); HtmlGenericControl listControl = new HtmlGenericControl("ul"); fieldset.Controls.Add(listControl); for (int i = 0; i &lt; this.Relationships.Count; i++) { CatalogRelationshipsDataSet.CatalogRelationship relationship = this.Relationships[i]; HtmlGenericControl listItem = new HtmlGenericControl("li"); listControl.Controls.Add(listItem); RelatedItemsContainer container = new RelatedItemsContainer(relationship); listItem.Controls.Add(container); Image Image = new Image(); Image.ImageUrl = relationship.DisplayName; LinkButton link = new LinkButton(); link.Text = relationship.DisplayName; ///ToDO Add Image or Image and description link.CommandName = "Redirect"; container.Controls.Add(link); } } } </code></pre> <p></p> <p><strong>Not asking anyone to do this for me just a reference or an idea.</strong> </p> <p>Thanks -overly frustrated and feeling humbled.</p>
[ { "answer_id": 116884, "author": "Wes P", "author_id": 13611, "author_profile": "https://Stackoverflow.com/users/13611", "pm_score": -1, "selected": false, "text": "<p>This is kind of a horrible question. I mean, .NET has an image control where you can set the source to anything you want. I'm not sure what you're wanting to be discussed.</p>\n" }, { "answer_id": 116892, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 0, "selected": false, "text": "<p>Check out the new <a href=\"http://www.codeplex.com/aspnet/Wiki/View.aspx?title=WebForms&amp;referringTitle=Home\" rel=\"nofollow noreferrer\">DynamicImage control</a> released in CodePlex by the ASP.NET team. </p>\n" }, { "answer_id": 116929, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": true, "text": "<p>I'm assuming you want to generate an image dynamicly based upon an url.</p>\n\n<p>What I typically do is a create a very lightweight HTTPHandler to serve the images:</p>\n\n<pre><code>using System;\nusing System.Web;\n\nnamespace Example\n{ \n public class GetImage : IHttpHandler\n {\n\n public void ProcessRequest(HttpContext context)\n {\n if (context.Request.QueryString(\"id\") != null)\n {\n // Code that uses System.Drawing to construct the image\n // ...\n context.Response.ContentType = \"image/pjpeg\";\n context.Response.BinaryWrite(Image);\n context.Response.End();\n }\n }\n\n public bool IsReusable\n {\n get\n {\n return false;\n }\n }\n }\n}\n</code></pre>\n\n<p>You can reference this directly in your img tag:</p>\n\n<pre><code>&lt;img src=\"GetImage.ashx?id=111\"/&gt;\n</code></pre>\n\n<p>Or, you could even create a server control that does it for you:</p>\n\n<pre><code>using System;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace Example.WebControl\n{\n\n [ToolboxData(\"&lt;{0}:DynamicImageCreator runat=server&gt;&lt;/{0}:DynamicImageCreator&gt;\")]\n public class DynamicImageCreator : Control\n {\n\n public int Id\n {\n get\n {\n if (ViewState[\"Id\" + this.ID] == null)\n return 0;\n else\n return ViewState[\"Id\"];\n }\n set\n {\n ViewState[\"Id\" + this.ID] = value;\n }\n }\n\n protected override void RenderContents(HtmlTextWriter output)\n {\n output.Write(\"&lt;img src='getImage.ashx?id=\" + this.Id + \"'/&gt;\");\n base.RenderContents(output);\n }\n }\n}\n</code></pre>\n\n<p>This could be used like</p>\n\n<pre><code>&lt;cc:DDynamicImageCreator id=\"db1\" Id=\"123\" runat=\"server/&gt;\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7911/" ]
I know this is a dumb question. For some reason my mind is blank on this. Any ideas? Sorry should have been more clear. Using a `HtmlGenericControl` to pull in link description as well as image. ``` private void InternalCreateChildControls() { if (this.DataItem != null && this.Relationships.Count > 0) { HtmlGenericControl fieldset = new HtmlGenericControl("fieldset"); this.Controls.Add(fieldset); HtmlGenericControl legend = new HtmlGenericControl("legend"); legend.InnerText = this.Caption; fieldset.Controls.Add(legend); HtmlGenericControl listControl = new HtmlGenericControl("ul"); fieldset.Controls.Add(listControl); for (int i = 0; i < this.Relationships.Count; i++) { CatalogRelationshipsDataSet.CatalogRelationship relationship = this.Relationships[i]; HtmlGenericControl listItem = new HtmlGenericControl("li"); listControl.Controls.Add(listItem); RelatedItemsContainer container = new RelatedItemsContainer(relationship); listItem.Controls.Add(container); Image Image = new Image(); Image.ImageUrl = relationship.DisplayName; LinkButton link = new LinkButton(); link.Text = relationship.DisplayName; ///ToDO Add Image or Image and description link.CommandName = "Redirect"; container.Controls.Add(link); } } } ``` **Not asking anyone to do this for me just a reference or an idea.** Thanks -overly frustrated and feeling humbled.
I'm assuming you want to generate an image dynamicly based upon an url. What I typically do is a create a very lightweight HTTPHandler to serve the images: ``` using System; using System.Web; namespace Example { public class GetImage : IHttpHandler { public void ProcessRequest(HttpContext context) { if (context.Request.QueryString("id") != null) { // Code that uses System.Drawing to construct the image // ... context.Response.ContentType = "image/pjpeg"; context.Response.BinaryWrite(Image); context.Response.End(); } } public bool IsReusable { get { return false; } } } } ``` You can reference this directly in your img tag: ``` <img src="GetImage.ashx?id=111"/> ``` Or, you could even create a server control that does it for you: ``` using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Example.WebControl { [ToolboxData("<{0}:DynamicImageCreator runat=server></{0}:DynamicImageCreator>")] public class DynamicImageCreator : Control { public int Id { get { if (ViewState["Id" + this.ID] == null) return 0; else return ViewState["Id"]; } set { ViewState["Id" + this.ID] = value; } } protected override void RenderContents(HtmlTextWriter output) { output.Write("<img src='getImage.ashx?id=" + this.Id + "'/>"); base.RenderContents(output); } } } ``` This could be used like ``` <cc:DDynamicImageCreator id="db1" Id="123" runat="server/> ```
116,876
<p>I'm trying to build a Windows installer using Nullsoft Install System that requires installation by an Administrator. The installer makes a "logs" directory. Since regular users can run this application, that directory needs to be writable by regular users. How do I specify that all users should have permission to have write access to that directory in the NSIS script language?</p> <p>I admit that this sounds a like a sort of bad idea, but the application is just an internal app used by only a few people on a private network. I just need the log files saved so that I can see why the app is broken if something bad happens. The users can't be made administrator.</p>
[ { "answer_id": 116914, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": false, "text": "<p>One way: call the shell, and use <a href=\"http://technet.microsoft.com/en-us/library/bb490872.aspx\" rel=\"noreferrer\"><code>cacls</code></a> or <a href=\"http://support.microsoft.com/kb/318754\" rel=\"noreferrer\"><code>xcacls</code></a>.</p>\n" }, { "answer_id": 116930, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>Why not create a log-directory in the user's %APPDATA% directory? Do you really need to put all the logs in the install directory? Why?</p>\n" }, { "answer_id": 117088, "author": "Jay R.", "author_id": 5074, "author_profile": "https://Stackoverflow.com/users/5074", "pm_score": 6, "selected": true, "text": "<p>Use the <a href=\"http://nsis.sourceforge.net/AccessControl_plug-in\" rel=\"noreferrer\">AccessControl</a> plugin and then add this to the script, where the \"logs\" directory is in the install directory.</p>\n\n<pre><code>AccessControl::GrantOnFile \"$INSTDIR\\logs\" \"(BU)\" \"FullAccess\"\n</code></pre>\n\n<p>That gives full access to the folder for all users.</p>\n" }, { "answer_id": 129118, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 3, "selected": false, "text": "<p>Instead of changing the permissions on directories under Program Files, why not put the logs in a location that is writeable by all users.</p>\n\n<p>See the 4.9.7.7 SetShellVarContext section in your NSIS documentation. You can use it with $APPDATA to get the application data folder that is writeable for all users.</p>\n" }, { "answer_id": 3925642, "author": "user474708", "author_id": 474708, "author_profile": "https://Stackoverflow.com/users/474708", "pm_score": 4, "selected": false, "text": "<p><code>AccessControl::GrantOnFile \"&lt;folder&gt;\" \"(BU)\" \"FullAccess\"</code> didn't work for me on a Windows Server 2008 machine. Instead I had to use this one:</p>\n\n<p><code>AccessControl::GrantOnFile \"&lt;folder&gt;\" \"(S-1-5-32-545)\" \"FullAccess\"</code></p>\n\n<p>S-1-5-32-545 is equivalent to \"Users\" according to <a href=\"https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems\" rel=\"noreferrer\">Microsoft Support: Well-known security identifiers in Windows operating systems</a>.</p>\n" }, { "answer_id": 5178533, "author": "Mirhahil", "author_id": 642661, "author_profile": "https://Stackoverflow.com/users/642661", "pm_score": 3, "selected": false, "text": "<p>It's an old issue now but as suggested by Sören APPDATA directory is a nice way to do what you want, the thing is :\nDon't take user's personnal APPDATA but the \"All Users\" APPDATA dir!\nThis way anyone will be able to access the log file ;-)</p>\n\n<p>Also, I read somewhere that using (BU) on the GrantOnFile is not working well with some systems (Win 7 x64 if I remember well), maybe you should use the SID \"(S-1-5-32-545)\" instead (it's the All Users' SID, this value is a constant on each Windows OS)</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5074/" ]
I'm trying to build a Windows installer using Nullsoft Install System that requires installation by an Administrator. The installer makes a "logs" directory. Since regular users can run this application, that directory needs to be writable by regular users. How do I specify that all users should have permission to have write access to that directory in the NSIS script language? I admit that this sounds a like a sort of bad idea, but the application is just an internal app used by only a few people on a private network. I just need the log files saved so that I can see why the app is broken if something bad happens. The users can't be made administrator.
Use the [AccessControl](http://nsis.sourceforge.net/AccessControl_plug-in) plugin and then add this to the script, where the "logs" directory is in the install directory. ``` AccessControl::GrantOnFile "$INSTDIR\logs" "(BU)" "FullAccess" ``` That gives full access to the folder for all users.
116,887
<p>I seem to be getting a strange error when I run my tests in rails, they are all failing for the same reason and none of the online documentation seems particularly helpful in regards to this particular error:</p> <pre><code>SQLite3::SQLException: cannot rollback - no transaction is active </code></pre> <p>This error is crippling my ability to test my application and seems to have appeared suddenly. I have the latest version of sqlite3 (3.6.2), the latest sqlite3-ruby (1.2.4) gem and the latest rails (2.1.1).</p>
[ { "answer_id": 117289, "author": "David Medinets", "author_id": 219658, "author_profile": "https://Stackoverflow.com/users/219658", "pm_score": 2, "selected": true, "text": "<p>Check <a href=\"http://dev.rubyonrails.org/ticket/4403\" rel=\"nofollow noreferrer\">http://dev.rubyonrails.org/ticket/4403</a> which shows a workaround. Could that be the problem you are encountering?</p>\n" }, { "answer_id": 129477, "author": "srboisvert", "author_id": 6805, "author_profile": "https://Stackoverflow.com/users/6805", "pm_score": 0, "selected": false, "text": "<p>I had this problem once but with MySQL. Turned out I hadn't created the test database. Doh! Rails and sqlite creates them automatically I believe (at least it does in windows).</p>\n\n<p>Are trying to do in memory testing? If not does the test database exist?</p>\n" }, { "answer_id": 140697, "author": "Eric Scrivner", "author_id": 2594, "author_profile": "https://Stackoverflow.com/users/2594", "pm_score": 0, "selected": false, "text": "<p>Thanks for the help. I actually ended up just deleting the rails folder and checking back out the last working copy from version control. I've made the identical changes and this problem hasn't reappeared, so either I messed up or rails had some sort of hiccup. Thankfully I had version control :-)</p>\n" }, { "answer_id": 41882721, "author": "Taylored Web Sites", "author_id": 666516, "author_profile": "https://Stackoverflow.com/users/666516", "pm_score": 0, "selected": false, "text": "<p>I got this error when running a test with the last statement being a click on a form submit. Once I did an assertion or should test, the test closed properly, and I didn't have to rerun the rake db:test:prepare</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2594/" ]
I seem to be getting a strange error when I run my tests in rails, they are all failing for the same reason and none of the online documentation seems particularly helpful in regards to this particular error: ``` SQLite3::SQLException: cannot rollback - no transaction is active ``` This error is crippling my ability to test my application and seems to have appeared suddenly. I have the latest version of sqlite3 (3.6.2), the latest sqlite3-ruby (1.2.4) gem and the latest rails (2.1.1).
Check <http://dev.rubyonrails.org/ticket/4403> which shows a workaround. Could that be the problem you are encountering?
116,888
<p>Given this data:</p> <pre><code>CREATE TABLE tmpTable( fldField varchar(10) null); INSERT INTO tmpTable SELECT 'XXX' UNION ALL SELECT 'XXX' UNION ALL SELECT 'ZZZ' UNION ALL SELECT 'ZZZ' UNION ALL SELECT 'YYY' SELECT CASE WHEN fldField like 'YYY' THEN 'OTH' ELSE 'XXX' END AS newField FROM tmpTable </code></pre> <p>The expected resultset is:<br> XXX<br> XXX<br> XXX<br> XXX<br> OTH </p> <p>What situation would casue SQL server 2000 to NOT find 'YYY'? And return the following as the resultset:<br> XXX<br> XXX<br> XXX<br> XXX<br> XXX </p> <p>The problem is with the like 'YYY', I have found other ways to write this to get it to work, but I want to know why this exact method doesn't work. Another difficulty is that it works in most of my SQL Server 2000 environments. I need to find out what is different between them to cause this. Thanks for your help.</p>
[ { "answer_id": 116924, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": -1, "selected": false, "text": "<p>You aren't specifying what you are selecting and checking the CASE against...</p>\n\n<pre><code>SELECT CASE fldField WHEN 'YYY' \nTHEN 'OTH' ELSE 'XXX' END AS newField FROM tmpTable\n</code></pre>\n" }, { "answer_id": 116932, "author": "Wes P", "author_id": 13611, "author_profile": "https://Stackoverflow.com/users/13611", "pm_score": 0, "selected": false, "text": "<p>How about <code>fldField = '%YYY%'</code>?</p>\n" }, { "answer_id": 117060, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 0, "selected": false, "text": "<p>It worked as expected on my SQL 2005 installation. If it works on other machines, it sounds like you've got an environment difference. Try comparing your connection properties in SQL Server Management Studio for a connection that works and one that doesn't to see if you can figure out what the differences are.</p>\n" }, { "answer_id": 117265, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 0, "selected": false, "text": "<p>I am an Oracle person, not a SQL*Server person, but it seems to me you should be either:-</p>\n\n<pre><code>SELECT\n CASE WHEN fldField like '%YYY%' THEN \n 'OTH' \n ELSE 'XXX'\n END AS newField \nFROM\n tmpTable\n</code></pre>\n\n<p>or ...</p>\n\n<pre><code>SELECT\n CASE WHEN fldField = 'YYY' THEN \n 'OTH' \n ELSE 'XXX'\n END AS newField \nFROM\n tmpTable\n</code></pre>\n\n<p>The second is the direction I'd go in, as at least in Oracle equality resolves quicker than like.</p>\n" }, { "answer_id": 117397, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 0, "selected": false, "text": "<p>When you use LIKE without specifying any search criteria, it behaves like an = comparison. In your example, I would expect it to work properly. In your real data, you probably have a hidden (non-printable) character in your data (think about Carriage Return, Line Feed, Tab, etc....).</p>\n\n<p>Take a look at this example...</p>\n\n<pre><code>Declare @tmpTable TABLE(\nfldField varchar(10) null);\n\nINSERT INTO @tmpTable\nSELECT 'XXX'\nUNION ALL \nSELECT 'XXX'\nUNION ALL\nSELECT 'ZZZ'\nUNION ALL\nSELECT 'ZZZ'\nUNION ALL\nSELECT 'YYY'\nUNION ALL\nSELECT 'YYY' + Char(10)\n\nSELECT CASE WHEN fldField like 'YYY' THEN 'OTH' ELSE 'XXX' END AS YourOriginalTest,\n CASE WHEN fldField like 'YYY%' THEN 'OTH' ELSE 'XXX' END AS newField\nFROM @tmpTable\n</code></pre>\n\n<p>You'll notice that the last piece of data I added is YYY and a Line Feed. If you select this data, you won't notice the line feed in the data, but it's there, so your LIKE condition (which is acting like an equal condition) doesn't match.</p>\n\n<p>The common 'hidden' characters are Tab, Carriage Return, and Line Feed. To determine if this is causing your problem...</p>\n\n<pre><code>Select *\nFrom Table\nWhere Column Like '%[' + Char(10) + Char(9) + Char(13) + ']%'\n</code></pre>\n" }, { "answer_id": 117468, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 1, "selected": false, "text": "<p>I ran the code on a SQL 2000 box and got identical results. Not only that, but when I ran some additional code to test I got some VERY bizarre results:</p>\n\n<pre><code>CREATE TABLE dbo.TestLike ( my_field varchar(10) null);\nGO\nCREATE CLUSTERED INDEX IDX_TestLike ON dbo.TestLike (my_field)\nGO\nINSERT INTO dbo.TestLike (my_field) VALUES ('XXX')\nINSERT INTO dbo.TestLike (my_field) VALUES ('XXX')\nINSERT INTO dbo.TestLike (my_field) VALUES ('ZZZ')\nINSERT INTO dbo.TestLike (my_field) VALUES ('ZZZ')\nINSERT INTO dbo.TestLike (my_field) VALUES ('YYY')\nGO\n\nSELECT\n my_field,\n case my_field when 'YYY' THEN 'Y' ELSE 'N' END AS C2,\n case when my_field like 'YYY' THEN 'Y' ELSE 'N' END AS C3,\n my_field\nFROM dbo.TestLike\nGO\n</code></pre>\n\n<p>My results:</p>\n\n<pre><code>my_field C2 C3 my_field\n---------- ---- ---- ----------\nN XXX N XXX\nN XXX N XXX\nY YYY N YYY\nN ZZZ N ZZZ\nN ZZZ N ZZZ\n</code></pre>\n\n<p>Notice how my_field has two different values in the same row? I've asked some others at the office here to give it a quick test. Looks like a bug to me.</p>\n" }, { "answer_id": 118231, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 0, "selected": false, "text": "<p>What a cute bug. I think I know the cause. If I'm right, then you'll get the results you expect from:</p>\n\n<pre><code>SELECT\n CASE\n WHEN fldField like 'YYY ' -- 7 spaces\n THEN 'OTH'\n ELSE 'XXX'\n END as newField\nfrom tmpTable\n</code></pre>\n\n<p>The bug is that varchar(10) is behaving like char(10) is supposed to. As for why it doesn't, you'll need to understand the old trivia question of how two strings with no metacharacters can be = but not LIKE each other.</p>\n\n<p>The issue is that a char(10) is internally supposed to be space padded. The like operator does <em>not</em> ignore those spaces. The = operator is supposed to in the case of chars. Memory tells me that Oracle ignores spaces for strings in general. Postgres does some tricks with casting. I have not used SQL*Server so I can't tell you how it does it.</p>\n" }, { "answer_id": 121432, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 2, "selected": true, "text": "<p>Check your service pack. After upgrading my SQL 2000 box to SP4 I now get the correct values for your situation.</p>\n\n<p>I'm still getting the swapped data that I reported in my earlier post though :(</p>\n\n<p>If you do <code>SELECT @@version</code> you should get 8.00.2039. Any version number less than that and you should install SP4.</p>\n" }, { "answer_id": 9697393, "author": "Avinash", "author_id": 1268320, "author_profile": "https://Stackoverflow.com/users/1268320", "pm_score": 0, "selected": false, "text": "<p>By adding (%) to the expression , it will work fine.</p>\n\n<pre><code>SELECT\nCASE \n WHEN fldField like '%YYY%' THEN 'OTH' \n ELSE 'XXX' END AS newField\nEND\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12470/" ]
Given this data: ``` CREATE TABLE tmpTable( fldField varchar(10) null); INSERT INTO tmpTable SELECT 'XXX' UNION ALL SELECT 'XXX' UNION ALL SELECT 'ZZZ' UNION ALL SELECT 'ZZZ' UNION ALL SELECT 'YYY' SELECT CASE WHEN fldField like 'YYY' THEN 'OTH' ELSE 'XXX' END AS newField FROM tmpTable ``` The expected resultset is: XXX XXX XXX XXX OTH What situation would casue SQL server 2000 to NOT find 'YYY'? And return the following as the resultset: XXX XXX XXX XXX XXX The problem is with the like 'YYY', I have found other ways to write this to get it to work, but I want to know why this exact method doesn't work. Another difficulty is that it works in most of my SQL Server 2000 environments. I need to find out what is different between them to cause this. Thanks for your help.
Check your service pack. After upgrading my SQL 2000 box to SP4 I now get the correct values for your situation. I'm still getting the swapped data that I reported in my earlier post though :( If you do `SELECT @@version` you should get 8.00.2039. Any version number less than that and you should install SP4.
116,894
<p>I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python's object oriented design differs somewhat from other languages I've worked with. So, even though my application is working, I'm curious whether there is a better way to accomplish my goals.</p> <p>Specifics: How does one typically implement the request-transform-render database workflow in Python? Currently, I am using pyodbc to fetch data, copying the results into attributes on an object, performing some calculations and merges using a list of these objects, then rendering the output from the list of objects. (Sample code below, SQL queries redacted.) Is this sane? Is there a better way? Are there any specific "gotchas" I've stumbled into in my relative ignorance of Python? I'm particularly concerned about how I've implemented the list of rows using the empty "Record" class.</p> <pre><code>class Record(object): pass def calculate_pnl(records, node_prices): for record in records: try: # fill RT and DA prices from the hash retrieved above if hasattr(record, 'sink') and record.sink: record.da = node_prices[record.sink][0] - node_prices[record.id][0] record.rt = node_prices[record.sink][1] - node_prices[record.id][1] else: record.da = node_prices[record.id][0] record.rt = node_prices[record.id][1] # calculate dependent values: RT-DA and PNL record.rtda = record.rt - record.da record.pnl = record.rtda * record.mw except: print sys.exc_info() def map_rows(cursor, mappings, callback=None): records = [] for row in cursor: record = Record() for field, attr in mappings.iteritems(): setattr(record, attr, getattr(row, field, None)) if not callback or callback(record): records.append(record) return records def get_positions(cursor): # get the latest position time cursor.execute("SELECT latest data time") time = cursor.fetchone().time hour = eelib.util.get_hour_ending(time) # fetch the current positions cursor.execute("SELECT stuff FROM atable", (hour)) # read the rows nodes = {} def record_callback(record): if abs(record.mw) &gt; 0: if record.id: nodes[record.id] = None return True else: return False records = util.map_rows(cursor, { 'id': 'id', 'name': 'name', 'mw': 'mw' }, record_callback) # query prices for node_id in nodes: # RT price row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, time, time)).fetchone() rt5 = row.lmp if row else None # DA price row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, hour, hour)).fetchone() da = row.da_lmp if row else None # update the hash value nodes[node_id] = (da, rt5) # calculate the position pricing calculate_pnl(records, nodes) # sort records.sort(key=lambda r: r.name) # return the records return records </code></pre>
[ { "answer_id": 116974, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 1, "selected": false, "text": "<p>Have you considered using an ORM? <a href=\"http://www.sqlalchemy.org/features.html\" rel=\"nofollow noreferrer\" title=\"SQL Alchemy features\">SQLAlchemy</a> is pretty good, and <a href=\"http://elixir.ematia.de/trac/wiki\" rel=\"nofollow noreferrer\" title=\"Elixir Wiki\">Elixir</a> makes it beautiful. It can really reduce the ammount of boilerplate code needed to deal with databases. Also, a lot of the <em>gotchas</em> mentioned have already shown up and the SQLAlchemy developers dealt with them.</p>\n" }, { "answer_id": 117012, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": -1, "selected": false, "text": "<p>Using a ORM for an iPhone app might be a bad idea because of performance issues, you want your code to be as fast as possible. So you can't avoid boilerplate code. If you are considering a ORM, besides SQLAlchemy I'd recommend Storm.</p>\n" }, { "answer_id": 117769, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 0, "selected": false, "text": "<p>Depending on how much you want to do with the data you may not need to populate an intermediate object. The cursor's header data structure will let you get the column names - a bit of introspection will let you make a dictionary with col-name:value pairs for the row.\nYou can pass the dictionary to the % operator. The docs for the odbc module will explain how to get at the column metadata.</p>\n\n<p>This snippet of code to shows the application of the % operator in this manner.</p>\n\n<pre><code>&gt;&gt;&gt; a={'col1': 'foo', 'col2': 'bar', 'col3': 'wibble'}\n&gt;&gt;&gt; 'Col1=%(col1)s, Col2=%(col2)s, Col3=%(col3)s' % a\n'Col1=foo, Col2=bar, Col3=wibble'\n&gt;&gt;&gt; \n</code></pre>\n" }, { "answer_id": 117994, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": true, "text": "<p>The empty Record class and the free-floating function that (generally) applies to an individual Record is a hint that you haven't designed your class properly.</p>\n\n<pre><code>class Record( object ):\n \"\"\"Assuming rtda and pnl must exist.\"\"\"\n def __init__( self ):\n self.da= 0\n self.rt= 0\n self.rtda= 0 # or whatever\n self.pnl= None # \n self.sink = None # Not clear what this is\n def setPnl( self, node_prices ):\n # fill RT and DA prices from the hash retrieved above\n # calculate dependent values: RT-DA and PNL\n</code></pre>\n\n<p>Now, your <code>calculate_pnl( records, node_prices )</code> is simpler and uses the object properly.</p>\n\n<pre><code>def calculate_pnl( records, node_prices ):\n for record in records:\n record.setPnl( node_prices )\n</code></pre>\n\n<p>The point isn't to trivially refactor the code in small ways.</p>\n\n<p>The point is this: <strong>A Class Encapsulates Responsibility</strong>.</p>\n\n<p>Yes, an empty-looking class <em>is</em> usually a problem. It means the responsibilities are scattered somewhere else.</p>\n\n<p>A similar analysis holds for the collection of records. This is more than a simple list, since the collection -- as a whole -- has operations it performs.</p>\n\n<p>The \"Request-Transform-Render\" isn't quite right. You have a Model (the Record class). Instances of the Model get built (possibly because of a Request.) The Model objects are responsible for their own state transformations and updates. Perhaps they get displayed (or rendered) by some object that examines their state.</p>\n\n<p>It's that \"Transform\" step that often violates good design by scattering responsibility all over the place. \"Transform\" is a hold-over from non-object design, where responsibility was a nebulous concept.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19031/" ]
I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python's object oriented design differs somewhat from other languages I've worked with. So, even though my application is working, I'm curious whether there is a better way to accomplish my goals. Specifics: How does one typically implement the request-transform-render database workflow in Python? Currently, I am using pyodbc to fetch data, copying the results into attributes on an object, performing some calculations and merges using a list of these objects, then rendering the output from the list of objects. (Sample code below, SQL queries redacted.) Is this sane? Is there a better way? Are there any specific "gotchas" I've stumbled into in my relative ignorance of Python? I'm particularly concerned about how I've implemented the list of rows using the empty "Record" class. ``` class Record(object): pass def calculate_pnl(records, node_prices): for record in records: try: # fill RT and DA prices from the hash retrieved above if hasattr(record, 'sink') and record.sink: record.da = node_prices[record.sink][0] - node_prices[record.id][0] record.rt = node_prices[record.sink][1] - node_prices[record.id][1] else: record.da = node_prices[record.id][0] record.rt = node_prices[record.id][1] # calculate dependent values: RT-DA and PNL record.rtda = record.rt - record.da record.pnl = record.rtda * record.mw except: print sys.exc_info() def map_rows(cursor, mappings, callback=None): records = [] for row in cursor: record = Record() for field, attr in mappings.iteritems(): setattr(record, attr, getattr(row, field, None)) if not callback or callback(record): records.append(record) return records def get_positions(cursor): # get the latest position time cursor.execute("SELECT latest data time") time = cursor.fetchone().time hour = eelib.util.get_hour_ending(time) # fetch the current positions cursor.execute("SELECT stuff FROM atable", (hour)) # read the rows nodes = {} def record_callback(record): if abs(record.mw) > 0: if record.id: nodes[record.id] = None return True else: return False records = util.map_rows(cursor, { 'id': 'id', 'name': 'name', 'mw': 'mw' }, record_callback) # query prices for node_id in nodes: # RT price row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, time, time)).fetchone() rt5 = row.lmp if row else None # DA price row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, hour, hour)).fetchone() da = row.da_lmp if row else None # update the hash value nodes[node_id] = (da, rt5) # calculate the position pricing calculate_pnl(records, nodes) # sort records.sort(key=lambda r: r.name) # return the records return records ```
The empty Record class and the free-floating function that (generally) applies to an individual Record is a hint that you haven't designed your class properly. ``` class Record( object ): """Assuming rtda and pnl must exist.""" def __init__( self ): self.da= 0 self.rt= 0 self.rtda= 0 # or whatever self.pnl= None # self.sink = None # Not clear what this is def setPnl( self, node_prices ): # fill RT and DA prices from the hash retrieved above # calculate dependent values: RT-DA and PNL ``` Now, your `calculate_pnl( records, node_prices )` is simpler and uses the object properly. ``` def calculate_pnl( records, node_prices ): for record in records: record.setPnl( node_prices ) ``` The point isn't to trivially refactor the code in small ways. The point is this: **A Class Encapsulates Responsibility**. Yes, an empty-looking class *is* usually a problem. It means the responsibilities are scattered somewhere else. A similar analysis holds for the collection of records. This is more than a simple list, since the collection -- as a whole -- has operations it performs. The "Request-Transform-Render" isn't quite right. You have a Model (the Record class). Instances of the Model get built (possibly because of a Request.) The Model objects are responsible for their own state transformations and updates. Perhaps they get displayed (or rendered) by some object that examines their state. It's that "Transform" step that often violates good design by scattering responsibility all over the place. "Transform" is a hold-over from non-object design, where responsibility was a nebulous concept.
116,896
<p>I would like Visual Studio to break when a handled exception happens (i.e. I don't just want to see a "First chance" message, I want to debug the actual exception).</p> <p>e.g. I want the debugger to break at the exception:</p> <pre><code>try { System.IO.File.Delete(someFilename); } catch (Exception) { //we really don't care at runtime if the file couldn't be deleted } </code></pre> <p>I came across <a href="http://www.syncfusion.com/faq/windowsforms/faq_c60c.aspx#q583q" rel="noreferrer">these</a> notes for Visual Studio.NET:</p> <blockquote> <p>1) In VS.NET go to the Debug Menu >> "Exceptions..." >> "Common Language Runtime Exceptions" >> "System" and select "System.NullReferenceException"</p> <p>2) In the bottom of that dialog there is a "When the exception is thrown:" group box, select "Break into the debugger" </p> <p>3) Run your scenario. When the exception is thrown, the debugger will stop and notify you with a dialog that says something like: "An exception of type "System.NullReferenceException" has been thrown. [Break] [Continue]" </p> <p>Hit [Break]. This will put you on the line of code that's causing the problem.</p> </blockquote> <p>But they do not apply to Visual Studio 2005 (there is no <strong>Exceptions</strong> option on the <strong>Debug</strong> menu).</p> <p>Does anyone know where the find this options dialog in Visual Studio that the "<em>When the exception is thrown</em>" group box, with the option to "<em>Break into the debugger</em>"?</p> <p><em>Update: The problem was that my <strong>Debug</strong> menu didn't have an <strong>Exceptions</strong> item. I customized the menu to manually add it.</em></p>
[ { "answer_id": 116913, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 6, "selected": false, "text": "<p>There is an 'exceptions' window in VS2005 ... try <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>E</kbd> when debugging and click on the 'Thrown' checkbox for the exception you want to stop on.</p>\n" }, { "answer_id": 116934, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 9, "selected": true, "text": "<p>With a solution open, go to the Debug - Windows - Exception Settings (<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>E</kbd>) menu option. From there you can choose to break on <em>Thrown</em> or <em>User-unhandled</em> exceptions.</p>\n<p>EDIT: My instance is set up with the C# &quot;profile&quot; perhaps it isn't there for other profiles?</p>\n" }, { "answer_id": 116975, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 3, "selected": false, "text": "<p>Check <a href=\"https://learn.microsoft.com/en-gb/visualstudio/debugger/managing-exceptions-with-the-debugger?view=vs-2015\" rel=\"nofollow noreferrer\">Managing Exceptions with the Debugger</a> page, it explains how to set this up.</p>\n\n<p>Essentially, here are the steps (during debugging):</p>\n\n<ol>\n<li><p>On the Debug menu, click Exceptions.</p></li>\n<li><p>In the Exceptions dialog box, select Thrown for an entire category of exceptions, for example, Common Language Runtime Exceptions.</p>\n\n<p>-or-</p>\n\n<p>Expand the node for a category of exceptions, for example, Common Language Runtime Exceptions, and select Thrown for a specific exception within that category.</p></li>\n</ol>\n" }, { "answer_id": 434023, "author": "Spencer Ruport", "author_id": 52551, "author_profile": "https://Stackoverflow.com/users/52551", "pm_score": 2, "selected": false, "text": "<p>A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:</p>\n\n<pre><code>if(!GlobalTestingBool)\n{\n try\n {\n SomeErrorProneMethod();\n }\n catch (...)\n {\n // ... Error handling ...\n }\n}\nelse\n{\n SomeErrorProneMethod();\n}\n</code></pre>\n\n<p>I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.</p>\n" }, { "answer_id": 37992602, "author": "markysdad", "author_id": 3961442, "author_profile": "https://Stackoverflow.com/users/3961442", "pm_score": 1, "selected": false, "text": "<p>The online documentation seems a little unclear, so I just performed a little test. Choosing to break on Thrown from the Exceptions dialog box causes the program execution to break on <em>any</em> exception, handled or unhandled. If you want to break on handled exceptions only, it seems your only recourse is to go through your code and put breakpoints on all your handled exceptions. This seems a little excessive, so it might be better to add a debug statement whenever you handle an exception. Then when you see that output, you can set a breakpoint at that line in the code.</p>\n" }, { "answer_id": 45819007, "author": "Beginner", "author_id": 3867787, "author_profile": "https://Stackoverflow.com/users/3867787", "pm_score": 6, "selected": false, "text": "<p>Took me a while to find the new place for expection settings, therefore a new answer.</p>\n\n<p><strong>Since Visual Studio 2015</strong> you control which Exceptions to stop on in the Exception Settings Window (Debug->Windows->Exception Settings). The shortcut is still <kbd>Ctrl</kbd>-<kbd>Alt</kbd>-<kbd>E</kbd>.</p>\n\n<p>The simplest way to handle custom exceptions is selecting \"all exceptions not in this list\".</p>\n\n<p>Here is a screenshot from the english version:</p>\n\n<p><a href=\"https://i.stack.imgur.com/DsdlA.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DsdlA.png\" alt=\"enter image description here\"></a></p>\n\n<p>Here is a screenshot from the german version:</p>\n\n<p><a href=\"https://i.stack.imgur.com/uFtgN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uFtgN.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 47681894, "author": "Sameer Alibhai", "author_id": 2343, "author_profile": "https://Stackoverflow.com/users/2343", "pm_score": 5, "selected": false, "text": "<p>From Visual Studio 2015 and onward, you need to go to the \"Exception Settings\" dialog (<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>E</kbd>) and check off the \"Common Language Runtime Exceptions\" (or a specific one you want i.e. <code>ArgumentNullException</code>) to make it break on <strong>handled</strong> exceptions.</p>\n\n<p>Step 1\n<a href=\"https://i.stack.imgur.com/An8K9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/An8K9.png\" alt=\"Step 1\"></a>\nStep 2\n<a href=\"https://i.stack.imgur.com/VFTit.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VFTit.png\" alt=\"Step 2\"></a></p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
I would like Visual Studio to break when a handled exception happens (i.e. I don't just want to see a "First chance" message, I want to debug the actual exception). e.g. I want the debugger to break at the exception: ``` try { System.IO.File.Delete(someFilename); } catch (Exception) { //we really don't care at runtime if the file couldn't be deleted } ``` I came across [these](http://www.syncfusion.com/faq/windowsforms/faq_c60c.aspx#q583q) notes for Visual Studio.NET: > > 1) In VS.NET go to the Debug Menu >> > "Exceptions..." >> "Common Language > Runtime Exceptions" >> "System" and > select "System.NullReferenceException" > > > 2) In the bottom of that dialog there > is a "When the exception is thrown:" > group box, select "Break into the > debugger" > > > 3) Run your scenario. When the > exception is thrown, the debugger will > stop and notify you with a dialog that > says something like: > "An exception of type "System.NullReferenceException" has > been thrown. > [Break] [Continue]" > > > Hit [Break]. This will put you on the > line of code that's causing the > problem. > > > But they do not apply to Visual Studio 2005 (there is no **Exceptions** option on the **Debug** menu). Does anyone know where the find this options dialog in Visual Studio that the "*When the exception is thrown*" group box, with the option to "*Break into the debugger*"? *Update: The problem was that my **Debug** menu didn't have an **Exceptions** item. I customized the menu to manually add it.*
With a solution open, go to the Debug - Windows - Exception Settings (`Ctrl`+`Alt`+`E`) menu option. From there you can choose to break on *Thrown* or *User-unhandled* exceptions. EDIT: My instance is set up with the C# "profile" perhaps it isn't there for other profiles?
116,905
<p>I would like to use my laptop as a web development (PHP, Python, etc.) machine, but I'm hesitant to do this unless I can ensure that it can not be accessed by the outside world.</p> <p>I'm guessing that something more than a firewall is necessary, such as configurations to the Apache configuration files, but I'm not sure what else I would need to be 100% sure it's locked down tightly.</p>
[ { "answer_id": 116920, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 3, "selected": true, "text": "<p>You need to configure the server daemon to only bind to localhost using the Listen directive like this:</p>\n\n<pre><code>Listen 127.0.0.1\n</code></pre>\n\n<p>An alternative is to configure access control for the main server like this</p>\n\n<pre><code>&lt;Directory \"/var/www/localhost/htdocs\"&gt;\nAllowOverride None\nDeny from all\nAllow from 127.0.0.1/255.0.0.0\n&lt;/Directory&gt;\n</code></pre>\n\n<p>Remember to put the root directory of your server in the Directory Directive.</p>\n" }, { "answer_id": 116921, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 2, "selected": false, "text": "<p>A firewall should be sufficient. Just make sure that you run apache in a non-standard port (typically 8080) and make sure your firewall blocks outside access to that port.</p>\n" }, { "answer_id": 116923, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "<p>Install a firewall and close all external ports but those who you want to use. If you are using Linux, there are nice frontends for iptables such as firestarter, if you use OS X there is an integrated firewall and Windows has one too. :)</p>\n\n<p>But yes, the Firewall is the way to go. (Or you can tell Apache to listen on <code>127.0.0.1:80</code> only)</p>\n" }, { "answer_id": 116928, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 3, "selected": false, "text": "<p>in the configuration file, change the LISTEN directive to only listen on the loop back address:</p>\n\n<p>Listen 127.0.0.1</p>\n" }, { "answer_id": 116933, "author": "Colen", "author_id": 13500, "author_profile": "https://Stackoverflow.com/users/13500", "pm_score": 0, "selected": false, "text": "<p>Put a router between you and the internet, and don't forward any ports to your laptop. That way anyone trying to access the laptop hits the router and can't get any further.</p>\n\n<p>You can forward ports to your main machine (or just put the main machine in the DMZ) if you need it to be available to incoming connections.</p>\n" }, { "answer_id": 116935, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 1, "selected": false, "text": "<p>Firewall should be enough. But you can use the <a href=\"http://httpd.apache.org/docs/2.0/bind.html\" rel=\"nofollow noreferrer\">Listen</a> directive as well.</p>\n" }, { "answer_id": 116943, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": 1, "selected": false, "text": "<p>A firewall will do just fine. But if you won't settle for just a firewall you can configure apache to just listen on your loopback device, or tell it to just accept connections from a set of addresses on your lan. The first method is easier, but that way you can access the web pages only from the machine apache is running on.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
I would like to use my laptop as a web development (PHP, Python, etc.) machine, but I'm hesitant to do this unless I can ensure that it can not be accessed by the outside world. I'm guessing that something more than a firewall is necessary, such as configurations to the Apache configuration files, but I'm not sure what else I would need to be 100% sure it's locked down tightly.
You need to configure the server daemon to only bind to localhost using the Listen directive like this: ``` Listen 127.0.0.1 ``` An alternative is to configure access control for the main server like this ``` <Directory "/var/www/localhost/htdocs"> AllowOverride None Deny from all Allow from 127.0.0.1/255.0.0.0 </Directory> ``` Remember to put the root directory of your server in the Directory Directive.
116,951
<p>I wanted to use <code>fstream</code> to read a txt file.</p> <p>I am using <code>inFile &gt;&gt; characterToConvert</code>, but the problem is that this omits any spaces and newline.</p> <p>I am writing an encryption program so I need to include the spaces and newlines.</p> <p>What would be the proper way to go about accomplishing this?</p>
[ { "answer_id": 116980, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 2, "selected": false, "text": "<p>The following c++ code will read an entire file...</p>\n\n<pre>\n<code>\n#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;string&gt;\nusing namespace std;\n\nint main () \n{\n string line;\n ifstream myfile (\"foo.txt\");\n\n if (myfile.is_open()){\n\n while (!myfile.eof()){\n getline (myfile,line);\n cout &lt;&lt; line &lt;&lt; endl;\n }\n myfile.close();\n }\n return 0;\n}\n</code>\n</pre>\n\n<p>post your code and I can give you more specific help to your problem...</p>\n" }, { "answer_id": 117015, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 5, "selected": false, "text": "<p>For encryption, you're better off opening your file in binary mode. Use something like this to put the bytes of a file into a vector:</p>\n\n<pre><code>std::ifstream ifs(\"foobar.txt\", std::ios::binary);\n\nifs.seekg(0, std::ios::end);\nstd::ifstream::pos_type filesize = ifs.tellg();\nifs.seekg(0, std::ios::beg);\n\nstd::vector&lt;char&gt; bytes(filesize);\n\nifs.read(&amp;bytes[0], filesize);\n</code></pre>\n\n<p>Edit: fixed a subtle bug as per the comments.</p>\n" }, { "answer_id": 117018, "author": "Adam Holmberg", "author_id": 20688, "author_profile": "https://Stackoverflow.com/users/20688", "pm_score": 4, "selected": false, "text": "<p>I haven't tested this, but I believe you need to clear the \"skip whitespace\" flag:</p>\n\n<pre><code>inFile.unsetf(ios_base::skipws);\n</code></pre>\n\n<p>I use the following reference for C++ streams:\n<a href=\"http://www.cplusplus.com/reference/iostream/\" rel=\"noreferrer\">IOstream Library</a></p>\n" }, { "answer_id": 117075, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>For encryption, you should probably use <a href=\"http://www.cplusplus.com/reference/iostream/istream/read.html\" rel=\"nofollow noreferrer\">read()</a>. Encryption algorithms usually deal with fixed-size blocks. Oh, and to open in binary mode (no translation frmo \\n\\r to \\n), pass ios_base::binary as the second parameter to constructor or open() call.</p>\n" }, { "answer_id": 117146, "author": "jdmichal", "author_id": 12275, "author_profile": "https://Stackoverflow.com/users/12275", "pm_score": 2, "selected": false, "text": "<p>You can call <a href=\"http://www.cplusplus.com/reference/iostream/istream/get.html\" rel=\"nofollow noreferrer\"><code>int fstream::get()</code></a>, which will read a single character from the stream. You can also use <a href=\"http://www.cplusplus.com/reference/iostream/istream/read.html\" rel=\"nofollow noreferrer\"><code>istream&amp; fstream::read(char*, streamsize)</code></a>, which does the same operation as <code>get()</code>, just over multiple characters. The given links include examples of using each method.</p>\n\n<p>I also recommend reading and writing in binary mode. This allows ASCII control characters to be properly read from and written to files. Otherwise, an encrypt/decrypt operation pair might result in non-identical files. To do this, you open the filestream with the <a href=\"http://www.cplusplus.com/reference/iostream/ios_base/openmode.html\" rel=\"nofollow noreferrer\"><code>ios::binary</code></a> flag. With a binary file, you want to use the <code>read()</code> method.</p>\n" }, { "answer_id": 117228, "author": "Jason Etheridge", "author_id": 2193, "author_profile": "https://Stackoverflow.com/users/2193", "pm_score": 6, "selected": false, "text": "<p>Probably the best way is to read the entire file's contents into a string, which can be done very easily using ifstream's <a href=\"http://en.cppreference.com/w/cpp/io/basic_ios/rdbuf\" rel=\"nofollow noreferrer\"><code>rdbuf()</code></a> method:</p>\n\n<pre><code>std::ifstream in(\"myfile\");\n\nstd::stringstream buffer;\nbuffer &lt;&lt; in.rdbuf();\n\nstd::string contents(buffer.str());\n</code></pre>\n\n<p>You can then use regular string manipulation now that you've got everything from the file.</p>\n\n<p>While <a href=\"https://stackoverflow.com/users/20678/tomek\">Tomek</a> was asking about reading a text file, the same approach will work for reading binary data, though the std::ios::binary flag needs to be provided when creating the input file stream.</p>\n" }, { "answer_id": 117763, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 2, "selected": false, "text": "<p>A lot of the benefit of the istream layer is providing basic formatting and parsing for simple types ro and from a stream. For the purposes that you describe, none of this is really important and you are just interested in the file as a stream of bytes.</p>\n\n<p>For these purpose you may be better of just using the basic_streambuf interface provided by a filebuf. The 'skip whitespace' behaviour is part of the istream interface functionality that you just don't need.</p>\n\n<p>filebuf underlies an ifstream, but it is perfectly valid to use it directly.</p>\n\n<pre><code>std::filebuf myfile;\nmyfile.open( \"myfile.dat\", std::ios_base::in | std::ios_base::binary );\n\n// gets next char, then moves 'get' pointer to next char in the file\nint ch = myfile.sbumpc();\n\n// get (up to) the next n chars from the stream\nstd::streamsize getcount = myfile.sgetn( char_array, n );\n</code></pre>\n\n<p>Also have a look at the functions snextc (moves the 'get' pointer forward and then returns the current char), sgetc (gets the current char but doesn't move the 'get' pointer) and sungetc (backs up the 'get' pointer by one position if possible).</p>\n\n<p>When you don't need any of the insertion and extraction operators provided by an istream class and just need a basic byte interface, often the streambuf interface (filebuf, stringbuf) is more appropriate than an istream interface (ifstream, istringstream).</p>\n" }, { "answer_id": 117944, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": -1, "selected": false, "text": "<p>As Charles Bailey correctly pointed out, you don't need fstream's services just to read bytes. So forget this iostream silliness, use fopen/fread and be done with it. C stdio is part of C++, you know ;)</p>\n" }, { "answer_id": 119331, "author": "Flame", "author_id": 5387, "author_profile": "https://Stackoverflow.com/users/5387", "pm_score": 0, "selected": false, "text": "<p>Simple</p>\n\n<pre><code>#include &lt;fstream&gt;\n#include &lt;iomanip&gt;\n\n\nifstream ifs (\"file\");\nifs &gt;&gt; noskipws\n</code></pre>\n\n<p>that's all.</p>\n" }, { "answer_id": 5646370, "author": "Iakov Minochkin", "author_id": 501213, "author_profile": "https://Stackoverflow.com/users/501213", "pm_score": 2, "selected": false, "text": "<pre><code>std::ifstream ifs( \"filename.txt\" );\n\nstd::string str( ( std::istreambuf_iterator&lt;char&gt;( ifs ) ), \n std::istreambuf_iterator&lt;char&gt;()\n );\n</code></pre>\n" }, { "answer_id": 11590855, "author": "MCA", "author_id": 710576, "author_profile": "https://Stackoverflow.com/users/710576", "pm_score": 0, "selected": false, "text": "<pre><code>ifstream ifile(path);\nstd::string contents((std::istreambuf_iterator&lt;char&gt;(ifile)), std::istreambuf_iterator&lt;char&gt;());\nifile.close();\n</code></pre>\n" }, { "answer_id": 12102853, "author": "user1621518", "author_id": 1621518, "author_profile": "https://Stackoverflow.com/users/1621518", "pm_score": 2, "selected": false, "text": "<p>Another better way is to use istreambuf_iterator, and the sample code is as below:</p>\n\n<pre><code>ifstream inputFile(\"test.data\");\n\nstring fileData(istreambuf_iterator&lt;char&gt;(inputFile), istreambuf_iterator&lt;char&gt;());\n</code></pre>\n" }, { "answer_id": 44571611, "author": "jdhao", "author_id": 6064933, "author_profile": "https://Stackoverflow.com/users/6064933", "pm_score": 0, "selected": false, "text": "<p>I also find that the <a href=\"http://www.cplusplus.com/reference/istream/istream/get/\" rel=\"nofollow noreferrer\">get()</a> method of ifstream object can also read all the characters of the file, which do not require unset <code>std::ios_base::skipws</code>. Quote from <em>C++ Primer</em>:</p>\n\n<blockquote>\n <p>Several of the unformatted operations deal with a stream one byte at a time. These operations, which are described in Table 17.19, read rather ignore whitespaces.</p>\n</blockquote>\n\n<p>These operations are list as below:\n<a href=\"http://www.cplusplus.com/reference/istream/istream/get/\" rel=\"nofollow noreferrer\">is.get()</a>, <a href=\"http://www.cplusplus.com/reference/ostream/ostream/put/\" rel=\"nofollow noreferrer\">os.put()</a>, <a href=\"http://www.cplusplus.com/reference/istream/istream/putback/?kw=putback\" rel=\"nofollow noreferrer\">is.putback()</a>, <a href=\"http://www.cplusplus.com/reference/istream/istream/unget/?kw=unget\" rel=\"nofollow noreferrer\">is.unget()</a> and <a href=\"http://www.cplusplus.com/reference/istream/istream/peek/?kw=peek\" rel=\"nofollow noreferrer\">is.peek()</a>.</p>\n\n<p>Below is a minimum working code</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;string&gt;\n\nint main(){\n std::ifstream in_file(\"input.txt\");\n\n char s;\n\n if (in_file.is_open()){\n int count = 0;\n while (in_file.get(s)){\n\n std::cout &lt;&lt; count &lt;&lt; \": \"&lt;&lt; (int)s &lt;&lt;'\\n';\n count++;\n }\n\n }\n else{\n std::cout &lt;&lt; \"Unable to open input.txt.\\n\";\n }\n in_file.close();\n\n return 0;\n }\n</code></pre>\n\n<p>The content of the input file (<code>cat input.txt</code>) is</p>\n\n<pre><code>ab cd\nef gh\n</code></pre>\n\n<p>The output of the program is:</p>\n\n<pre><code>0: 97\n1: 98\n2: 32\n3: 99\n4: 100\n5: 10\n6: 101\n7: 102\n8: 32\n9: 103\n10: 104\n11: 32\n12: 10\n</code></pre>\n\n<p>10 and 32 are decimal representation of newline and space character. Obviously, all characters have been read.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I wanted to use `fstream` to read a txt file. I am using `inFile >> characterToConvert`, but the problem is that this omits any spaces and newline. I am writing an encryption program so I need to include the spaces and newlines. What would be the proper way to go about accomplishing this?
Probably the best way is to read the entire file's contents into a string, which can be done very easily using ifstream's [`rdbuf()`](http://en.cppreference.com/w/cpp/io/basic_ios/rdbuf) method: ``` std::ifstream in("myfile"); std::stringstream buffer; buffer << in.rdbuf(); std::string contents(buffer.str()); ``` You can then use regular string manipulation now that you've got everything from the file. While [Tomek](https://stackoverflow.com/users/20678/tomek) was asking about reading a text file, the same approach will work for reading binary data, though the std::ios::binary flag needs to be provided when creating the input file stream.
116,967
<p>Is it possible to call a JavaScript function from the IMG SRC tag to get an image url?</p> <p>Like this:</p> <pre><code>&lt;IMG SRC="GetImage()" /&gt; &lt;script language="javascript"&gt; function GetImage() {return "imageName/imagePath.jpg"} &lt;/script&gt; </code></pre> <p>This is using .NET 2.0.</p>
[ { "answer_id": 116979, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": -1, "selected": false, "text": "<p>No. The Img's SRC attribute is not an event, therefore the inline JS will never fire.</p>\n" }, { "answer_id": 116981, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 1, "selected": false, "text": "<p>You cannot do it inline the image @src, but you should be able to call it from an inline script block immediately following your image:</p>\n\n<pre><code>&lt;img src=\"\" id=\"myImage\"/&gt;\n&lt;script type=\"text/javascript\"&gt;\n document.getElementById(\"myImage\").src = GetImage();\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 116990, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 5, "selected": true, "text": "<p>Nope. It's not possible, at least not in all browsers. You can do something like this instead:</p>\n\n<pre><code>&lt;img src=\"blank.png\" id=\"image\" alt=\"just nothing\"&gt;\n&lt;script type=\"text/javascript\"&gt;\n document.getElementById('image').src = \"yourpicture.png\";\n&lt;/script&gt;\n</code></pre>\n\n<p>Your favourite JavaScript framework will provide nicer ways :)</p>\n" }, { "answer_id": 116991, "author": "Jack B Nimble", "author_id": 3800, "author_profile": "https://Stackoverflow.com/users/3800", "pm_score": 0, "selected": false, "text": "<p>Are you looking for this.src ?`</p>\n\n<pre><code>&lt;img src='images/test.jpg' onmouseover=\"alert(this.src);\"&gt; \n</code></pre>\n" }, { "answer_id": 116995, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 0, "selected": false, "text": "<p>Since you're using .NET, you could add the <code>runat=\"server\"</code> attribute and set the <code>src</code> in your codebehind.</p>\n" }, { "answer_id": 117001, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 0, "selected": false, "text": "<p>You <strong>might</strong> be able to do it on the server side. Alternately you could attach an onload event to swap the image src out. I guess the question then becomes, why would you have to use Javascript in the first pace?</p>\n" }, { "answer_id": 117418, "author": "ceetheman", "author_id": 16154, "author_profile": "https://Stackoverflow.com/users/16154", "pm_score": 1, "selected": false, "text": "<p>you could dynamically feed the image by calling an aspx page in the SRC.</p>\n\n<p>Ex; </p>\n\n<pre><code>&lt;img src=\"provideImage.aspx?someparameter=x\" /&gt;\n</code></pre>\n\n<p>On the page side, you`ll need to put the image in the response and change the content type for an image.</p>\n\n<p>The only \"problem\" is that your images won't be indexed a you better put some cache on that provider page or you'll ravage the server.</p>\n" }, { "answer_id": 118366, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Is it possible to call a JavaScript function from the IMG SRC tag to get an image url?</p>\n</blockquote>\n\n<p>Do you mean doing something like the following?</p>\n\n<pre><code>&lt;img src=\"javascript:GetImage()\" /&gt;\n</code></pre>\n\n<p>Unfortunately, no - you can't do that. However, you can do the following hack:</p>\n\n<pre><code>function getImageUrl(img) {\n var imageSrc = \"imageName/imagePath.jpg\";\n if(img.src != imageSrc) { // don't get stuck in an endless loop\n img.src = imageSrc;\n }\n}\n</code></pre>\n\n<p>Then, have the following html:</p>\n\n<pre><code>&lt;img src=\"http://yourdomain.com/images/empty.gif\" onload=\"getImageUrl(this)\" /&gt;\n</code></pre>\n\n<p>The onload event will only fire if you have an actual image set to the src attribute - if you don't set that attribute or set it to an empty string or something similar, you will get no love. Set it to a single pixel transparent gif or something similar.</p>\n\n<p>Anyway, this hack works, but depending on what you are really trying to accomplish, this may not be the best solution. I don't know why you would want to do this, but maybe you have a good reason (that you would like to share with us!).</p>\n" }, { "answer_id": 118414, "author": "Jeremy DeGroot", "author_id": 20820, "author_profile": "https://Stackoverflow.com/users/20820", "pm_score": 0, "selected": false, "text": "<p>I've had to do something like this before, and IIRC the trick winds up being that you can't change an src attribute of an image that's part of the DOM tree. So your best bet is to write your HTML skeleton without the image and 1)create an onLoad function that generates a new img element with document.createElement, 2) set the src attribute with setAttribute(), and 3) attach it to your DOM tree.</p>\n" }, { "answer_id": 355662, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>OnLoad event of image called again and again do some thing like this </p>\n\n<p></p>\n" }, { "answer_id": 355667, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>OnLoad event of image called again and again do some thing like this \n\n</p>\n" }, { "answer_id": 4027479, "author": "jdizzle", "author_id": 70603, "author_profile": "https://Stackoverflow.com/users/70603", "pm_score": 4, "selected": false, "text": "<p>If you're in the mood for hacks, this works as well.</p>\n\n<pre><code>&lt;img src='blah' onerror=\"this.src='url to image'\"&gt;\n</code></pre>\n" }, { "answer_id": 10512781, "author": "dodysugianto", "author_id": 1384114, "author_profile": "https://Stackoverflow.com/users/1384114", "pm_score": 0, "selected": false, "text": "<p>how about this?</p>\n\n<pre><code>var imgsBlocks = new Array( '/1.png', '/2.png', '/3.png');\nfunction getImageUrl(elemid) { \nvar ind = document.getElementById(elemid).selectedIndex;\ndocument.getElementById(\"get_img\").src=imgsBlocks[ind]; \n}\n</code></pre>\n\n<p>it's not work?</p>\n\n<pre><code>&lt;img src=\"'+imgsBlocks[2]+'\" id=\"get_img\"/&gt;\n</code></pre>\n" }, { "answer_id": 74036810, "author": "saisuresh", "author_id": 11801147, "author_profile": "https://Stackoverflow.com/users/11801147", "pm_score": 0, "selected": false, "text": "<p>You may try this way also</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const myImage = new Image(200, 200);\nmyImage.src = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoHCBEPEQ8PDxEPEQ8PEQ8PDw8RDxEPDw8PGBQZGRkUGBgcIS4lHB4rHxgYJzsmKzMxNzc1GiRIRTszPzA0QzEBDAwMEA8QGRISHjEhISE2MTQ0NDQxMTE0MTExMTQ0NDQ0NDExMTE0NDE0MTExMTQ0NDQ0MTQxMTExPzExNDQxMf/AABEIAM4A9QMBIgACEQEDEQH/xAAbAAEAAgMBAQAAAAAAAAAAAAAAAQcCBQYEA//EAEgQAAIBAgIDCwgIBAMJAAAAAAABAgMEERIFBiEHExYxNFR0krKz0jIzNVFhcnOTIkFCYnGRodEVgZTBI1LwFBckJVOio7HC/8QAGQEBAAMBAQAAAAAAAAAAAAAAAAEDBAUC/8QAKxEBAAIABAUDAwUBAAAAAAAAAAECAxExUQQTFDKBEiEzQXGxImGh0fAj/9oADAMBAAIRAxEAPwC5gAAAAAgwqVFFOUmlFJtybwSS42yvNOa+1HKULKMVCLw36azOXtjHiS9rx/ke8PDtiTlV4veK6rGBTj1v0jziXy6fhIet2kecy6lPwmjo8TeFfPquQFNcLtI85n1KfhIet+kecy6lPwkdHibwnn1XMCmeF+kecz6lLwmPDDSPOZ9Wn4R0eJvBz6roBS/DDSPOZ9Sn4SOGGkecz6lPwjpL7x/vBz6rpBSz1w0jzmfVp+EjhhpLnMurT8I6S+8HPquoFK8MdJc5n1KXhJ4YaR51PqU/COkv+xz67SukFLcMNI85n1KfhHDDSPOZ9Sn4R0l/2OfXaV0gpbhhpHnU+pT8I4X6R5zLq0/CR0l94OfVdIKX4X6S5zPqU/CFrfpHnM+pT8I6S/7HPrtK6CSmaWuekIvNv+f7s4U3F/jgkdxqrrjC9kqFaKpXGH0UsclXDjy48T9j/U8X4e9Izeq4tbTk64AFKwAAAAAAAAAAHH7o99KnaxpReDuJ5Ze2EVma/m8EVeiw91LyLP363ZiV6dXhIyw48seNP60MgkM0qWGBDMmYshIQySGBBBLIIkQyDIggAMQglBJAxIGSRkomOJKkBLIJxIJEmVGrKnOE4PLOEozjJbGpJ4pmJDIF96Nut/oUK3FvtOnUw9WaKeH6nrNTqtyCx6NQ7CNscafaZhvjQABCQAAAAAAAHBbqXkWfv1ezErwsPdS8iz9+r2YldnW4T4o8/lixu+QMhkmhUgxZkyGBABBCUMgkggCMQCAxIxIbLD1Q1IjKMbm+jmzJTp27xSS405+v3fzK8TErhxnL3Wk20cZo3Q9zdvChQqTX1zy5aa/Gb2fyxOltdzm7mk6tahS9iUqsl+WC/UtGnTjCKjFKMUsFGKSSXsSMzDbirzp7NEYNfqr+nuZw+3dzb+5RhD/22fX/AHa2/Objq0/2O7JK+fibvXKpsq7WPUinZWtW5jXqTdPJhCUYJPNUjHjXvHEplxboPo25/Gh30CnEbeGva9Zm3v7s+LWKzlDMxZkYs0K15ar8gsejUOwjamq1X5BY9Ft+wjanGtrLfGkAAISAAAAAAAA4LdT83Z/Eq9lFdFi7qfm7P36vZRXZ1+E+KPP5YsbvlDBANGapDDJMWEoIMzFkCCCSCBAYDZA6bULQivLnPUWNG2yVJp8UqmP0I+3am2vZ7S4kczqBYKhYUZYYSr415P62peT/ANuB0xyce/rvO0NuHXKqQCClYkHNaS11sLaThKpKrUWyUaMd8wfqctkf1NTLdLtvs29y1626Uf8A6LIwcSfeIeJxKx9W23QvRtz+NDvoFNxO61k12oX1pVtoUq8KlR03FzUMiyzjJ4tSx4ov6jhkb+GpatJi0Ze7Pi2ibewGTiQ2aFS89WOQWPRbfsI2pq9WeQ2PRbfu4m0OLbWW+ukAAISAAAAAAAA4HdT83Z/Eq9hFeFibqfm7P4lXsIrs6/CfFHn8sWN3yxIZkQaFSCGZEMhIQSYgRgRgZmBACEM8owXHOUYL8W8P7ks9Wh4Z7q1i/tXFBf8AkiebTlGaYXtbUVTp04LYoQjFL1JJL+x9wDiOgHA7penJ0YQs6UnCVaLlWktj3riUU/qxeOPsXtO+Kf3SZ5tIyX+ShRj+eaX9y/h6xbEjNXizlVyijgsFgl6icCQdRjMCUQSgAYDAvTVnkNj0W37uJtDV6tchsei2/YibQ4ttZb66QAAhIAAAAAAADgd1Pzdn8Sr2EV2WLup+bs/iVewiuzrcJ8UeWLG75DFmRjgaZVBDJIZCQhkkEAYtmR2W5paUq1W5VanTqKNOm4qpCM1F5ntWZbCvFv6KzbZ6rX1Tk4py/wBYnv1ff/GWfSbftouj+C2nNLX+npfsTDQ1rFxlC2toyi1KMo0KcZRkuJppbGY54yJjL0/yujAndsAAYmkKZ3Q3/wAyr+yFDsIuY8NfRdtVk51LehObwTnOjCcmlxYtrEtwcTl2zyzeL19UZKDxGJfP8Ds+aWv9PS/YfwSz5pa/09L9jT1kbKeRO6hsTJFra9aMtqWj7idO3t4Ti6OE4UYQksasE8GlitjZVKNOFicyueiu9PTOQSyCWWPC89WuQ2PRbfu4m0NXq1yGx6Lb92jaHFnWW+NIAAQkAAAAAAABwO6n5uz+JV7CK8LE3U/N2fv1eyiuzr8J8UefyxY3fIQSyGaVSCGAyEhDJBAxZ3W5T567+HT7cjhjudyrz138Kn25Gfifit/vqswu+FmAgHJbUgAAAQBIIAHNboXoy596h30CnUXFuh+jbj3rfvoFOnR4P45+7Lj9zIhkkM1KV56tchsei2/do2hq9WuQ2PRbfu0bQ4s6y310gABCQAAAAAAAHA7qXm7T36vZRXhYe6n5u09+r2UV4dfhPijz+WLG75CCSDRKpAZJDISgAMCD16M0tcWcpStqjpymlGTUKc8yTxS+kn6zyMhnmYiYylMezfcNNJc6l8mh4D16H1t0hUuranO4coVK9KE471RWaMppNYqGK2HKnu0Byyz6TQ7cSm+FT0z7R9fo9Re2ce6+QAcluCsNcdZr62vq1ChXcKUY0nGO90pYOUE3tlFvjLPKZ3QPSVx7tDu4mjhqxa+U+/sqxpmK+zDhnpLnT+TQ8A4Z6S5zL5NDwGgB0OVTaGb1W3be/wBZb25pyo167nTnlcob3SjjlkpLbGKfGkalAHqtYr7Q8zMzqkhmRiyRemrfIrLo1v3cTZms1c5FZdGt+7ibM4s6y3xpAACEgAAAAAAAOC3U/N2fv1eyivCw91Lzdn8Sr2EV2dfhPijz+WLG75CCTE0KkkMkghIQwQwIYDMSBke3QHLLPpNv24nhPdoDlln0m37cTxftn7S9RrC+QAcVvCmt0D0lX92h3cS5Smd0D0lce7Q7uJp4T5PCnH7XOgkg6TKkAASQySGBeurnIrLotv3cTZGt1c5FZdFt+7ibI4s6y310gABCQAAAAAAAHB7qXm7T4lTsortFibqXm7T4lTsoro6/CfFHn8sWN3ykxJBpVIIZJDISEAhkCTEMxIA9+gOWWfSaHbieA9+gOWWfSaHbieL9s/aXqNYXyADit4Uzug+krj3aHdxLmKZ3QfSVz7tDuomnhPk8Kcftc8AQdJkSAAMjFmZgwleurvIrLotv3cTZGs1d5FZdFt+7ibM4s6y310gABCQAAAAAAAHB7qXm7T4lTsIrss7dKs5VLWFWKx3iopT9kJLK3+eUrDE63Bz/AMo8sWNH60kEkM1KkGLMiGQlBizIxZAkwMzAgD36A5ZZ9Jt+3E8LPdoDlln0m37cTxftn7S9RrC+QAcVvCmd0H0lc+7Q7qJcxTO6D6Sufdod1E08J8nj+lOP2ueIAOkypAAQyMWQZ06cpyjCCcpzkoQS+uTeCX5hK8tXeRWXRbfu4mzPLo633mjRo/8ASp06f45Ypf2PUcWdXQjQABAAAADCE1JKUWnFpNNPFNPiaZmAAAHxrUozjKE0pQmnGUWsVKLWDTK105qJXpylOzwq0Xi1TcsKsPu7dkl7ccfxLQILMPFthznV4vSLaqRer96nh/slxs+42Rwfvea3Hy2XfgDT1t9oV9PXdR/B+95pcfLYer99zS4+Wy8BgOtvtH8/2ciN5UfwevuaXHy2Y8Hr7mlx1GXlgMCOtvtByI3lRnB2+5pc/LY4O33NLjqMvMkdZfaP5ORG6i+Dt9zS46jPZoXQN7C6tZzta8YQuKMpycGlGKmm2y5xgeZ4u0xllBGBWPqkAGVeFT67aGuq1/XqUretUhKNFRnCDcXhTing/wAUWwRgWYeJOHOcPN6+qMlF8Hb7mlx1GODt9zW4+Wy9MBgX9ZbaFXIjdRnB6+5pcfLY4O33NLn5bLzGA6u20HIjdSNDVi/m1GNpWXtnFQiv5yZ3WqOpqtJK4uXGdwvIjHFwo4ra8X5UtvH9R2oPF+IveMtHquFWs5oRIBnWgAAAADXav8js+i2/dxNia7V/kdn0W37uJsQAAAAAAAAPLeXkKEYyqNpSlGEcsJzk5y4koxTZ4rTTVOpJwnjCpvtSko5ZuMstScE1LLg/J24cTeDPbe2kLinKnUzZJbJKMnHMuLB4fUeaehqLy7Jpwc5QlGpNSi51d8bTx/zfpsA8tPWSjOUYxjWcZ1Y0Yz3mooPNQ35Sxy7Fl/fiM6WslpUjmhWzxSm2406klGMYxlKTwjsWWcXi9m0+tLQdvFRUYzSjKnJLfJtKUaW9J8f1weV+tH0o6LpU1HB1PowlTg3VnKUaclBNJt7PIj+QHyenKKqSg1VWFOhVUt4q/T3yU4xillxcsY8X7M+dzrBQjFVIzUoKdGFSbU4U4Kc4xeMmsFJKSeV7fwPotC0FhgpppQimqk01knKpF8fGnKW37zXEI6Bt1FwyyyYwnKm5ycJTi01NpvbJ5Vi3xgemrf04qnmzp1VjBb3NywwTbcUsYpYrFvDA8stYLVLM5ywwzeZreRlzZ/J8nBN5uLZxn3ejabVNN1G6Kyxlvk82VxScXLHFppLHHjaPjHQdulJZZtOnKjtqTbVJxcci27Ek3h6sWB6aOkKU4xmppKdSVKKlF05OpFyTjlkk1LGMtj9R4rvTcaU60JRj/hOEVmqZZScsn0sGsFBZ1jLHZg9hs7e3jSUlFYKU51Htb+nOTk3+bZ8Kuj6cpynJ1HKUJwX+JPCEZJKWVY/RbwW1AeCGnc6ouNGco11UUMtSDc5wU24x+px+j5WK8qP1Y4IafTbUqUkqc4wryzxcaeaq6cXF/aWZPF7MMGeuroejPDzkUoqMIwqzhGGEXBSST2SUW1ij5LQdvhFSUpQglDJKTcJwi8YwlHilFPFpP1sD4z0+lGdSNGbhTqqm5OUY4xcacoyS+8qiwTw4ni0Zz0xLJXnGEGrdzzRlWlCpki5LM45HxuOxbcTPg/arOoUlTjUljUhSbpQqfRjHLKMcE44QWz8fWz7vRlPFylnlKUqbbnOU/Jk5Rjt+ypPHAD1UZSlGLlHLJxi5RxTcZNbY4rjwPsAAAAAAAAAAAAH/2Q==';\ndocument.body.appendChild(myImage);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20682/" ]
Is it possible to call a JavaScript function from the IMG SRC tag to get an image url? Like this: ``` <IMG SRC="GetImage()" /> <script language="javascript"> function GetImage() {return "imageName/imagePath.jpg"} </script> ``` This is using .NET 2.0.
Nope. It's not possible, at least not in all browsers. You can do something like this instead: ``` <img src="blank.png" id="image" alt="just nothing"> <script type="text/javascript"> document.getElementById('image').src = "yourpicture.png"; </script> ``` Your favourite JavaScript framework will provide nicer ways :)
116,968
<p>I have a database full of customer data. It's so big that it's really cumbersome to operate on, and I'd rather just slim it down to 10% of the customers, which is plenty for development. I have an awful lot of tables and I don't want to alter them all with "ON DELETE CASCADE", especially because this is a one-time deal.</p> <p>Can I do a delete operation that cascades through all my tables without setting them up first? If not, what is my best option?</p>
[ { "answer_id": 117044, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 2, "selected": false, "text": "<p>I usually just hand write the queries to delete the records I don't want and save that as a .sql file for future reference. The pseudocode is:</p>\n\n<ol>\n<li>select id's of records from the main table that I want to delete into a temp table</li>\n<li>write a delete query for each related table which joins to the temp table.</li>\n<li>write a delete query for the main table joining to my temp table.</li>\n</ol>\n" }, { "answer_id": 117046, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 2, "selected": false, "text": "<p>My suggestion is to go ahead and write a script that will add the on delete cascade to each relationship in the database while exporting a list of modified relationships. Then you can reverse the process and remove the on delete cascade command on each table in the list.</p>\n" }, { "answer_id": 117064, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 2, "selected": false, "text": "<p>Personally if you are going to leave the records in production, I would also leave them in development. Otherwise you may write code that works fine when the recordset is small but times out when faced with the real recordset.</p>\n\n<p>But if you are determined to do this, I would copy the id field of the records you want to dete from the main table first to a work table. Then I would take each related table and write a delete joining to that worktable to only delete those records. Finish up with the parent table. Make sure this ia written in a script and saved so the next time you want to do a similar thing to your test data, you can easily run it without having to figure out what are the reated tables that need records deleted from them.</p>\n" }, { "answer_id": 117186, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 3, "selected": false, "text": "<p>Go into SQL Server Management Studio and right-click the database. Select Tasks->Generate Scripts. Click Next twice. On the Options window choose set it to generate CREATE statements only, and put everything to False except for the Foreign Keys. Click Next. Select Tables and Click Next again. Click the \"Select All\" button and click Next then Finish and send the script to your choice of a query window or file (don't use the clipboard, since it might be a big script). <strong>Now remove all of the script that adds the tables</strong> and you should be left with a script to create your foreign keys.</p>\n\n<p>Make a copy of that script because it is how you'll restore your database to its current state. Use a search and replace to add the ON DELETE CASCADE to the end of each constraint. This might vary depending on how your FKs are currently set up and you might need to do some manual editing.</p>\n\n<p>Repeat the script generation, but this time set it to generate DROP statements only. <strong>Be sure to manually remove the table drops that are generated</strong>. Run the drops, then run your edited creates to make them all cascade on delete. Do your deletes, run the drop script again and then run the script that you saved off at the start.</p>\n\n<p>Also - <strong>MAKE A BACKUP OF YOUR DB FIRST!</strong> Even if it's just a dev database, it will save you some headache if part of the script isn't quite right.</p>\n\n<p>Hope this helps!</p>\n\n<p>BTW - you should definitely do some testing with your full test data as another poster suggested, but I can see why you might not need that for initial development. Just don't forget to include that as part of QA at some point.</p>\n" }, { "answer_id": 117239, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 3, "selected": false, "text": "<p>Unless you want to maintain all related queries as proposed by Chris, the ON DELETE CASCADE is by far the quickest and the most direct solution. And if you don't want it to be permanent, why don't you have some T-SQL code that will switch this option on and off like here</p>\n\n<ol>\n<li><p>remove the original <code>Tbl_A_MyFK</code> constraint (without the ON DELETE CASCADE)</p>\n\n<p><code>ALTER TABLE Tbl_A DROP CONSTRAINT Tbl_A_MyFK</code></p></li>\n<li><p>set the constraint <code>Tbl_A_MyFK</code> with the ON DELETE CASCADE </p>\n\n<p><code>ALTER TABLE Tbl_A ADD CONSTRAINT Tbl_A_MyFK FOREIGN KEY (MyFK) REFERENCES Tbl_B(Column) ON DELETE CASCADE</code></p></li>\n<li><p>Here you can do your delete</p>\n\n<p><code>DELETE FROM Tbl_A WHERE ...</code></p></li>\n<li><p>drop your constraint <code>Tbl_A_MyFK</code></p>\n\n<p><code>ALTER TABLE Tbl_A DROP CONSTRAINT Tbl_A_MyFK</code></p></li>\n<li><p>set the constraint <code>Tbl_A_MyFK</code> without the ON DELETE CASCADE</p>\n\n<p><code>ALTER TABLE Tbl_A ADD CONSTRAINT Tbl_A_MyFK FOREIGN KEY (MyFK) REFERENCES (Tbl_B)</code> </p></li>\n</ol>\n" }, { "answer_id": 118167, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 7, "selected": true, "text": "<p>Combining your advice and a script I found online, I made a procedure that will produce SQL you can run to perform a cascaded delete regardless of <code>ON DELETE CASCADE</code>. It was probably a big waste of time, but I had a good time writing it. An advantage of doing it this way is, you can put a <code>GO</code> statement between each line, and it doesn't have to be one big transaction. The original was a recursive procedure; this one unrolls the recursion into a stack table.</p>\n\n<pre><code>create procedure usp_delete_cascade (\n @base_table_name varchar(200), @base_criteria nvarchar(1000)\n)\nas begin\n -- Adapted from http://www.sqlteam.com/article/performing-a-cascade-delete-in-sql-server-7\n -- Expects the name of a table, and a conditional for selecting rows\n -- within that table that you want deleted.\n -- Produces SQL that, when run, deletes all table rows referencing the ones\n -- you initially selected, cascading into any number of tables,\n -- without the need for \"ON DELETE CASCADE\".\n -- Does not appear to work with self-referencing tables, but it will\n -- delete everything beneath them.\n -- To make it easy on the server, put a \"GO\" statement between each line.\n\n declare @to_delete table (\n id int identity(1, 1) primary key not null,\n criteria nvarchar(1000) not null,\n table_name varchar(200) not null,\n processed bit not null,\n delete_sql varchar(1000)\n )\n\n insert into @to_delete (criteria, table_name, processed) values (@base_criteria, @base_table_name, 0)\n\n declare @id int, @criteria nvarchar(1000), @table_name varchar(200)\n while exists(select 1 from @to_delete where processed = 0) begin\n select top 1 @id = id, @criteria = criteria, @table_name = table_name from @to_delete where processed = 0 order by id desc\n\n insert into @to_delete (criteria, table_name, processed)\n select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_name +'] where ' + @criteria + ')',\n referencing_table.name,\n 0\n from sys.foreign_key_columns fk\n inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id \n and fk.parent_column_id = referencing_column.column_id \n inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id \n and fk.referenced_column_id = referenced_column.column_id \n inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id \n inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id \n inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id\n where referenced_table.name = @table_name\n and referencing_table.name != referenced_table.name\n\n update @to_delete set\n processed = 1\n where id = @id\n end\n\n select 'print ''deleting from ' + table_name + '...''; delete from [' + table_name + '] where ' + criteria from @to_delete order by id desc\nend\n\nexec usp_delete_cascade 'root_table_name', 'id = 123'\n</code></pre>\n" }, { "answer_id": 5505602, "author": "dan", "author_id": 686446, "author_profile": "https://Stackoverflow.com/users/686446", "pm_score": 1, "selected": false, "text": "<p>after select you have to build and execute the actual delete</p>\n\n<pre><code>declare @deleteSql nvarchar(1200)\ndeclare delete_cursor cursor for\nselect table_name, criteria \nfrom @to_delete\norder by id desc\n\nopen delete_cursor\n\nfetch next from delete_cursor\ninto @table_name, @criteria\n\nwhile @@fetch_status = 0\nbegin\n select @deleteSql = 'delete from ' + @table_name + ' where ' + @criteria\n --print @deleteSql\n-- exec sp_execute @deleteSql\nEXEC SP_EXECUTESQL @deleteSql\n\n fetch next from delete_cursor\n into @table_name, @criteria\nend\nclose delete_cursor\ndeallocate delete_cursor\n</code></pre>\n" }, { "answer_id": 7691473, "author": "kevin_fitz", "author_id": 251056, "author_profile": "https://Stackoverflow.com/users/251056", "pm_score": 2, "selected": false, "text": "<p>Taking the accepted answer a bit further, I had the need to do this across tables in different schemas. I have updated the script to include schema in the outputted delete scripts.</p>\n\n<pre><code>CREATE PROCEDURE usp_delete_cascade (\n @base_table_schema varchar(100), @base_table_name varchar(200), @base_criteria nvarchar(1000)\n)\nas begin\n\n -- Expects the name of a table, and a conditional for selecting rows\n -- within that table that you want deleted.\n -- Produces SQL that, when run, deletes all table rows referencing the ones\n -- you initially selected, cascading into any number of tables,\n -- without the need for \"ON DELETE CASCADE\".\n -- Does not appear to work with self-referencing tables, but it will\n -- delete everything beneath them.\n -- To make it easy on the server, put a \"GO\" statement between each line.\n\n declare @to_delete table (\n id int identity(1, 1) primary key not null,\n criteria nvarchar(1000) not null,\n table_schema varchar(100),\n table_name varchar(200) not null,\n processed bit not null,\n delete_sql varchar(1000)\n )\n\n insert into @to_delete (criteria, table_schema, table_name, processed) values (@base_criteria, @base_table_schema, @base_table_name, 0)\n\n declare @id int, @criteria nvarchar(1000), @table_name varchar(200), @table_schema varchar(100)\n while exists(select 1 from @to_delete where processed = 0) begin\n select top 1 @id = id, @criteria = criteria, @table_name = table_name, @table_schema = table_schema from @to_delete where processed = 0 order by id desc\n\n insert into @to_delete (criteria, table_schema, table_name, processed)\n select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_schema + '].[' + @table_name +'] where ' + @criteria + ')',\n schematable.name,\n referencing_table.name,\n 0\n from sys.foreign_key_columns fk\n inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id \n and fk.parent_column_id = referencing_column.column_id \n inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id \n and fk.referenced_column_id = referenced_column.column_id \n inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id \n inner join sys.schemas schematable on referencing_table.schema_id = schematable.schema_id\n inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id \n inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id\n where referenced_table.name = @table_name\n and referencing_table.name != referenced_table.name\n\n update @to_delete set\n processed = 1\n where id = @id\n end\n\n select 'print ''deleting from ' + table_name + '...''; delete from [' + table_schema + '].[' + table_name + '] where ' + criteria from @to_delete order by id desc\nend\n\nexec usp_delete_cascade 'schema', 'RootTable', 'Id = 123'\nexec usp_delete_cascade 'schema', 'RootTable', 'GuidId = ''A7202F84-FA57-4355-B499-1F8718E29058'''\n</code></pre>\n" }, { "answer_id": 8214267, "author": "croisharp", "author_id": 745682, "author_profile": "https://Stackoverflow.com/users/745682", "pm_score": 2, "selected": false, "text": "<p>Kevin post is incomplete, his t-sql sp only prints the command, to execute these command, before last end add this</p>\n\n<pre><code>DECLARE @commandText VARCHAR(8000)\n DECLARE curDeletes CURSOR FOR\n select 'delete from [' + table_name + '] where ' + criteria from @to_delete order by id desc\n\n OPEN curDeletes\n FETCH NEXT FROM curDeletes\n INTO\n @commandText\n\n WHILE(@@FETCH_STATUS=0)\n BEGIN\n EXEC (@commandText)\n FETCH NEXT FROM curDeletes INTO @commandText\n END\n CLOSE curDeletes\n DEALLOCATE curDeletes\n</code></pre>\n" }, { "answer_id": 12833632, "author": "Neil", "author_id": 1547203, "author_profile": "https://Stackoverflow.com/users/1547203", "pm_score": 3, "selected": false, "text": "<p>Here's a version of the accepted answer optimised for sparsely populated data models. It checks for the existence of data in a FK chain before adding it to the deletion list. I use it to clean up test data. </p>\n\n<p>Don't use it in an active transactional db- it will hold locks way too long.</p>\n\n<pre><code>/*\n-- ============================================================================\n-- Purpose: Performs a cascading hard-delete.\n-- Not for use on an active transactional database- it holds locks for too long.\n-- (http://stackoverflow.com/questions/116968/in-sql-server-2005-can-i-do-a-cascade-delete-without-setting-the-property-on-my)\n-- eg:\nexec dbo.hp_Common_Delete 'tblConsumer', 'Surname = ''TestDxOverdueOneReviewWm''', 1\n-- ============================================================================\n*/\ncreate proc [dbo].[hp_Common_Delete]\n(\n @TableName sysname, \n @Where nvarchar(4000), -- Shouldn't include 'where' keyword, e.g. Surname = 'smith', NOT where Surname = 'smith'\n @IsDebug bit = 0\n)\nas\nset nocount on\n\nbegin try\n -- Prepare tables to store deletion criteria. \n -- #tmp_to_delete stores criteria that is tested for results before being added to #to_delete\n create table #to_delete\n (\n id int identity(1, 1) primary key not null,\n criteria nvarchar(4000) not null,\n table_name sysname not null,\n processed bit not null default(0)\n )\n create table #tmp_to_delete \n (\n id int primary key identity(1,1), \n criteria nvarchar(4000) not null, \n table_name sysname not null\n )\n\n -- Open a transaction (it'll be a long one- don't use this on production!)\n -- We need a transaction around criteria generation because we only \n -- retain criteria that has rows in the db, and we don't want that to change under us.\n begin tran\n -- If the top-level table meets the deletion criteria, add it\n declare @Sql nvarchar(4000)\n set @Sql = 'if exists(select top(1) * from ' + @TableName + ' where ' + @Where + ') \n insert #to_delete (criteria, table_name) values (''' + replace(@Where, '''', '''''') + ''', ''' + @TableName + ''')'\n exec (@Sql)\n\n -- Loop over deletion table, walking foreign keys to generate delete targets\n declare @id int, @tmp_id int, @criteria nvarchar(4000), @new_criteria nvarchar(4000), @table_name sysname, @new_table_name sysname\n while exists(select 1 from #to_delete where processed = 0) \n begin\n -- Grab table/criteria to work on\n select top(1) @id = id, \n @criteria = criteria, \n @table_name = table_name \n from #to_delete \n where processed = 0 \n order by id desc\n\n -- Insert all immediate child tables into a temp table for processing\n insert #tmp_to_delete\n select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_name +'] where ' + @criteria + ')',\n referencing_table.name\n from sys.foreign_key_columns fk\n inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id \n and fk.parent_column_id = referencing_column.column_id \n inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id \n and fk.referenced_column_id = referenced_column.column_id \n inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id \n inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id \n inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id\n where referenced_table.name = @table_name\n and referencing_table.name != referenced_table.name\n\n -- Loop on child table criteria, and insert them into delete table if they have records in the db\n select @tmp_id = max(id) from #tmp_to_delete\n while (@tmp_id &gt;= 1)\n begin\n select @new_criteria = criteria, @new_table_name = table_name from #tmp_to_delete where id = @tmp_id\n set @Sql = 'if exists(select top(1) * from ' + @new_table_name + ' where ' + @new_criteria + ') \n insert #to_delete (criteria, table_name) values (''' + replace(@new_criteria, '''', '''''') + ''', ''' + @new_table_name + ''')'\n exec (@Sql)\n\n set @tmp_id = @tmp_id - 1\n end\n truncate table #tmp_to_delete\n\n -- Move to next record\n update #to_delete \n set processed = 1\n where id = @id\n end\n\n -- We have a list of all tables requiring deletion. Actually delete now.\n select @id = max(id) from #to_delete \n while (@id &gt;= 1)\n begin\n select @criteria = criteria, @table_name = table_name from #to_delete where id = @id\n set @Sql = 'delete from [' + @table_name + '] where ' + @criteria\n if (@IsDebug = 1) print @Sql\n exec (@Sql)\n\n -- Next record\n set @id = @id - 1\n end\n commit\nend try\n\nbegin catch\n -- Any error results in a rollback of the entire job\n if (@@trancount &gt; 0) rollback\n\n declare @message nvarchar(2047), @errorProcedure nvarchar(126), @errorMessage nvarchar(2048), @errorNumber int, @errorSeverity int, @errorState int, @errorLine int\n select @errorProcedure = isnull(error_procedure(), N'hp_Common_Delete'), \n @errorMessage = isnull(error_message(), N'hp_Common_Delete unable to determine error message'), \n @errorNumber = error_number(), @errorSeverity = error_severity(), @errorState = error_state(), @errorLine = error_line()\n\n -- Prepare error information as it would be output in SQL Mgt Studio\n declare @event nvarchar(2047)\n select @event = 'Msg ' + isnull(cast(@errorNumber as varchar), 'null') + \n ', Level ' + isnull(cast(@errorSeverity as varchar), 'null') + \n ', State ' + isnull(cast(@errorState as varchar), 'null') + \n ', Procedure ' + isnull(@errorProcedure, 'null') + \n ', Line ' + isnull(cast(@errorLine as varchar), 'null') + \n ': ' + isnull(@errorMessage, '@ErrorMessage null')\n print @event\n\n -- Re-raise error to ensure admin/job runners understand there was a failure\n raiserror(@errorMessage, @errorSeverity, @errorState)\nend catch\n</code></pre>\n" }, { "answer_id": 16877011, "author": "Łukasz Nojek", "author_id": 1454656, "author_profile": "https://Stackoverflow.com/users/1454656", "pm_score": 2, "selected": false, "text": "<p>Expansion of croisharp's answer to take triggers into consideration, i.e. schema-aware solution that disables all affecting triggers, deletes rows, and enables the triggers.</p>\n\n<pre><code>CREATE PROCEDURE usp_delete_cascade (\n@base_table_schema varchar(100),\n@base_table_name varchar(200),\n@base_criteria nvarchar(1000)\n)\nas begin\n\n -- Expects the name of a table, and a conditional for selecting rows\n -- within that table that you want deleted.\n -- Produces SQL that, when run, deletes all table rows referencing the ones\n -- you initially selected, cascading into any number of tables,\n -- without the need for \"ON DELETE CASCADE\".\n -- Does not appear to work with self-referencing tables, but it will\n -- delete everything beneath them.\n -- To make it easy on the server, put a \"GO\" statement between each line.\n\n declare @to_delete table (\n id int identity(1, 1) primary key not null,\n criteria nvarchar(1000) not null,\n table_schema varchar(100),\n table_name varchar(200) not null,\n processed bit not null,\n delete_sql varchar(1000)\n )\n\n insert into @to_delete (criteria, table_schema, table_name, processed) values (@base_criteria, @base_table_schema, @base_table_name, 0)\n\n declare @id int, @criteria nvarchar(1000), @table_name varchar(200), @table_schema varchar(100)\n while exists(select 1 from @to_delete where processed = 0) begin\n select top 1 @id = id, @criteria = criteria, @table_name = table_name, @table_schema = table_schema from @to_delete where processed = 0 order by id desc\n\n insert into @to_delete (criteria, table_schema, table_name, processed)\n select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_schema + '].[' + @table_name +'] where ' + @criteria + ')',\n schematable.name,\n referencing_table.name,\n 0\n from sys.foreign_key_columns fk\n inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id \n and fk.parent_column_id = referencing_column.column_id \n inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id \n and fk.referenced_column_id = referenced_column.column_id \n inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id \n inner join sys.schemas schematable on referencing_table.schema_id = schematable.schema_id\n inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id \n inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id\n where referenced_table.name = @table_name\n and referencing_table.name != referenced_table.name\n\n update @to_delete set\n processed = 1\n where id = @id\n end\n\n select 'print ''deleting from ' + table_name + '...''; delete from [' + table_schema + '].[' + table_name + '] where ' + criteria from @to_delete order by id desc\n\n DECLARE @commandText VARCHAR(8000), @triggerOn VARCHAR(8000), @triggerOff VARCHAR(8000)\n DECLARE curDeletes CURSOR FOR\n select\n 'DELETE FROM [' + table_schema + '].[' + table_name + '] WHERE ' + criteria,\n 'ALTER TABLE [' + table_schema + '].[' + table_name + '] DISABLE TRIGGER ALL',\n 'ALTER TABLE [' + table_schema + '].[' + table_name + '] ENABLE TRIGGER ALL'\n from @to_delete order by id desc\n\n OPEN curDeletes\n FETCH NEXT FROM curDeletes INTO @commandText, @triggerOff, @triggerOn\n\n WHILE(@@FETCH_STATUS=0)\n BEGIN\n EXEC (@triggerOff)\n EXEC (@commandText)\n EXEC (@triggerOn)\n FETCH NEXT FROM curDeletes INTO @commandText, @triggerOff, @triggerOn\n END\n CLOSE curDeletes\n DEALLOCATE curDeletes\nend\n</code></pre>\n" }, { "answer_id": 17875032, "author": "prampe", "author_id": 2621638, "author_profile": "https://Stackoverflow.com/users/2621638", "pm_score": 0, "selected": false, "text": "<p>This script has two issues:\n1. You must indicate the condition 1=1 in order to delete all table base.\n2. This creates the direct relations with the base table only. If the final table has another table parent relation, the the delete fail</p>\n\n<p>DELETE FROM [dbo].[table2] WHERE TableID in (select [ID] from [dbo].[table3] where 1=1)</p>\n\n<p>If table2 has a parent relation table1</p>\n" }, { "answer_id": 33266262, "author": "Jason Zheng", "author_id": 5472816, "author_profile": "https://Stackoverflow.com/users/5472816", "pm_score": 1, "selected": false, "text": "<p>Post here a script that will work with foreign keys contain more than one column. </p>\n\n<pre><code>create procedure usp_delete_cascade (\n@TableName varchar(200), @Where nvarchar(1000)\n) as begin\n\ndeclare @to_delete table (\n id int identity(1, 1) primary key not null,\n criteria nvarchar(1000) not null,\n table_name varchar(200) not null,\n processed bit not null default(0),\n delete_sql varchar(1000)\n)\n DECLARE @MyCursor CURSOR\n\ndeclare @referencing_column_name varchar(1000)\ndeclare @referencing_table_name varchar(1000)\n declare @Sql nvarchar(4000)\ninsert into @to_delete (criteria, table_name) values ('', @TableName)\n\n\ndeclare @id int, @criteria nvarchar(1000), @table_name varchar(200)\nwhile exists(select 1 from @to_delete where processed = 0) begin\n select top 1 @id = id, @criteria = criteria, @table_name = table_name from @to_delete where processed = 0 order by id desc\n SET @MyCursor = CURSOR FAST_FORWARD\n FOR\n select referencing_column.name as column_name,\n referencing_table.name as table_name\n from sys.foreign_key_columns fk\n inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id \n and fk.parent_column_id = referencing_column.column_id \n inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id \n and fk.referenced_column_id = referenced_column.column_id \n inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id \n inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id \n inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id\n where referenced_table.name = @table_name\n and referencing_table.name != referenced_table.name\n\n OPEN @MyCursor\n FETCH NEXT FROM @MYCursor\n INTO @referencing_column_name, @referencing_table_name\n\n WHILE @@FETCH_STATUS = 0\n\n BEGIN\n PRINT @referencing_column_name\n PRINT @referencing_table_name\n update @to_delete set criteria = criteria + ' AND '+@table_name+'.'+@referencing_column_name+'='+ @referencing_table_name+'.'+@referencing_column_name\n where table_name = @referencing_table_name\n\n if(@@ROWCOUNT = 0)\n BEGIN\n --if(@id &lt;&gt; 1)\n --BEGIN\n insert into @to_delete (criteria, table_name)\n VALUES( ' LEFT JOIN '+@table_name+' ON '+@table_name+'.'+@referencing_column_name+'='+ @referencing_table_name+'.'+@referencing_column_name+ @criteria,\n @referencing_table_name\n )\n --END\n --ELSE\n --BEGIN\n --insert into @to_delete (criteria, table_name)\n --VALUES( ' LEFT JOIN '+@table_name+' ON '+@table_name+'.'+@referencing_column_name+'='+ @referencing_table_name+'.'+@referencing_column_name,\n --@referencing_table_name\n --)\n --END\n END\n FETCH NEXT FROM @MYCursor\n INTO @referencing_column_name, @referencing_table_name\n END\n\n\n CLOSE @MyCursor \n DEALLOCATE @MyCursor \n update @to_delete set\n processed = 1\n where id = @id\nend\n\n--select 'print ''deleting from ' + table_name + '...''; delete from [' + table_name + '] where ' + criteria from @to_delete order by id desc\n\n--select id, table_name, criteria, @Where from @to_delete order by id desc\n\nselect @id = max(id) from @to_delete\nwhile (@id &gt;= 1)\nbegin\n select @criteria = criteria, @table_name = table_name from @to_delete where id = @id\n set @Sql = 'delete [' + @table_name + '] from [' + @table_name + '] ' + @criteria+' WHERE '+@Where\n exec (@Sql)\n PRINT @Sql\n\n -- Next record\n set @id = @id - 1\nend\nend\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/116968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10906/" ]
I have a database full of customer data. It's so big that it's really cumbersome to operate on, and I'd rather just slim it down to 10% of the customers, which is plenty for development. I have an awful lot of tables and I don't want to alter them all with "ON DELETE CASCADE", especially because this is a one-time deal. Can I do a delete operation that cascades through all my tables without setting them up first? If not, what is my best option?
Combining your advice and a script I found online, I made a procedure that will produce SQL you can run to perform a cascaded delete regardless of `ON DELETE CASCADE`. It was probably a big waste of time, but I had a good time writing it. An advantage of doing it this way is, you can put a `GO` statement between each line, and it doesn't have to be one big transaction. The original was a recursive procedure; this one unrolls the recursion into a stack table. ``` create procedure usp_delete_cascade ( @base_table_name varchar(200), @base_criteria nvarchar(1000) ) as begin -- Adapted from http://www.sqlteam.com/article/performing-a-cascade-delete-in-sql-server-7 -- Expects the name of a table, and a conditional for selecting rows -- within that table that you want deleted. -- Produces SQL that, when run, deletes all table rows referencing the ones -- you initially selected, cascading into any number of tables, -- without the need for "ON DELETE CASCADE". -- Does not appear to work with self-referencing tables, but it will -- delete everything beneath them. -- To make it easy on the server, put a "GO" statement between each line. declare @to_delete table ( id int identity(1, 1) primary key not null, criteria nvarchar(1000) not null, table_name varchar(200) not null, processed bit not null, delete_sql varchar(1000) ) insert into @to_delete (criteria, table_name, processed) values (@base_criteria, @base_table_name, 0) declare @id int, @criteria nvarchar(1000), @table_name varchar(200) while exists(select 1 from @to_delete where processed = 0) begin select top 1 @id = id, @criteria = criteria, @table_name = table_name from @to_delete where processed = 0 order by id desc insert into @to_delete (criteria, table_name, processed) select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_name +'] where ' + @criteria + ')', referencing_table.name, 0 from sys.foreign_key_columns fk inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id and fk.parent_column_id = referencing_column.column_id inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id and fk.referenced_column_id = referenced_column.column_id inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id where referenced_table.name = @table_name and referencing_table.name != referenced_table.name update @to_delete set processed = 1 where id = @id end select 'print ''deleting from ' + table_name + '...''; delete from [' + table_name + '] where ' + criteria from @to_delete order by id desc end exec usp_delete_cascade 'root_table_name', 'id = 123' ```
117,006
<p>In git, it is up to each user to specify the correct author in their local git config file. When they push to a centralized bare repository, the commit messages on the repository will have the author names that they used when committing to their own repository.</p> <p>Is there a way enforce that a set of known authors for commits are used? The "central" repository will be accessible via ssh.</p> <p>I know that this is complicated by the fact that some people may be pushing commits that were made by others. Of course, you should also only allow people you trust to push to your repositories, but it would be great if there was a way to prevent user error here.</p> <p>Is there a simple solution to this problem in git? </p>
[ { "answer_id": 117026, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 0, "selected": false, "text": "<p>What you could do is create a bunch of different user accounts, put them all in the same group and give that group write access to the repository. Then you should be able to write a simple incoming hook that checks if the user that executes the script is the same as the user in the changeset.</p>\n\n<p>I've never done it because I trust the guys that check code into my repositories, but if there is a way, that's probably the one explained above.</p>\n" }, { "answer_id": 117032, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 0, "selected": false, "text": "<p>git wasn't initially designed to work like svn with a big central repository. Perhaps you can pull from people as needed, and refuse to pull if they have their author set inaccurately?</p>\n" }, { "answer_id": 117282, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 0, "selected": false, "text": "<p>If you want to manage rights to an internet facing git repo, I suggest you look at <a href=\"http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way\" rel=\"nofollow noreferrer\">Gitosis</a> rather than whipping up your own. Identity is provided by private/public key pairs.</p>\n\n<p>Read me <a href=\"https://stackoverflow.com/questions/109440/best-git-repository-hosting-for-commercial-project#110007\">pimping it here</a>, too.</p>\n" }, { "answer_id": 641979, "author": "Anders Waldenborg", "author_id": 24082, "author_profile": "https://Stackoverflow.com/users/24082", "pm_score": 3, "selected": false, "text": "<p>Use the PRE-RECEIVE hook (see <a href=\"http://git-scm.com/docs/githooks\" rel=\"noreferrer\" title=\"githooks(5)\">githooks(5)</a> for details). There you get old sha and new sha for each ref updated. And can easily list the changes and check that they have proper author (git rev-list --pretty=format:\"%an %ae%n\" oldsha..newsha).</p>\n\n<p>Here is an example script:</p>\n\n<pre><code>#!/bin/bash\n#\n# This pre-receive hooks checks that all new commit objects\n# have authors and emails with matching entries in the files\n# valid-emails.txt and valid-names.txt respectively.\n#\n# The valid-{emails,names}.txt files should contain one pattern per\n# line, e.g:\n#\n# ^.*@0x63.nu$\n# ^[email protected]$\n#\n# To just ensure names are just letters the following pattern\n# could be used in valid-names.txt:\n# ^[a-zA-Z ]*$\n#\n\n\nNOREV=0000000000000000000000000000000000000000\n\nwhile read oldsha newsha refname ; do\n # deleting is always safe\n if [[ $newsha == $NOREV ]]; then\n continue\n fi\n\n # make log argument be \"..$newsha\" when creating new branch\n if [[ $oldsha == $NOREV ]]; then\n revs=$newsha\n else\n revs=$oldsha..$newsha\n fi\n echo $revs\n git log --pretty=format:\"%h %ae %an%n\" $revs | while read sha email name; do\n if [[ ! $sha ]]; then\n continue\n fi\n grep -q -f valid-emails.txt &lt;&lt;&lt;\"$email\" || {\n echo \"Email address '$email' in commit $sha not registred when updating $refname\"\n exit 1\n }\n grep -q -f valid-names.txt &lt;&lt;&lt;\"$name\" || {\n echo \"Name '$name' in commit $sha not registred when updating $refname\"\n exit 1\n }\n done\ndone\n</code></pre>\n" }, { "answer_id": 642182, "author": "dsvensson", "author_id": 5962, "author_profile": "https://Stackoverflow.com/users/5962", "pm_score": 4, "selected": true, "text": "<p>We use the following to prevent accidental unknown-author commits (for example when doing a fast commit from a customer's server or something). It should be placed in .git/hooks/pre-receive and made executable.</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport subprocess\nfrom itertools import islice, izip\nimport sys\n\nold, new, branch = sys.stdin.read().split()\n\nauthors = {\n \"John Doe\": \"[email protected]\"\n}\n\nproc = subprocess.Popen([\"git\", \"rev-list\", \"--pretty=format:%an%n%ae%n\", \"%s..%s\" % (old, new)], stdout=subprocess.PIPE)\ndata = [line.strip() for line in proc.stdout.readlines() if line.strip()]\n\ndef print_error(commit, author, email, message):\n print \"*\" * 80\n print \"ERROR: Unknown Author!\"\n print \"-\" * 80\n proc = subprocess.Popen([\"git\", \"rev-list\", \"--max-count=1\", \"--pretty=short\", commit], stdout=subprocess.PIPE)\n print proc.stdout.read().strip()\n print \"*\" * 80\n raise SystemExit(1)\n\nfor commit, author, email in izip(islice(data, 0, None, 3), islice(data, 1, None, 3), islice(data, 2, None, 3)):\n _, commit_hash = commit.split()\n if not author in authors:\n print_error(commit_hash, author, email, \"Unknown Author\")\n elif authors[author] != email:\n print_error(commit_hash, author, email, \"Unknown Email\")\n</code></pre>\n" }, { "answer_id": 36801917, "author": "mrts", "author_id": 258772, "author_profile": "https://Stackoverflow.com/users/258772", "pm_score": 2, "selected": false, "text": "<p>We use Gitlab and so it makes sense for us to validate authors against Gitlab group members.</p>\n\n<p>The following script (based on @dsvensson's answer) that should be installed as pre-receive hook does exactly that:</p>\n\n<pre><code>from __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys\nimport os\nimport subprocess\nimport urllib2\nimport json\nimport contextlib\nimport codecs\nfrom itertools import islice, izip\n\nGITLAB_SERVER = 'https://localhost'\nGITLAB_TOKEN = 'SECRET'\nGITLAB_GROUP = 4\nEMAIL_DOMAIN = 'example.com'\n\ndef main():\n commits = get_commits_from_push()\n authors = get_gitlab_group_members()\n for commit, author, email in commits:\n if author not in authors:\n die('Unknown author', author, commit, authors)\n if email != authors[author]:\n die('Unknown email', email, commit, authors)\n\ndef get_commits_from_push():\n old, new, branch = sys.stdin.read().split()\n rev_format = '--pretty=format:%an%n%ae'\n command = ['git', 'rev-list', rev_format, '{0}..{1}'.format(old, new)]\n # branch delete, let it through\n if new == '0000000000000000000000000000000000000000':\n sys.exit(0)\n # new branch\n if old == '0000000000000000000000000000000000000000':\n command = ['git', 'rev-list', rev_format, new, '--not', '--branches=*']\n output = subprocess.check_output(command)\n commits = [line.strip() for line in unicode(output, 'utf-8').split('\\n') if line.strip()]\n return izip(islice(commits, 0, None, 3),\n islice(commits, 1, None, 3),\n islice(commits, 2, None, 3))\n\ndef get_gitlab_group_members():\n url = '{0}/api/v3/groups/{1}/members'.format(GITLAB_SERVER, GITLAB_GROUP)\n headers = {'PRIVATE-TOKEN': GITLAB_TOKEN}\n request = urllib2.Request(url, None, headers)\n with contextlib.closing(urllib2.urlopen(request)) as response:\n members = json.load(response)\n return dict((member['name'], '{}@{}'.format(member['username'], EMAIL_DOMAIN))\n for member in members)\n\ndef die(reason, invalid_value, commit, authors):\n message = []\n message.append('*' * 80)\n message.append(\"ERROR: {0} '{1}' in {2}\"\n .format(reason, invalid_value, commit))\n message.append('-' * 80)\n message.append('Allowed authors and emails:')\n print('\\n'.join(message), file=sys.stderr)\n for name, email in authors.items():\n print(u\" '{0} &lt;{1}&gt;'\".format(name, email), file=sys.stderr)\n sys.exit(1)\n\ndef set_locale(stream):\n return codecs.getwriter('utf-8')(stream)\n\nif __name__ == '__main__':\n # avoid Unicode errors in output\n sys.stdout = set_locale(sys.stdout)\n sys.stderr = set_locale(sys.stderr)\n\n # you may want to skip HTTPS certificate validation:\n # import ssl\n # if hasattr(ssl, '_create_unverified_context'):\n # ssl._create_default_https_context = ssl._create_unverified_context\n\n main()\n</code></pre>\n\n<p>See <a href=\"http://doc.gitlab.com/ce/hooks/custom_hooks.html\" rel=\"nofollow\">GitLab custom Git hooks docs</a> for installation instructions.</p>\n\n<p>Only <code>get_gitlab_group_members()</code> is Gitlab-specific, other logic applies to any pre-receive hook (including handling branch deletions and creations).</p>\n\n<p>The script is now <a href=\"https://github.com/mrts/validate-git-commit-authors-against-gitlab\" rel=\"nofollow\">available in GitHub</a>, please feel free to send pull requests for any mistakes/improvements.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
In git, it is up to each user to specify the correct author in their local git config file. When they push to a centralized bare repository, the commit messages on the repository will have the author names that they used when committing to their own repository. Is there a way enforce that a set of known authors for commits are used? The "central" repository will be accessible via ssh. I know that this is complicated by the fact that some people may be pushing commits that were made by others. Of course, you should also only allow people you trust to push to your repositories, but it would be great if there was a way to prevent user error here. Is there a simple solution to this problem in git?
We use the following to prevent accidental unknown-author commits (for example when doing a fast commit from a customer's server or something). It should be placed in .git/hooks/pre-receive and made executable. ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess from itertools import islice, izip import sys old, new, branch = sys.stdin.read().split() authors = { "John Doe": "[email protected]" } proc = subprocess.Popen(["git", "rev-list", "--pretty=format:%an%n%ae%n", "%s..%s" % (old, new)], stdout=subprocess.PIPE) data = [line.strip() for line in proc.stdout.readlines() if line.strip()] def print_error(commit, author, email, message): print "*" * 80 print "ERROR: Unknown Author!" print "-" * 80 proc = subprocess.Popen(["git", "rev-list", "--max-count=1", "--pretty=short", commit], stdout=subprocess.PIPE) print proc.stdout.read().strip() print "*" * 80 raise SystemExit(1) for commit, author, email in izip(islice(data, 0, None, 3), islice(data, 1, None, 3), islice(data, 2, None, 3)): _, commit_hash = commit.split() if not author in authors: print_error(commit_hash, author, email, "Unknown Author") elif authors[author] != email: print_error(commit_hash, author, email, "Unknown Email") ```
117,007
<p>I have some WCF methods that are used to transmit information from a server application to a website frontend for use in binding. I'm sending the result as an XElement that is a root of an XML tree containing the data I want to bind against.</p> <p>I'd like to create some tests that examine the data and ensure it comes across as expected. </p> <p>My current thinking is this: Every method that returns an XElement tree has a corresponding schema (.XSD) file. This file is included within the assembly that contains my WCF classes as an embedded resource.</p> <p>Tests call the method on these methods and compares the result against these embedded schemas.</p> <p>Is this a good idea? If not, what other ways can I use to provide a "guarantee" of what kind of XML a method will return?</p> <p>If it is, how do you validate an XElement against a schema? And how can I get that schema from the assembly it's embedded in?</p>
[ { "answer_id": 117217, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 5, "selected": true, "text": "<p>Id say validating xml with a xsd schema is a good idea.<br/>\n<br/>\nHow to validate a XElement with the loaded schema:\nAs you see in this example you need to validate the XDocument first to get populate the \"post-schema-validation infoset\" (There might be a solution to do this without using the Validate method on the XDOcument but Im yet to find one):<br/></p>\n\n<pre><code>String xsd =\n@\"&lt;xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'&gt;\n &lt;xsd:element name='root'&gt;\n &lt;xsd:complexType&gt;\n &lt;xsd:sequence&gt;\n &lt;xsd:element name='child1' minOccurs='1' maxOccurs='1'&gt;\n &lt;xsd:complexType&gt;\n &lt;xsd:sequence&gt;\n &lt;xsd:element name='grandchild1' minOccurs='1' maxOccurs='1'/&gt;\n &lt;xsd:element name='grandchild2' minOccurs='1' maxOccurs='2'/&gt;\n &lt;/xsd:sequence&gt;\n &lt;/xsd:complexType&gt;\n &lt;/xsd:element&gt;\n &lt;/xsd:sequence&gt;\n &lt;/xsd:complexType&gt;\n &lt;/xsd:element&gt;\n &lt;/xsd:schema&gt;\";\nString xml = @\"&lt;?xml version='1.0'?&gt;\n&lt;root&gt;\n &lt;child1&gt;\n &lt;grandchild1&gt;alpha&lt;/grandchild1&gt;\n &lt;grandchild2&gt;beta&lt;/grandchild2&gt;\n &lt;/child1&gt;\n&lt;/root&gt;\";\nXmlSchemaSet schemas = new XmlSchemaSet();\nschemas.Add(\"\", XmlReader.Create(new StringReader(xsd)));\nXDocument doc = XDocument.Load(XmlReader.Create(new StringReader(xml)));\nBoolean errors = false;\ndoc.Validate(schemas, (sender, e) =&gt;\n{\n Console.WriteLine(e.Message);\n errors = true;\n}, true);\nerrors = false;\nXElement child = doc.Element(\"root\").Element(\"child1\");\nchild.Validate(child.GetSchemaInfo().SchemaElement, schemas, (sender, e) =&gt;\n{\n Console.WriteLine(e.Message);\n errors = true;\n});\n</code></pre>\n\n<p>How to read the embedded schema from an assembly and add it to the XmlSchemaSet:<br/></p>\n\n<pre><code>Assembly assembly = Assembly.GetExecutingAssembly();\n// you can use reflector to get the full namespace of your embedded resource here\nStream stream = assembly.GetManifestResourceStream(\"AssemblyRootNamespace.Resources.XMLSchema.xsd\");\nXmlSchemaSet schemas = new XmlSchemaSet();\nschemas.Add(null, XmlReader.Create(stream));\n</code></pre>\n" }, { "answer_id": 120502, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 2, "selected": false, "text": "<p>If you're doing some light-weight work and XSDs are overkill, consider also possibly strongly typing your XML data. For example, I have a number of classes in a project that derive from XElement. One is ExceptionXElement, another is HttpHeaderXElement, etc. In them, I inherit from XElement and add Parse and TryParse methods that take strings containing XML data to create an instance from. If TryParse() returns false, the string does not conform to the XML data I expect (the root element has the wrong name, missing children elements, etc.).</p>\n\n<p>For example:</p>\n\n<pre><code>public class MyXElement : XElement \n{\n\n public MyXElement(XElement element)\n : base(element)\n { }\n\n public static bool TryParse(string xml, out MyXElement myElement)\n {\n XElement xmlAsXElement;\n\n try\n {\n xmlAsXElement = XElement.Parse(xml);\n }\n catch (XmlException)\n {\n myElement = null;\n return false;\n }\n\n // Use LINQ to check if xmlAsElement has correct nodes...\n }\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have some WCF methods that are used to transmit information from a server application to a website frontend for use in binding. I'm sending the result as an XElement that is a root of an XML tree containing the data I want to bind against. I'd like to create some tests that examine the data and ensure it comes across as expected. My current thinking is this: Every method that returns an XElement tree has a corresponding schema (.XSD) file. This file is included within the assembly that contains my WCF classes as an embedded resource. Tests call the method on these methods and compares the result against these embedded schemas. Is this a good idea? If not, what other ways can I use to provide a "guarantee" of what kind of XML a method will return? If it is, how do you validate an XElement against a schema? And how can I get that schema from the assembly it's embedded in?
Id say validating xml with a xsd schema is a good idea. How to validate a XElement with the loaded schema: As you see in this example you need to validate the XDocument first to get populate the "post-schema-validation infoset" (There might be a solution to do this without using the Validate method on the XDOcument but Im yet to find one): ``` String xsd = @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='root'> <xsd:complexType> <xsd:sequence> <xsd:element name='child1' minOccurs='1' maxOccurs='1'> <xsd:complexType> <xsd:sequence> <xsd:element name='grandchild1' minOccurs='1' maxOccurs='1'/> <xsd:element name='grandchild2' minOccurs='1' maxOccurs='2'/> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>"; String xml = @"<?xml version='1.0'?> <root> <child1> <grandchild1>alpha</grandchild1> <grandchild2>beta</grandchild2> </child1> </root>"; XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add("", XmlReader.Create(new StringReader(xsd))); XDocument doc = XDocument.Load(XmlReader.Create(new StringReader(xml))); Boolean errors = false; doc.Validate(schemas, (sender, e) => { Console.WriteLine(e.Message); errors = true; }, true); errors = false; XElement child = doc.Element("root").Element("child1"); child.Validate(child.GetSchemaInfo().SchemaElement, schemas, (sender, e) => { Console.WriteLine(e.Message); errors = true; }); ``` How to read the embedded schema from an assembly and add it to the XmlSchemaSet: ``` Assembly assembly = Assembly.GetExecutingAssembly(); // you can use reflector to get the full namespace of your embedded resource here Stream stream = assembly.GetManifestResourceStream("AssemblyRootNamespace.Resources.XMLSchema.xsd"); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(null, XmlReader.Create(stream)); ```
117,014
<p>How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.</p>
[ { "answer_id": 117047, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>import os;\nprint os.environ.get( \"USERNAME\" )\n</code></pre>\n\n<p>That should do the job.</p>\n" }, { "answer_id": 117092, "author": "Jim In Texas", "author_id": 15079, "author_profile": "https://Stackoverflow.com/users/15079", "pm_score": 1, "selected": false, "text": "<p>I don't know Python, but for windows the underlying api is <a href=\"http://msdn.microsoft.com/en-us/library/ms724435(VS.85).aspx\" rel=\"nofollow noreferrer\">GetUserNameEx</a>, I assume you can call that in Python if os.environ.get( \"USERNAME\" ) doesn't tell you everything you need to know.</p>\n" }, { "answer_id": 1992923, "author": "Adam", "author_id": 116819, "author_profile": "https://Stackoverflow.com/users/116819", "pm_score": 2, "selected": false, "text": "<pre><code>win32api.GetUserName()\n\nwin32api.GetUserNameEx(...) \n</code></pre>\n\n<p>See:\n<a href=\"http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html\" rel=\"nofollow noreferrer\">http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html</a></p>\n" }, { "answer_id": 23963670, "author": "gaur_ab", "author_id": 2761597, "author_profile": "https://Stackoverflow.com/users/2761597", "pm_score": -1, "selected": false, "text": "<p>Pretty old question but to refresh the answer to the original question \"How can I retrieve the name of the currently logged in user, using a python script?\" use:</p>\n\n<pre><code>import os\nprint (os.getlogin())\n</code></pre>\n\n<p>Per Python documentation: getlogin - Return the name of the user logged in on the controlling terminal of the process.</p>\n" }, { "answer_id": 24649918, "author": "n611x007", "author_id": 611007, "author_profile": "https://Stackoverflow.com/users/611007", "pm_score": 3, "selected": false, "text": "<p>as in <a href=\"https://stackoverflow.com/a/842096/611007\">https://stackoverflow.com/a/842096/611007</a> by <a href=\"https://stackoverflow.com/users/102243/konstantin-tenzin\">Konstantin Tenzin</a></p>\n\n<blockquote>\n <p>Look at <a href=\"http://docs.python.org/library/getpass.html\" rel=\"nofollow noreferrer\">getpass</a> module</p>\n\n<pre><code>import getpass\ngetpass.getuser()\n</code></pre>\n \n <p>Availability: Unix, Windows</p>\n \n <p>Note \"<em>this function looks at the values of various environment\n variables to determine the user name. Therefore, this function should\n not be relied on for access control purposes (or possibly any other\n purpose, since it allows any user to impersonate any other).</em>\"</p>\n</blockquote>\n\n<p>at least, definitely preferable over <code>getenv</code>.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.
Try this: ``` import os; print os.environ.get( "USERNAME" ) ``` That should do the job.
117,127
<p>Please excuse the vague title. If anyone has a suggestion, please let me know! Also please retag with more appropriate tags!</p> <p><strong>The Problem</strong></p> <p>I want to have an instance of an imported class be able to view things in the scope (globals, locals) of the importer. Since I'm not sure of the exact mechanism at work here, I can describe it much better with snippets than words.</p> <pre><code>## File 1 def f1(): print "go f1!" class C1(object): def do_eval(self,x): # maybe this should be do_evil, given what happens print "evaling" eval(x) eval(x,globals(),locals()) </code></pre> <p>Then run this code from an iteractive session, there there will be lots of <code>NameErrors</code></p> <pre><code>## interactive class C2(object): def do_eval(self,x): # maybe this should be do_evil, given what happens print "evaling" eval(x) eval(x,globals(),locals()) def f2(): print "go f2!" from file1 import C1 import file1 C1().do_eval('file1.f1()') C1().do_eval('f1()') C1().do_eval('f2()') file1.C1().do_eval('file1.f1()') file1.C1().do_eval('f1()') file1.C1().do_eval('f2()') C2().do_eval('f2()') C2().do_eval('file1.f1()') C2().do_eval('f1()') </code></pre> <p>Is there a common idiom / pattern for this sort of task? Am I barking up the wrong tree entirely? </p>
[ { "answer_id": 117174, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 1, "selected": false, "text": "<p>Functions are always executed in the scope they are defined in, as are methods and class bodies. They are never executed in another scope. Because importing is just another assignment statement, and everything in Python is a reference, the functions, classes and modules don't even know where they are imported to.</p>\n\n<p>You can do two things: explicitly pass the 'environment' you want them to use, or use stack hackery to access their caller's namespace. The former is vastly preferred over the latter, as it's not as implementation-dependent and fragile as the latter.</p>\n\n<p>You may wish to look at the string.Template class, which tries to do something similar.</p>\n" }, { "answer_id": 117433, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 3, "selected": true, "text": "<p>In this example, you can simply hand over functions as objects to the methods in <code>C1</code>:</p>\n\n<pre><code>&gt;&gt;&gt; class C1(object):\n&gt;&gt;&gt; def eval(self, x):\n&gt;&gt;&gt; x()\n&gt;&gt;&gt;\n&gt;&gt;&gt; def f2(): print \"go f2\"\n&gt;&gt;&gt; c = C1()\n&gt;&gt;&gt; c.eval(f2)\ngo f2\n</code></pre>\n\n<p>In Python, you can pass functions and classes to other methods and invoke/create them there.</p>\n\n<p>If you want to actually evaluate a code string, you have to specify the environment, as already mentioned by Thomas.</p>\n\n<p>Your module from above, slightly changed:</p>\n\n<pre><code>## File 1\ndef f1(): print \"go f1!\"\n\nclass C1(object):\n def do_eval(self, x, e_globals = globals(), e_locals = locals()):\n eval(x, e_globals, e_locals)\n</code></pre>\n\n<p>Now, in the interactive interpreter:</p>\n\n<pre><code>&gt;&gt;&gt; def f2():\n&gt;&gt;&gt; print \"go f2!\"\n&gt;&gt;&gt; from file1 import * # 1\n&gt;&gt;&gt; C1().do_eval(\"f2()\") # 2\nNameError: name 'f2' is not defined\n\n&gt;&gt;&gt; C1().do_eval(\"f2()\", globals(), locals()) #3\ngo f2!\n&gt;&gt;&gt; C1().do_eval(\"f1()\", globals(), locals()) #4\ngo f1!\n</code></pre>\n\n<h2>Some annotations</h2>\n\n<ol>\n<li>Here, we insert all objects from <code>file1</code> into this module's namespace</li>\n<li><code>f2</code> is not in the namespace of <code>file1</code>, therefore we get a <code>NameError</code></li>\n<li>Now we pass the environment explictly, and the code can be evaluated</li>\n<li><code>f1</code> is in the namespace of this module, because we imported it</li>\n</ol>\n\n<p><strong>Edit</strong>: Added code sample on how to explicitly pass environment for <code>eval</code>.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842/" ]
Please excuse the vague title. If anyone has a suggestion, please let me know! Also please retag with more appropriate tags! **The Problem** I want to have an instance of an imported class be able to view things in the scope (globals, locals) of the importer. Since I'm not sure of the exact mechanism at work here, I can describe it much better with snippets than words. ``` ## File 1 def f1(): print "go f1!" class C1(object): def do_eval(self,x): # maybe this should be do_evil, given what happens print "evaling" eval(x) eval(x,globals(),locals()) ``` Then run this code from an iteractive session, there there will be lots of `NameErrors` ``` ## interactive class C2(object): def do_eval(self,x): # maybe this should be do_evil, given what happens print "evaling" eval(x) eval(x,globals(),locals()) def f2(): print "go f2!" from file1 import C1 import file1 C1().do_eval('file1.f1()') C1().do_eval('f1()') C1().do_eval('f2()') file1.C1().do_eval('file1.f1()') file1.C1().do_eval('f1()') file1.C1().do_eval('f2()') C2().do_eval('f2()') C2().do_eval('file1.f1()') C2().do_eval('f1()') ``` Is there a common idiom / pattern for this sort of task? Am I barking up the wrong tree entirely?
In this example, you can simply hand over functions as objects to the methods in `C1`: ``` >>> class C1(object): >>> def eval(self, x): >>> x() >>> >>> def f2(): print "go f2" >>> c = C1() >>> c.eval(f2) go f2 ``` In Python, you can pass functions and classes to other methods and invoke/create them there. If you want to actually evaluate a code string, you have to specify the environment, as already mentioned by Thomas. Your module from above, slightly changed: ``` ## File 1 def f1(): print "go f1!" class C1(object): def do_eval(self, x, e_globals = globals(), e_locals = locals()): eval(x, e_globals, e_locals) ``` Now, in the interactive interpreter: ``` >>> def f2(): >>> print "go f2!" >>> from file1 import * # 1 >>> C1().do_eval("f2()") # 2 NameError: name 'f2' is not defined >>> C1().do_eval("f2()", globals(), locals()) #3 go f2! >>> C1().do_eval("f1()", globals(), locals()) #4 go f1! ``` Some annotations ---------------- 1. Here, we insert all objects from `file1` into this module's namespace 2. `f2` is not in the namespace of `file1`, therefore we get a `NameError` 3. Now we pass the environment explictly, and the code can be evaluated 4. `f1` is in the namespace of this module, because we imported it **Edit**: Added code sample on how to explicitly pass environment for `eval`.
117,135
<p>What resources have to be manually cleaned up in <em>C#</em> and what are the consequences of not doing so?</p> <p>For example, say I have the following code:</p> <pre><code>myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); // Use Brush </code></pre> <p>If I don't clean up the brush using the dispose method, I'm assuming the garbage collector frees the memory used at program termination? Is this correct?</p> <p>What other resources do I need to manually clean up?</p>
[ { "answer_id": 117164, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 3, "selected": false, "text": "<ul>\n<li>Handles to internal windows data structures.</li>\n<li>Database connections.</li>\n<li>File handles.</li>\n<li>Network connections.</li>\n<li>COM/OLE references.</li>\n</ul>\n\n<p>The list goes on.</p>\n\n<p>It's important to call <code>Dispose</code> or even better yet, use the <code>using</code> pattern.</p>\n\n<pre><code>using (SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black))\n{\n // use myBrush\n}\n</code></pre>\n\n<hr>\n\n<p>If you don't dispose something, it'll be cleaned up when the garbage collector notices that there are no more references to it, which may be after some time.</p>\n\n<p>In the case of <code>System.Drawing.Brush</code>, Windows will keep internal windows structures for the brush loaded in memory until all programs release their handle.</p>\n" }, { "answer_id": 117165, "author": "Brett Veenstra", "author_id": 307, "author_profile": "https://Stackoverflow.com/users/307", "pm_score": 2, "selected": false, "text": "<p>Generally, anything that implements IDisposable should cause you to pause and research the resource you're using.</p>\n\n<p>GC only happens when there's memory pressure, so you cannot predict when. Although an unload of the AppDomain will certainly trigger it.</p>\n" }, { "answer_id": 117178, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": -1, "selected": false, "text": "<p>The garbage collector will handle any managed resources. In your example, the brush will be cleaned up when the garbage collector decides to, which will happen some time after the last reference to the brush is no longer valid.</p>\n\n<p>There are certain things that need to be manually cleaned up, but those are pointers retrieved from unmanaged sources, such as DLL calls, nothing within the .NET Framework needs this treatment however.</p>\n" }, { "answer_id": 117183, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 0, "selected": false, "text": "<p>Well, as long as you use the managed version of the resources and don't call the windows APIs by yourself, you should be OK. Only worry about having to delete/destroy a resource when what you get is an IntPtr, as \"windows handles\" (and a whole lot other things) are known in .NET, and not an object.</p>\n\n<p>By the way, the resource (as any other .NET object) will be flagged for collection as soon as you leave the current context, so if you create the Brush inside a method, it will be flagged when you exit it.</p>\n" }, { "answer_id": 117184, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 3, "selected": false, "text": "<p>If you don't dispose something, it'll be cleaned up when the garbage collector notices that there are no more references to it in your code, which may be after some time. For something like that, it doesn't really matter, but for an open file it probably does.</p>\n\n<p>In general, if something has a Dispose method, you should call it when you've finished with it, or, if you can, wrap it up in a <code>using</code> statement:</p>\n\n<pre><code>using (SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black))\n{\n // use myBrush\n}\n</code></pre>\n" }, { "answer_id": 117194, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>If it's managed (i.e. part of the framework) you don't need to worry about it. If it implements IDisposable just wrap it in a <code>using</code> block.</p>\n\n<p>If you want to use unmanaged resources then you need to read up on finalisers and implementing IDisposable yourself.</p>\n\n<p>There's a lot more detail under <a href=\"https://stackoverflow.com/questions/12368/how-to-dispose-a-class-in-net#36737\">this question</a></p>\n" }, { "answer_id": 117206, "author": "Eric Tobia", "author_id": 20700, "author_profile": "https://Stackoverflow.com/users/20700", "pm_score": 2, "selected": true, "text": "<p>Technically anything that inherits from IDisposable should be proactively disposed. You can use the 'using' statement to make things easier.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/yh598w02.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/yh598w02.aspx</a></p>\n\n<p>Sometimes you will see inconsistent use of IDisposable derived objects in documentation sample code as well as code that is generated by tools (i.e. visual studio).</p>\n\n<p>What's nice about IDisposable is that it gives you the ability to <em>proactively</em> release the underlying unmanaged resource. Sometimes you really want to do this - think network connections and file resources for example.</p>\n" }, { "answer_id": 117225, "author": "ArielBH", "author_id": 11659, "author_profile": "https://Stackoverflow.com/users/11659", "pm_score": 0, "selected": false, "text": "<p>First upon program termination, you can assume that memory used by the process will be eliminated with the process itself.</p>\n\n<p>While using dispose or destructor in.net, one must understand that the time of when the dispose function is called by the GC is non-deterministic. That why it is recommended to use the using or calling the dispose explicitly.</p>\n\n<p>When using resources such as files, memory objects such as semaphors and resources that live outside of the managed world of .net must be freed.</p>\n\n<p>The SolidBrush for example, you need to dispose because it is a GDI object and living outside of the .net world.</p>\n" }, { "answer_id": 117231, "author": "David Cournapeau", "author_id": 11465, "author_profile": "https://Stackoverflow.com/users/11465", "pm_score": 0, "selected": false, "text": "<p>The garbage collector does not only free up at program termination, otherwise it would not be really useful (on any decent/recent OS, when the process exits, all its memory is cleaned up automatically by the OS anyway).</p>\n\n<p>One of the big advantage of C# compared to C/C++ is that you don't have to care about freeing allocated objects (most of the time at least); the gc does it when the runtime decides (various strategies when/how to do it).</p>\n\n<p>Many ressources are not taken care of by the gc: file, thread-related ressources (locks), network connections, etc...</p>\n" }, { "answer_id": 117237, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 2, "selected": false, "text": "<p>The consequences of not disposing your IDisposables can vary from a negligible performance hit to crashing your app.</p>\n\n<p>The Brush object in your example will be cleaned up by the GC when it feels like it. But your program won't have had the benefit of that bit of extra memory you would have gained by cleaning it up earlier. If you are using a lot of Brush objects this might become significant. The GC is also more efficient at cleaning up objects if they haven't been around very long, because it is a generational garbage collector.</p>\n\n<p>On the other hand, the consequences of not disposing database connection objects could mean you run out of pooled database connections very quickly and cause your app to crash.</p>\n\n<p>Either use</p>\n\n<pre><code>using (new DisposableThing...\n{\n ...\n}\n</code></pre>\n\n<p>Or, if you need to hold on to a reference to an IDisposable in your object for its lifetime, implement IDisposable on your object and call the IDisposable's Dispose method.</p>\n\n<pre><code>class MyClass : IDisposable\n{\n private IDisposable disposableThing;\n\n public void DoStuffThatRequiresHavingAReferenceToDisposableThing() { ... }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n //etc... (see IDisposable on msdn)\n</code></pre>\n\n<p>} </p>\n" }, { "answer_id": 117269, "author": "spdevsolutions", "author_id": 19086, "author_profile": "https://Stackoverflow.com/users/19086", "pm_score": 0, "selected": false, "text": "<p>One place to be careful is Objects that <em>look</em> small to GC but are not... In the SharePoint API for example, the SPWeb object has a small footprint as far as the GC is concerned and so will have low priority for collection, but it has really grabbed a bunch of memory (in the heap I believe) that the GC doesn't know about. You will run into some fun memory issues if you are foreaching a whole bunch of these for example, always remember to use using or dispose! </p>\n" }, { "answer_id": 117272, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 1, "selected": false, "text": "<p>As others have said, using is your friend.\nI wrote <a href=\"http://www.atalasoft.com/cs/blogs/stevehawley/archive/2006/09/21/10887.aspx\" rel=\"nofollow noreferrer\">this blog entry</a> about how to implement IDisposable in a fairly straightforward way that is less error-prone by factoring out the parts that are the most important.</p>\n" }, { "answer_id": 117652, "author": "lotsoffreetime", "author_id": 18248, "author_profile": "https://Stackoverflow.com/users/18248", "pm_score": 1, "selected": false, "text": "<p>A trick I use when I can't remember whether a given object is a disposable resource is to type \".Dispose\" (at most!) after the declaration to get Intellisense to check for me:</p>\n\n<pre><code>MemoryStream ms = new MemoryStream().Dispose\n</code></pre>\n\n<p>Then delete the .Dispose and use the using() directive:</p>\n\n<pre><code>using(MemoryStream ms = new MemoryStream())\n{\n ...\n}\n</code></pre>\n" }, { "answer_id": 4330086, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "<p>Rather than thinking of an object as \"holding\" resources that need to be released, it's better to think in terms of an object as having altered something (possibly outside the computer!) which will outlive it, in a way could be harmful if it not undone or \"cleaned up\", but which only the object can clean up. While this alteration commonly takes the form of some concrete object in a pool being marked \"busy\", its precise form doesn't matter. What matters is that the changes need to be undone, and the object holds information necessary to do that.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
What resources have to be manually cleaned up in *C#* and what are the consequences of not doing so? For example, say I have the following code: ``` myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); // Use Brush ``` If I don't clean up the brush using the dispose method, I'm assuming the garbage collector frees the memory used at program termination? Is this correct? What other resources do I need to manually clean up?
Technically anything that inherits from IDisposable should be proactively disposed. You can use the 'using' statement to make things easier. <http://msdn.microsoft.com/en-us/library/yh598w02.aspx> Sometimes you will see inconsistent use of IDisposable derived objects in documentation sample code as well as code that is generated by tools (i.e. visual studio). What's nice about IDisposable is that it gives you the ability to *proactively* release the underlying unmanaged resource. Sometimes you really want to do this - think network connections and file resources for example.
117,150
<p>I love vim and the speed it gives me. But sometimes, my fingers are too speedy and I find myself typing <code>:WQ</code> instead of <code>:wq</code>. (On a German keyboard, you have to press <kbd>Shift</kbd> to get the colon <code>:</code>.) Vim will then complain that <code>WQ</code> is <code>Not an editor command</code>.</p> <p>Is there some way to make <code>W</code> and <code>Q</code> editor commands?</p>
[ { "answer_id": 117221, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 7, "selected": true, "text": "<p>Try </p>\n\n<pre><code> :command WQ wq\n :command Wq wq\n :command W w\n :command Q q\n</code></pre>\n\n<p>This way you can define your own commands. See <code>:help command</code> for more information.</p>\n" }, { "answer_id": 119821, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 4, "selected": false, "text": "<p>And you can use </p>\n\n<pre><code>:cmap WQ wq\n</code></pre>\n\n<p>as well.\nE.g. I have </p>\n\n<pre><code>cmap h tab help\n</code></pre>\n\n<p>in my <code>.vimrc</code> which means opening help pages in a new tab.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/117150/can-i-re-map-commands-in-vim/119821#comment18676583_119821\">Thanks for the tip Jim Stewart</a>:</p>\n\n<blockquote>\n <p>But here is a much better solution as the above (for the help mapping,\n so that it only applies when you do :h):</p>\n\n<pre><code>cnoreabbrev &lt;expr&gt; h getcmdtype() == \":\" &amp;&amp; getcmdline() == \"h\" ? \"tab h\" : \"h\"\n</code></pre>\n</blockquote>\n" }, { "answer_id": 4125577, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 5, "selected": false, "text": "<p>Alternative way to do it:</p>\n\n<p>Use '<a href=\"http://vimdoc.sourceforge.net/htmldoc/map.html#Abbreviations\" rel=\"noreferrer\">command abbreviations</a>'</p>\n\n<pre><code>:ca WQ wq\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7498/" ]
I love vim and the speed it gives me. But sometimes, my fingers are too speedy and I find myself typing `:WQ` instead of `:wq`. (On a German keyboard, you have to press `Shift` to get the colon `:`.) Vim will then complain that `WQ` is `Not an editor command`. Is there some way to make `W` and `Q` editor commands?
Try ``` :command WQ wq :command Wq wq :command W w :command Q q ``` This way you can define your own commands. See `:help command` for more information.
117,173
<p><strong>I do not currently have this issue</strong>, but you never know, and thought experiments are always fun.</p> <p><strong>Ignoring the obvious problems that you would have to have with your architecture to even be attempting this</strong>, let's assume that you had some horribly-written code of someone else's design, and you needed to do a bunch of wide and varied operations in the same code block, e.g.:</p> <pre><code>WidgetMaker.SetAlignment(57); contactForm["Title"] = txtTitle.Text; Casserole.Season(true, false); ((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true; </code></pre> <p>Multiplied by a hundred. Some of these might work, others might go badly wrong. What you need is the C# equivalent of "on error resume next", otherwise you're going to end up copying and pasting try-catches around the many lines of code.</p> <p>How would you attempt to tackle this problem?</p>
[ { "answer_id": 117202, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 3, "selected": false, "text": "<p><code>On Error Resume Next</code> is a really bad idea in the C# world. Nor would adding the equivalent to <code>On Error Resume Next</code> actually help you. All it would do is leave you in a bad state which could cause more subtle errors, data loss and possibly data corruption.</p>\n\n<p>But to give the questioner his due, you could add a global handler and check the TargetSite to see which method borked. Then you could at least know what line it borked on. The next part would be to try and figure out how to set the \"next statement\" the same way the debugger does it. Hopefully your stack won't have unwound at this point or you can re-create it, but it's certainly worth a shot. However, given this approach the code would have to run in Debug mode every time so that you would have your debug symbols included.</p>\n" }, { "answer_id": 117218, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 0, "selected": false, "text": "<p>Unfortunately you are probably out of luck. On Error Resume Next is a legacy option that is generally heavily discouraged, and does not have an equivalent to my knowledge in C#.</p>\n\n<p>I would recommend leaving the code in VB (It sounds like that was the source, given your specific request for OnError ResumeNext) and interfacing with or from a C# dll or exe that implements whatever new code you need. Then preform refactoring to cause the code to be safe, and convert this safe code to C# as you do this.</p>\n" }, { "answer_id": 117229, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 2, "selected": false, "text": "<p>Rewrite the code. Try to find sets of statements which logically depend on each other, so that if one fails then the next ones make no sense, and hive them off into their own functions and put try-catches round them, if you want to ignore the result of that and continue.</p>\n" }, { "answer_id": 117232, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": -1, "selected": false, "text": "<p>Hilite each line, one at a time, 'Surround with' try/catch. That avoids the copying pasting you mentioned</p>\n" }, { "answer_id": 117235, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 5, "selected": false, "text": "<p>Refactor into individual, well-named methods:</p>\n\n<pre><code>AdjustFormWidgets();\nSetContactTitle(txtTitle.Text);\nSeasonCasserole();\n</code></pre>\n\n<p>Each of those is protected appropriately.</p>\n" }, { "answer_id": 117252, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 1, "selected": false, "text": "<p>If you can get the compiler to give you an expression tree for this code, then you could modify that expression tree by replacing each statement with a new try-catch block that wraps the original statement. This isn't as far-fetched as it sounds; for LINQ, C# acquired the ability to capture lambda expressions as expression trees that can be manipulated in user code at runtime.</p>\n\n<p>This approach is not possible today with .NET 3.5 -- if for no other reason than the lack of a \"try\" statement in System.Linq.Expressions. However, it may very well be viable in a future version of C# once the merge of the DLR and LINQ expression trees is complete.</p>\n" }, { "answer_id": 117261, "author": "tyshock", "author_id": 16448, "author_profile": "https://Stackoverflow.com/users/16448", "pm_score": -1, "selected": false, "text": "<p>Ignoring all the reasons you'd want to avoid doing this.......</p>\n\n<p>If it were simply a need to keep # of lines down, you could try something like:</p>\n\n<pre>\nint totalMethodCount = xxx;\nfor(int counter = 0; counter &lt; totalMethodCount; counter++) {\n try {\n if (counter == 0) WidgetMaker.SetAlignment(57);\n if (counter == 1) contactForm[\"Title\"] = txtTitle.Text;\n if (counter == 2) Casserole.Season(true, false);\n if (counter == 3) ((RecordKeeper)Session[\"CasseroleTracker\"]).Seasoned = true;\n } catch (Exception ex) {\n // log here\n }\n}\n</pre>\n\n<p>However, you'd have to keep an eye on variable scope if you try to reuse any of the results of the calls.</p>\n" }, { "answer_id": 117268, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 3, "selected": false, "text": "<p>This is one of the things that having a preprocessor is useful for. You could define a macro that swallows exceptions, then with a quick script add that macro to all lines.</p>\n\n<p>So, if this were C++, you could do something like this:</p>\n\n<pre><code>#define ATTEMPT(x) try { x; } catch (...) { }\n// ...\nATTEMPT(WidgetMaker.SetAlignment(57));\nATTEMPT(contactForm[\"Title\"] = txtTitle.Text);\nATTEMPT(Casserole.Season(true, false));\nATTEMPT(((RecordKeeper)Session[\"CasseroleTracker\"]).Seasoned = true);\n</code></pre>\n\n<p>Unfortunately, not many languages seem to include a preprocessor like C/C++ did.</p>\n\n<p>You could create your own preprocessor and add it as a pre-build step. If you felt like completely automating it you could probably write a preprocessor that would take the actual code file and add the try/catch stuff in on its own (so you don't have to add those ATTEMPT() blocks to the code manually). Making sure it only modified the lines it's supposed to could be difficult though (have to skip variable declarations, loop constructs, etc to that you don't break the build).</p>\n\n<p>However, I think these are horrible ideas and should never be done, but the question was asked. :)</p>\n\n<p>Really, you shouldn't ever do this. You need to find what's causing the error and fix it. Swallowing/ignoring errors is a bad thing to do, so I think the <em>correct</em> answer here is \"Fix the bug, don't ignore it!\". :)</p>\n" }, { "answer_id": 117288, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 0, "selected": false, "text": "<p>You could look at integrating the Enterprise Library's Exception Handling component for one idea of how to handle unhandled exceptions.</p>\n\n<p>If this is for ASP.Net applications, there is a function in the Global.asax called, \"Application_Error\" that gets called in most cases with catastrophic failure being the other case usually.</p>\n" }, { "answer_id": 117333, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 1, "selected": false, "text": "<p>You <em>could</em> use goto, but it's still messy.</p>\n\n<p>I've actually wanted a sort of single statement try-catch for a while. It would be helpful in certain cases, like adding logging code or something that you don't want to interrupt the main program flow if it fails. </p>\n\n<p>I suspect something could be done with some of the features associated with linq, but don't really have time to look into it at the moment. If you could just find a way to wrap a statement as an anonymous function, then use another one to call that within a try-catch block it would work... but not sure if that's possible just yet.</p>\n" }, { "answer_id": 117349, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 3, "selected": false, "text": "<h2><a href=\"http://en.wikipedia.org/wiki/Fail-fast\" rel=\"nofollow noreferrer\">Fail Fast</a></h2>\n<p>To elaborate, I guess I am questioning the question. If an exception is thrown, why would you want your code to simply continue as if nothing has happened? Either you expect exceptions in certain situations, in which case you write a try-catch block around that code and handle them, or there is an unexpected error, in which case you should prefer your application to abort, or retry, or fail. Not carry on like a wounded zombie moaning 'brains'.</p>\n" }, { "answer_id": 117370, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>This may help you in identifing the pieces that have the most problems. </p>\n\n<p>@ JB King\nThanks for reminding me. The Logging application block has a Instrumentation Event that can be used to trace events, you can find more info on the MS Enterprise library docs. </p>\n\n<pre><code>Using (New InstEvent)\n&lt;series of statements&gt; \nEnd Using\n</code></pre>\n\n<p>All of the steps in this using will be traced to a log file, and you can parse that out to see where the log breaks (ex is thrown) and id the high offenders.</p>\n\n<p>Refactoring is really your best bet, but if you have a lot, this may help you pinpoint the worst offenders. </p>\n" }, { "answer_id": 117733, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 4, "selected": false, "text": "<p>I would say <strong>do nothing</strong>.</p>\n\n<p>Yup thats right, do NOTHING.</p>\n\n<p>You have clearly identified two things to me:</p>\n\n<ol>\n<li>You know the architecture is borked.</li>\n<li>There is a ton of this crap.</li>\n</ol>\n\n<p>I say:</p>\n\n<ul>\n<li>Do nothing.</li>\n<li>Add a global error handler to send you an email every time it goes boom.</li>\n<li>Wait until something falls over (or fails a test)</li>\n<li>Correct that (Refactoring as necessary <strong>within the scope of the page</strong>).</li>\n<li>Repeat every time a problem occurs.</li>\n</ul>\n\n<p>You will have this cleared up in no time if it is that bad. Yeah I know it sounds sucky and you may be pulling your hair out with bugfixes to begin with, but it will allow you to <strong>fix the needy/buggy code before</strong> the (large) amount of <strong>code that may actually be working</strong> no matter how crappy it looks.</p>\n\n<p>Once you start winning the war, you will have a better handle on the code (due to all your refactoring) you will have a better idea for a winning design for it..</p>\n\n<p>Trying to wrap all of it in bubble wrap is probably going to take just a long to do and you will still not be any closer to fixing the problems.</p>\n" }, { "answer_id": 117737, "author": "Lost Plugin Writer", "author_id": 7425, "author_profile": "https://Stackoverflow.com/users/7425", "pm_score": 6, "selected": false, "text": "<pre><code>public delegate void VoidDelegate();\n\npublic static class Utils\n{\n public static void Try(VoidDelegate v) {\n try {\n v();\n }\n catch {}\n }\n}\n\nUtils.Try( () =&gt; WidgetMaker.SetAlignment(57) );\nUtils.Try( () =&gt; contactForm[\"Title\"] = txtTitle.Text );\nUtils.Try( () =&gt; Casserole.Season(true, false) );\nUtils.Try( () =&gt; ((RecordKeeper)Session[\"CasseroleTracker\"]).Seasoned = true );\n</code></pre>\n" }, { "answer_id": 117888, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 5, "selected": true, "text": "<p>It's pretty obvious that you'd write the code in VB.NET, which actually does have <a href=\"http://msdn.microsoft.com/en-us/library/5hsw66as.aspx\" rel=\"noreferrer\">On Error Resume Next</a>, and export it in a DLL to C#. Anything else is just being a glutton \n for punishment.</p>\n" }, { "answer_id": 118742, "author": "Christopher Elliott", "author_id": 5072, "author_profile": "https://Stackoverflow.com/users/5072", "pm_score": 2, "selected": false, "text": "<p>As someone mentioned, VB allows this. How about doing it the same way in C#? Enter trusty reflector: </p>\n\n<p>This: </p>\n\n<pre><code>Sub Main()\n On Error Resume Next\n\n Dim i As Integer = 0\n\n Dim y As Integer = CInt(5 / i)\n\n\nEnd Sub\n</code></pre>\n\n<p>Translates into this: </p>\n\n<pre><code>public static void Main()\n{\n // This item is obfuscated and can not be translated.\n int VB$ResumeTarget;\n try\n {\n int VB$CurrentStatement;\n Label_0001:\n ProjectData.ClearProjectError();\n int VB$ActiveHandler = -2;\n Label_0009:\n VB$CurrentStatement = 2;\n int i = 0;\n Label_000E:\n VB$CurrentStatement = 3;\n int y = (int) Math.Round((double) (5.0 / ((double) i)));\n goto Label_008F;\n Label_0029:\n VB$ResumeTarget = 0;\n switch ((VB$ResumeTarget + 1))\n {\n case 1:\n goto Label_0001;\n\n case 2:\n goto Label_0009;\n\n case 3:\n goto Label_000E;\n\n case 4:\n goto Label_008F;\n\n default:\n goto Label_0084;\n }\n Label_0049:\n VB$ResumeTarget = VB$CurrentStatement;\n switch (((VB$ActiveHandler &gt; -2) ? VB$ActiveHandler : 1))\n {\n case 0:\n goto Label_0084;\n\n case 1:\n goto Label_0029;\n }\n }\n catch (object obj1) when (?)\n {\n ProjectData.SetProjectError((Exception) obj1);\n goto Label_0049;\n }\nLabel_0084:\n throw ProjectData.CreateProjectError(-2146828237);\nLabel_008F:\n if (VB$ResumeTarget != 0)\n {\n ProjectData.ClearProjectError();\n }\n}\n</code></pre>\n" }, { "answer_id": 118781, "author": "Sam Hendley", "author_id": 20866, "author_profile": "https://Stackoverflow.com/users/20866", "pm_score": 1, "selected": false, "text": "<p>Why not use the reflection in c#? You could create a class that reflects on the code and use line #s as the hint for what to put in each individual try/catch block. This has a few advantages: </p>\n\n<ol>\n<li>Its slightly less ugly as it doesn't really you require mangle your source code and you can use it only during debug modes.</li>\n<li>You learn something interesting about c# while implementing it.</li>\n</ol>\n\n<p>I however would recommend against any of this, unless of course you are taking over maintance of someelses work and you need to get a handle on the exceptions so you can fix them. Might be fun to write though.</p>\n" }, { "answer_id": 122140, "author": "b w", "author_id": 4126, "author_profile": "https://Stackoverflow.com/users/4126", "pm_score": 1, "selected": false, "text": "<p>Fun question; very terrible.</p>\n\n<p>It'd be nice if you could use a macro. But this is blasted C#, so you might solve it with some preprocessor work or some external tool to wrap your lines in individual try-catch blocks. Not sure if you meant you didn't want to <em>manually</em> wrap them or that you wanted to avoid try-catch <em>entirely</em>.</p>\n\n<p>Messing around with this, I tried labeling every line and jumping back from a single catch, without much luck. However, <a href=\"https://stackoverflow.com/questions/117173/c-try-catch-every-line-of-code-without-individual-try-catch-blocks#118742\">Christopher uncovered the correct way to do this</a>. There's some <a href=\"http://dotnetthoughts.wordpress.com/2007/10/12/why-language-is-important-why-i-prefer-c/\" rel=\"nofollow noreferrer\">interesting additional discussion of this at Dot Net Thoughts</a> and at <a href=\"http://blogs.msdn.com/jmstall/archive/2008/04/12/codegen-for-on-error-resume-next.aspx\" rel=\"nofollow noreferrer\">Mike Stall's .NET Blog</a>.</p>\n\n<p><em>EDIT: Of course. The <code>try-catch</code> / <code>switch-goto</code> solution listed won't actually compile since the <code>try</code> labels are out-of-scope in <code>catch</code>. Anyone know what's missing to make something like this compile?</em></p>\n\n<p>You could automate this with a compiler preprocess step or maybe hack up <a href=\"http://blogs.msdn.com/jmstall/archive/2005/02/21/377806.aspx\" rel=\"nofollow noreferrer\">Mike Stall's Inline IL tool</a> to inject some error-ignorance.</p>\n\n<p>(<a href=\"https://stackoverflow.com/questions/117173/c-try-catch-every-line-of-code-without-individual-try-catch-blocks#117202\">Orion Adrian's answer about examining the Exception</a> and trying to set the next instruction is interesting too.)</p>\n\n<p>All in all, it seems like an interesting and instructive exercise. Of course, you'd have to decide at what point the effort to simulate ON ERROR RESUME NEXT outweighs the effort to fix the code. :-)</p>\n" }, { "answer_id": 6928785, "author": "Andrew Neely", "author_id": 825386, "author_profile": "https://Stackoverflow.com/users/825386", "pm_score": 1, "selected": false, "text": "<p>Catch the errors in the <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception%28v=VS.90%29.aspx\" rel=\"nofollow\">UnhandledException Event</a> of the application. That way, unhandled execptions can even be logged as to the sender and whatever other information the developer would reasonable.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
**I do not currently have this issue**, but you never know, and thought experiments are always fun. **Ignoring the obvious problems that you would have to have with your architecture to even be attempting this**, let's assume that you had some horribly-written code of someone else's design, and you needed to do a bunch of wide and varied operations in the same code block, e.g.: ``` WidgetMaker.SetAlignment(57); contactForm["Title"] = txtTitle.Text; Casserole.Season(true, false); ((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true; ``` Multiplied by a hundred. Some of these might work, others might go badly wrong. What you need is the C# equivalent of "on error resume next", otherwise you're going to end up copying and pasting try-catches around the many lines of code. How would you attempt to tackle this problem?
It's pretty obvious that you'd write the code in VB.NET, which actually does have [On Error Resume Next](http://msdn.microsoft.com/en-us/library/5hsw66as.aspx), and export it in a DLL to C#. Anything else is just being a glutton for punishment.
117,189
<p>I have a search form with a query builder. The builder is activated by a button. Something like this</p> <pre><code>&lt;h:form id="search_form"&gt; &lt;h:outputLabel for="expression" value="Expression"/&gt; &lt;h:inputText id="expression" required="true" value="#{searcher.expression}"/&gt; &lt;button onclick="openBuilder(); return false;"&gt;Open Builder&lt;/button&gt; &lt;h:commandButton value="Search" action="#{searcher.search}"/&gt; &lt;/h:form&gt; </code></pre> <p>The result is HTML that has both a <code>&lt;button/&gt;</code> and an <code>&lt;input type="submit"/&gt;</code> in the form. If the user enters a string into the expression field and hits the enter key rather than clicking the submit button, the query builder is displayed when the expected behavior is that the search be submitted. What gives?</p>
[ { "answer_id": 117246, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 3, "selected": true, "text": "<p>A button in an HTML form is assumed to be used to submit the form. Change button to input type=\"button\" and that should fix it.</p>\n\n<p>Alternatively, add type=\"button\" to the button element.</p>\n" }, { "answer_id": 117338, "author": "stefano m", "author_id": 19261, "author_profile": "https://Stackoverflow.com/users/19261", "pm_score": 1, "selected": false, "text": "<p>as first, give an ID to Search button.\nThen,on textbox, you could intercept client event <strong>onkeydown</strong>, with a (javascript) function like this:</p>\n\n<pre><code> function KeyDownHandler(event)\n {\n // process only the Enter key\n if (event.keyCode == 13)\n {\n // cancel the default submit\n event.returnValue=false;\n event.cancel = true;\n // submit the form by programmatically clicking the specified button\n document.getElementById('searchButtonId').click();\n }\n }\n</code></pre>\n\n<p>I hoper i help you.</p>\n" }, { "answer_id": 118570, "author": "user13229", "author_id": 13229, "author_profile": "https://Stackoverflow.com/users/13229", "pm_score": 0, "selected": false, "text": "<p><strong>if there is a single input field</strong> within the form, many browsers submit the forms automatically when the enter key is hit. </p>\n\n<p>Try</p>\n\n<ol>\n<li>Add another input field. Hide it by styling it so it isn't visible. (e.g., <code>&lt;input type=\"text\" name=\"bogusField\" style=\"display: none;\" /&gt;</code></li>\n<li>Block the enter key form submit behavior within a JavaScript event handler (e.g., <a href=\"http://jennifermadden.com/javascript/stringEnterKeyDetector.html\" rel=\"nofollow noreferrer\">here</a> or <a href=\"http://www.dynamicdrive.com/dynamicindex16/disableenter.htm\" rel=\"nofollow noreferrer\">here</a>). Even better, use a GUI toolkit that may help with this (e.g., GWT)</li>\n</ol>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
I have a search form with a query builder. The builder is activated by a button. Something like this ``` <h:form id="search_form"> <h:outputLabel for="expression" value="Expression"/> <h:inputText id="expression" required="true" value="#{searcher.expression}"/> <button onclick="openBuilder(); return false;">Open Builder</button> <h:commandButton value="Search" action="#{searcher.search}"/> </h:form> ``` The result is HTML that has both a `<button/>` and an `<input type="submit"/>` in the form. If the user enters a string into the expression field and hits the enter key rather than clicking the submit button, the query builder is displayed when the expected behavior is that the search be submitted. What gives?
A button in an HTML form is assumed to be used to submit the form. Change button to input type="button" and that should fix it. Alternatively, add type="button" to the button element.
117,211
<p>I have a Tix.ComboBox with an editable text field. How do I force the variable holding the value for the text to update?</p> <p>Let me give a more concrete explanation. I have a combo box and a button. When I click the button, it pops up a message box with the value of the combo box. Let's say the combo box text field currently has the value "thing1". If I type "new" into the box and then click on the button with my mouse, it will pops up the message "thing1". If I type "new" in the box and then tab focus away from the combo box and then click the button the pop up message says "new".</p> <p>Ho do I force the combo box to update it's value to new without requiring that I tab away from the combo box?</p> <p>I have included sample code.</p> <pre><code>import Tix import tkMessageBox class App(object): def __init__(self, window): window.winfo_toplevel().wm_title("test") self.window = window self.combo = Tix.ComboBox(window) self.combo.insert(Tix.END, 'thing1') self.combo.insert(Tix.END, 'thing2') self.combo.entry['state'] = "normal" self.combo['editable'] = True self.combo.pack() button = Tix.Button(window) button['text'] = "Go" button['command'] = self.go button.pack() def go(self): tkMessageBox.showinfo('info', self.combo['value']) if __name__ == '__main__': root = Tix.Tk() App(root) root.mainloop() </code></pre>
[ { "answer_id": 117384, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 4, "selected": true, "text": "<p>woo!\nsolved it on my own.</p>\n\n<p>Use </p>\n\n<pre><code>self.combo['selection']\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>self.combo['value']\n</code></pre>\n" }, { "answer_id": 207117, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "<p><i>NOTE: copy of Moe's answer that can be selected as chosen answer</i></p>\n\n<p>woo!\nsolved it on my own.</p>\n\n<p>Use </p>\n\n<pre><code>self.combo['selection']\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>self.combo['value']\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3051/" ]
I have a Tix.ComboBox with an editable text field. How do I force the variable holding the value for the text to update? Let me give a more concrete explanation. I have a combo box and a button. When I click the button, it pops up a message box with the value of the combo box. Let's say the combo box text field currently has the value "thing1". If I type "new" into the box and then click on the button with my mouse, it will pops up the message "thing1". If I type "new" in the box and then tab focus away from the combo box and then click the button the pop up message says "new". Ho do I force the combo box to update it's value to new without requiring that I tab away from the combo box? I have included sample code. ``` import Tix import tkMessageBox class App(object): def __init__(self, window): window.winfo_toplevel().wm_title("test") self.window = window self.combo = Tix.ComboBox(window) self.combo.insert(Tix.END, 'thing1') self.combo.insert(Tix.END, 'thing2') self.combo.entry['state'] = "normal" self.combo['editable'] = True self.combo.pack() button = Tix.Button(window) button['text'] = "Go" button['command'] = self.go button.pack() def go(self): tkMessageBox.showinfo('info', self.combo['value']) if __name__ == '__main__': root = Tix.Tk() App(root) root.mainloop() ```
woo! solved it on my own. Use ``` self.combo['selection'] ``` instead of ``` self.combo['value'] ```
117,226
<p>I have a <code>PHP</code> script that listens on a queue. Theoretically, it's never supposed to die. Is there something to check if it's still running? Something like <code>Ruby's God ( http://god.rubyforge.org/ )</code> for <code>PHP</code>?</p> <p>God is language agnostic but it would be nice to have a solution that works on windows as well.</p>
[ { "answer_id": 117287, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 2, "selected": false, "text": "<p>Simple bash script</p>\n\n<pre><code>#!/bin/bash\nwhile [true]; do\n if ! pidof -x script.php;\n then\n php script.php &amp;\n fi\ndone\n</code></pre>\n" }, { "answer_id": 117506, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 0, "selected": false, "text": "<p>One possible solution is to have it listen on a port using the socket functions. You can check that the socket is still listening with a simple script. Even a monitoring service like pingdom could monitor its status. If it dies, the socket is no longer listening.</p>\n\n<p>Plenty of solutions.. Good luck.</p>\n" }, { "answer_id": 120586, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 2, "selected": false, "text": "<p>Not for windows, but... </p>\n\n<p>I've got a couple of long-running PHP scripts, that have a shell script wrapping it. You can optionally return a value from the script that will be checked in the shell-script to exit, restart immediately, or sleep for a few seconds -and then restart.</p>\n\n<p>Here's a simple one that just keeps running the PHP script till it's manually stopped.</p>\n\n<pre>#!/bin/bash\nclear\ndate\nphp -f cli-SCRIPT.php\necho \"wait a little while ...\"; sleep 10\nexec $0</pre>\n\n<p>The \"exec $0\" restarts the script, without creating a sub-process that will have to unravel later (and take up resources in the meantime). This bash script wraps a mail-sender, so it's not a problem if it exits and pauses for a moment.</p>\n" }, { "answer_id": 121717, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 3, "selected": false, "text": "<p>Just append a second command after the script. When/if it stops, the second command is invoked. Eg.:</p>\n\n<pre><code>php daemon.php 2&gt;&amp;1 | mail -s \"Daemon stopped\" [email protected]\n</code></pre>\n\n<h3>Edit:</h3>\n\n<p>Technically, this invokes the mailer right away, but only completes the command when the php script ends. Doing this captures the output of the php-script and includes in the mail body, which can be useful for debugging what caused the script to halt.</p>\n" }, { "answer_id": 121887, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 0, "selected": false, "text": "<p>If you have your hands on the script, you can just ask him to set a time value every X times in db, and then let a cron job check if that value is up to date.</p>\n" }, { "answer_id": 122568, "author": "Daniel Schierbeck", "author_id": 20321, "author_profile": "https://Stackoverflow.com/users/20321", "pm_score": 0, "selected": false, "text": "<p>troelskn wrote:</p>\n\n<blockquote>\n <p>Just append a second command after the script. When/if it stops, the second command is invoked. Eg.:</p>\n\n<pre><code>php daemon.php | mail -s \"Daemon stopped\" [email protected]\n</code></pre>\n</blockquote>\n\n<p>This will call <code>mail</code> each time a line is printed in daemon.php (which should be never, but still.)</p>\n\n<p>Instead, use the double ampersand operator to separate the commands, i.e.</p>\n\n<pre><code>php daemon.php &amp; mail -s \"Daemon stopped\" [email protected]\n</code></pre>\n" }, { "answer_id": 8465822, "author": "Jay", "author_id": 1092461, "author_profile": "https://Stackoverflow.com/users/1092461", "pm_score": 4, "selected": false, "text": "<p>I had the same issue - wanting to check if a script is running. So I came up with this and I run it as a cron job. It grabs the running processes as an array and cycles though each line and checks for the file name. Seems to work fine. Replace #user# with your script user.</p>\n\n<pre><code>exec(\"ps -U #user# -u #user# u\", $output, $result);\nforeach ($output AS $line) if(strpos($line, \"test.php\")) echo \"found\";\n</code></pre>\n" }, { "answer_id": 32478281, "author": "Justin Levene", "author_id": 1938802, "author_profile": "https://Stackoverflow.com/users/1938802", "pm_score": 4, "selected": false, "text": "<p>In linux run ps as follows:</p>\n\n<pre><code>ps -C php -f\n</code></pre>\n\n<p>You could then do in a php script:</p>\n\n<pre><code>$output = shell_exec('ps -C php -f');\nif (strpos($output, \"php my_script.php\")===false) { \n shell_exec('php my_script.php &gt; /dev/null 2&gt;&amp;1 &amp;');\n}\n</code></pre>\n\n<p>The above code lists all php processes running in full, then checks to see if \"my_script.php\" is in the list of running processes, if not it runs the process and does not wait for the process to terminate to carry on doing what it was doing.</p>\n" }, { "answer_id": 33761271, "author": "Zvonimir Burić", "author_id": 1895587, "author_profile": "https://Stackoverflow.com/users/1895587", "pm_score": 1, "selected": false, "text": "<p>You can write in your crontab something like this:</p>\n\n<pre><code>0 3 * * * /usr/bin/php -f /home/test/test.php my_special_cron\n</code></pre>\n\n<p>Your test.php file should look like this:</p>\n\n<pre><code>&lt;?php\n\nphp_sapi_name() == 'cli' || exit;\n\nif($argv[1]) {\n substr_count(shell_exec('ps -ax'), $argv[1]) &lt; 3 || exit;\n}\n\n// your code here\n</code></pre>\n\n<p>That way you will have only one active instace of the cron job with <code>my-special-cron</code> as process key. So you can add more jobs within the same php file.</p>\n\n<p><code>test.php system_send_emails sendEmails</code></p>\n\n<p><code>test.php system_create_orders orderExport</code> </p>\n" }, { "answer_id": 36348388, "author": "Burak Kurkcu", "author_id": 2517120, "author_profile": "https://Stackoverflow.com/users/2517120", "pm_score": 1, "selected": false, "text": "<p>Inspired from Justin Levene's answer and improved it as <code>ps -C</code> doesn't work in Mac, which I need in my case. So you can use this in a php script (maybe just before you need daemon alive), tested in both Mac OS X 10.11.4 &amp; Ubuntu 14.04:</p>\n\n<pre><code>$daemonPath = \"FULL_PATH_TO_DAEMON\";\n$runningPhpProcessesOfDaemon = (int) shell_exec(\"ps aux | grep -c '[p]hp \".$daemonPath.\"'\");\nif ($runningPhpProcessesOfDaemon === 0) {\n shell_exec('php ' . $daemonPath . ' &gt; /dev/null 2&gt;&amp;1 &amp;');\n}\n</code></pre>\n\n<p>Small but useful detail: Why <code>grep -c '[p]hp ...'</code> instead of <code>grep -c 'php ...'</code>? </p>\n\n<p>Because while counting processes <code>grep -c 'php ...'</code> will be counted as a process that fits in our pattern. So using a regex for first letter of php makes our command different from pattern we search. </p>\n" }, { "answer_id": 39642531, "author": "Jack Simth", "author_id": 2640003, "author_profile": "https://Stackoverflow.com/users/2640003", "pm_score": 0, "selected": false, "text": "<p>If you're having trouble checking for the PHP script directly, you can make a trivial wrapper and check for that. I'm not sufficiently familiar with Windows scripting to put how it's done here, but in Bash, it'd look like...</p>\n\n<p>wrapper_for_test_php.sh</p>\n\n<pre><code>#!/bin/bash\nphp test.php\n</code></pre>\n\n<p>Then you'd just check for the wrapper like you'd check for any other bash script: pidof -x wrapper_for_test_php.sh</p>\n" }, { "answer_id": 40463579, "author": "Kamaro", "author_id": 2858817, "author_profile": "https://Stackoverflow.com/users/2858817", "pm_score": 0, "selected": false, "text": "<p>I have used cmder for windows and based on this script I came up with this one that I managed to deploy on linux later.</p>\n\n<pre><code>#!/bin/bash\n clear\n date\n while true\n do\n php -f processEmails.php\n echo \"wait a little while for 5 secobds...\"; \n sleep 5\n done \n</code></pre>\n" }, { "answer_id": 59525734, "author": "Dom DaFonte", "author_id": 7506883, "author_profile": "https://Stackoverflow.com/users/7506883", "pm_score": 2, "selected": false, "text": "<p>Here is what I did to combat a similar issue. This helps in the event anyone else has a parameterized php script that you want cron to execute frequently, but only want one execution to run at any time. Add this to the top of your php script, or create a common method. </p>\n\n<pre><code>$runningScripts = shell_exec('ps -ef |grep '.strtolower($parameter).' |grep '.dirname(__FILE__).' |grep '.basename(__FILE__).' |grep -v grep |wc -l');\nif($runningScripts &gt; 1){\n die();\n}\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a `PHP` script that listens on a queue. Theoretically, it's never supposed to die. Is there something to check if it's still running? Something like `Ruby's God ( http://god.rubyforge.org/ )` for `PHP`? God is language agnostic but it would be nice to have a solution that works on windows as well.
I had the same issue - wanting to check if a script is running. So I came up with this and I run it as a cron job. It grabs the running processes as an array and cycles though each line and checks for the file name. Seems to work fine. Replace #user# with your script user. ``` exec("ps -U #user# -u #user# u", $output, $result); foreach ($output AS $line) if(strpos($line, "test.php")) echo "found"; ```
117,248
<p>I have a number of tables that use the trigger/sequence column to simulate auto_increment on their primary keys which has worked great for some time.</p> <p>In order to speed the time necessary to perform regression testing against software that uses the db, I create control files using some sample data, and added running of these to the build process.</p> <p>This change is causing most of the tests to crash though as the testing process installs the schema from scratch, and the sequences are returning values that already exist in the tables. Is there any way to programtically say "Update sequences to max value in column" or do I need to write out a whole script by hand that updates all these sequences, or can I/should I change the trigger that substitutes the null value for the sequence to some how check this (though I think this might cause the mutating table problem)?</p>
[ { "answer_id": 117295, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 0, "selected": false, "text": "<p>As part of your schema rebuild, why not drop and recreate the sequence? </p>\n" }, { "answer_id": 117360, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 2, "selected": true, "text": "<p>You can generate a script to create the sequences with the start values you need (based on their existing values)....</p>\n\n<pre><code>SELECT 'CREATE SEQUENCE '||sequence_name||' START WITH '||last_number||';'\nFROM ALL_SEQUENCES\nWHERE OWNER = your_schema\n</code></pre>\n\n<p>(If I understand the question correctly)</p>\n" }, { "answer_id": 142768, "author": "JoshL", "author_id": 20625, "author_profile": "https://Stackoverflow.com/users/20625", "pm_score": 1, "selected": false, "text": "<p>Here's a simple way to update a sequence value - in this case setting the sequence to 1000 if it is currently 50:</p>\n\n<pre><code>alter sequence MYSEQUENCE increment by 950 nocache;\nselect MYSEQUENCE_S.nextval from dual;\nalter sequence MYSEQUENCE increment by 1;\n</code></pre>\n\n<p>Kudos to the creators of PL/SQL Developer for including this technique in their tool.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I have a number of tables that use the trigger/sequence column to simulate auto\_increment on their primary keys which has worked great for some time. In order to speed the time necessary to perform regression testing against software that uses the db, I create control files using some sample data, and added running of these to the build process. This change is causing most of the tests to crash though as the testing process installs the schema from scratch, and the sequences are returning values that already exist in the tables. Is there any way to programtically say "Update sequences to max value in column" or do I need to write out a whole script by hand that updates all these sequences, or can I/should I change the trigger that substitutes the null value for the sequence to some how check this (though I think this might cause the mutating table problem)?
You can generate a script to create the sequences with the start values you need (based on their existing values).... ``` SELECT 'CREATE SEQUENCE '||sequence_name||' START WITH '||last_number||';' FROM ALL_SEQUENCES WHERE OWNER = your_schema ``` (If I understand the question correctly)
117,250
<p>For example, the standard division symbol '/' rounds to zero:</p> <pre><code>&gt;&gt;&gt; 4 / 100 0 </code></pre> <p>However, I want it to return 0.04. What do I use?</p>
[ { "answer_id": 117256, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 0, "selected": false, "text": "<p>Try 4.0/100</p>\n" }, { "answer_id": 117257, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 1, "selected": false, "text": "<p>A simple route 4 / 100.0 </p>\n\n<p>or</p>\n\n<p>4.0 / 100</p>\n" }, { "answer_id": 117258, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<p>You need to tell Python to use floating point values, not integers. You can do that simply by using a decimal point yourself in the inputs:</p>\n\n<pre><code>&gt;&gt;&gt; 4/100.0\n0.040000000000000001\n</code></pre>\n" }, { "answer_id": 117264, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 8, "selected": true, "text": "<p>There are three options:</p>\n\n<pre><code>&gt;&gt;&gt; 4 / float(100)\n0.04\n&gt;&gt;&gt; 4 / 100.0\n0.04\n</code></pre>\n\n<p>which is the same behavior as the C, C++, Java etc, or </p>\n\n<pre><code>&gt;&gt;&gt; from __future__ import division\n&gt;&gt;&gt; 4 / 100\n0.04\n</code></pre>\n\n<p>You can also activate this behavior by passing the argument <code>-Qnew</code> to the Python interpreter:</p>\n\n<pre><code>$ python -Qnew\n&gt;&gt;&gt; 4 / 100\n0.04\n</code></pre>\n\n<p>The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the <code>//</code> operator. </p>\n\n<p><strong>Edit</strong>: added section about <code>-Qnew</code>, thanks to <a href=\"https://stackoverflow.com/users/6899/\">ΤΖΩΤΖΙΟΥ</a>!</p>\n" }, { "answer_id": 117270, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 3, "selected": false, "text": "<p>Make one or both of the terms a floating point number, like so:</p>\n\n<pre><code>4.0/100.0\n</code></pre>\n\n<p>Alternatively, turn on the feature that will be default in Python 3.0, 'true division', that does what you want. At the top of your module or script, do:</p>\n\n<pre><code>from __future__ import division\n</code></pre>\n" }, { "answer_id": 117285, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": 0, "selected": false, "text": "<p>You cant get a decimal value by dividing one integer with another, you'll allways get an integer that way (result truncated to integer). You need at least one value to be a decimal number.</p>\n" }, { "answer_id": 117682, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 5, "selected": false, "text": "<p>Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:</p>\n\n<pre><code>&gt;&gt;&gt; 0.4/100.\n0.0040000000000000001\n</code></pre>\n\n<p>If you actually want a <em>decimal</em> value, do this:</p>\n\n<pre><code>&gt;&gt;&gt; import decimal\n&gt;&gt;&gt; decimal.Decimal('4') / decimal.Decimal('100')\nDecimal(\"0.04\")\n</code></pre>\n\n<p>That will give you an object that properly knows that 4 / 100 in <em>base 10</em> is \"0.04\". Floating-point numbers are actually in base 2, i.e. binary, not decimal.</p>\n" }, { "answer_id": 117806, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "<p>You might want to look at Python's <a href=\"http://docs.python.org/lib/module-decimal.html\" rel=\"noreferrer\">decimal</a> package, also. This will provide nice decimal results.</p>\n\n<pre><code>&gt;&gt;&gt; decimal.Decimal('4')/100\nDecimal(\"0.04\")\n</code></pre>\n" }, { "answer_id": 48145519, "author": "Jai Narayan", "author_id": 5622450, "author_profile": "https://Stackoverflow.com/users/5622450", "pm_score": 1, "selected": false, "text": "<p>Here we have two possible cases given below </p>\n\n<pre><code>from __future__ import division\n\nprint(4/100)\nprint(4//100)\n</code></pre>\n" }, { "answer_id": 48924804, "author": "T. Samuel", "author_id": 8643901, "author_profile": "https://Stackoverflow.com/users/8643901", "pm_score": -1, "selected": false, "text": "<p>Import division from future library like this: </p>\n\n<pre><code>from__future__ import division\n</code></pre>\n" }, { "answer_id": 51169141, "author": "DaredevilRanon", "author_id": 9946483, "author_profile": "https://Stackoverflow.com/users/9946483", "pm_score": 0, "selected": false, "text": "<p>Add the following function in your code with its callback.</p>\n\n<pre><code># Starting of the function\ndef divide(number_one, number_two, decimal_place = 4):\n quotient = number_one/number_two\n remainder = number_one % number_two\n if remainder != 0:\n quotient_str = str(quotient)\n for loop in range(0, decimal_place):\n if loop == 0:\n quotient_str += \".\"\n surplus_quotient = (remainder * 10) / number_two\n quotient_str += str(surplus_quotient)\n remainder = (remainder * 10) % number_two\n if remainder == 0:\n break\n return float(quotient_str)\n else:\n return quotient\n#Ending of the function\n\n# Calling back the above function\n# Structure : divide(&lt;divident&gt;, &lt;divisor&gt;, &lt;decimal place(optional)&gt;)\ndivide(1, 7, 10) # Output : 0.1428571428\n# OR\ndivide(1, 7) # Output : 0.1428\n</code></pre>\n\n<p>This function works on the basis of \"Euclid Division Algorithm\". This function is very useful if you don't want to import any external header files in your project.</p>\n\n<p>Syntex : divide([divident], [divisor], [decimal place(optional))</p>\n\n<p>Code : <code>divide(1, 7, 10)</code> OR <code>divide(1, 7)</code></p>\n\n<p>Comment below for any queries.</p>\n" }, { "answer_id": 54601667, "author": "Appu", "author_id": 11036079, "author_profile": "https://Stackoverflow.com/users/11036079", "pm_score": 0, "selected": false, "text": "<p>You could also try adding a \".0\" at the end of the number.</p>\n\n<p>4.0/100.0</p>\n" }, { "answer_id": 59146683, "author": "Marc-André Yelle", "author_id": 9196500, "author_profile": "https://Stackoverflow.com/users/9196500", "pm_score": -1, "selected": false, "text": "<p>It's only dropping the fractional part after decimal.\nHave you tried : 4.0 / 100</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
For example, the standard division symbol '/' rounds to zero: ``` >>> 4 / 100 0 ``` However, I want it to return 0.04. What do I use?
There are three options: ``` >>> 4 / float(100) 0.04 >>> 4 / 100.0 0.04 ``` which is the same behavior as the C, C++, Java etc, or ``` >>> from __future__ import division >>> 4 / 100 0.04 ``` You can also activate this behavior by passing the argument `-Qnew` to the Python interpreter: ``` $ python -Qnew >>> 4 / 100 0.04 ``` The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the `//` operator. **Edit**: added section about `-Qnew`, thanks to [ΤΖΩΤΖΙΟΥ](https://stackoverflow.com/users/6899/)!
117,293
<p>How far do you go with <code>const</code>? Do you just make functions <code>const</code> when necessary or do you go the whole hog and use it everywhere? For example, imagine a simple mutator that takes a single boolean parameter:</p> <pre><code>void SetValue(const bool b) { my_val_ = b; } </code></pre> <p>Is that <code>const</code> actually useful? Personally I opt to use it extensively, including parameters, but in this case I wonder if it's worthwhile?</p> <p>I was also surprised to learn that you can omit <code>const</code> from parameters in a function declaration but can include it in the function definition, e.g.:</p> <p><strong>.h file</strong></p> <pre><code>void func(int n, long l); </code></pre> <p><strong>.cpp file</strong></p> <pre><code>void func(const int n, const long l) </code></pre> <p>Is there a reason for this? It seems a little unusual to me.</p>
[ { "answer_id": 117308, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 9, "selected": true, "text": "<p>The reason is that <code>const</code> for the parameter only applies locally within the function, since it is working on a copy of the data. This means the function signature is really the same anyways. It's probably bad style to do this a lot though.</p>\n<p>I personally tend to not use <code>const</code> except for reference and pointer parameters. For copied objects it doesn't really matter, although it can be safer as it signals intent within the function. It's really a judgement call. I do tend to use <code>const_iterator</code> though when looping on something and I don't intend on modifying it, so I guess to each his own, as long as <code>const</code> correctness for reference types is rigorously maintained.</p>\n" }, { "answer_id": 117311, "author": "Asaf R", "author_id": 6827, "author_profile": "https://Stackoverflow.com/users/6827", "pm_score": 3, "selected": false, "text": "<p>I use const on function parameters that are references (or pointers) which are only [in] data and will not be modified by the function. Meaning, when the purpose of using a reference is to avoid copying data and not to allow changing the passed parameter.</p>\n\n<p>Putting const on the boolean b parameter in your example only puts a constraint on the implementation and doesn't contribute for the class's interface (although not changing parameters is usually advised).</p>\n\n<p>The function signature for</p>\n\n<pre><code>void foo(int a);\n</code></pre>\n\n<p>and </p>\n\n<pre><code>void foo(const int a);\n</code></pre>\n\n<p>is the same, which explains your .c and .h</p>\n\n<p>Asaf</p>\n" }, { "answer_id": 117322, "author": "Luke Halliwell", "author_id": 3974, "author_profile": "https://Stackoverflow.com/users/3974", "pm_score": 2, "selected": false, "text": "<p>In the case you mention, it doesn't affect callers of your API, which is why it's not commonly done (and isn't necessary in the header). It only affects the implementation of your function.</p>\n\n<p>It's not particularly a bad thing to do, but the benefits aren't that great given that it doesn't affect your API, and it adds typing, so it's not usually done.</p>\n" }, { "answer_id": 117324, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 0, "selected": false, "text": "<p>I wouldn't put const on parameters like that - everyone already knows that a boolean (as opposed to a boolean&amp;) is constant, so adding it in will make people think \"wait, what?\" or even that you're passing the parameter by reference.</p>\n" }, { "answer_id": 117326, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 0, "selected": false, "text": "<p>the thing to remember with const is that it is much easier to make things const from the start, than it is to try and put them in later.</p>\n\n<p>Use const when you want something to be unchanged - its an added hint that describes what your function does and what to expect. I've seen many an C API that could do with some of them, especially ones that accept c-strings!</p>\n\n<p>I'd be more inclined to omit the const keyword in the cpp file than the header, but as I tend to cut+paste them, they'd be kept in both places. I have no idea why the compiler allows that, I guess its a compiler thing. Best practice is definitely to put your const keyword in both files.</p>\n" }, { "answer_id": 117329, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 3, "selected": false, "text": "<p>Ah, a tough one. On one side, a declaration is a contract and it really does not make sense to pass a const argument by value. On the other hand, if you look at the function implementation, you give the compiler more chances to optimize if you declare an argument constant.</p>\n" }, { "answer_id": 117332, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 0, "selected": false, "text": "<p>All the consts in your examples have no purpose. C++ is pass-by-value by default, so the function gets copies of those ints and booleans. Even if the function does modify them, the caller's copy is not affected. </p>\n\n<p>So I'd avoid extra consts because </p>\n\n<ul>\n<li>They're redudant</li>\n<li>They clutter up\nthe text</li>\n<li>They prevent me from\nchanging the passed in value in\ncases where it might be useful or efficient.</li>\n</ul>\n" }, { "answer_id": 117339, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": -1, "selected": false, "text": "<p>There's really no reason to make a value-parameter \"const\" as the function can only modify a copy of the variable anyway.</p>\n\n<p>The reason to use \"const\" is if you're passing something bigger (e.g. a struct with lots of members) by reference, in which case it ensures that the function can't modify it; or rather, the compiler will complain if you try to modify it in the conventional way. It prevents it from being accidentally modified.</p>\n" }, { "answer_id": 117365, "author": "Dror Helper", "author_id": 11361, "author_profile": "https://Stackoverflow.com/users/11361", "pm_score": 2, "selected": false, "text": "<p>I use const were I can. Const for parameters means that they should not change their value. This is especially valuable when passing by reference. const for function declares that the function should not change the classes members.</p>\n" }, { "answer_id": 117383, "author": "Aurélien Gâteau", "author_id": 20107, "author_profile": "https://Stackoverflow.com/users/20107", "pm_score": 2, "selected": false, "text": "<p>I do not use const for value-passed parametere. The caller does not care whether you modify the parameter or not, it's an implementation detail.</p>\n\n<p>What is really important is to mark methods as const if they do not modify their instance. Do this as you go, because otherwise you might end up with either lots of const_cast&lt;> or you might find that marking a method const requires changing a lot of code because it calls other methods which should have been marked const.</p>\n\n<p>I also tend to mark local vars const if I do not need to modify them. I believe it makes the code easier to understand by making it easier to identify the \"moving parts\".</p>\n" }, { "answer_id": 117408, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Const parameter is useful only when the parameter is passed by reference i.e., either reference or pointer. When compiler sees a const parameter, it make sure that the variable used in the parameter is not modified within the body of the function. Why would anyone want to make a by-value parameter as constant? :-)</p>\n" }, { "answer_id": 117409, "author": "Attila", "author_id": 20322, "author_profile": "https://Stackoverflow.com/users/20322", "pm_score": 1, "selected": false, "text": "<p>If the parameter is passed by value (and is not a reference), usually there is not much difference whether the parameter is declared as const or not (unless it contains a reference member -- not a problem for built-in types). If the parameter is a reference or pointer, it is usually better to protect the referenced/pointed-to memory, not the pointer itself (I think you cannot make the reference itself const, not that it matters much as you cannot change the referee).\nIt seems a good idea to protect everything you can as const. You can omit it without fear of making a mistake if the parameters are just PODs (including built-in types) and there is no chance of them changing further along the road (e.g. in your example the bool parameter).</p>\n\n<p>I didn't know about the .h/.cpp file declaration difference, but it does make some sense. At the machine code level, nothing is \"const\", so if you declare a function (in the .h) as non-const, the code is the same as if you declare it as const (optimizations aside). However, it helps you to enlist the compiler that you will not change the value of the variable inside the implementation of the function (.ccp). It might come handy in the case when you're inheriting from an interface that allows change, but you don't need to change to parameter to achieve the required functionality.</p>\n" }, { "answer_id": 117452, "author": "jdmichal", "author_id": 12275, "author_profile": "https://Stackoverflow.com/users/12275", "pm_score": 2, "selected": false, "text": "<p>I tend to use const wherever possible. (Or other appropriate keyword for the target language.) I do this purely because it allows the compiler to make extra optimizations that it would not be able to make otherwise. Since I have no idea what these optimizations may be, I always do it, even where it seems silly.</p>\n\n<p>For all I know, the compiler might very well see a const value parameter, and say, \"Hey, this function isn't modifying it anyway, so I can pass by reference and save some clock cycles.\" I don't think it ever would do such a thing, since it changes the function signature, but it makes the point. Maybe it does some different stack manipulation or something... The point is, I don't know, but I do know trying to be smarter than the compiler only leads to me being shamed.</p>\n\n<p>C++ has some extra baggage, with the idea of const-correctness, so it becomes even more important.</p>\n" }, { "answer_id": 117458, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 7, "selected": false, "text": "<p>The following two lines are functionally equivalent:</p>\n\n<pre><code>int foo (int a);\nint foo (const int a);\n</code></pre>\n\n<p>Obviously you won't be able to modify <code>a</code> in the body of <code>foo</code> if it's defined the second way, but there's no difference from the outside.</p>\n\n<p>Where <code>const</code> really comes in handy is with reference or pointer parameters:</p>\n\n<pre><code>int foo (const BigStruct &amp;a);\nint foo (const BigStruct *a);\n</code></pre>\n\n<p>What this says is that foo can take a large parameter, perhaps a data structure that's gigabytes in size, without copying it. Also, it says to the caller, \"Foo won't* change the contents of that parameter.\" Passing a const reference also allows the compiler to make certain performance decisions.</p>\n\n<p>*: Unless it casts away the const-ness, but that's another post.</p>\n" }, { "answer_id": 117488, "author": "Dan Hewett", "author_id": 17975, "author_profile": "https://Stackoverflow.com/users/17975", "pm_score": 3, "selected": false, "text": "<p>const is pointless when the argument is passed by value since you will not be modifying the caller's object.</p>\n\n<p>const should be preferred when passing by reference, unless the purpose of the function is to modify the passed value.</p>\n\n<p>Finally, a function which does not modify current object (this) can, and probably should be declared const. An example is below:</p>\n\n<pre><code>int SomeClass::GetValue() const {return m_internalValue;}\n</code></pre>\n\n<p>This is a promise to not modify the object to which this call is applied. In other words, you can call:</p>\n\n<pre><code>const SomeClass* pSomeClass;\npSomeClass-&gt;GetValue();\n</code></pre>\n\n<p>If the function was not const, this would result in a compiler warning.</p>\n" }, { "answer_id": 117557, "author": "rlerallut", "author_id": 20055, "author_profile": "https://Stackoverflow.com/users/20055", "pm_score": 9, "selected": false, "text": "<blockquote>\n<p><em><code>const</code> is pointless when the argument is passed by value since you will\nnot be modifying the caller's object.</em></p>\n</blockquote>\n<p>Wrong.</p>\n<p>It's about self-documenting your code and your assumptions.</p>\n<p>If your code has many people working on it and your functions are non-trivial then you should mark <code>const</code> any and everything that you can. When writing industrial-strength code, you should always assume that your coworkers are psychopaths trying to get you any way they can (especially since it's often yourself in the future).</p>\n<p>Besides, as somebody mentioned earlier, it <em>might</em> help the compiler optimize things a bit (though it's a long shot).</p>\n" }, { "answer_id": 117909, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 7, "selected": false, "text": "<p>Sometimes (too often!) I have to untangle someone else's C++ code. And we all know that <em>someone else's</em> C++ code is a complete mess almost by definition :) So the first thing I do to decipher local data flow is put <strong>const</strong> in every variable definition until compiler starts barking. This means const-qualifying value arguments as well, because they are just fancy local variables initialized by caller.</p>\n\n<p>Ah, I wish variables were <strong>const</strong> by default and <strong>mutable</strong> was required for non-const variables :)</p>\n" }, { "answer_id": 117932, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 5, "selected": false, "text": "<p>When I coded C++ for a living I consted everything I possibly could. Using const is a great way to help the compiler help you. For instance, const-ing your method return values can save you from typos such as: </p>\n\n<pre><code>foo() = 42\n</code></pre>\n\n<p>when you meant:</p>\n\n<pre><code>foo() == 42\n</code></pre>\n\n<p>If foo() is defined to return a non-const reference:</p>\n\n<pre><code>int&amp; foo() { /* ... */ }\n</code></pre>\n\n<p>The compiler will happily let you assign a value to the anonymous temporary returned by the function call. Making it const:</p>\n\n<pre><code>const int&amp; foo() { /* ... */ }\n</code></pre>\n\n<p>Eliminates this possibility.</p>\n" }, { "answer_id": 118117, "author": "Lloyd", "author_id": 9952, "author_profile": "https://Stackoverflow.com/users/9952", "pm_score": 3, "selected": false, "text": "<p>Marking value parameters 'const' is definitely a subjective thing.</p>\n\n<p>However I actually prefer to mark value parameters const, just like in your example.</p>\n\n<pre><code>void func(const int n, const long l) { /* ... */ }\n</code></pre>\n\n<p>The value to me is in clearly indicating that the function parameter values are never changed by the function. They will have the same value at the beginning as at the end. For me, it is part of keeping to a very functional programming sort of style.</p>\n\n<p>For a short function, it's arguably a waste of time/space to have the 'const' there, since it's usually pretty obvious that the arguments aren't modified by the function.</p>\n\n<p>However for a larger function, its a form of implementation documentation, and it is enforced by the compiler.</p>\n\n<p>I can be sure if I make some computation with 'n' and 'l', I can refactor/move that computation without fear of getting a different result because I missed a place where one or both is changed.</p>\n\n<p>Since it is an implementation detail, you don't need to declare the value parameters const in the header, just like you don't need to declare the function parameters with the same names as the implementation uses.</p>\n" }, { "answer_id": 120462, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>As parameters are being passed by value,it doesnt make any difference if you specify const or not from the calling function's perspective.It basically does not make any sense to declare pass by value parameters as const.</p>\n" }, { "answer_id": 120483, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 5, "selected": false, "text": "<p>const should have been the default in C++.\nLike this :</p>\n\n<pre><code>int i = 5 ; // i is a constant\n\nvar int i = 5 ; // i is a real variable\n</code></pre>\n" }, { "answer_id": 290101, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I say const your value parameters.</p>\n\n<p>Consider this buggy function:</p>\n\n<pre><code>bool isZero(int number)\n{\n if (number = 0) // whoops, should be number == 0\n return true;\n else\n return false;\n}\n</code></pre>\n\n<p>If the number parameter was const, the compiler would stop and warn us of the bug.</p>\n" }, { "answer_id": 822378, "author": "Void", "author_id": 69998, "author_profile": "https://Stackoverflow.com/users/69998", "pm_score": 4, "selected": false, "text": "<p>There is a good discussion on this topic in the old \"Guru of the Week\" articles on comp.lang.c++.moderated <a href=\"http://tinyurl.com/d7a8ds\" rel=\"noreferrer\">here</a>.</p>\n\n<p>The corresponding GOTW article is available on Herb Sutter's web site <a href=\"http://www.gotw.ca/gotw/006.htm\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 827084, "author": "sdcvvc", "author_id": 100020, "author_profile": "https://Stackoverflow.com/users/100020", "pm_score": 2, "selected": false, "text": "<p>On compiler optimizations: <a href=\"http://www.gotw.ca/gotw/081.htm\" rel=\"nofollow noreferrer\">http://www.gotw.ca/gotw/081.htm</a></p>\n" }, { "answer_id": 11036371, "author": "Adisak", "author_id": 14904, "author_profile": "https://Stackoverflow.com/users/14904", "pm_score": 7, "selected": false, "text": "<p>Extra Superfluous const are bad from an API stand-point:</p>\n<p>Putting extra superfluous const's in your code for intrinsic type parameters passed by value <strong>clutters your API</strong> while making no meaningful promise to the caller or API user (it only hampers the implementation).</p>\n<p>Too many 'const' in an API when not needed is like &quot;<strong>crying wolf</strong>&quot;, eventually people will start ignoring 'const' because it's all over the place and means nothing most of the time.</p>\n<p>The &quot;reductio ad absurdum&quot; argument to extra consts in API are good for these first two points would be is if more const parameters are good, then every argument that can have a const on it, SHOULD have a const on it. In fact, if it were truly that good, you'd want const to be the default for parameters and have a keyword like &quot;mutable&quot; only when you want to change the parameter.</p>\n<p>So lets try putting in const whereever we can:</p>\n<pre><code>void mungerum(char * buffer, const char * mask, int count);\n\nvoid mungerum(char * const buffer, const char * const mask, const int count);\n</code></pre>\n<p>Consider the line of code above. Not only is the declaration more cluttered and longer and harder to read but three of the four 'const' keywords can be safely ignored by the API user. However, the extra use of 'const' has made the second line potentially <strong>DANGEROUS!</strong></p>\n<p>Why?</p>\n<p>A quick misread of the first parameter <code>char * const buffer</code> might make you think that it will not modify the memory in data buffer that is passed in -- however, this is not true! <strong>Superfluous 'const' can lead to dangerous and incorrect assumptions about your API</strong> when scanned or misread quickly.</p>\n<hr />\n<p>Superfluous const are bad from a Code Implementation stand-point as well:</p>\n<pre><code>#if FLEXIBLE_IMPLEMENTATION\n #define SUPERFLUOUS_CONST\n#else\n #define SUPERFLUOUS_CONST const\n#endif\n\nvoid bytecopy(char * SUPERFLUOUS_CONST dest,\n const char *source, SUPERFLUOUS_CONST int count);\n</code></pre>\n<p>If FLEXIBLE_IMPLEMENTATION is not true, then the API is “promising” not to implement the function the first way below.</p>\n<pre><code>void bytecopy(char * SUPERFLUOUS_CONST dest,\n const char *source, SUPERFLUOUS_CONST int count)\n{\n // Will break if !FLEXIBLE_IMPLEMENTATION\n while(count--)\n {\n *dest++=*source++;\n }\n}\n\nvoid bytecopy(char * SUPERFLUOUS_CONST dest,\n const char *source, SUPERFLUOUS_CONST int count)\n{\n for(int i=0;i&lt;count;i++)\n {\n dest[i]=source[i];\n }\n}\n</code></pre>\n<p>That’s a very silly promise to make. Why should you make a promise that gives no benefit at all to your caller and only limits your implementation?</p>\n<p>Both of these are perfectly valid implementations of the same function though so all you’ve done is tied one hand behind your back unnecessarily.</p>\n<p>Furthermore, it’s a very shallow promise that is easily (and legally circumvented).</p>\n<pre><code>inline void bytecopyWrapped(char * dest,\n const char *source, int count)\n{\n while(count--)\n {\n *dest++=*source++;\n }\n}\nvoid bytecopy(char * SUPERFLUOUS_CONST dest,\n const char *source,SUPERFLUOUS_CONST int count)\n{\n bytecopyWrapped(dest, source, count);\n}\n</code></pre>\n<p>Look, I implemented it that way anyhow even though I promised not to – just using a wrapper function. It’s like when the bad guy promises not to kill someone in a movie and orders his henchman to kill them instead.</p>\n<p>Those superfluous const’s are worth no more than a promise from a movie bad-guy.</p>\n<hr />\n<p>But the ability to lie gets even worse:</p>\n<p>I have been enlightened that you can mismatch const in header (declaration) and code (definition) by using spurious const. The const-happy advocates claim this is a good thing since it lets you put const only in the definition.</p>\n<pre><code>// Example of const only in definition, not declaration\nstruct foo { void test(int *pi); };\nvoid foo::test(int * const pi) { }\n</code></pre>\n<p>However, the converse is true... you can put a spurious const only in the declaration and ignore it in the definition. This only makes superfluous const in an API more of a terrible thing and a horrible lie - see this example:</p>\n<pre><code>struct foo\n{\n void test(int * const pi);\n};\n\nvoid foo::test(int *pi) // Look, the const in the definition is so superfluous I can ignore it here\n{\n pi++; // I promised in my definition I wouldn't modify this\n}\n</code></pre>\n<hr />\n<p>All the superfluous const actually does is make the implementer's code less readable by forcing him to use another local copy or a wrapper function when he wants to change the variable or pass the variable by non-const reference.</p>\n<p>Look at this example. Which is more readable ? Is it obvious that the only reason for the extra variable in the second function is because some API designer threw in a superfluous const ?</p>\n<pre><code>struct llist\n{\n llist * next;\n};\n\nvoid walkllist(llist *plist)\n{\n llist *pnext;\n while(plist)\n {\n pnext=plist-&gt;next;\n walk(plist);\n plist=pnext; // This line wouldn't compile if plist was const\n }\n}\n\nvoid walkllist(llist * SUPERFLUOUS_CONST plist)\n{\n llist * pnotconst=plist;\n llist *pnext;\n while(pnotconst)\n {\n pnext=pnotconst-&gt;next;\n walk(pnotconst);\n pnotconst=pnext;\n }\n}\n</code></pre>\n<hr />\n<p>Hopefully we've learned something here. Superfluous const is an API-cluttering eyesore, an annoying nag, a shallow and meaningless promise, an unnecessary hindrance, and occasionally leads to very dangerous mistakes.</p>\n" }, { "answer_id": 11622623, "author": "user541686", "author_id": 541686, "author_profile": "https://Stackoverflow.com/users/541686", "pm_score": 3, "selected": false, "text": "<h3>If you use the <code>-&gt;*</code> or <code>.*</code> operators, it's a must.</h3>\n<p>It prevents you from writing something like</p>\n<pre><code>void foo(Bar *p) { if (++p-&gt;*member &gt; 0) { ... } }\n</code></pre>\n<p>which I almost did right now, and which probably doesn't do what you intend.</p>\n<p>What I intended to say was</p>\n<pre><code>void foo(Bar *p) { if (++(p-&gt;*member) &gt; 0) { ... } }\n</code></pre>\n<p>and if I had put a <code>const</code> in between <code>Bar *</code> and <code>p</code>, the compiler would have told me that.</p>\n" }, { "answer_id": 29439871, "author": "HarshaXsoad", "author_id": 4587281, "author_profile": "https://Stackoverflow.com/users/4587281", "pm_score": 2, "selected": false, "text": "<p>May be this wont be a valid argument. but if we increment the value of a const variable inside a function compiler will give us an error:\n \"<strong>error: increment of read-only parameter</strong>\". so that means we can use const key word as a way to prevent accidentally modifying our variables inside functions(which we are not supposed to/read-only). so if we accidentally did it at the compile time compiler will let us know that. this is specially important if you are not the only one who is working on this project.</p>\n" }, { "answer_id": 29510533, "author": "PavDub", "author_id": 3840660, "author_profile": "https://Stackoverflow.com/users/3840660", "pm_score": -1, "selected": false, "text": "<p>I know the question is \"a bit\" outdated but as I came accross it somebody else may also do so in future... ...still I doubt the poor fellow will list down here to read my comment :)</p>\n\n<p>It seems to me that we are still too confined to C-style way of thinking. In the OOP paradigma we play around with objects, not types. Const object may be conceptually different from a non-const object, specifically in the sense of logical-const (in contrast to bitwise-const). Thus even if const correctness of function params is (perhaps) an over-carefulness in case of PODs it is not so in case of objects. If a function works with a const object it should say so. Consider the following code snippet</p>\n\n<pre><code>#include &lt;iostream&gt;\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nclass SharedBuffer {\nprivate:\n\n int fakeData;\n\n int const &amp; Get_(int i) const\n {\n\n std::cout &lt;&lt; \"Accessing buffer element\" &lt;&lt; std::endl;\n return fakeData;\n\n }\n\npublic:\n\n int &amp; operator[](int i)\n {\n\n Unique();\n return const_cast&lt;int &amp;&gt;(Get_(i));\n\n }\n\n int const &amp; operator[](int i) const\n {\n\n return Get_(i);\n\n }\n\n void Unique()\n {\n\n std::cout &lt;&lt; \"Making buffer unique (expensive operation)\" &lt;&lt; std::endl;\n\n }\n\n};\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nvoid NonConstF(SharedBuffer x)\n{\n\n x[0] = 1;\n\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nvoid ConstF(const SharedBuffer x)\n{\n\n int q = x[0];\n\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint main()\n{\n\n SharedBuffer x;\n\n NonConstF(x);\n\n std::cout &lt;&lt; std::endl;\n\n ConstF(x);\n\n return 0;\n\n}\n</code></pre>\n\n<p>ps.: you may argue that (const) reference would be more appropriate here and gives you the same behaviour. Well, right. Just giving a different picture from what I could see elsewhere...</p>\n" }, { "answer_id": 44228229, "author": "Paul Stearns", "author_id": 2027333, "author_profile": "https://Stackoverflow.com/users/2027333", "pm_score": -1, "selected": false, "text": "<p>Being a VB.NET programmer that needs to use a C++ program with 50+ exposed functions, and a .h file that sporadically uses the const qualifier, it is difficult to know when to access a variable using ByRef or ByVal.</p>\n\n<p>Of course the program tells you by generating an exception error on the line where you made the mistake, but then you need to guess which of the 2-10 parameters is wrong.</p>\n\n<p>So now I have the distasteful task of trying to convince a developer that they should really define their variables (in the .h file) in a manner that allows an automated method of creating all of the VB.NET function definitions easily. They will then smugly say, \"read the ... documentation.\" </p>\n\n<p>I have written an awk script that parses a .h file, and creates all of the Declare Function commands, but without an indicator as to which variables are R/O vs R/W, it only does half the job.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>At the encouragement of another user I am adding the following;</p>\n\n<p>Here is an example of a (IMO) poorly formed .h entry;</p>\n\n<pre><code>typedef int (EE_STDCALL *Do_SomethingPtr)( int smfID, const char* cursor_name, const char* sql );\n</code></pre>\n\n<p>The resultant VB from my script;</p>\n\n<pre><code> Declare Function Do_Something Lib \"SomeOther.DLL\" (ByRef smfID As Integer, ByVal cursor_name As String, ByVal sql As String) As Integer\n</code></pre>\n\n<p>Note the missing \"const\" on the first parameter. Without it, a program (or another developer) has no Idea the 1st parameter should be passed \"ByVal.\" By adding the \"const\" it makes the .h file self documenting so that developers using other languages can easily write working code.</p>\n" }, { "answer_id": 45323048, "author": "YvesgereY", "author_id": 995896, "author_profile": "https://Stackoverflow.com/users/995896", "pm_score": 2, "selected": false, "text": "<p>To summarize:</p>\n\n<ul>\n<li>\"Normally const pass-by-value is unuseful and misleading at best.\" From <a href=\"http://www.gotw.ca/gotw/006.htm\" rel=\"nofollow noreferrer\">GOTW006</a></li>\n<li>But you can add them in the .cpp as you would do with variables.</li>\n<li>Note that the standard library doesn't use const. E.g. <code>std::vector::at(size_type pos)</code>. What's good enough for the standard library is good for me.</li>\n</ul>\n" }, { "answer_id": 60823004, "author": "Gabriel Staples", "author_id": 4561887, "author_profile": "https://Stackoverflow.com/users/4561887", "pm_score": 4, "selected": false, "text": "<h2>1. Best answer based on my assessment:</h2>\n<p><a href=\"https://stackoverflow.com/questions/117293/use-of-const-for-function-parameters/11036371#11036371\">The answer by @Adisak</a> is the best answer here based on my assessment. Note that this answer is in part the best because it is also <strong>the <em>most well-backed-up with real code examples</em></strong>, <em>in addition to using sound and well-thought-out logic.</em></p>\n<h2>2. My own words (agreeing with the best answer):</h2>\n<ol>\n<li>For pass-by-value there is no benefit to adding <code>const</code>. All it does is:\n<ol>\n<li>limit the implementer to have to make a copy every time they want to change an input param in the source code (which change would have no side effects anyway since what's passed in is already a copy since it's pass-by-value). And frequently, changing an input param which is passed by value is used to implement the function, so adding <code>const</code> everywhere can hinder this.</li>\n<li>and adding <code>const</code> unnecessarily clutters the code with <code>const</code>s everywhere, drawing attention away from the <code>const</code>s that are truly necessary to have safe code.</li>\n</ol>\n</li>\n<li>When dealing with <em>pointers</em> or <em>references</em>, however, <code>const</code> is critically important when needed, and <em>must</em> be used, as it prevents undesired side effects with persistent changes <em>outside</em> the function, and therefore every single pointer or reference <em>must</em> use <code>const</code> when the param is an input only, not an output. Using <code>const</code> <em>only</em> on parameters passed by reference or pointer has the additional benefit of making it <em>really obvious</em> which parameters are pointers or references. It's one more thing to stick out and say &quot;Watch out! Any param with <code>const</code> next to it is a reference or pointer!&quot;.</li>\n<li>What I've described above has frequently been the consensus achieved in professional software organizations I have worked in, and has been considered best practice. Sometimes even, the rule has been strict: <strong>&quot;don't ever use const on parameters which are passed by value, but always use it on parameters passed by reference or pointer if they are inputs only.&quot;</strong></li>\n</ol>\n<h2>3. <a href=\"https://google.github.io/styleguide/cppguide.html\" rel=\"noreferrer\">Google's words</a> (agreeing with me and the best answer):</h2>\n<p>(From the &quot;<a href=\"https://google.github.io/styleguide/cppguide.html#Use_of_const\" rel=\"noreferrer\">Google C++ Style Guide</a>&quot;)</p>\n<blockquote>\n<p>For a function parameter passed by value, const has no effect on the caller, thus is not recommended in function declarations. See <a href=\"https://abseil.io/tips/109\" rel=\"noreferrer\">TotW #109</a>.</p>\n</blockquote>\n<blockquote>\n<p>Using const on local variables is neither encouraged nor discouraged.</p>\n</blockquote>\n<p>Source: the &quot;Use of const&quot; section of the Google C++ Style Guide: <a href=\"https://google.github.io/styleguide/cppguide.html#Use_of_const\" rel=\"noreferrer\">https://google.github.io/styleguide/cppguide.html#Use_of_const</a>. This is actually a really valuable section, so read the whole section.</p>\n<p>Note that &quot;TotW #109&quot; stands for <a href=\"https://abseil.io/tips/109\" rel=\"noreferrer\">&quot;Tip of the Week #109: Meaningful <code>const</code> in Function Declarations&quot;</a>, and is also a useful read. It is more informative and less prescriptive on what to do, and based on context came <em>before</em> the Google C++ Style Guide rule on <code>const</code> quoted just above, but as a result of the clarity it provided, the <code>const</code> rule quoted just above was added to the Google C++ Style Guide.</p>\n<p>Also note that even though I'm quoting the Google C++ Style Guide here in defense of my position, it does NOT mean I always follow the guide or always recommend following the guide. Some of the things they recommend are just plain weird, such as <a href=\"https://google.github.io/styleguide/cppguide.html#Constant_Names\" rel=\"noreferrer\">their <code>kDaysInAWeek</code>-style naming convention for &quot;Constant Names&quot;</a>. <em>However, it is still nonetheless useful and relevant to point out when one of the world's most successful and influential technical and software companies uses the same justification as I and others like @Adisak do to back up our viewpoints on this matter.</em></p>\n<h2>4. Clang's linter, <code>clang-tidy</code>, has some options for this:</h2>\n<p>A. It's also worth noting that Clang's linter, <code>clang-tidy</code>, has an option, <code>readability-avoid-const-params-in-decls</code>, <a href=\"https://clang.llvm.org/extra/clang-tidy/checks/readability-avoid-const-params-in-decls.html\" rel=\"noreferrer\">described here</a>, to support <strong>enforcing in a code base <em>not</em> using <code>const</code> for pass-by-value function parameters</strong>:</p>\n<blockquote>\n<p>Checks whether a function declaration has parameters that are top level const.</p>\n</blockquote>\n<blockquote>\n<p>const values in declarations do not affect the signature of a function, so they should not be put there.</p>\n</blockquote>\n<blockquote>\n<p>Examples:</p>\n</blockquote>\n<blockquote>\n<pre><code>void f(const string); // Bad: const is top level.\nvoid f(const string&amp;); // Good: const is not top level.\n</code></pre>\n</blockquote>\n<p>And here are two more examples I'm adding myself for completeness and clarity:</p>\n<pre><code>void f(char * const c_string); // Bad: const is top level. [This makes the _pointer itself_, NOT what it points to, const]\nvoid f(const char * c_string); // Good: const is not top level. [This makes what is being _pointed to_ const]\n</code></pre>\n<p>B. It also has this option: <code>readability-const-return-type</code> - <a href=\"https://clang.llvm.org/extra/clang-tidy/checks/readability-const-return-type.html\" rel=\"noreferrer\">https://clang.llvm.org/extra/clang-tidy/checks/readability-const-return-type.html</a></p>\n<h2>5. My pragmatic approach to how I'd word a style guide on the matter:</h2>\n<p>I'd simply copy and paste this into my style guide:</p>\n<p>[COPY/PASTE START]</p>\n<ol>\n<li><strong>Always use</strong> <code>const</code> on function parameters passed by reference or pointer when their contents (what they point to) are intended NOT to be changed. This way, it becomes obvious when a variable passed by reference or pointer IS expected to be changed, because it will lack <code>const</code>. In this use case <code>const</code> prevents accidental side effects outside the function.</li>\n<li>It is <strong>not recommended</strong> to use <code>const</code> on function parameters passed by value, because <code>const</code> has no effect on the caller: even if the variable is changed in the function there will be no side effects outside the function. See the following resources for additional justification and insight:\n<ol>\n<li><a href=\"https://google.github.io/styleguide/cppguide.html#Use_of_const\" rel=\"noreferrer\">&quot;Google C++ Style Guide&quot; &quot;Use of const&quot; section</a></li>\n<li><a href=\"https://abseil.io/tips/109\" rel=\"noreferrer\">&quot;Tip of the Week #109: Meaningful <code>const</code> in Function Declarations&quot;</a></li>\n<li><a href=\"https://stackoverflow.com/questions/117293/use-of-const-for-function-parameters/11036371#11036371\">Adisak's Stack Overflow answer on &quot;Use of 'const' for function parameters&quot;</a></li>\n</ol>\n</li>\n<li>&quot;<strong>Never use</strong> top-level <code>const</code> [ie: <code>const</code> on parameters <em>passed by value</em>] on function parameters in <em>declarations that are not definitions</em> (and be careful not to copy/paste a meaningless <code>const</code>). It is meaningless and ignored by the compiler, it is visual noise, and it could mislead readers&quot; (<a href=\"https://abseil.io/tips/109\" rel=\"noreferrer\">https://abseil.io/tips/109</a>, emphasis added).</li>\n<li>The only <code>const</code> qualifiers that have an effect on compilation are those placed in the function definition, NOT those in a forward declaration of the function, such as in a function (method) declaration in a header file.</li>\n<li><strong>Never use</strong> top-level <code>const</code> [ie: <code>const</code> on variables <em>passed by value</em>] on values <em>returned</em> by a function.</li>\n<li>Using <code>const</code> on pointers or references returned by a function is <strong>up to the implementer</strong>, as it is sometimes useful.</li>\n<li>TODO: enforce some of the above with the following <code>clang-tidy</code> options:</li>\n<li><a href=\"https://clang.llvm.org/extra/clang-tidy/checks/readability-avoid-const-params-in-decls.html\" rel=\"noreferrer\">https://clang.llvm.org/extra/clang-tidy/checks/readability-avoid-const-params-in-decls.html</a></li>\n<li><a href=\"https://clang.llvm.org/extra/clang-tidy/checks/readability-const-return-type.html\" rel=\"noreferrer\">https://clang.llvm.org/extra/clang-tidy/checks/readability-const-return-type.html</a></li>\n</ol>\n<p>Here are some code examples to demonstrate the <code>const</code> rules described above:</p>\n<p><strong><code>const</code> Parameter Examples:</strong><br />\n(some are borrowed from <a href=\"https://clang.llvm.org/extra/clang-tidy/checks/readability-avoid-const-params-in-decls.html\" rel=\"noreferrer\">here</a>)</p>\n<pre><code>void f(const std::string); // Bad: const is top level.\nvoid f(const std::string&amp;); // Good: const is not top level.\n\nvoid f(char * const c_string); // Bad: const is top level. [This makes the _pointer itself_, NOT what it points to, const]\nvoid f(const char * c_string); // Good: const is not top level. [This makes what is being _pointed to_ const]\n</code></pre>\n<p><strong><code>const</code> Return Type Examples:</strong><br />\n(some are borrowed from <a href=\"https://clang.llvm.org/extra/clang-tidy/checks/readability-const-return-type.html\" rel=\"noreferrer\">here</a>)</p>\n<pre><code>// BAD--do not do this:\nconst int foo();\nconst Clazz foo();\nClazz *const foo();\n\n// OK--up to the implementer:\nconst int* foo();\nconst int&amp; foo();\nconst Clazz* foo();\n</code></pre>\n<p>[COPY/PASTE END]</p>\n<p><sub>Keywords: use of <code>const</code> in function parameters; coding standards; C and C++ coding standards; coding guidelines; best practices; code standards; const return values</sub></p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
How far do you go with `const`? Do you just make functions `const` when necessary or do you go the whole hog and use it everywhere? For example, imagine a simple mutator that takes a single boolean parameter: ``` void SetValue(const bool b) { my_val_ = b; } ``` Is that `const` actually useful? Personally I opt to use it extensively, including parameters, but in this case I wonder if it's worthwhile? I was also surprised to learn that you can omit `const` from parameters in a function declaration but can include it in the function definition, e.g.: **.h file** ``` void func(int n, long l); ``` **.cpp file** ``` void func(const int n, const long l) ``` Is there a reason for this? It seems a little unusual to me.
The reason is that `const` for the parameter only applies locally within the function, since it is working on a copy of the data. This means the function signature is really the same anyways. It's probably bad style to do this a lot though. I personally tend to not use `const` except for reference and pointer parameters. For copied objects it doesn't really matter, although it can be safer as it signals intent within the function. It's really a judgement call. I do tend to use `const_iterator` though when looping on something and I don't intend on modifying it, so I guess to each his own, as long as `const` correctness for reference types is rigorously maintained.
117,312
<p>I work with a bunch of sets in order to generate constrained random traffic, but I want to be able to call a Specman macro that computes the complement of a set with syntax like:</p> <pre><code>COMPLEMENT begin domain=[0..10,24..30], complementing_set=[2..3,27..30] end </code></pre> <p>and have it generate:</p> <pre><code>[0..1,4..10,24..26] </code></pre> <p>Every time I need the complement of a set I'm using fully populated lists (e.g. {0;1;2;3....} ) and then removing elements, instead of using Specman's built-in int_range_list object. And I'm also doing a lot of these set calculations at run-time instead of compile-time.</p>
[ { "answer_id": 146590, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 2, "selected": false, "text": "<p>You can try this:</p>\n\n<pre><code>var domain: list of int = {0..10, 24..30}; \nvar complementing_set: list of int = {2..3, 27..30};\nvar complement: list of int = domain.all(it in complementing set);\n</code></pre>\n\n<p>The <code>all</code> pseudo-method generates a sublist of the parent list of all the elements in the parent list for which the condition in the parentheses holds.</p>\n" }, { "answer_id": 10928047, "author": "guy", "author_id": 1441644, "author_profile": "https://Stackoverflow.com/users/1441644", "pm_score": 1, "selected": false, "text": "<p>one more way may be to use uints, say you have a 500 possible values:</p>\n\n<pre><code>domain : uint(bits:500);\ncomplement : uint(bits:500);\nset : uint(bits:500) = domain &amp; ~complement;\n</code></pre>\n\n<p>you can later extract the indices with</p>\n\n<pre><code>set_l : list of uint = set[.]].all_indices(it==1);\n</code></pre>\n\n<p>depending on your domain to possible values ratio this method may be quicker to calculate</p>\n" }, { "answer_id": 22993713, "author": "Yuri Tsoglin", "author_id": 3518556, "author_profile": "https://Stackoverflow.com/users/3518556", "pm_score": 2, "selected": false, "text": "<p>In the recent versions of Specman, you can use the pre-defined <code>set</code> type, that serves exactly this purpose. For example, you can do things like this:</p>\n\n<pre><code>var s1: set = [1..5, 10..15];\nvar s2: set = [4..13];\nvar s3: set = s1.intersect(s2);\n</code></pre>\n\n<p>and even like this:</p>\n\n<pre><code>x: int;\ny: int;\n........\nvar s1: set = [x..y];\nvar s2: set = [1..10];\nvar s3: set = s1.union(s2);\n</code></pre>\n\n<p>etc.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20712/" ]
I work with a bunch of sets in order to generate constrained random traffic, but I want to be able to call a Specman macro that computes the complement of a set with syntax like: ``` COMPLEMENT begin domain=[0..10,24..30], complementing_set=[2..3,27..30] end ``` and have it generate: ``` [0..1,4..10,24..26] ``` Every time I need the complement of a set I'm using fully populated lists (e.g. {0;1;2;3....} ) and then removing elements, instead of using Specman's built-in int\_range\_list object. And I'm also doing a lot of these set calculations at run-time instead of compile-time.
You can try this: ``` var domain: list of int = {0..10, 24..30}; var complementing_set: list of int = {2..3, 27..30}; var complement: list of int = domain.all(it in complementing set); ``` The `all` pseudo-method generates a sublist of the parent list of all the elements in the parent list for which the condition in the parentheses holds.
117,318
<p>Consider this code...</p> <pre><code>using System.Threading; //... Timer someWork = new Timer( delegate(object state) { //Do some work here... }, null, 0, 60000); HttpContext.Current.Application["SomeWorkItem"] = someWork; </code></pre> <p>Could this be dangerous? Caching a timer in the Application to perform some work in the background while your site runs seems safe, but I wondered if anyone has some experience with this.</p> <p>I'm sure that writing a Service to run in the background would certainly be much better, but sometimes that isn't always an option. Is this an alternative?</p>
[ { "answer_id": 117342, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 2, "selected": false, "text": "<p>The problem with this is that you are not guaranteed the process still being alive. IIS will reclaim the process basically whenever it feels like it, so you run the risk of it not being performed.</p>\n\n<p>If you need this work done then you need to either code it into a web call, or have a service running in the background of the server.</p>\n" }, { "answer_id": 117351, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 1, "selected": false, "text": "<p>That would be dangerous as there can be times when the worker process gets recycled or the AppDomain crashes and the Work Item is killed and you may want it to recover what it was doing, it may not be possible.</p>\n\n<p>A Windows service may be OK if you can get that work item out into a service. If an HttpContext is required for the work though you may want to have a windows service call a webservice to do the call periodically that may work though likely not ideal.</p>\n" }, { "answer_id": 117377, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 0, "selected": false, "text": "<p>That makes sense, but just for fun, what if the work doesn't need to run if the site gets shut down? If it's associated with the Application_Start event and only needs to run while people are browsing the site, what are the risks at that point?</p>\n\n<p>Good answers, I'm just curious a little more about how that works on the inside.</p>\n" }, { "answer_id": 117385, "author": "Arthur Chaparyan", "author_id": 18234, "author_profile": "https://Stackoverflow.com/users/18234", "pm_score": 0, "selected": false, "text": "<p>I would recommend you setup a scheduled task to run a page on your site. I usually point the scheduled task to a .vbs file with the following:</p>\n\n<pre>\nOn Error Resume Next\nDim objRequest\nDim URL\n\nSet objRequest = CreateObject(\"Microsoft.XMLHTTP\")\nURL = \"http://www.mywebsite.com/cron/pagetorun.ashx\"\n\nobjRequest.open \"POST\", URL , false\n\nobjRequest.Send\n\nSet objRequest = Nothing\n</pre>\n" }, { "answer_id": 117400, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 3, "selected": true, "text": "<p>This would generally be a bad idea, as System.Threading.Timer uses threads from the ThreadPool, the same as ASP.Net.</p>\n\n<p>If for what ever reason your timer delegate blocks or stops, the timer will simply begin a new Thread after the timeout period, which eats in to the Threads available for ASP.net.</p>\n\n<p>If they all begin blocking, effectively you will not be able to serve any more web requests (probably a bad thing)</p>\n" }, { "answer_id": 223240, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Omar Al Zabir has an excellent post on using cache item callbacks for this purpose.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/aspnet/ASPNETService.aspx?fid=229682&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;fr=76&amp;select=1334820\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/ASPNETService.aspx?fid=229682&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;fr=76&amp;select=1334820</a></p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17091/" ]
Consider this code... ``` using System.Threading; //... Timer someWork = new Timer( delegate(object state) { //Do some work here... }, null, 0, 60000); HttpContext.Current.Application["SomeWorkItem"] = someWork; ``` Could this be dangerous? Caching a timer in the Application to perform some work in the background while your site runs seems safe, but I wondered if anyone has some experience with this. I'm sure that writing a Service to run in the background would certainly be much better, but sometimes that isn't always an option. Is this an alternative?
This would generally be a bad idea, as System.Threading.Timer uses threads from the ThreadPool, the same as ASP.Net. If for what ever reason your timer delegate blocks or stops, the timer will simply begin a new Thread after the timeout period, which eats in to the Threads available for ASP.net. If they all begin blocking, effectively you will not be able to serve any more web requests (probably a bad thing)
117,337
<p>Let's assume that some developer in my team shelved his changes that he did in branch A. And I am working on branch B. Can I unshelve his changes into branch B? (By GUI or command prompt) </p>
[ { "answer_id": 117371, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 1, "selected": false, "text": "<p>The shelf information includes the specific path it goes to. Unfortunately I don't know of any automatic way to unshelve to any location other than the one it was shelved to. The times I've wanted to do this I had to check out the equivalent files in the new branch, unshelve from the old branch, then manually copy the files over.</p>\n\n<p>EDIT: Well, I guess I was doing it the hard way. I'll have to try out Curt's solution. :)</p>\n" }, { "answer_id": 117376, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 8, "selected": true, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/vstudio/bb980963.aspx\" rel=\"noreferrer\">Visual Studio Power Tools</a> should let you do this.</p>\n\n<pre><code>C:\\src\\2\\Merlin\\Main&gt;tfpt unshelve /?\ntfpt unshelve - Unshelve into workspace with pending changes\n\nAllows a shelveset to be unshelved into a workspace with pending changes.\nMerges content between local and shelved changes. Allows migration of shelved\nchanges from one branch into another by rewriting server paths.\n\nUsage: tfpt unshelve [shelvesetname[;username]] [/nobackup]\n [/migrate /source:serverpath /target:serverpath]\n\n shelvesetname The name of the shelveset to unshelve\n /nobackup Skip the creation of a backup shelveset\n /migrate Rewrite the server paths of the shelved items\n (for example to unshelve into another branch)\n /source:serverpath Source location for path rewrite (supply with /migrate)\n /target:serverpath Target location for path rewrite (supply with /migrate)\n /nobackup Skip the creation of a backup shelveset\n</code></pre>\n\n<p>For example to merge a shelve set called \"Shelve Set Name\" created on Branch1 to Branch2 use this:</p>\n\n<pre><code>&gt;tfpt unshelve \"Shelve Set Name\";domain\\userName /migrate /source:\"$/Project/Branch1/\" /target:\"$/Project/Branch2/\"\n</code></pre>\n" }, { "answer_id": 5428836, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 5, "selected": false, "text": "<p><strong>Alternative solution to tfpt that avoids having to merge each file manually</strong></p>\n\n<p>The problem with the tfs power tool is that <a href=\"http://blogs.msdn.com/b/mohamedg/archive/2009/04/30/how-to-move-a-shelveset-to-another-branch.aspx\" rel=\"noreferrer\">you're doing a 'baseless merge' so have to confirm every file</a>. I had a shelveset of over 800 files and I never trust the 'auto merge' button and didn't want to go through each file in turn - so I had to find another way!</p>\n\n<ul>\n<li>Download and install the <a href=\"http://www.attrice.info/cm/tfs/\" rel=\"noreferrer\">TFS Shelveset Sidekick</a>. </li>\n<li>The tool appears under 'Tools' in VS2010</li>\n<li>Run the 'Shelveset Sidekick' tool, click Search to show shelvesets</li>\n<li>Right click on your shelveset and select 'Export Shelveset'</li>\n<li>Save to an empty location such as <code>C:\\temp\\shelveset-name</code></li>\n<li>Now have a complete directory structure containing JUST the new files </li>\n</ul>\n\n<p>(Note: There's no progress bar when exporting - so if you have a large shelveset that takes a long time to export you'll just have to check in Windows Explorer (File>Properties>Size) that the files are still coming down if you think it's frozen).</p>\n\n<p>You now just have to copy them over to the new branch with Windows Explorer.</p>\n\n<p>This worked for me :</p>\n\n<ul>\n<li>Checking out the whole solution first (in the new branch)</li>\n<li>Close that solution</li>\n<li>Take TFS offline from within VS (<a href=\"http://visualstudiogallery.msdn.microsoft.com/425f09d8-d070-4ab1-84c1-68fa326190f4?SRC=Home\" rel=\"noreferrer\">Tool to do this</a>) - <em>see below for why this is important...</em></li>\n<li>Copy files over in Windows Explorer. The directory structure in <code>c:\\temp\\shelveset-name</code> will have to be renamed to correspond to the new branch. <strong>Tip: Make sure you copy to the right place!!!</strong></li>\n<li>Bring VS online</li>\n<li>It should find all the changes and add the new files</li>\n<li>If it asks you to bind the sourcecontrol be sure to verify the path is correct for the new branch.</li>\n<li>Test - and then checkin the new files</li>\n</ul>\n\n<p>Important: I've found that if you don't first take TFS offline then you'll end up with any new files (from your unshelves changeset) showing without a little red check mark and you'll have to exclude and include them again to get them to add. If anyone has an alternative solution to this problem I'd love to know - refreshing doesn't seem to work.</p>\n" }, { "answer_id": 50260445, "author": "T.S.", "author_id": 1704458, "author_profile": "https://Stackoverflow.com/users/1704458", "pm_score": 0, "selected": false, "text": "<p>I spent good amount of time to get this done and I had few issues to overcome. It is possible but here few issues and few rules to follow to avois these issues </p>\n\n<p>Error:</p>\n\n<blockquote>\n <p>unable to determine the workspace</p>\n</blockquote>\n\n<p>This particular issue was solved by running the command from <strong>source</strong> branch root folder. This is contrary to some answers on SO where they say to use \"target\" branch - no, use \"source\":</p>\n\n<pre><code>cd [your !!source!! branch root]\ntfpt unshelve /migrate /source:\"$/MyCollection/Development/Maint1.1\" /target:\"$/MyCollection/Development/Maint1.2\" \"myShelveset;UserName\"\n</code></pre>\n\n<p>Second issue appeared after this. Seem that it couldn't connect to TFS server. What I realized, I have multiple VS installed and connected to different TFS servers. I was using VS12 and I had workspace and server connection. But I didn't realize that same connection needs to be replicated in VS13 for TFPT2013 to work. It connects to same server and workspace.</p>\n\n<p>I also tried doing it using TFPT2015 but I installed it and it didn't install TFPT.exe hence it was useless. So I tried from TFPT2013 to TFS2015 and it worked for this particular command. I wonder, why not, if VS12/13 works fine against TFS2015?</p>\n\n<p><strong>To summarize</strong></p>\n\n<ul>\n<li>Use CMD or DevCMD - doesn't matter</li>\n<li>run command from <strong>source</strong> branch root folder</li>\n<li>verify Team Explorer Server connection for specific VS</li>\n<li>TF Power Tools 2013 work against TFS v15, at least <em>migrate</em> option works</li>\n</ul>\n" }, { "answer_id": 57855774, "author": "JohnH", "author_id": 3057983, "author_profile": "https://Stackoverflow.com/users/3057983", "pm_score": 0, "selected": false, "text": "<p>The following steps can be used for small size shelvesets (~20 files or less).</p>\n\n<ol>\n<li>On the shelveset and target branches, start by having all pending updates checked in or rolled back.</li>\n<li>On the shelveset branch, unshelve the files from the applicable shelveset.</li>\n<li>On the target branch, checkout any of the existing files that were in the unshelved shelveset.</li>\n<li>Compare the unshelved files on the shelveset branch with those on the target branch to identify those files that require merge updates (if any).</li>\n<li>If needed, manually make merge updates to the applicable files of the prior step and save these files in the target branch workspace.</li>\n<li>Copy the other shelveset files from the shelveset branch workspace to the target branch workspace.</li>\n<li>Compare the new updated files in the target branch workspace with the checked in files. Make any corrections as needed.</li>\n<li>Check in the new updated files on the target branch.</li>\n<li>Rollback the unhelved files on the shelveset branch.</li>\n</ol>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11374/" ]
Let's assume that some developer in my team shelved his changes that he did in branch A. And I am working on branch B. Can I unshelve his changes into branch B? (By GUI or command prompt)
The [Visual Studio Power Tools](http://msdn.microsoft.com/en-us/vstudio/bb980963.aspx) should let you do this. ``` C:\src\2\Merlin\Main>tfpt unshelve /? tfpt unshelve - Unshelve into workspace with pending changes Allows a shelveset to be unshelved into a workspace with pending changes. Merges content between local and shelved changes. Allows migration of shelved changes from one branch into another by rewriting server paths. Usage: tfpt unshelve [shelvesetname[;username]] [/nobackup] [/migrate /source:serverpath /target:serverpath] shelvesetname The name of the shelveset to unshelve /nobackup Skip the creation of a backup shelveset /migrate Rewrite the server paths of the shelved items (for example to unshelve into another branch) /source:serverpath Source location for path rewrite (supply with /migrate) /target:serverpath Target location for path rewrite (supply with /migrate) /nobackup Skip the creation of a backup shelveset ``` For example to merge a shelve set called "Shelve Set Name" created on Branch1 to Branch2 use this: ``` >tfpt unshelve "Shelve Set Name";domain\userName /migrate /source:"$/Project/Branch1/" /target:"$/Project/Branch2/" ```
117,346
<p>I'm working on a C++ application that needs detailed timing information, down to the millisecond level. </p> <p>We intend to gather the time to second accuracy using the standard <code>time()</code> function in <code>&lt;ctime&gt;</code>. We would like to additionally gather the milliseconds elapsed since the last second given by <code>time()</code>. </p> <p>Does anyone know a convenient method for obtaining this information? </p>
[ { "answer_id": 117359, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": -1, "selected": false, "text": "<p>Look into the QueryPerformanceCounter methods if this is for Windows.</p>\n" }, { "answer_id": 117369, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>There is not a portable solution to this problem, since ANSI C does not define a standard millisecond-accurate time function. If you're using Windows, you can use GetTickCount(), timeGetTime(), or QueryPerformanceCounter()/QueryPerformanceFrequency(). Keep in mind that these have different accuracies and different runtime costs.</p>\n\n<p>There are other similar functions in other operating systems; I'm not sure what they are off the top of my head.</p>\n" }, { "answer_id": 117381, "author": "jdmichal", "author_id": 12275, "author_profile": "https://Stackoverflow.com/users/12275", "pm_score": 0, "selected": false, "text": "<p>Anything not in the <code>(c)time.h</code> header requires OS-specific methods. I believe all those methods are second resolution.</p>\n\n<p>What OS are you working in?</p>\n" }, { "answer_id": 117432, "author": "Justin Rudd", "author_id": 12968, "author_profile": "https://Stackoverflow.com/users/12968", "pm_score": 4, "selected": false, "text": "<p>Boost.DateTime has millisecond and nanosecond representations <strong>IF</strong> the underlying platform supports them. While it is using platform specific code, it is keeping those details out of your code. </p>\n\n<p>If that is a big deal, they do have another way of doing platform independent subsecond resolution. <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/date_time/posix_time.html#time_duration_intro\" rel=\"noreferrer\">This page</a> a couple of paragraphs down talks about how to do it.</p>\n\n<p>(From the Page)</p>\n\n<p>For example, let's suppose we want to construct using a count that represents tenths of a second. That is, each tick is 0.1 second.</p>\n\n<pre><code>int number_of_tenths = 5;\n//create a resolution independent count -- divide by 10 since there are \n//10 tenths in a second. \nint count = number_of_tenths*(time_duration::ticks_per_second()/10);\ntime_duration td(1,2,3,count); //01:02:03.5 //no matter the resolution settings\n</code></pre>\n" }, { "answer_id": 117564, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "<p><strong>High Resolution, Low Overhead Timing for Intel Processors</strong></p>\n\n<p>If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained counter you can get for performance measurement.</p>\n\n<p>Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy.</p>\n\n<p>When I run this on my box, I get</p>\n\n<pre>\n11867927879484732\n11867927879692217\nit took this long to call printf: 207485\n</pre>\n\n<p>Here's the <a href=\"http://cs.smu.ca/~jamuir/rdtscpm1.pdf\" rel=\"nofollow noreferrer\">Intel developer's guide</a> that gives tons of detail.</p>\n\n<pre><code>#include &lt; stdio.h &gt; // stackoverflow bug: pre tag eats the filenames,\n#include &lt; stdint.h &gt; // so i had to put spaces in the angle brackets\n\ninline uint64_t rdtsc() {\n uint32_t lo, hi;\n __asm__ __volatile__ (\n \"xorl %%eax, %%eax\\n\"\n \"cpuid\\n\"\n \"rdtsc\\n\"\n : \"=a\" (lo), \"=d\" (hi)\n :\n : \"%ebx\", \"%ecx\");\n return (uint64_t)hi &lt;&lt; 32 | lo;\n}\n\nmain()\n{\n unsigned long long x;\n unsigned long long y;\n x = rdtsc();\n printf(\"%lld\\n\",x);\n y = rdtsc();\n printf(\"%lld\\n\",y);\n printf(\"it took this long to call printf: %lld\\n\",y-x);\n}\n</code></pre>\n" }, { "answer_id": 117709, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms724408(VS.85).aspx\" rel=\"nofollow noreferrer\">GetTickCount</a> in Windows\n<a href=\"http://linux.die.net/man/2/gettimeofday\" rel=\"nofollow noreferrer\">gettimeofday</a> in *nix\n<a href=\"http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx\" rel=\"nofollow noreferrer\">QueryPerformanceCounter</a> in Windows for better resolution (though GetTickCount should do it)</p>\n" }, { "answer_id": 117728, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 2, "selected": false, "text": "<p>If you're on Unix, <strong>gettimeofday()</strong> will return seconds and microseconds, up to the resolution of the system clock.</p>\n\n<pre><code>int gettimeofday(struct timeval *tv, struct timezone *tz);\n\nstruct timeval {\n time_t tv_sec; /* seconds */\n suseconds_t tv_usec; /* microseconds */\n};\n</code></pre>\n" }, { "answer_id": 117899, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>#include &lt;ctime&gt;\n\nclock_t elapsed = static_cast&lt;double&gt;(clock() / CLOCKS_PER_SEC);\n</code></pre>\n\n<p>elapsed will be the elapsed processor time, in seconds.</p>\n\n<p>resolution is operation system dependent, but is generally better than millisecond resolution on most systems.</p>\n" }, { "answer_id": 118146, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": -1, "selected": false, "text": "<p>Intel's <a href=\"http://www.threadingbuildingblocks.org/\" rel=\"nofollow noreferrer\">Threading Building Blocks library</a> has a function for this, but TBB is currently only availble on Intel and clones (that is, it's not available on SPARCs, PowerPC, ARM, etc.)</p>\n" }, { "answer_id": 122199, "author": "Mathieu Pagé", "author_id": 5861, "author_profile": "https://Stackoverflow.com/users/5861", "pm_score": 2, "selected": false, "text": "<p>As other have said, there is not a portable way to do this.</p>\n\n<p>What I do (On msvc++ and linux/g++) is I use the following class that use QueryPerformanceCounter on Windows and gettimeofday on Linux. It's a timer class that can get you the elapsed time between two calls. You might want to modify it to fits your needs.</p>\n\n<pre><code>#if defined(_MSC_VER)\n# define NOMINMAX // workaround un bug dans windows.h qui define des macros\n // \"min\" et \"max\" qui entrent en conflit avec la STL.\n# include &lt;windows.h&gt;\n#else\n# include &lt;sys/time.h&gt;\n#endif\n\nnamespace Utils\n{\n\n /**\n * Implémente un chronométre qui mesure le temps etre deux appels.\n */\n class CTimer\n {\n private:\n# if defined(_MSC_VER)\n LARGE_INTEGER m_depart;\n# else\n timeval m_depart;\n# endif\n\n public:\n /**\n * Démarre le timer.\n * \n * Cette fonction sert à démarrer le timer. Si le timer est déja\n * démarrer, elle le redémarre simplement.\n */\n inline void start()\n {\n# if defined(_MSC_VER)\n QueryPerformanceCounter(&amp;m_depart);\n# else\n gettimeofday(&amp;m_depart, 0);\n# endif\n\n };\n\n /**\n * Retourne le nombre de secondes depuis le départ du timer.\n * \n * @return Nombre de secondes écoulés depuis le départ du timer\n */\n inline float GetSecondes() const\n {\n# if defined(_MSC_VER)\n LARGE_INTEGER now;\n LARGE_INTEGER freq;\n\n QueryPerformanceCounter(&amp;now);\n QueryPerformanceFrequency(&amp;freq);\n\n return (now.QuadPart - m_depart.QuadPart) / static_cast&lt;float&gt;(freq.QuadPart);\n# else\n timeval now;\n gettimeofday(&amp;now, 0);\n\n return now.tv_sec - m_depart.tv_sec + (now.tv_usec - m_depart.tv_usec) / 1000000.0f;\n# endif\n };\n };\n}\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20716/" ]
I'm working on a C++ application that needs detailed timing information, down to the millisecond level. We intend to gather the time to second accuracy using the standard `time()` function in `<ctime>`. We would like to additionally gather the milliseconds elapsed since the last second given by `time()`. Does anyone know a convenient method for obtaining this information?
Boost.DateTime has millisecond and nanosecond representations **IF** the underlying platform supports them. While it is using platform specific code, it is keeping those details out of your code. If that is a big deal, they do have another way of doing platform independent subsecond resolution. [This page](http://www.boost.org/doc/libs/1_36_0/doc/html/date_time/posix_time.html#time_duration_intro) a couple of paragraphs down talks about how to do it. (From the Page) For example, let's suppose we want to construct using a count that represents tenths of a second. That is, each tick is 0.1 second. ``` int number_of_tenths = 5; //create a resolution independent count -- divide by 10 since there are //10 tenths in a second. int count = number_of_tenths*(time_duration::ticks_per_second()/10); time_duration td(1,2,3,count); //01:02:03.5 //no matter the resolution settings ```
117,348
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/506368/how-do-i-serialize-an-enum-value-as-an-int">How do I serialize an enum value as an int?</a> </p> </blockquote> <p>Hi, all!</p> <p>I'm wondering if there's a way to force the serialization of an enum value into its integer value, instead of its string representation.</p> <p>To put you into context: We're using, in a web application that heavily relies on web services, a single baseclass for all our request headers, independantly of the type of request. </p> <p>I want to add a Result field to the header, so we'll have a place to pass hints back to the calling app as to how the operation went on the web service side. We already have an enum declared to that effect, but since we have legacy apps that call on those web services that may not know about those enums, I'd like to send serialize those values as integers.</p> <p>We've already had to cut down on the length of those headers by using the [XmlElement(ElementName = "string representationOfAttributeName")] because we occasionally exceeded IE maximum url length, and I wondered whether there's a similar Attributes to force the serialization of enum values into integers.</p> <p>Anyone ever heard of such an attribute?</p> <p>As ever, thanks for the help, Pascal</p>
[ { "answer_id": 117374, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 4, "selected": true, "text": "<p>Enums do serialize to ints. But generally, if you don't like the way one of your properties gets serialized to XML, you can just do this:</p>\n\n<pre><code>[XmlIgnore]\npublic MyThing MyThing { get; set; }\n\n[XmlElement(\"MyThing\")]\n[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]\npublic string MyThingForSerialization\n{\n get { return //convert MyThing to string; }\n set { MyThing = //convert string to MyThing; }\n}\n</code></pre>\n" }, { "answer_id": 316994, "author": "Nikos Tsokos", "author_id": 15228, "author_profile": "https://Stackoverflow.com/users/15228", "pm_score": 3, "selected": false, "text": "<p>Enums do NOT serialize as int as default. \nI am using XMLSerializer to serialize a class and i have the same problem as described. </p>\n\n<p>(The example of Matt Howells seems to work if you change the scope of MyThingForSerialization to public but i would like to see a better implementation cause this creates 1 extra public property) </p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3403/" ]
> > **Possible Duplicate:** > > [How do I serialize an enum value as an int?](https://stackoverflow.com/questions/506368/how-do-i-serialize-an-enum-value-as-an-int) > > > Hi, all! I'm wondering if there's a way to force the serialization of an enum value into its integer value, instead of its string representation. To put you into context: We're using, in a web application that heavily relies on web services, a single baseclass for all our request headers, independantly of the type of request. I want to add a Result field to the header, so we'll have a place to pass hints back to the calling app as to how the operation went on the web service side. We already have an enum declared to that effect, but since we have legacy apps that call on those web services that may not know about those enums, I'd like to send serialize those values as integers. We've already had to cut down on the length of those headers by using the [XmlElement(ElementName = "string representationOfAttributeName")] because we occasionally exceeded IE maximum url length, and I wondered whether there's a similar Attributes to force the serialization of enum values into integers. Anyone ever heard of such an attribute? As ever, thanks for the help, Pascal
Enums do serialize to ints. But generally, if you don't like the way one of your properties gets serialized to XML, you can just do this: ``` [XmlIgnore] public MyThing MyThing { get; set; } [XmlElement("MyThing")] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string MyThingForSerialization { get { return //convert MyThing to string; } set { MyThing = //convert string to MyThing; } } ```
117,352
<p>I have this C-code to do multiplications over GF(8):</p> <pre><code>int32_t GaloisMultiply (int32_t a, int32_t b) { int32_t i; int32_t mask = 0x100; int32_t y = 0; for(i=0;i&lt;8;i++) { if(b &amp; mask) { y ^= a; } mask &gt;&gt;= 1; y &lt;&lt;= 1; } if(b &amp; 0x1) { y ^= a; } return(y); } </code></pre> <p>That's more or less the text-book implementation.</p> <p>I wonder if I there is a clever optimization for above algorithm if I can assert that a is always b, e.g. I do squaring instead of multiplication. I'm not after a cryptographic use btw. I just want to make use of the fact that x*x in GF(8) interleaves the bits of x with zero bits one by one.</p> <p>There are already quite clever methods to do the bit interleaving, but since I've found out that x*x in GF(8) does the bit interleaving thing (by accident) I can't stop trying to use it for bit-interleaving optimizations.</p> <p>Any ideas?</p>
[ { "answer_id": 117388, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>You could probably write some assembly to do a slightly better job. However, I'd be pretty surprised if this was the bottleneck in your application; have you done any profiling? This function doesn't seem like it's worth optimizing.</p>\n" }, { "answer_id": 117390, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 0, "selected": false, "text": "<p>This is probably not what you are looking for, but here's one minor speedup:</p>\n\n<p>Pass only one argument, if they are guaranteed to be the same.</p>\n" }, { "answer_id": 117435, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": true, "text": "<p>Table-based? <a href=\"http://www.samiam.org/galois.html\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>And when you are limited to x*x, it's a sparse matrix.</p>\n\n<p>Here's another <a href=\"http://www.cs.utk.edu/~plank/plank/papers/CS-07-593/\" rel=\"nofollow noreferrer\">good paper (and a library)</a></p>\n" }, { "answer_id": 117460, "author": "rlerallut", "author_id": 20055, "author_profile": "https://Stackoverflow.com/users/20055", "pm_score": 0, "selected": false, "text": "<p>It might help the compiler a bit to mark \"a\" and \"b\" as const. Or unrolling the loop by hand. It would be sad if it helped, though...</p>\n\n<p>Isn't it a patent minefield, by the way ?</p>\n" }, { "answer_id": 117473, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>int32_t GaloisMultiply( int32_t a ) \n{\n int32_t y = 0;\n int32_t b = a &amp; 0x01ff;\n\n while ( b ) \n {\n if ( b &amp; 1 ) \n y ^= a;\n\n a &lt;&lt;= 1;\n b &gt;&gt;= 1;\n }\n return y;\n}\n</code></pre>\n\n<p>Or if you like:</p>\n\n<pre><code>int32_t GaloisMultiply( int32_t a ) \n{\n int32_t y = 0;\n for ( int32_t b = a &amp; 0x01ff; b; b &gt;&gt;= 1 )\n {\n if ( b &amp; 1 ) \n y ^= a;\n\n a &lt;&lt;= 1;\n }\n return y;\n}\n</code></pre>\n\n<p>The reason that this approach is more efficient than the original code above is primarily because the loop is only performed until all the 'interesting' bits in the argument are consumed as opposed to blindly checking all (9) bits.</p>\n\n<p>A table based approach will be faster though.</p>\n" }, { "answer_id": 145930, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Lookup table is definitely the fastest for polynomial basis galois squaring. It is also the fastest for multiplication when using GF(8), but the tables get too large for larger fields as used in ECC. For multiplication in larger fields, the best algorithm is the 'left to right combine' method...(see <a href=\"https://rads.stackoverflow.com/amzn/click/com/038795273X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/Elliptic-Cryptography-Springer-Professional-Computing/dp/038795273X</a> algorithm 2.36, page 50).</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
I have this C-code to do multiplications over GF(8): ``` int32_t GaloisMultiply (int32_t a, int32_t b) { int32_t i; int32_t mask = 0x100; int32_t y = 0; for(i=0;i<8;i++) { if(b & mask) { y ^= a; } mask >>= 1; y <<= 1; } if(b & 0x1) { y ^= a; } return(y); } ``` That's more or less the text-book implementation. I wonder if I there is a clever optimization for above algorithm if I can assert that a is always b, e.g. I do squaring instead of multiplication. I'm not after a cryptographic use btw. I just want to make use of the fact that x\*x in GF(8) interleaves the bits of x with zero bits one by one. There are already quite clever methods to do the bit interleaving, but since I've found out that x\*x in GF(8) does the bit interleaving thing (by accident) I can't stop trying to use it for bit-interleaving optimizations. Any ideas?
Table-based? [link](http://www.samiam.org/galois.html) And when you are limited to x\*x, it's a sparse matrix. Here's another [good paper (and a library)](http://www.cs.utk.edu/~plank/plank/papers/CS-07-593/)
117,355
<p>I'm trying to find the most reusable, yet elegant, piece of code possible for determining if an IEnumerable. In the ideal, this should be a function I can call absolutely any time I need to tell if an IEnumerable is empty.</p> <p>While I have developed an answer for .NET 3.5 that has worked well for me so far, my current thought is that there is no perfect answer, since an IEnumerable can technically encapsulate a collection (or queue of iterators) that modifies the underlying results as it iterates, which would cause problems. However, this would also be an impediment to implementing IEnumerable.Count(), and that didn't stop MS from providing it.</p> <p>So I thought I'd put it to SO to see if someone has a better one, and in case someone else should find it useful.</p> <p><strong>Edit:</strong> Wow, I can't believe I didn't know about IEnumerable.Any. I knew it existed, but never bothered to check what it did. Let this be a lesson. Read the documentation. Just because a method name doesn't imply it does what you want, doesn't mean it doesn't do what you want.</p>
[ { "answer_id": 117367, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 6, "selected": true, "text": "<pre><code>!enumerable.Any()\n</code></pre>\n\n<p>Will attempt to grab the first element only.</p>\n\n<p>To expand on how/why this works, any determines if any of the components of an <code>IEnumerable</code> match a given function, if none is given, then any component will succeed, meaning the function will return true if an element exists in the enumerable.</p>\n" }, { "answer_id": 117480, "author": "Matt", "author_id": 2338, "author_profile": "https://Stackoverflow.com/users/2338", "pm_score": 2, "selected": false, "text": "<p>For .net 1/2:</p>\n\n<pre><code>IEnumerator e;\ntry\n{\n e = enumerable.GetEnumerator();\n return e.MoveNext();\n}\nfinally\n{ \n if (e is IDisposable)\n e.Dispose();\n}\n</code></pre>\n\n<p>Or, with generics:</p>\n\n<pre><code>using (IEnumerator&lt;T&gt; e = enumerable.GetEnumerator())\n{\n return e.MoveNext();\n}\n</code></pre>\n" }, { "answer_id": 117507, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>One thing to be careful of with either of these methods is that not all enumerations can be rolled-back, for instance all implementations of System.Data.IDataReader can only run through once.</p>\n\n<p>In these cases you don't really have a cost in a <code>foreach</code> loop, so long as you account for the fact that it might not even loop once.</p>\n" }, { "answer_id": 117560, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "<p>You're right that there is no perfect answer. IEnumerable only supports iteration and doesn't guarantee that the enumeration is repeatable. You can't find out if an enumeration contains elements without calling MoveNext at least once, and once you've done so you can't guarantee to be able to reuse the enumeration: it is allowable for IEnumerable.Reset to throw a NotSupportedException. From <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.reset.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.reset.aspx</a>:</p>\n\n<p>\"The Reset method is provided for COM interoperability. It does not necessarily need to be implemented; instead, the implementer can simply throw a NotSupportedException.\"</p>\n\n<p>Extension methods like IEnumerable&lt;T&gt;.Count and IEnumerable&lt;T&gt;.Any need to call MoveNext under the covers. Useful wrappers, but don't avoid the fact that in the (rare) cases where an enumeration doesn't support Reset, you could have a problem.</p>\n" }, { "answer_id": 641233, "author": "Olmo", "author_id": 38670, "author_profile": "https://Stackoverflow.com/users/38670", "pm_score": 0, "selected": false, "text": "<p>The first method has a simple implementation of Empty extension method: \n<a href=\"http://signum.codeplex.com/SourceControl/changeset/view/25903#510468\" rel=\"nofollow noreferrer\">http://signum.codeplex.com/SourceControl/changeset/view/25903#510468</a></p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2729/" ]
I'm trying to find the most reusable, yet elegant, piece of code possible for determining if an IEnumerable. In the ideal, this should be a function I can call absolutely any time I need to tell if an IEnumerable is empty. While I have developed an answer for .NET 3.5 that has worked well for me so far, my current thought is that there is no perfect answer, since an IEnumerable can technically encapsulate a collection (or queue of iterators) that modifies the underlying results as it iterates, which would cause problems. However, this would also be an impediment to implementing IEnumerable.Count(), and that didn't stop MS from providing it. So I thought I'd put it to SO to see if someone has a better one, and in case someone else should find it useful. **Edit:** Wow, I can't believe I didn't know about IEnumerable.Any. I knew it existed, but never bothered to check what it did. Let this be a lesson. Read the documentation. Just because a method name doesn't imply it does what you want, doesn't mean it doesn't do what you want.
``` !enumerable.Any() ``` Will attempt to grab the first element only. To expand on how/why this works, any determines if any of the components of an `IEnumerable` match a given function, if none is given, then any component will succeed, meaning the function will return true if an element exists in the enumerable.
117,356
<p>I've currently got multiple select's on a page that are added dynamically with <code>ajax</code> calls using jquery.</p> <p>The problem I've had is I could not get the change event to work on the added select unless I use the <code>onchange</code> inside the tag e.g. </p> <pre><code>&lt;select id="Size" size="1" onchange="onChange(this);"&gt; </code></pre> <p>This works, but I'm wondering if there's a way to get it to be assigned by jquery. I've tried using <code>$('select').change(onChange($(this));</code> in the usual place of <code>$(document).ready</code> but that didn't work.</p> <p>I've tried adding the event with bind after the ajax call but that did not work either.</p> <p>Any better way to assign the event?</p>
[ { "answer_id": 117392, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>$('select').change(onChange($(this));</p>\n</blockquote>\n\n<p>You need to understand the difference between calling a function and passing it around as an object. Functions are first-class objects in JavaScript, they are an object just like anything else, so they can be stored in variables, passed as arguments to other functions, and so on.</p>\n\n<p>The code as you have it calls the onChange function, and gives the result to jQuery's change function. You don't want that. The idea is to pass <em>the function itself</em> to jQuery's change function, and jQuery calls it when it is appropriate to do so.</p>\n\n<p>When you have parentheses - () - after a function's name, then you are calling it. Otherwise, you are treating it as an object. So what you <em>intend</em> to do can be accomplished like this:</p>\n\n<pre><code>$('select').change(onChange);\n</code></pre>\n" }, { "answer_id": 117404, "author": "Gilean", "author_id": 6305, "author_profile": "https://Stackoverflow.com/users/6305", "pm_score": 3, "selected": true, "text": "<p>I had a similar problem and found this solution <a href=\"http://groups.google.com/group/jquery-en/browse_thread/thread/9b79d65b47952583?pli=1\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<blockquote>\n <p>When you do something like this: </p>\n\n<pre><code>$('p').click( function() { alert('blah'); } ) \n</code></pre>\n \n <p>All the <em>currently existing</em> 'p'\n elements will have a click handler\n attached. Now if you go on to add\n other 'p' elements to the page they\n <em>will not</em> have the your click handler attached to them. You would\n need to \"rerun\" the</p>\n\n<pre><code>$('p').click( function() { alert('blah'); } )\n</code></pre>\n \n <p>on the new elements to attach the\n handlers to them. </p>\n \n <p>You might like to look at the\n <a href=\"http://plugins.jquery.com/project/livequery\" rel=\"nofollow noreferrer\">\"LiveQuery\" plugin</a> as is manages\n all newly added elements so they get\n the previously attached handlers\n attached to them when they're added\n to a page.</p>\n \n <p>Karl Rudd</p>\n</blockquote>\n\n<p>So after you add the select's you'll have to repeat the change() call.</p>\n" }, { "answer_id": 117925, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 0, "selected": false, "text": "<p>After adding the select to your page you need to add the change event to it:</p>\n\n<pre><code>$('#newSelect').change(\n function() \n { \n onChange(this)\n }\n);\n</code></pre>\n\n<p>If your selects all have the same class, it's best to unbind first, and then rebind:</p>\n\n<pre><code>$('.classname').unbind(\"change\");\n$('.classname').change(\n function() \n { \n onChange(this)\n }\n);\n</code></pre>\n" }, { "answer_id": 119776, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thanks guys for the help, the answers worked but not for what I was doing. I finally figured it out using firebug. I was trying to assign the change event before the ajax had finished doing it's stuff (I'm new to this ajax stuff as you may have noticed).</p>\n\n<p>I added the event assigning to a callback on the load() and now it all works great.</p>\n\n<pre><code> $(this).load('ploc002.php', {JobNumber: JobNumber, Edit: this.id}, function()\n {\n // The DOM has been changed by the AJAX call\n // Now we need to reassign the onchange events\n $('select,input').change( function()\n {\n onChange(this)\n });\n });\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've currently got multiple select's on a page that are added dynamically with `ajax` calls using jquery. The problem I've had is I could not get the change event to work on the added select unless I use the `onchange` inside the tag e.g. ``` <select id="Size" size="1" onchange="onChange(this);"> ``` This works, but I'm wondering if there's a way to get it to be assigned by jquery. I've tried using `$('select').change(onChange($(this));` in the usual place of `$(document).ready` but that didn't work. I've tried adding the event with bind after the ajax call but that did not work either. Any better way to assign the event?
I had a similar problem and found this solution [here](http://groups.google.com/group/jquery-en/browse_thread/thread/9b79d65b47952583?pli=1): > > When you do something like this: > > > > ``` > $('p').click( function() { alert('blah'); } ) > > ``` > > All the *currently existing* 'p' > elements will have a click handler > attached. Now if you go on to add > other 'p' elements to the page they > *will not* have the your click handler attached to them. You would > need to "rerun" the > > > > ``` > $('p').click( function() { alert('blah'); } ) > > ``` > > on the new elements to attach the > handlers to them. > > > You might like to look at the > ["LiveQuery" plugin](http://plugins.jquery.com/project/livequery) as is manages > all newly added elements so they get > the previously attached handlers > attached to them when they're added > to a page. > > > Karl Rudd > > > So after you add the select's you'll have to repeat the change() call.
117,361
<p>I am trying to bind an event to a "method" of a particular instance of a Javascript "class" using jQuery. The requirement is that I in the event handler should be able to use the "this" keyword to refer to the instance I originally bound the event to.</p> <p>In more detail, say I have a "class" as follows:</p> <pre><code>function Car(owner) { this.owner = owner; } Car.prototype = { drive: function() { alert("Driving "+this.owner+"s car!"); } } </code></pre> <p>And an instance:</p> <pre><code>var myCar = new Car("Bob"); </code></pre> <p>I now want to bind an event to the drive "method" of my car so that when ever I click a button for example the drive "method" is called on the myCar instance of the Car "class".</p> <p>Up until now I've been using the following function to create a closure that allows me to comfortably access instance members using the "this" keyword in my "methods".</p> <pre><code>function createHandler( obj, method ) { return function( event ) { return obj[method](event||window.event); } } </code></pre> <p>I've used it as follows:</p> <pre><code>document.getElementById("myButton") .addEventListener("click", createHandler(myCar,"drive")); </code></pre> <p>How do I accomplish something like this with JQuery? </p> <p>I'm specifically asking about associating "this" with a designated instance, the other cruft all around I can handle on my own.</p>
[ { "answer_id": 117456, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 3, "selected": true, "text": "<p>Just use an anonymous function:</p>\n\n<pre><code>$(\"#myButton\").click(function() { myCar.drive(); });\n</code></pre>\n" }, { "answer_id": 33007772, "author": "Ben Bozorg", "author_id": 4728122, "author_profile": "https://Stackoverflow.com/users/4728122", "pm_score": 0, "selected": false, "text": "<p>Try this :</p>\n\n<pre><code>$(\"#myButton\").each(function() {\n\nvar $btn = $(this);\n\n $btn.on('click',function(){\n\n // Do whatever you want.\n\n });\n});\n</code></pre>\n\n<p>Here you first create a loop to target all #myButton elements (Which is wrong in your example, You should be using Class instead) like:</p>\n\n<pre><code>$(\".myButton\").each(...\n</code></pre>\n\n<p>Then we attach the click event handler to all of them.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2105/" ]
I am trying to bind an event to a "method" of a particular instance of a Javascript "class" using jQuery. The requirement is that I in the event handler should be able to use the "this" keyword to refer to the instance I originally bound the event to. In more detail, say I have a "class" as follows: ``` function Car(owner) { this.owner = owner; } Car.prototype = { drive: function() { alert("Driving "+this.owner+"s car!"); } } ``` And an instance: ``` var myCar = new Car("Bob"); ``` I now want to bind an event to the drive "method" of my car so that when ever I click a button for example the drive "method" is called on the myCar instance of the Car "class". Up until now I've been using the following function to create a closure that allows me to comfortably access instance members using the "this" keyword in my "methods". ``` function createHandler( obj, method ) { return function( event ) { return obj[method](event||window.event); } } ``` I've used it as follows: ``` document.getElementById("myButton") .addEventListener("click", createHandler(myCar,"drive")); ``` How do I accomplish something like this with JQuery? I'm specifically asking about associating "this" with a designated instance, the other cruft all around I can handle on my own.
Just use an anonymous function: ``` $("#myButton").click(function() { myCar.drive(); }); ```
117,372
<p>I have an script that receives an encrypted url and from that generates a download, the most critic par of the script is this:</p> <pre><code>$MimeType = new MimeType(); $mimetype = $MimeType-&gt;getType($filename); $basename = basename($filename); header("Content-type: $mimetype"); header("Content-Disposition: attachment; filename=\"$basename\""); header('Content-Length: '. filesize($filename)); if ( @readfile($filename)===false ) { header("HTTP/1.0 500 Internal Server Error"); loadErrorPage('500'); } </code></pre> <p>Downloads works as charm in any Browser except IE, I have seen problems related to 'no-cache' headers but I don't send anything like that, they talk about utf-8 characters, but there is not any <code>utf-8 characters</code>(and the $filename has not any utf-8 characteres neither).</p>
[ { "answer_id": 117428, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://bytes.com/forum/thread554529.html\" rel=\"nofollow noreferrer\">This site</a> has a problem similar to yours in IE6. To summarize:</p>\n\n<blockquote>\n <p>session_start() by default sends a cache control header including \"no-store\".\n Internet Explorer takes this a bit too literally, but doesn't have appropriate\n error handling for the case, and as a result explodes cryptically when you\n attempt to save the output page to disk.</p>\n \n <p>Before session_start(), add \"session_cache_limiter('none');\", or look up that\n function and tweak the limiter as appropriate (probably 'private' is closer to\n the mark).</p>\n</blockquote>\n\n<p>I realize the code snippet you posted does not include a call to <code>session_start();</code>, but I figured I'd share this possible solution in case you do have a call to it and just didn't show us.</p>\n" }, { "answer_id": 117613, "author": "levhita", "author_id": 7946, "author_profile": "https://Stackoverflow.com/users/7946", "pm_score": 3, "selected": false, "text": "<p>I solved it by sending the headers</p>\n\n<pre><code>header('Pragma: public');\nheader('Cache-Control: max-age=0');\n</code></pre>\n\n<p>I didn't knew that session_start() send headers by it's own.</p>\n\n<p>I found the answer in the comments section of: <a href=\"http://www.alagad.com/go/blog-entry/error-internet-explorer-cannot-download-filename-from-webserver\" rel=\"noreferrer\">Error: Internet Explorer Cannot Download FileName from WebServer</a></p>\n" }, { "answer_id": 246350, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Use this</p>\n\n<p>In IE7 Browser go to internet option--> security--->custom level --->downloads \nthen enabled autometic prompting for file download.</p>\n\n<p>this will solve the problem.</p>\n\n<p>hope this will help</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7946/" ]
I have an script that receives an encrypted url and from that generates a download, the most critic par of the script is this: ``` $MimeType = new MimeType(); $mimetype = $MimeType->getType($filename); $basename = basename($filename); header("Content-type: $mimetype"); header("Content-Disposition: attachment; filename=\"$basename\""); header('Content-Length: '. filesize($filename)); if ( @readfile($filename)===false ) { header("HTTP/1.0 500 Internal Server Error"); loadErrorPage('500'); } ``` Downloads works as charm in any Browser except IE, I have seen problems related to 'no-cache' headers but I don't send anything like that, they talk about utf-8 characters, but there is not any `utf-8 characters`(and the $filename has not any utf-8 characteres neither).
[This site](http://bytes.com/forum/thread554529.html) has a problem similar to yours in IE6. To summarize: > > session\_start() by default sends a cache control header including "no-store". > Internet Explorer takes this a bit too literally, but doesn't have appropriate > error handling for the case, and as a result explodes cryptically when you > attempt to save the output page to disk. > > > Before session\_start(), add "session\_cache\_limiter('none');", or look up that > function and tweak the limiter as appropriate (probably 'private' is closer to > the mark). > > > I realize the code snippet you posted does not include a call to `session_start();`, but I figured I'd share this possible solution in case you do have a call to it and just didn't show us.
117,378
<p><strong>The situation</strong><br> I have a Git repo and an SVN repo that both hold the same source code but different commit histories. The Git repo has a lot of small well commented submits... while the SVN repo has a few huge commits with comments like "Lots of stuff". Both series of commits follow the same changes made in the code and are roughly equivalent.</p> <p><strong>The desired outcome</strong><br> I would like to switch to using Git-SVN <em>without</em> losing the detailed history from the current Git repo. This should be done by 'grafting' the history from the Git repo onto an SVN branch of the project (branched from the point I really started using Git).</p> <p><strong>Why would you do that? (history)</strong><br> A while ago I started to play with Git. I started by setting up a Git repo in a project I had under SVN control. With a little config, I had both Git and SVN working in parallel on the same source code.</p> <p>This was a great way for me to learn and play with Git, while still having the safety net of SVN. It was a sandbox with real data basically. I didn't have the time to really <em>learn</em> Git but I really wanted to tinker with it. This was actually a pretty good way to learn Git for me.</p> <p>At first, after doing some edits, I would commit to SVN and then to Git... then play with Git knowing my changes were safely in SVN. Soon I was committing more frequently to Git than SVN... Now, SVN commits have fallen to an annoying chore I have to do sometimes.</p> <p>When learning the difference between <code>git revert</code> and <code>svn revert</code> I was <em>VERY</em> glad I had been checking in to the SVN repo. I almost lost a few weeks' work assuming that the two worked the same.</p> <p>I now know the glories of Git-SVN and I am using it happily on several other projects. I fully realized when I started that I might lose my Git repo and have to setup a new one 'properly' using <code>git-svn init</code>... but having played with Git for a while now, I'm sure there is some way of hacking the Git history into SVN.</p>
[ { "answer_id": 117593, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 2, "selected": false, "text": "<p>That could be tough to do what you want. You can import a git repo into svn via something like this: <a href=\"http://code.google.com/p/support/wiki/ImportingFromGit\" rel=\"nofollow noreferrer\">http://code.google.com/p/support/wiki/ImportingFromGit</a>, but I think you will have conflicts. You could just recreate your SVN repo from scratch based on your git repo.</p>\n\n<p>For future reference, it probably would've been easier to just use Git as an SVN client:</p>\n\n<pre><code>git-svn clone path/to/your/svn/repo\ngit-commit -a -m 'my small change'\nvi some files to change.txt\ngit-commit -a -m 'another small change' \ngit-svn dcommit # sends your little changes as individual svn commits\n</code></pre>\n" }, { "answer_id": 137168, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I think this should be possible in one of two ways... I'll outline them now and try to flesh them out later if I can figure them out. If anyone can see how to flesh a part out or knows why a part won't work... please comment!</p>\n\n<p><strong>1 - In place using git-svn</strong><br>\n<em>(The following are pseudo commands THEY ARE NOT REAL - DO NOT USE THEM)</em></p>\n\n<pre><code>rm .svn\n(configure git-svn '/myproject/branch/git-remerge')\ngit svn sync_versions --svn_revision=123 --hash=ad346f221455\ngit svn dcommit\n</code></pre>\n\n<p><strong>2 - Using a separate git-svn repo as a proxy</strong><br>\n<em>(The following are pseudo commands THEY ARE NOT REAL - DO NOT USE THEM)</em></p>\n\n<pre><code>mkdir ../svn_proxy\ncd ../svn_proxy\ngit svn init\ngit checkout hash_of_svn_branch_point\ngit pull ../messy_repo\n</code></pre>\n" }, { "answer_id": 141948, "author": "Aurélien Gâteau", "author_id": 20107, "author_profile": "https://Stackoverflow.com/users/20107", "pm_score": 1, "selected": false, "text": "<p>You may want to checkout <a href=\"http://wiki.darcs.net/DarcsWiki/Tailor\" rel=\"nofollow noreferrer\">Tailor</a>. I used it to convert a git repository into an svn one so that my work could be hosted in our company svn server. It's quite flexible, so it may be able to do what you want.</p>\n" }, { "answer_id": 144170, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It seems that this is <em>NOT</em> possible. While it is possible to have the current git repo joined to the current svn repo, it does not seem possible to replay the history of the git repo in to the svn repo.</p>\n\n<p>The main problem I had was getting git-svn to 'latch' on to a single svn commit. The answer to this problem seems to be <code>git-svn set-tree</code>. This blog post was most helpful:<br>\n<a href=\"http://www.reonsoft.com/~john/blog/2008/06/05/git-first-git-svn-later/\" rel=\"nofollow noreferrer\">http://www.reonsoft.com/~john/blog/2008/06/05/git-first-git-svn-later/</a></p>\n\n<p>This is as far as I could get trying to keep the history in svn: </p>\n\n<pre><code>git branch svn-reconsile HASH_OF_SECOND_COMMIT\ngit checkout -f svn-reconsile\n\ngit svn init file://path/to/repos/myproject/branches/git-import\ngit svn fetch\n\ngit svn set-tree HASH_OF_SECOND_COMMIT\n\ngit rebase git-svn\n\ngit merge master\n\ngit svn dcommit\n</code></pre>\n\n<p>The problem is that the <code>git svn dcommit</code> will only make one revision in svn... not one for each commit in the <code>master</code> branch.... therefor the history is squashed in svn.</p>\n\n<p>So the easier solution is to simply jump start git-svn using set-tree and be satisfied that the history is still in git even if it's not in svn. This can be done with the following: </p>\n\n<pre><code>git svn init file://path/to/repos/myproject/branches/git-import\ngit svn fetch\n\ngit svn set-tree HASH_OF_MOST_RECENT_COMMIT\n\ngit rebase git-svn\n</code></pre>\n\n<p>If anyone has any idea how to get around the squashing problem (I <em>have</em> tried <code>--no-squash</code>) please comment! In leu of clever comments I'm just going to accept keeping the git history and grafting to the most recent svn revision using the second code chunk above.</p>\n" }, { "answer_id": 3552739, "author": "Simon Ruggier", "author_id": 428978, "author_profile": "https://Stackoverflow.com/users/428978", "pm_score": 0, "selected": false, "text": "<p>From the git svn repository that you are trying to migrate to, do something like the following:</p>\n\n<pre><code>git remote add old-repo &lt;path-to-old-repo&gt;\ngit fetch old-repo\n# to browse and figure out the hashes, if that helps\ngitk --all &amp;\n\n# for each branch you want to graft\ngit rebase --onto &lt;new git svn branch base&gt; &lt;old-repo branch base&gt; &lt;old-repo branch tip&gt;\n\n# when done\ngit remote rm old-repo\n</code></pre>\n\n<p>For your information, you should also be able to do the same thing using git format-patch and git am, but git rebase should be more friendly.</p>\n" }, { "answer_id": 5319123, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 0, "selected": false, "text": "<p>I did a bunch of work on this when dealing with git histories for memcached from a few things. A lot of what I was working on was verifying everyone was properly credited for work.</p>\n\n<p>I built a <a href=\"https://github.com/dustin/bindir/blob/master/git-tree-converge.py\" rel=\"nofollow\">tool</a> to generate a report showing exactly where trees converged regardless of commit hashes, git histories, authors, committers, etc... Take a look at this <a href=\"http://public.west.spy.net/memcached/compare.html\" rel=\"nofollow\">example report</a> that we used to see where two unrelated repositories containing the same information converged.</p>\n\n<p>From there, I just did lots of manual grafting and <code>filter-branch</code>ing after lots of google and mailing list searches to figure out who these people who contributed changes actually were.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
**The situation** I have a Git repo and an SVN repo that both hold the same source code but different commit histories. The Git repo has a lot of small well commented submits... while the SVN repo has a few huge commits with comments like "Lots of stuff". Both series of commits follow the same changes made in the code and are roughly equivalent. **The desired outcome** I would like to switch to using Git-SVN *without* losing the detailed history from the current Git repo. This should be done by 'grafting' the history from the Git repo onto an SVN branch of the project (branched from the point I really started using Git). **Why would you do that? (history)** A while ago I started to play with Git. I started by setting up a Git repo in a project I had under SVN control. With a little config, I had both Git and SVN working in parallel on the same source code. This was a great way for me to learn and play with Git, while still having the safety net of SVN. It was a sandbox with real data basically. I didn't have the time to really *learn* Git but I really wanted to tinker with it. This was actually a pretty good way to learn Git for me. At first, after doing some edits, I would commit to SVN and then to Git... then play with Git knowing my changes were safely in SVN. Soon I was committing more frequently to Git than SVN... Now, SVN commits have fallen to an annoying chore I have to do sometimes. When learning the difference between `git revert` and `svn revert` I was *VERY* glad I had been checking in to the SVN repo. I almost lost a few weeks' work assuming that the two worked the same. I now know the glories of Git-SVN and I am using it happily on several other projects. I fully realized when I started that I might lose my Git repo and have to setup a new one 'properly' using `git-svn init`... but having played with Git for a while now, I'm sure there is some way of hacking the Git history into SVN.
That could be tough to do what you want. You can import a git repo into svn via something like this: <http://code.google.com/p/support/wiki/ImportingFromGit>, but I think you will have conflicts. You could just recreate your SVN repo from scratch based on your git repo. For future reference, it probably would've been easier to just use Git as an SVN client: ``` git-svn clone path/to/your/svn/repo git-commit -a -m 'my small change' vi some files to change.txt git-commit -a -m 'another small change' git-svn dcommit # sends your little changes as individual svn commits ```
117,379
<p>I'm successfully using VBScript within WScript to remotely read and write IIS configurations from the server. When I attempt to run these same scripts from my desk box they fail, though. Example:</p> <pre><code>Dim vdir Set vdir = GetObject("IIS://servername/w3svc/226/root") </code></pre> <p>Error = "Invalid syntax"</p> <p>The code works perfectly when run from one IIS server to another, but I'd like to run it from my XP Workstation. It would seem reasonable that there's a download of ADSI available that will make things work from my desktop, but I cannot find one. I downloaded <a href="http://www.microsoft.com/downloads/details.aspx?familyid=9688F8B9-1034-4EF6-A3E5-2A2A57B5C8E4&amp;displaylang=en" rel="nofollow noreferrer">ADAM</a> but that only got me a small portion of the functionality I need. </p> <p>Any hints out there? Thank you. </p>
[ { "answer_id": 117593, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 2, "selected": false, "text": "<p>That could be tough to do what you want. You can import a git repo into svn via something like this: <a href=\"http://code.google.com/p/support/wiki/ImportingFromGit\" rel=\"nofollow noreferrer\">http://code.google.com/p/support/wiki/ImportingFromGit</a>, but I think you will have conflicts. You could just recreate your SVN repo from scratch based on your git repo.</p>\n\n<p>For future reference, it probably would've been easier to just use Git as an SVN client:</p>\n\n<pre><code>git-svn clone path/to/your/svn/repo\ngit-commit -a -m 'my small change'\nvi some files to change.txt\ngit-commit -a -m 'another small change' \ngit-svn dcommit # sends your little changes as individual svn commits\n</code></pre>\n" }, { "answer_id": 137168, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I think this should be possible in one of two ways... I'll outline them now and try to flesh them out later if I can figure them out. If anyone can see how to flesh a part out or knows why a part won't work... please comment!</p>\n\n<p><strong>1 - In place using git-svn</strong><br>\n<em>(The following are pseudo commands THEY ARE NOT REAL - DO NOT USE THEM)</em></p>\n\n<pre><code>rm .svn\n(configure git-svn '/myproject/branch/git-remerge')\ngit svn sync_versions --svn_revision=123 --hash=ad346f221455\ngit svn dcommit\n</code></pre>\n\n<p><strong>2 - Using a separate git-svn repo as a proxy</strong><br>\n<em>(The following are pseudo commands THEY ARE NOT REAL - DO NOT USE THEM)</em></p>\n\n<pre><code>mkdir ../svn_proxy\ncd ../svn_proxy\ngit svn init\ngit checkout hash_of_svn_branch_point\ngit pull ../messy_repo\n</code></pre>\n" }, { "answer_id": 141948, "author": "Aurélien Gâteau", "author_id": 20107, "author_profile": "https://Stackoverflow.com/users/20107", "pm_score": 1, "selected": false, "text": "<p>You may want to checkout <a href=\"http://wiki.darcs.net/DarcsWiki/Tailor\" rel=\"nofollow noreferrer\">Tailor</a>. I used it to convert a git repository into an svn one so that my work could be hosted in our company svn server. It's quite flexible, so it may be able to do what you want.</p>\n" }, { "answer_id": 144170, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It seems that this is <em>NOT</em> possible. While it is possible to have the current git repo joined to the current svn repo, it does not seem possible to replay the history of the git repo in to the svn repo.</p>\n\n<p>The main problem I had was getting git-svn to 'latch' on to a single svn commit. The answer to this problem seems to be <code>git-svn set-tree</code>. This blog post was most helpful:<br>\n<a href=\"http://www.reonsoft.com/~john/blog/2008/06/05/git-first-git-svn-later/\" rel=\"nofollow noreferrer\">http://www.reonsoft.com/~john/blog/2008/06/05/git-first-git-svn-later/</a></p>\n\n<p>This is as far as I could get trying to keep the history in svn: </p>\n\n<pre><code>git branch svn-reconsile HASH_OF_SECOND_COMMIT\ngit checkout -f svn-reconsile\n\ngit svn init file://path/to/repos/myproject/branches/git-import\ngit svn fetch\n\ngit svn set-tree HASH_OF_SECOND_COMMIT\n\ngit rebase git-svn\n\ngit merge master\n\ngit svn dcommit\n</code></pre>\n\n<p>The problem is that the <code>git svn dcommit</code> will only make one revision in svn... not one for each commit in the <code>master</code> branch.... therefor the history is squashed in svn.</p>\n\n<p>So the easier solution is to simply jump start git-svn using set-tree and be satisfied that the history is still in git even if it's not in svn. This can be done with the following: </p>\n\n<pre><code>git svn init file://path/to/repos/myproject/branches/git-import\ngit svn fetch\n\ngit svn set-tree HASH_OF_MOST_RECENT_COMMIT\n\ngit rebase git-svn\n</code></pre>\n\n<p>If anyone has any idea how to get around the squashing problem (I <em>have</em> tried <code>--no-squash</code>) please comment! In leu of clever comments I'm just going to accept keeping the git history and grafting to the most recent svn revision using the second code chunk above.</p>\n" }, { "answer_id": 3552739, "author": "Simon Ruggier", "author_id": 428978, "author_profile": "https://Stackoverflow.com/users/428978", "pm_score": 0, "selected": false, "text": "<p>From the git svn repository that you are trying to migrate to, do something like the following:</p>\n\n<pre><code>git remote add old-repo &lt;path-to-old-repo&gt;\ngit fetch old-repo\n# to browse and figure out the hashes, if that helps\ngitk --all &amp;\n\n# for each branch you want to graft\ngit rebase --onto &lt;new git svn branch base&gt; &lt;old-repo branch base&gt; &lt;old-repo branch tip&gt;\n\n# when done\ngit remote rm old-repo\n</code></pre>\n\n<p>For your information, you should also be able to do the same thing using git format-patch and git am, but git rebase should be more friendly.</p>\n" }, { "answer_id": 5319123, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 0, "selected": false, "text": "<p>I did a bunch of work on this when dealing with git histories for memcached from a few things. A lot of what I was working on was verifying everyone was properly credited for work.</p>\n\n<p>I built a <a href=\"https://github.com/dustin/bindir/blob/master/git-tree-converge.py\" rel=\"nofollow\">tool</a> to generate a report showing exactly where trees converged regardless of commit hashes, git histories, authors, committers, etc... Take a look at this <a href=\"http://public.west.spy.net/memcached/compare.html\" rel=\"nofollow\">example report</a> that we used to see where two unrelated repositories containing the same information converged.</p>\n\n<p>From there, I just did lots of manual grafting and <code>filter-branch</code>ing after lots of google and mailing list searches to figure out who these people who contributed changes actually were.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14127/" ]
I'm successfully using VBScript within WScript to remotely read and write IIS configurations from the server. When I attempt to run these same scripts from my desk box they fail, though. Example: ``` Dim vdir Set vdir = GetObject("IIS://servername/w3svc/226/root") ``` Error = "Invalid syntax" The code works perfectly when run from one IIS server to another, but I'd like to run it from my XP Workstation. It would seem reasonable that there's a download of ADSI available that will make things work from my desktop, but I cannot find one. I downloaded [ADAM](http://www.microsoft.com/downloads/details.aspx?familyid=9688F8B9-1034-4EF6-A3E5-2A2A57B5C8E4&displaylang=en) but that only got me a small portion of the functionality I need. Any hints out there? Thank you.
That could be tough to do what you want. You can import a git repo into svn via something like this: <http://code.google.com/p/support/wiki/ImportingFromGit>, but I think you will have conflicts. You could just recreate your SVN repo from scratch based on your git repo. For future reference, it probably would've been easier to just use Git as an SVN client: ``` git-svn clone path/to/your/svn/repo git-commit -a -m 'my small change' vi some files to change.txt git-commit -a -m 'another small change' git-svn dcommit # sends your little changes as individual svn commits ```
117,401
<h2>experimenting with Cockburn use cases in code</h2> <p>I was writing some complicated UI code. I decided to employ Cockburn use cases with fish,kite,and sea levels (discussed by Martin Fowler in his book 'UML Distilled'). I wrapped Cockburn use cases in static C# objects so that I could test logical conditions against static constants which represented steps in a UI workflow. The idea was that you could read the code and know what it was doing because the wrapped objects and their public contants gave you ENGLISH use cases via namespaces.</p> <p>Also, I was going to use reflection to pump out error messages that included the described use cases. The idea is that the stack trace could include some UI use case steps IN ENGLISH.... It turned out to be a fun way to achieve a mini,psuedo light-weight Domain Language but without having to write a DSL compiler. So my question is whether or not this is a good way to do this? Has anyone out there ever done something similar? </p> <hr> <p><em>c# example snippets follow</em></p> <p>Assume we have some aspx page which has 3 user controls (with lots of clickable stuff). User must click on stuff in one particular user control (possibly making some kind of selection) and then the UI must visually cue the user that the selection was successful. Now, while that item is selected, the user must browse through a gridview to find an item within one of the other user controls and then select something. This sounds like an easy thing to manage but the code can get ugly. </p> <p>In my case, the user controls all sent event messages which were captured by the main page. This way, the page acted like a central processor of UI events and could keep track of what happens when the user is clicking around. </p> <p>So, in the main aspx page, we capture the first user control's event.</p> <pre><code>using MyCompany.MyApp.Web.UseCases; protected void MyFirstUserControl_SomeUIWorkflowRequestCommingIn(object sender, EventArgs e) { // some code here to respond and make "state" changes or whatever // // blah blah blah // finally we have this (how did we know to call fish level method?? because we knew when we wrote the code to send the event in the user control) UpdateUserInterfaceOnFishLevelUseCaseGoalSuccess(FishLevel.SomeNamedUIWorkflow.SelectedItemForPurchase) } protected void UpdateUserInterfaceOnFishLevelGoalSuccess(FishLevel.SomeNamedUIWorkflow goal) { switch (goal) { case FishLevel.SomeNamedUIWorkflow.NewMasterItemSelected: //call some UI related methods here including methods for the other user controls if necessary.... break; case FishLevel.SomeNamedUIWorkFlow.DrillDownOnDetails: //call some UI related methods here including methods for the other user controls if necessary.... break; case FishLevel.SomeNamedUIWorkFlow.CancelMultiSelect: //call some UI related methods here including methods for the other user controls if necessary.... break; // more cases... } } } //also we have protected void UpdateUserInterfaceOnSeaLevelGoalSuccess(SeaLevel.SomeNamedUIWorkflow goal) { switch (goal) { case SeaLevel.CheckOutWorkflow.ChangedCreditCard: // do stuff // more cases... } } } </code></pre> <p>So, in the MyCompany.MyApp.Web.UseCases namespace we might have code like this:</p> <pre><code>class SeaLevel... class FishLevel... class KiteLevel... </code></pre> <p>The workflow use cases embedded in the classes could be inner classes or static methods or enumerations or whatever gives you the cleanest namespace. I can't remember what I did originally but you get the picture.</p>
[ { "answer_id": 120551, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>I think this is a variation on the Mediator Pattern from <em>Design Patterns</em> (Gang of Four) -- so I would say that it is a valid way to do this. In the Pattern, they discuss that the complicated interaction between controls is the reason to use it.</p>\n\n<p>Edit: Link to <a href=\"http://en.wikipedia.org/wiki/Mediator_pattern\" rel=\"nofollow noreferrer\">Mediator on Wikipedia</a></p>\n" }, { "answer_id": 2986453, "author": "Alistair Cockburn", "author_id": 359955, "author_profile": "https://Stackoverflow.com/users/359955", "pm_score": 2, "selected": false, "text": "<p>I've never done it, but I've often thought about writing code in UC style, with main success path first and extensions put in as exceptions caught down below. Have not found the excuse to do it - would love to see someone try it and code, even if after the experiment we conclude it's awful, it will still be interesting to try out and refer to.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20714/" ]
experimenting with Cockburn use cases in code --------------------------------------------- I was writing some complicated UI code. I decided to employ Cockburn use cases with fish,kite,and sea levels (discussed by Martin Fowler in his book 'UML Distilled'). I wrapped Cockburn use cases in static C# objects so that I could test logical conditions against static constants which represented steps in a UI workflow. The idea was that you could read the code and know what it was doing because the wrapped objects and their public contants gave you ENGLISH use cases via namespaces. Also, I was going to use reflection to pump out error messages that included the described use cases. The idea is that the stack trace could include some UI use case steps IN ENGLISH.... It turned out to be a fun way to achieve a mini,psuedo light-weight Domain Language but without having to write a DSL compiler. So my question is whether or not this is a good way to do this? Has anyone out there ever done something similar? --- *c# example snippets follow* Assume we have some aspx page which has 3 user controls (with lots of clickable stuff). User must click on stuff in one particular user control (possibly making some kind of selection) and then the UI must visually cue the user that the selection was successful. Now, while that item is selected, the user must browse through a gridview to find an item within one of the other user controls and then select something. This sounds like an easy thing to manage but the code can get ugly. In my case, the user controls all sent event messages which were captured by the main page. This way, the page acted like a central processor of UI events and could keep track of what happens when the user is clicking around. So, in the main aspx page, we capture the first user control's event. ``` using MyCompany.MyApp.Web.UseCases; protected void MyFirstUserControl_SomeUIWorkflowRequestCommingIn(object sender, EventArgs e) { // some code here to respond and make "state" changes or whatever // // blah blah blah // finally we have this (how did we know to call fish level method?? because we knew when we wrote the code to send the event in the user control) UpdateUserInterfaceOnFishLevelUseCaseGoalSuccess(FishLevel.SomeNamedUIWorkflow.SelectedItemForPurchase) } protected void UpdateUserInterfaceOnFishLevelGoalSuccess(FishLevel.SomeNamedUIWorkflow goal) { switch (goal) { case FishLevel.SomeNamedUIWorkflow.NewMasterItemSelected: //call some UI related methods here including methods for the other user controls if necessary.... break; case FishLevel.SomeNamedUIWorkFlow.DrillDownOnDetails: //call some UI related methods here including methods for the other user controls if necessary.... break; case FishLevel.SomeNamedUIWorkFlow.CancelMultiSelect: //call some UI related methods here including methods for the other user controls if necessary.... break; // more cases... } } } //also we have protected void UpdateUserInterfaceOnSeaLevelGoalSuccess(SeaLevel.SomeNamedUIWorkflow goal) { switch (goal) { case SeaLevel.CheckOutWorkflow.ChangedCreditCard: // do stuff // more cases... } } } ``` So, in the MyCompany.MyApp.Web.UseCases namespace we might have code like this: ``` class SeaLevel... class FishLevel... class KiteLevel... ``` The workflow use cases embedded in the classes could be inner classes or static methods or enumerations or whatever gives you the cleanest namespace. I can't remember what I did originally but you get the picture.
I've never done it, but I've often thought about writing code in UC style, with main success path first and extensions put in as exceptions caught down below. Have not found the excuse to do it - would love to see someone try it and code, even if after the experiment we conclude it's awful, it will still be interesting to try out and refer to.
117,407
<ul> <li>You can use App.config; but it only supports key/value pairs.</li> <li>You can use .Net configuration, configuration sections; but it can be really complex.</li> <li>You can use Xml Serialization/Deserialization by yourself; your classes-your way.</li> <li>You can use some other method; what can they be? ...</li> </ul> <p>Which of these or other methods (if there are) do you prefer? Why?</p>
[ { "answer_id": 117417, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 4, "selected": false, "text": "<p>If I can get away with it I will just use the App.Config, however, if I need something more complex I will use custom configuration sections. Yes it is a pain to get an understanding of in the beginning, but a unified configuration source, and familiar configuration for all settings is worth the time investment in my opinion.</p>\n" }, { "answer_id": 117421, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 0, "selected": false, "text": "<p>I keep most of my config in IoC container, e.g. Spring.Net.</p>\n" }, { "answer_id": 117440, "author": "Chris", "author_id": 19290, "author_profile": "https://Stackoverflow.com/users/19290", "pm_score": 1, "selected": false, "text": "<p>I use a custom xml configuration file, where a different config file is used for each environment (dev/qa/prod). The config files are templates that are dynamically instantiated with things like host/port configurations for services - this makes multi environments and failover very easy as it can be handled by the template instantiation code.</p>\n\n<p>Of course if you have very little config and are not concerned with multiple environments then app.config is more standard and is probably the best way to go.</p>\n" }, { "answer_id": 117444, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 1, "selected": false, "text": "<p>I find <a href=\"http://msdn.microsoft.com/en-us/library/aa903356(VS.71).aspx\" rel=\"nofollow noreferrer\">NameValueCollectionHandler</a> the easiest and best, and I generally would link off to an external config file via the configSource attribute.</p>\n\n<p>I try to put the ABSOLUTE MINIMUM configuration in config files, with most of it being configured in code with an Application that is self-aware of its deployment environment (such as by machine name or IP Address if known). Of course this required much more pre-planning and knowledge of your environments, but much less headache when deploying.</p>\n" }, { "answer_id": 117470, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": 2, "selected": false, "text": "<p>I was a network/system admin in the past, and now I develop internal utilities for database applications. What I've found is this:</p>\n\n<p>Simple Non-Nested configuration files are the best for applications that won't be changing where they access their resources very much.</p>\n\n<p>Anything more complex needs to go into a database with an administration UI. This only applies to regular business users. If you are worried about the database getting corrupted, then use the complex configuration file approach. Files tend to corrupt less than databases.</p>\n\n<p>Now, if your users are other developers, then you will have a lot more flexibility on what to use to store your configurations.</p>\n" }, { "answer_id": 117475, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 0, "selected": false, "text": "<p>If you have .NET 3.0 available, I find the XamlReader/XamlWriter very handy for storing settings. They can write/read any .NET object to XAML if:</p>\n\n<ul>\n<li>The object has a parameterless constructor</li>\n<li>The properties to read/write have public getters and setters</li>\n</ul>\n\n<p>It is especially nice that you don't have to decorate your settings objects with any attributes. </p>\n" }, { "answer_id": 117597, "author": "JohnIdol", "author_id": 1311500, "author_profile": "https://Stackoverflow.com/users/1311500", "pm_score": 5, "selected": true, "text": "<p>When key value pairs are not enough I use Configuration Sections as they are not complex to use (unless you need a complex section):</p>\n\n<p>Define your custom section:</p>\n\n<pre><code> public class CustomSection : ConfigurationSection\n {\n [ConfigurationProperty(\"LastName\", IsRequired = true,\n DefaultValue = \"TEST\")]\n public String LastName\n {\n get { return (String)base[\"LastName\"]; }\n set { base[\"LastName\"] = value; }\n }\n\n [ConfigurationProperty(\"FirstName\", IsRequired = true, DefaultValue =\n \"TEST\")]\n public String FirstName\n {\n get { return (String)base[\"FirstName\"]; }\n set { base[\"FirstName\"] = value; }\n }\n\n public CustomSection()\n {\n\n }\n }\n</code></pre>\n\n<p>Programmatically create your section (if it doesn't already exist):</p>\n\n<pre><code> // Create a custom section.\n static void CreateSection()\n {\n try\n {\n\n CustomSection customSection;\n\n // Get the current configuration file.\n System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@\"ConfigurationTest.exe\");\n\n // Create the section entry \n // in the &lt;configSections&gt; and the \n // related target section in &lt;configuration&gt;.\n if (config.Sections[\"CustomSection\"] == null)\n {\n customSection = new CustomSection();\n config.Sections.Add(\"CustomSection\", customSection);\n customSection.SectionInformation.ForceSave = true;\n config.Save(ConfigurationSaveMode.Full);\n }\n }\n catch (ConfigurationErrorsException err)\n {\n //manage exception - give feedback or whatever\n }\n\n }\n</code></pre>\n\n<p>Following CustomSection definition and actual CustomSection will be created for you:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;configuration&gt;\n &lt;configSections&gt;\n &lt;section name=\"CustomSection\" type=\"ConfigurationTest.CustomSection, ConfigurationTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" allowLocation=\"true\" allowDefinition=\"Everywhere\" allowExeDefinition=\"MachineToApplication\" overrideModeDefault=\"Allow\" restartOnExternalChanges=\"true\" requirePermission=\"true\" /&gt;\n &lt;/configSections&gt;\n &lt;CustomSection LastName=\"TEST\" FirstName=\"TEST\" /&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>Now Retrieve your section properties:</p>\n\n<pre><code> CustomSection section = (CustomSection)ConfigurationManager.GetSection(\"CustomSection\");\n string lastName = section.LastName;\n string firstName = section.FirstName;\n</code></pre>\n" }, { "answer_id": 117627, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>dataset.WriteXML()/dataset.ReadXML() work pretty well for me when the app.config doesn't cut it anymore.</p>\n" }, { "answer_id": 117655, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 2, "selected": false, "text": "<p>Put your configuration into a database. If you run your app on more than 1 machine (eg a client-server app) then all the per-machine config systems are a PITA. A single config area is the best way to place your configuration. Write a gui to manage it and you'll be very happy.</p>\n\n<p>Rolling out app.config files to 200 client boxes.. its not fun, especially when one gets missed (and they do, believe me).</p>\n" }, { "answer_id": 119866, "author": "spinodal", "author_id": 11374, "author_profile": "https://Stackoverflow.com/users/11374", "pm_score": 0, "selected": false, "text": "<p>Mostly I prefer using custom xml file and Xml Serialization method to read and write this config files... Not restricted to key/value pairs and not complex to implement... </p>\n" }, { "answer_id": 120269, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 0, "selected": false, "text": "<p>I've had good luck rolling my own special class that returns config data from a \".settings\" file associated with the calling assembly. The file is XML, and the settings class exposes it publicly as an XDocument. Additionally, the indexer for this settings class returns element values from /settings/setting nodes.</p>\n\n<p>Works great for simple applications where you just need a key/value pair access to settings, and works great for complicated settings where you need to define your own structure and use System.Xml.Linq to query the XML document.</p>\n\n<p>Another benefit of rolling your own is that you can use FileSystemWatcher and callback Action type to automatically fire a method when the file changes at runtime.</p>\n" }, { "answer_id": 120310, "author": "Valery", "author_id": 8468, "author_profile": "https://Stackoverflow.com/users/8468", "pm_score": 1, "selected": false, "text": "<p>I thing key/value configurations work pretty well for simple configurations files. It becomes a problem when the file starts to grow and difficult to maintain. We started to split configuration file to \"common\" and \"specific\" applications configurations. The file access is transparent to app, \"common\" values are the same in most cases, but \"specific\" differ for every deployed application.</p>\n" }, { "answer_id": 335851, "author": "marto", "author_id": 29555, "author_profile": "https://Stackoverflow.com/users/29555", "pm_score": 1, "selected": false, "text": "<p>I use a custom xml config file. Each setting has a key, value and type. </p>\n\n<p>It has one main section that contains all settings and additional sections containing setting overrides for particular environments (dev, staging, live). This i don't need to replace sections of the file when deploying.\nI have a small wrapper which you can call to get a particular setting or a dictionary containing all of them.</p>\n\n<p>I recently created a <a href=\"http://www.olegsych.com/2007/12/text-template-transformation-toolkit/\" rel=\"nofollow noreferrer\">T4 template</a> that will read the config file and create a static strongly typed settings class. That's been a huge timesaver.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11374/" ]
* You can use App.config; but it only supports key/value pairs. * You can use .Net configuration, configuration sections; but it can be really complex. * You can use Xml Serialization/Deserialization by yourself; your classes-your way. * You can use some other method; what can they be? ... Which of these or other methods (if there are) do you prefer? Why?
When key value pairs are not enough I use Configuration Sections as they are not complex to use (unless you need a complex section): Define your custom section: ``` public class CustomSection : ConfigurationSection { [ConfigurationProperty("LastName", IsRequired = true, DefaultValue = "TEST")] public String LastName { get { return (String)base["LastName"]; } set { base["LastName"] = value; } } [ConfigurationProperty("FirstName", IsRequired = true, DefaultValue = "TEST")] public String FirstName { get { return (String)base["FirstName"]; } set { base["FirstName"] = value; } } public CustomSection() { } } ``` Programmatically create your section (if it doesn't already exist): ``` // Create a custom section. static void CreateSection() { try { CustomSection customSection; // Get the current configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"ConfigurationTest.exe"); // Create the section entry // in the <configSections> and the // related target section in <configuration>. if (config.Sections["CustomSection"] == null) { customSection = new CustomSection(); config.Sections.Add("CustomSection", customSection); customSection.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Full); } } catch (ConfigurationErrorsException err) { //manage exception - give feedback or whatever } } ``` Following CustomSection definition and actual CustomSection will be created for you: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="CustomSection" type="ConfigurationTest.CustomSection, ConfigurationTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="true" /> </configSections> <CustomSection LastName="TEST" FirstName="TEST" /> </configuration> ``` Now Retrieve your section properties: ``` CustomSection section = (CustomSection)ConfigurationManager.GetSection("CustomSection"); string lastName = section.LastName; string firstName = section.FirstName; ```
117,415
<p>The subversion concept of branching appears to be focused on creating an [un]stable fork of the entire repository on which to do development. Is there a mechanism for creating branches of individual files?</p> <p>For a use case, think of a common header (*.h) file that has multiple platform-specific source (*.c) implementations. This type of branch is a permanent one. All of these branches would see ongoing development with occasional cross-branch merging. This is in sharp contrast to unstable development/stable release branches which generally have a finite lifespan.</p> <p>I <strong>do not</strong> want to branch the entire repository (cheap or not) as it would create an unreasonable amount of maintenance to continuously merge between the trunk and all the branches. At present I'm using ClearCase, which has a different concept of branching that makes this easy. I've been asked to consider transitioning to SVN but this paradigm difference is important. I'm much more concerned about being able to easily create alternate versions for individual files than about things like cutting a stable release branch.</p>
[ { "answer_id": 117442, "author": "Matt", "author_id": 2338, "author_profile": "https://Stackoverflow.com/users/2338", "pm_score": 1, "selected": false, "text": "<p>A Subversion \"branch\" is just a copy of something in your repository. So if you wanted to branch a file you'd just do:</p>\n\n<pre><code>svn copy myfile.c myfile_branch.c\n</code></pre>\n" }, { "answer_id": 117451, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 0, "selected": false, "text": "<p>A branch in SVN is just a copy. I believe that to do it the way you are hoping to, you'd have to have each version of the file in a separate directory in the repository, and check it out into your source folder. I.E. treat that file like a separate project.</p>\n" }, { "answer_id": 117500, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 3, "selected": false, "text": "<p>You don't have to branch the entire repository. You could make branches of folders in your project (such as an include folder). As others have noted, you can also do a \"copy\" of just a single file. Once you have a copy of a file or folder, you \"switch\" to the branched file or folder to work on the branch version.</p>\n\n<p>If you create a separate branches folder in the repository, you could copy your branched files there via server side commands:</p>\n\n<pre>\nsvn copy svn://server/project/header.h svn://server/branched_files/header.h\n</pre>\n\n<p>Then you could switch that file to use the <code>branches_files</code> repository path</p>\n" }, { "answer_id": 117585, "author": "richq", "author_id": 4596, "author_profile": "https://Stackoverflow.com/users/4596", "pm_score": 3, "selected": true, "text": "<p>Sadly, I think the real answer here is that ClearCase handles this situation a lot better than Subversion. With subversion, you have to branch <em>everything</em>, but ClearCase allows a kind of \"lazy branch\" idea that means only a certain group of files are branched, the rest of them still follow the trunk (or whichever branch you specify).</p>\n\n<p>The other solutions provided here don't really work as you intend, they are just copying the file to a different path. Now you have to do odd things to actually use that file.</p>\n\n<p>Erm, sorry. That wasn't really a very good answer. But there isn't a good solution to this with Subversion. Its model is branch and merge.</p>\n\n<p>Edit: OK, so expanding on what crashmstr said. You could do this:</p>\n\n<pre><code>svn cp $REP/trunk/file.h $REP/branched_files/file.h\nsvn co $REP/trunk\nsvn switch $REP/branched_files/file.h file.h\n</code></pre>\n\n<p>But wow!, is that prone to errors. Whenever you do a svn st you will see this:</p>\n\n<pre><code>svn st\n S file.h\n</code></pre>\n\n<p>A bit noisy that. And when you want to branch a few files or modules within a large source repository it will start to get very messy. </p>\n\n<p>Actually, there's probably a decent project in here for simulating something like ClearCase's branched files with svn properties and switching, writing a wrapper around the bog standard svn client to deal with all the mess.</p>\n" }, { "answer_id": 117602, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 1, "selected": false, "text": "<p>I don't think there is much point in branching a single file? There is no way to test it with the trunk code?</p>\n\n<p>You could take a patch instead if you want to back out changes and apply them later on.</p>\n" }, { "answer_id": 117633, "author": "rlerallut", "author_id": 20055, "author_profile": "https://Stackoverflow.com/users/20055", "pm_score": 1, "selected": false, "text": "<p>Are you sure you really need this feature <em>in your VCS</em> ?</p>\n\n<p>Why not use the C preprocessor and #ifdef away the code you don't need ? Or any similar tool.</p>\n\n<p>something like:</p>\n\n<pre><code>// foo.h:\nvoid Foo();\n\n// foo_win32.c\n#ifdef _WIN32\nvoid Foo()\n{\n ...\n}\n#endif\n\n// foo_linux.c\n#ifdef _GNUC\nvoid Foo()\n{\n ...\n}\n#endif\n</code></pre>\n\n<p>Sometimes if it doesn't fit right, then it's not the right solution.</p>\n" }, { "answer_id": 117840, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 2, "selected": false, "text": "<p>Here is how I understand your problem. You have the following tree: </p>\n\n<pre>\ntime.h\ntime.c\n</pre>\n\n<p>and you need to decline it for multiple architectures : </p>\n\n<pre>\ntime.h is comon\ntime.c (for x386), time.c (for ia64), time.c (for alpha),...\n</pre>\n\n<p>Also in your current VCS you can do this by creating as many branches from time.c as needed and when you checkout the files from the VCS you automatically check the latest time.h from the common trunk and the latest time.c from the branch you are working on. </p>\n\n<p>The problem you are concerned about is that if you use SVN when checking out a branch you will have to merge time.h from trunk very often or risk working on an older file (as compared to the trunk) that amount of overhead is not acceptable to you. </p>\n\n<p>Depending on the structure of your source code, there might be a solution though. imagine that you have</p>\n\n<pre> \n/\n/headers/\n/headers/test.h\n/source/\n/source/test.c\n</pre>\n\n<p>Then you could branch /, and use the <a href=\"http://svnbook.red-bean.com/en/1.0/ch07s03.html\" rel=\"nofollow noreferrer\">svn:externals</a> feature to link your headers to the trunk's head. It only works on directories and bears some limitations with regard to committing back to test.h (you have to go in the header directory for it to work) but it could work.</p>\n" }, { "answer_id": 117880, "author": "cdeszaq", "author_id": 20770, "author_profile": "https://Stackoverflow.com/users/20770", "pm_score": 0, "selected": false, "text": "<p>A branch in Subversion is exactly what you are talking about. All of the files are an exact copy of the trunk, with the exception of the ones you change. This is the \"cheap copy\" methodology talked about in the SVN Book. The only caveat is the need to merge the trunk into the branch from time to time to insure that the changes made there are reflected in the branch. Of course, if those changes are not desired, no trunk->branch merges need to happen.</p>\n\n<p>One easy way to allow for trunk changes to be merged in automatically(which simulates the Clear Case paradigm) would be to use a pre-commit hook script to merge the trunk changes in prior to the commit.(in fact, this is always a good strategy to prevent code drift).</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233/" ]
The subversion concept of branching appears to be focused on creating an [un]stable fork of the entire repository on which to do development. Is there a mechanism for creating branches of individual files? For a use case, think of a common header (\*.h) file that has multiple platform-specific source (\*.c) implementations. This type of branch is a permanent one. All of these branches would see ongoing development with occasional cross-branch merging. This is in sharp contrast to unstable development/stable release branches which generally have a finite lifespan. I **do not** want to branch the entire repository (cheap or not) as it would create an unreasonable amount of maintenance to continuously merge between the trunk and all the branches. At present I'm using ClearCase, which has a different concept of branching that makes this easy. I've been asked to consider transitioning to SVN but this paradigm difference is important. I'm much more concerned about being able to easily create alternate versions for individual files than about things like cutting a stable release branch.
Sadly, I think the real answer here is that ClearCase handles this situation a lot better than Subversion. With subversion, you have to branch *everything*, but ClearCase allows a kind of "lazy branch" idea that means only a certain group of files are branched, the rest of them still follow the trunk (or whichever branch you specify). The other solutions provided here don't really work as you intend, they are just copying the file to a different path. Now you have to do odd things to actually use that file. Erm, sorry. That wasn't really a very good answer. But there isn't a good solution to this with Subversion. Its model is branch and merge. Edit: OK, so expanding on what crashmstr said. You could do this: ``` svn cp $REP/trunk/file.h $REP/branched_files/file.h svn co $REP/trunk svn switch $REP/branched_files/file.h file.h ``` But wow!, is that prone to errors. Whenever you do a svn st you will see this: ``` svn st S file.h ``` A bit noisy that. And when you want to branch a few files or modules within a large source repository it will start to get very messy. Actually, there's probably a decent project in here for simulating something like ClearCase's branched files with svn properties and switching, writing a wrapper around the bog standard svn client to deal with all the mess.
117,461
<p>I want alwaysPositive to be assigned a positive number with all possible values for lareValue1 and largeValue2 (these are at least 1).</p> <p>The following statement causes a buffer overflow:</p> <pre><code>int alwaysPositive = (largeValue1 + largeValue2) / 2; </code></pre> <p>I know I can prevent it by substracting and adding:</p> <pre><code>int alwaysPositive = largeValue1 + ((largeValue2 - largeValue1) / 2); </code></pre> <p>But in other programming languages I can use an unsigned bitshift to do the trick:</p> <pre><code>int alwaysPositive3 = (largeValue1 + largeValue2) &gt;&gt;&gt; 1; </code></pre> <p>How can I do this in C#?</p> <hr> <p>The answers below all solve the problem. There are probably lots of ways to do this, but they all (including my solutions) have one thing in common: they all look obfuscated. </p>
[ { "answer_id": 117519, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 0, "selected": false, "text": "<p>You could use uints:</p>\n\n<pre><code>uint alwaysPositive = (uint)(largeValue1 + largeValue2) / 2;\n</code></pre>\n" }, { "answer_id": 117526, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 0, "selected": false, "text": "<p>Not to nitpick, but you mean \"integer overflow\" rather than \"buffer overflow\".</p>\n\n<p>I don't know C#, so there may be another way, but you could mimic an unsigned shift by just masking off the top bit: (x >> 1) &amp; 0x80000000</p>\n" }, { "answer_id": 117542, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 2, "selected": false, "text": "<p>You can do it this way: </p>\n\n<pre><code> x = largeValue1;\n y = largeValue2; \n return (x&amp;y)+((x^y)/2);\n</code></pre>\n\n<p>That's a bit-twiddling way to get the average of two integers without overflow.</p>\n\n<p>If you want you can replace the division by two with a bit-shift, but the compiler will do that for you anyways.</p>\n" }, { "answer_id": 117670, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 2, "selected": false, "text": "<pre><code>int alwaysPositive = (largeValue1 &gt;&gt; 1) + (largeValue2 &gt;&gt; 1) + (largeValue1 &amp; largeValue2 &amp; 0x01);\n</code></pre>\n\n<p>The idea behind the above is that if you pre-divide the results before you add them, then you will avoid the overflow as both high-order bits will be unset. You then add some slight correction logic to increase the value by one if both were positive (round down). If you only care if either one was positive (round off) then you could change it to </p>\n\n<pre><code>int alwaysPositive = (largeValue1 &gt;&gt; 1) + (largeValue2 &gt;&gt; 1) + ((largeValue1 | largeValue2) &amp; 0x01);\n</code></pre>\n" }, { "answer_id": 117808, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 0, "selected": false, "text": "<pre><code>try\n{\n checked { alwaysPositive3 = (largeValue1 + largeValue2); }\n}\ncatch (OverflowException ex)\n{\n // Corrective logic\n}\n</code></pre>\n" }, { "answer_id": 117858, "author": "Doug McClean", "author_id": 11173, "author_profile": "https://Stackoverflow.com/users/11173", "pm_score": 2, "selected": false, "text": "<p><code>unchecked((largeValue1 + largeValue2) &gt;&gt; 1)</code> is another option.</p>\n\n<p>See the documentation for the <a href=\"http://msdn.microsoft.com/en-us/library/a569z7k8.aspx\" rel=\"nofollow noreferrer\">unchecked keyword</a>.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376/" ]
I want alwaysPositive to be assigned a positive number with all possible values for lareValue1 and largeValue2 (these are at least 1). The following statement causes a buffer overflow: ``` int alwaysPositive = (largeValue1 + largeValue2) / 2; ``` I know I can prevent it by substracting and adding: ``` int alwaysPositive = largeValue1 + ((largeValue2 - largeValue1) / 2); ``` But in other programming languages I can use an unsigned bitshift to do the trick: ``` int alwaysPositive3 = (largeValue1 + largeValue2) >>> 1; ``` How can I do this in C#? --- The answers below all solve the problem. There are probably lots of ways to do this, but they all (including my solutions) have one thing in common: they all look obfuscated.
You can do it this way: ``` x = largeValue1; y = largeValue2; return (x&y)+((x^y)/2); ``` That's a bit-twiddling way to get the average of two integers without overflow. If you want you can replace the division by two with a bit-shift, but the compiler will do that for you anyways.
117,471
<p>I have a database issue that i currently cannot wrap my head around with an easy solution. In my db I have a table that stores event values.. 0's and 1's with a timestamp. Issue being that it is possible for there to be the same event to occur twice as a business rule. Like below</p> <ul> <li>'2008-09-22 16:28:14.133', 0</li> <li>'2008-09-22 16:28:35.233', 1</li> <li>'2008-09-22 16:29:16.353', 1</li> <li>'2008-09-22 16:31:37.273', 0</li> <li>'2008-09-22 16:35:43.134', 0</li> <li>'2008-09-22 16:36:39.633', 1</li> <li>'2008-09-22 16:41:40.733', 0</li> </ul> <p>in real life these events are cycled and I’m trying to query over to get the cycles of these but I need to ignore the duplicate values ( 1,1 ) the current solution is using a SQL cursor to loop each and throw out the value if the previous was the same. I’ve considered using a trigger on the insert to clean up in a post processed table but I can’t think of an easy solution to do this set based.</p> <p>Any ideas or suggestions?</p> <p>Thanks</p>
[ { "answer_id": 117575, "author": "tyshock", "author_id": 16448, "author_profile": "https://Stackoverflow.com/users/16448", "pm_score": 1, "selected": false, "text": "<p>(preface.......i've only done this in oracle, but I'm pretty sure if the db supports triggers it's all possible)</p>\n\n<p>Have a before insert trigger that selects the row with the max timestamp value. If that row's value is the same as the one you wish to insert, ignore it.</p>\n\n<p>This should keep them all in a correct state.</p>\n\n<p>Now, if you need both sets of states stored, the trigger can always insert on the all-inclusive table, but do the lookup and insert on the 'filtered' table only when the value changes.</p>\n" }, { "answer_id": 117587, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>Just so that I understand the problem.</p>\n\n<p>You have, if you order the row set based on the timestamp, sometimes <em>duplicate</em> values occuring next to each other, like the above pair of 1's in the 2nd and 3rt item? and then you have double 0's in the 4th and 5th, is that it?</p>\n\n<p>And you want the last of the corresponding pair (or sequence if there are more than 2)?</p>\n\n<p>Why do you need to remove them? I'm asking because unless they occupy a significant share of the size of this table, it might be easier to filter them out like you do sequentially when you need to process or display them.</p>\n\n<p>A solution, though not a very good one, would be to retrieve the minimum timestamp <em>above</em> the timestamp of the current row you're examining, and then retrieve the value from that, and if it's the same, don't return the current row.</p>\n\n<p>Here's the SQL to get everything:</p>\n\n<pre><code>SELECT timestamp, value\nFROM yourtable\n</code></pre>\n\n<p>And here's how to join in to get the minimum timestamp above the current one:</p>\n\n<pre><code>SELECT T1.timestamp, MIN(T2.timestamp) AS next_timestamp, T1.value\nFROM yourtable T1, yourtable T2\nWHERE T2.timestamp &gt; T1.timestamp\nGROUP BY T1.timestamp, T1.value\n</code></pre>\n\n<p>(I fear the above query will be horribly slow)</p>\n\n<p>And then to retrieve the value corresponding to that minimum timestamp</p>\n\n<pre><code>SELECT T3.timestamp, T3.value\nFROM (\n SELECT T1.timestamp, MIN(T2.timestamp) AS next_timestamp, T1.value\n FROM yourtable T1, yourtable T2\n WHERE T2.timestamp &gt; T1.timestamp\n GROUP BY T1.timestamp, T1.value\n) T3, yourtable AS T4\nWHERE T3.next_timestamp = T4.timestamp\n AND T3.value &lt;&gt; T4.value\n</code></pre>\n\n<p>Unfortunately this doesn't produce the last value, as it needs a following value to compare against. A simple dummy sentinel-value (you can union that in if you need to) will handle that.</p>\n\n<p>Here's the sqlite database dump I tested the above query against:</p>\n\n<pre><code>BEGIN TRANSACTION;\nCREATE TABLE yourtable (timestamp datetime, value int);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:28:14.133',0);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:28:35.233',1);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:29:16.353',1);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:31:37.273',0);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:35:43.134',0);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:36:39.633',1);\nINSERT INTO \"yourtable\" VALUES('2008-09-22 16:41:40.733',0);\nINSERT INTO \"yourtable\" VALUES('2099-12-31 23:59:59.999',2);\nCOMMIT;\n</code></pre>\n\n<p>And here is the (formatted) output:</p>\n\n<pre><code>timestamp value\n2008-09-22 16:28:14.133 0\n2008-09-22 16:29:16.353 1\n2008-09-22 16:35:43.134 0\n2008-09-22 16:36:39.633 1\n2008-09-22 16:41:40.733 0\n</code></pre>\n" }, { "answer_id": 117662, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This problem is really a data capture problem. A typical database engine is not a good choice to solve it. A simple preprocessor should detect the change in the input data set and store only the relevant data (time stamp, etc.).</p>\n\n<p>An easy solution is in a database environment (for example in Oracle) to create a package which can have local memory variables for storing last input data set and eliminate unneeded database access.</p>\n\n<p>Of course you can use all the power of the database environment to define the \"change in input data set\" and store the filtered data. So it could be easy or complex as you whish.</p>\n" }, { "answer_id": 117681, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": true, "text": "<p>This uses a SQL Server Common Table Expression, but it can be inlined, with table t with columns dt and cyclestate:</p>\n\n<pre><code>;WITH Firsts AS (\n SELECT t1.dt\n ,MIN(t2.dt) AS Prevdt\n FROM t AS t1\n INNER JOIN t AS t2\n ON t1.dt &lt; t2.dt\n AND t2.cyclestate &lt;&gt; t1.cyclestate\n GROUP BY t1.dt\n)\nSELECT MIN(t1.dt) AS dt_start\n ,t2.dt AS dt_end\nFROM t AS t1\nINNER JOIN Firsts\n ON t1.dt = Firsts.dt\nINNER JOIN t AS t2\n ON t2.dt = Firsts.Prevdt\n AND t1.cyclestate &lt;&gt; t2.cyclestate\nGROUP BY t2.dt\n ,t2.cyclestate\nHAVING MIN(t1.cyclestate) = 0\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20737/" ]
I have a database issue that i currently cannot wrap my head around with an easy solution. In my db I have a table that stores event values.. 0's and 1's with a timestamp. Issue being that it is possible for there to be the same event to occur twice as a business rule. Like below * '2008-09-22 16:28:14.133', 0 * '2008-09-22 16:28:35.233', 1 * '2008-09-22 16:29:16.353', 1 * '2008-09-22 16:31:37.273', 0 * '2008-09-22 16:35:43.134', 0 * '2008-09-22 16:36:39.633', 1 * '2008-09-22 16:41:40.733', 0 in real life these events are cycled and I’m trying to query over to get the cycles of these but I need to ignore the duplicate values ( 1,1 ) the current solution is using a SQL cursor to loop each and throw out the value if the previous was the same. I’ve considered using a trigger on the insert to clean up in a post processed table but I can’t think of an easy solution to do this set based. Any ideas or suggestions? Thanks
This uses a SQL Server Common Table Expression, but it can be inlined, with table t with columns dt and cyclestate: ``` ;WITH Firsts AS ( SELECT t1.dt ,MIN(t2.dt) AS Prevdt FROM t AS t1 INNER JOIN t AS t2 ON t1.dt < t2.dt AND t2.cyclestate <> t1.cyclestate GROUP BY t1.dt ) SELECT MIN(t1.dt) AS dt_start ,t2.dt AS dt_end FROM t AS t1 INNER JOIN Firsts ON t1.dt = Firsts.dt INNER JOIN t AS t2 ON t2.dt = Firsts.Prevdt AND t1.cyclestate <> t2.cyclestate GROUP BY t2.dt ,t2.cyclestate HAVING MIN(t1.cyclestate) = 0 ```
117,512
<p>Given a simple (id, description) table t1, such as</p> <pre><code>id description -- ----------- 1 Alice 2 Bob 3 Carol 4 David 5 Erica 6 Fred </code></pre> <p>And a parent-child relationship table t2, such as</p> <pre><code>parent child ------ ----- 1 2 1 3 4 5 5 6 </code></pre> <p>Oracle offers a way of traversing this as a tree with some custom syntax extensions:</p> <pre><code>select parent, child, sys_connect_by_path(child, '/') as "path" from t2 connect by prior parent = child </code></pre> <p>The exact syntax is not important, and I've probably made a mistake in the above. The important thing is that the above will produce something that looks like</p> <pre><code>parent child path ------ ----- ---- 1 2 /1/2 1 3 /1/3 4 5 /4/5 4 6 /4/5/6 5 6 /5/6 </code></pre> <p>My question is this: is it possible to join another table within the sys_connect_by_path(), such as the t1 table above, to produce something like:</p> <pre><code>parent child path ------ ----- ---- 1 2 /Alice/Bob 1 3 /Alice/Carol ... and so on... </code></pre>
[ { "answer_id": 117578, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 4, "selected": true, "text": "<p>In your query, replace T2 with a subquery that joins T1 and T2, and returns parent, child and child description. Then in the sys_connect_by_path function, reference the child description from your subquery.</p>\n" }, { "answer_id": 117596, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT parent, child, parents.description||sys_connect_by_path(childs.description, '/') AS \"path\"\nFROM T1 parents, T1 childs, T2\nWHERE T2.parent = parents.id\nAND T2.child = childs.id\nCONNECT BY PRIOR parent = child\n</code></pre>\n" }, { "answer_id": 119726, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 3, "selected": false, "text": "<p>Based on Mike McAllister's idea, the following uses a derived table to achieve the desired result:</p>\n\n<pre><code>select\n T.PARENT\n ,T.CHILD\n ,sys_connect_by_path(T.CDESC, '/')\nfrom\n (\n select\n t2.parent as PARENT\n ,t2.child as CHILD\n ,t1.description as CDESC\n from\n t1, t2\n where\n t2.child = t1.id\n ) T\nwhere\n level &gt; 1 and connect_by_isleaf = 1\nconnect by prior\n T.CHILD = T.PARENT\n</code></pre>\n\n<p>In my problem, all the parents are anchored under a \"super-parent\" root, which means that the paths can be fully described with SYS_CONNECT_BY_PATH, thereby obviating the need for cagcowboy's technique of concatenating the parent with the path.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18625/" ]
Given a simple (id, description) table t1, such as ``` id description -- ----------- 1 Alice 2 Bob 3 Carol 4 David 5 Erica 6 Fred ``` And a parent-child relationship table t2, such as ``` parent child ------ ----- 1 2 1 3 4 5 5 6 ``` Oracle offers a way of traversing this as a tree with some custom syntax extensions: ``` select parent, child, sys_connect_by_path(child, '/') as "path" from t2 connect by prior parent = child ``` The exact syntax is not important, and I've probably made a mistake in the above. The important thing is that the above will produce something that looks like ``` parent child path ------ ----- ---- 1 2 /1/2 1 3 /1/3 4 5 /4/5 4 6 /4/5/6 5 6 /5/6 ``` My question is this: is it possible to join another table within the sys\_connect\_by\_path(), such as the t1 table above, to produce something like: ``` parent child path ------ ----- ---- 1 2 /Alice/Bob 1 3 /Alice/Carol ... and so on... ```
In your query, replace T2 with a subquery that joins T1 and T2, and returns parent, child and child description. Then in the sys\_connect\_by\_path function, reference the child description from your subquery.
117,514
<p>How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()</p> <pre><code>import datetime, re from datetime import tzinfo class myTimeZone(tzinfo): """docstring for myTimeZone""" def utfoffset(self, dt): return timedelta(hours=1) def myDateHandler(aDateString): """u'Sat, 6 Sep 2008 21:16:33 EDT'""" _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)') day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups() month = [ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ].index(month.upper()) + 1 dt = datetime.datetime( int(year), int(month), int(day), int(hour), int(minute), int(second) ) # dt = dt - datetime.timedelta(hours=1) # dt = dt - dt.tzinfo.utfoffset(myTimeZone()) return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0) def main(): print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT") if __name__ == '__main__': main() </code></pre>
[ { "answer_id": 117523, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 4, "selected": false, "text": "<p>The Python standard library doesn't contain timezone information, because unfortunately timezone data changes a lot faster than Python. You need a third-party module for this; the usual choice is <a href=\"http://pytz.sourceforge.net\" rel=\"noreferrer\">pytz</a></p>\n" }, { "answer_id": 117615, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 5, "selected": false, "text": "<p>I recommend <code>babel</code> and <code>pytz</code> when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezones.</p>\n\n<ul>\n<li><a href=\"http://babel.pocoo.org/\" rel=\"noreferrer\">Babel</a></li>\n<li><a href=\"http://pytz.sourceforge.net/\" rel=\"noreferrer\">pytz</a></li>\n</ul>\n" }, { "answer_id": 1893437, "author": "Carlos H Romano", "author_id": 268789, "author_profile": "https://Stackoverflow.com/users/268789", "pm_score": 3, "selected": false, "text": "<p>For the current local timezone, you can you use:</p>\n\n<pre><code>&gt;&gt;&gt; import time\n&gt;&gt;&gt; offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone\n&gt;&gt;&gt; offset / 60 / 60 * -1\n-9\n</code></pre>\n\n<p>The value returned is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we'd actually like it, hence the <code>* -1</code>.</p>\n\n<p><code>localtime().tm_isdst</code> will be zero if daylight savings is currently not in effect (although this may not be correct if an area has recently changed their daylight savings law).</p>\n" }, { "answer_id": 65087160, "author": "FObersteiner", "author_id": 10197418, "author_profile": "https://Stackoverflow.com/users/10197418", "pm_score": 2, "selected": false, "text": "<h2>Python &gt;= 3.9</h2>\n<p>Python comes with <a href=\"https://docs.python.org/3/library/zoneinfo.html\" rel=\"nofollow noreferrer\">zoneinfo</a> as part of the standard lib. Example usage:</p>\n<pre><code>from datetime import datetime, timezone\nfrom zoneinfo import ZoneInfo\nUTC = datetime(2012,11,10,9,0,0, tzinfo=timezone.utc)\n\n# convert to another tz with &quot;astimezone&quot;:\neastern = UTC.astimezone(ZoneInfo(&quot;US/Eastern&quot;))\n\n# note that it is safe to use &quot;replace&quot;,\n# to get the same wall time in a different tz:\npacific = eastern.replace(tzinfo=ZoneInfo(&quot;US/Pacific&quot;))\n\nprint(UTC.isoformat())\nprint(eastern.isoformat())\nprint(pacific.isoformat())\n\n# 2012-11-10T09:00:00+00:00\n# 2012-11-10T04:00:00-05:00\n# 2012-11-10T04:00:00-08:00\n</code></pre>\n<p>Also note <a href=\"https://docs.python.org/3/library/zoneinfo.html#data-sources\" rel=\"nofollow noreferrer\">this section from the docs</a>:</p>\n<blockquote>\n<p>The zoneinfo module does not directly provide time zone data, and instead pulls time zone information from the system time zone database or the first-party PyPI package <a href=\"https://pypi.org/project/tzdata/\" rel=\"nofollow noreferrer\">tzdata</a>, if available.</p>\n</blockquote>\n<p>So don't forget to call a <code>pip install tzdata</code>, on Windows at least.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9338/" ]
How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone() ``` import datetime, re from datetime import tzinfo class myTimeZone(tzinfo): """docstring for myTimeZone""" def utfoffset(self, dt): return timedelta(hours=1) def myDateHandler(aDateString): """u'Sat, 6 Sep 2008 21:16:33 EDT'""" _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)') day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups() month = [ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ].index(month.upper()) + 1 dt = datetime.datetime( int(year), int(month), int(day), int(hour), int(minute), int(second) ) # dt = dt - datetime.timedelta(hours=1) # dt = dt - dt.tzinfo.utfoffset(myTimeZone()) return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0) def main(): print myDateHandler("Sat, 6 Sep 2008 21:16:33 EDT") if __name__ == '__main__': main() ```
I recommend `babel` and `pytz` when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezones. * [Babel](http://babel.pocoo.org/) * [pytz](http://pytz.sourceforge.net/)
117,536
<p>I've tried restarting apache and the cached pages still appear, so there must be a folder someplace. I don't have a 'public/cache', so what other places should I look? Is there a URL flag that could trigger this effect as well?</p>
[ { "answer_id": 117775, "author": "user19898", "author_id": 19898, "author_profile": "https://Stackoverflow.com/users/19898", "pm_score": 0, "selected": false, "text": "<p>First, have you cleared your browsers cache? You can do this through the browser menus, in options somewhere.</p>\n\n<p>The next question I would ask is are you running the app in production or development mode?</p>\n" }, { "answer_id": 117916, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 1, "selected": false, "text": "<p>I'm in development mode.</p>\n\n<p>I discovered I had to restart the apache service and clear the browser cache to get my changes to appear 100% of the time.</p>\n" }, { "answer_id": 118893, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": -1, "selected": false, "text": "<p>Ctrl+F5 will forcibly reload the page, and all it's linked assets. </p>\n\n<p>It's kind of like clearing the cache for just that one page.</p>\n" }, { "answer_id": 118951, "author": "johnp", "author_id": 19837, "author_profile": "https://Stackoverflow.com/users/19837", "pm_score": 4, "selected": true, "text": "<p>You need to touch a file to have phusion clear out, like:</p>\n\n<pre><code>touch /webapps/mycook/tmp/restart.txt\n</code></pre>\n\n<p>See the <a href=\"http://www.modrails.com/documentation/Users%20guide.html#_redeploying_restarting_the_ruby_on_rails_application\" rel=\"noreferrer\">docs</a></p>\n" }, { "answer_id": 48336423, "author": "Arman Petrosyan", "author_id": 2195130, "author_profile": "https://Stackoverflow.com/users/2195130", "pm_score": 0, "selected": false, "text": "<p>For those who come here nowadays </p>\n\n<p>Now there is more abilities to restart passanger from ssh \nHere is the updated <a href=\"https://www.phusionpassenger.com/library/admin/nginx/restart_app.html\" rel=\"nofollow noreferrer\">doc</a> </p>\n\n<pre><code>passenger-config restart-app\n</code></pre>\n\n<p>or </p>\n\n<pre><code>passenger-config restart-app /Users/phusion/testapp\n</code></pre>\n\n<p>and the old way which can be done if you had only FTP access </p>\n\n<pre><code>touch tmp/restart.txt\n</code></pre>\n\n<p>this one will be done not immediately, passanger will look for its modified timestamp to be changed to perform restart. </p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13320/" ]
I've tried restarting apache and the cached pages still appear, so there must be a folder someplace. I don't have a 'public/cache', so what other places should I look? Is there a URL flag that could trigger this effect as well?
You need to touch a file to have phusion clear out, like: ``` touch /webapps/mycook/tmp/restart.txt ``` See the [docs](http://www.modrails.com/documentation/Users%20guide.html#_redeploying_restarting_the_ruby_on_rails_application)
117,547
<p>Documentation can be found <a href="http://github.com/madrobby/scriptaculous/wikis/droppables" rel="nofollow noreferrer">here</a></p> <p>It says in the example:</p> <p><strong>onDrop: Called whenever a Draggable is released over the Droppable and the Droppable is accepts it. The callback gets three parameters: the Draggable element, the Droppable element and the Event. You can extract additional information about the drop – like if the Ctrl or Shift keys were pressed – from the Event object.</strong></p> <p>Then it gives some code</p> <p>Droppables.add('shopping_cart', { accept: 'products', onDrop: function(element) { $('shopping_cart_text').update('Dropped the ' + element.alt + ' on me.'); } });</p> <p>It uses the ambiguous word 'element' in the code. <strong>My question is, does anyone have a good example on how to reference the draggable element and the droppable element in this callback javascript function?</strong></p>
[ { "answer_id": 117583, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 3, "selected": true, "text": "<p>Going by the example further down the page, the callback function can take as many of the parameters as you need:</p>\n\n<pre><code>onDrop: function() { $('droppable_demo').highlight(); }\n</code></pre>\n\n<p>In this case, they have used none of the callback parameters. To this end, presumably to access all three as mentioned in the paragraph you quoted, you can define:</p>\n\n<pre><code>onDrop: function(dragged, dropped, event) { }\n</code></pre>\n" }, { "answer_id": 1429302, "author": "Mark", "author_id": 45175, "author_profile": "https://Stackoverflow.com/users/45175", "pm_score": 0, "selected": false, "text": "<p>I added this example to the documentation...</p>\n\n<pre><code> Droppables.add('shopping_cart', {\n accept: 'products',\n onDrop: function(dragged, dropped, event) {\n alert('Dragged: ' + dragged.id);\n alert('Dropped onto: ' + dropped.id);\n alert('Held ctrl key: ' + event.ctrlKey);\n }\n});\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Documentation can be found [here](http://github.com/madrobby/scriptaculous/wikis/droppables) It says in the example: **onDrop: Called whenever a Draggable is released over the Droppable and the Droppable is accepts it. The callback gets three parameters: the Draggable element, the Droppable element and the Event. You can extract additional information about the drop – like if the Ctrl or Shift keys were pressed – from the Event object.** Then it gives some code Droppables.add('shopping\_cart', { accept: 'products', onDrop: function(element) { $('shopping\_cart\_text').update('Dropped the ' + element.alt + ' on me.'); } }); It uses the ambiguous word 'element' in the code. **My question is, does anyone have a good example on how to reference the draggable element and the droppable element in this callback javascript function?**
Going by the example further down the page, the callback function can take as many of the parameters as you need: ``` onDrop: function() { $('droppable_demo').highlight(); } ``` In this case, they have used none of the callback parameters. To this end, presumably to access all three as mentioned in the paragraph you quoted, you can define: ``` onDrop: function(dragged, dropped, event) { } ```
117,570
<p>On our web application, the search results are displayed in sortable tables. The user can click on any column and sort the result. The problem is some times, the user does a broad search and gets a lot of data returned. To make the sortable part work, you probably need all the results, which takes a long time. Or I can retrieve few results at a time, but then sorting won't really work well. What's the best practice to display sortable tables that might contain lots of data? </p> <hr> <p>Thanks for all the advises. I will certainly going over these.</p> <p>We are using an existing Javascript framework that has the sortable table; "lots" of results means hundreds. The problem is that our users are at some remote site and a lot of delay is the network time to send/receive data from the data center. Sorting the data at the database side and only send one page worth of results at a time is nice; but when the user clicks some column header, another round trip is done, which always add 3-4 seconds. </p> <p>Well, I guess that might be the network team's problem :)</p>
[ { "answer_id": 117586, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 2, "selected": false, "text": "<p>You should be doing paging back on the database server. E.g. on SQL 2005 and SQL 2008 there are paging techniques. I'd suggest looking at paging options for whatever system you're looking at.</p>\n" }, { "answer_id": 117592, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>You could do the sorting on the server. AJAX would eliminate the necessity of a full refresh, but there'd still be a delay. Sides, databases a generally very fast at sorting.</p>\n" }, { "answer_id": 117606, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>For these situations I employ techniques on the SQL Server side that not only leverage the database for the sorting, but also use custom paging to ONLY return the specific records needed. </p>\n\n<p>It is a bit of a pain to implemement at first, but the performance is amazing afterwards!</p>\n" }, { "answer_id": 117624, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 0, "selected": false, "text": "<p>How large is \"a lot\" of data? Hundreds of rows? Thousands?</p>\n\n<p>Sorting can be done via JavaScript painlessly with <a href=\"http://mochikit.com/examples/sortable_tables/index.html\" rel=\"nofollow noreferrer\">Mochikit Sortable Tables</a>. However, if the data takes a long time to sort (most likely a second or two [or three!]) then you may want to give the user some visual cue that soming is happening and the page didn't just freeze. For example, tint the screen (a la Lightbox) and display a \"sorting\" animation or text.</p>\n" }, { "answer_id": 117642, "author": "tyshock", "author_id": 16448, "author_profile": "https://Stackoverflow.com/users/16448", "pm_score": 3, "selected": true, "text": "<p>Using sorting paging at the database level is the correct answer. If your query returns 1000 rows, but you're only going to show the user 10 of them, there is no need for the other 990 to be sent across the network. </p>\n\n<p>Here is a mysql example. Say you need 10 rows, 21-30, from the 'people' table:</p>\n\n<pre>\nSELECT * FROM people LIMIT 21, 10 \n</pre>\n" }, { "answer_id": 118683, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 2, "selected": false, "text": "<p>What database are you using as there some good paging option in SQL 2005 and upwards using ROW_NUMBER to allow you to do paging on the server. I found this good one on <a href=\"http://www.cristiandarie.ro/asp20-sql-server-ecommerce/\" rel=\"nofollow noreferrer\">Christian Darie's blog</a></p>\n\n<p>eg This procedure which is used to page products in a category. You just pass in the pagenumber you want and the number of products on the page etc</p>\n\n<pre><code>CREATE PROCEDURE GetProductsInCategory\n(@CategoryID INT,\n@DescriptionLength INT,\n@PageNumber INT,\n@ProductsPerPage INT,\n@HowManyProducts INT OUTPUT)\nAS\n\n-- declare a new TABLE variable\nDECLARE @Products TABLE\n(RowNumber INT,\n ProductID INT,\n Name VARCHAR(50),\n Description VARCHAR(5000),\n Price MONEY,\n Image1FileName VARCHAR(50),\n Image2FileName VARCHAR(50),\n OnDepartmentPromotion BIT,\n OnCatalogPromotion BIT)\n\n-- populate the table variable with the complete list of products\nINSERT INTO @Products\nSELECT ROW_NUMBER() OVER (ORDER BY Product.ProductID),\n Product.ProductID, Name, \n SUBSTRING(Description, 1, @DescriptionLength) + '...' AS Description,\n Price, Image1FileName, Image2FileName, OnDepartmentPromotion, OnCatalogPromotion\nFROM Product INNER JOIN ProductCategory\n ON Product.ProductID = ProductCategory.ProductID\nWHERE ProductCategory.CategoryID = @CategoryID\n\n-- return the total number of products using an OUTPUT variable\nSELECT @HowManyProducts = COUNT(ProductID) FROM @Products\n\n-- extract the requested page of products\nSELECT ProductID, Name, Description, Price, Image1FileName,\n Image2FileName, OnDepartmentPromotion, OnCatalogPromotion\nFROM @Products\nWHERE RowNumber &gt; (@PageNumber - 1) * @ProductsPerPage\n AND RowNumber &lt;= @PageNumber * @ProductsPerPage\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20460/" ]
On our web application, the search results are displayed in sortable tables. The user can click on any column and sort the result. The problem is some times, the user does a broad search and gets a lot of data returned. To make the sortable part work, you probably need all the results, which takes a long time. Or I can retrieve few results at a time, but then sorting won't really work well. What's the best practice to display sortable tables that might contain lots of data? --- Thanks for all the advises. I will certainly going over these. We are using an existing Javascript framework that has the sortable table; "lots" of results means hundreds. The problem is that our users are at some remote site and a lot of delay is the network time to send/receive data from the data center. Sorting the data at the database side and only send one page worth of results at a time is nice; but when the user clicks some column header, another round trip is done, which always add 3-4 seconds. Well, I guess that might be the network team's problem :)
Using sorting paging at the database level is the correct answer. If your query returns 1000 rows, but you're only going to show the user 10 of them, there is no need for the other 990 to be sent across the network. Here is a mysql example. Say you need 10 rows, 21-30, from the 'people' table: ``` SELECT * FROM people LIMIT 21, 10 ```
117,623
<p>Backstory: I'm using <a href="http://logging.apache.org/log4net/index.html" rel="noreferrer">log4net</a> to handle all logging for a project I'm working on. One particular method can be called under several different circumstances -- some that warrant the log messages to be errors and others that warrant the log messages to be warnings.</p> <p>So, as an example, how could I turn</p> <pre><code>Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer) If (B - A) &gt; 5 Then log.ErrorFormat("Difference ({0}) is outside of acceptable range.", (B - A)) End If End Sub </code></pre> <p>Into something more along the lines of:</p> <pre><code>Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer, "Some delegate info here") If (B - A) &gt; 5 Then **delegateinfo**.Invoke("Difference ({0}) is outside of acceptable range.", (B - A)) End If End Sub </code></pre> <p>So that I could call it and pass either log.ErrorFormat or log.WarnFormat as the delegate?</p> <p>I'm using VB.NET with VS 2008 and .NET 3.5 SP1. Also, I'm fairly new to delegates in general, so if this question should be worded differently to remove any ambiguities, let me know.</p> <p>EDIT: Also, how could I initialize the delegate to either the ErrorFormat or the WarnFormat in the class constructor? Would it be as easy as <code>myDelegate = log.ErrorFormat</code>? I would imagine there is more to it than that (pardon my ignorance on the subject -- delegates are really something I want to learn more about, but so far they have eluded my understanding).</p>
[ { "answer_id": 117646, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 0, "selected": false, "text": "<pre><code>Public Delegate errorCall(ByVal error As String, Params objs As Objects())\nCheckDifference(10, 0, AddressOf log.ErrorFormat)\n</code></pre>\n\n<p>Please forgive the formatting :P</p>\n\n<p>Basically though, create the delegate that you want, with the correct signature, and pass the address of it to the method.</p>\n" }, { "answer_id": 117653, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 1, "selected": false, "text": "<p>You'll first want to declare a delegate at the Class/Module level (all this code is from memory/not tested):</p>\n\n<pre><code>Private Delegate Sub LogErrorDelegate(txt as string, byval paramarray fields() as string)\n</code></pre>\n\n<p>Then .. you'll want to declare it as a property to your class e.g.</p>\n\n<pre><code>Private _LogError\nPublic Property LogError as LogErrorDelegate\n Get \n Return _LogError\n End Get\n Set(value as LogErrorDelegate)\n _LogError = value\n End Set\nEnd Property\n</code></pre>\n\n<p>The way to instantiate the delegate is:</p>\n\n<pre><code>Dim led as New LogErrorDelegate(AddressOf log.ErrorFormat)\n</code></pre>\n" }, { "answer_id": 117672, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 5, "selected": true, "text": "<p>Declare your delegate signature:</p>\n\n<pre><code>Public Delegate Sub Format(ByVal value As String)\n</code></pre>\n\n<p>Define your Test function:</p>\n\n<pre><code>Public Sub CheckDifference(ByVal A As Integer, _\n ByVal B As Integer, _\n ByVal format As Format)\n If (B - A) &gt; 5 Then\n format.Invoke(String.Format( _\n \"Difference ({0}) is outside of acceptable range.\", (B - A)))\n End If\nEnd Sub\n</code></pre>\n\n<p>Somewhere in your code call your Test function:</p>\n\n<pre><code>CheckDifference(Foo, Bar, AddressOf log.WriteWarn)\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>CheckDifference(Foo, Bar, AddressOf log.WriteError)\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108/" ]
Backstory: I'm using [log4net](http://logging.apache.org/log4net/index.html) to handle all logging for a project I'm working on. One particular method can be called under several different circumstances -- some that warrant the log messages to be errors and others that warrant the log messages to be warnings. So, as an example, how could I turn ``` Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer) If (B - A) > 5 Then log.ErrorFormat("Difference ({0}) is outside of acceptable range.", (B - A)) End If End Sub ``` Into something more along the lines of: ``` Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer, "Some delegate info here") If (B - A) > 5 Then **delegateinfo**.Invoke("Difference ({0}) is outside of acceptable range.", (B - A)) End If End Sub ``` So that I could call it and pass either log.ErrorFormat or log.WarnFormat as the delegate? I'm using VB.NET with VS 2008 and .NET 3.5 SP1. Also, I'm fairly new to delegates in general, so if this question should be worded differently to remove any ambiguities, let me know. EDIT: Also, how could I initialize the delegate to either the ErrorFormat or the WarnFormat in the class constructor? Would it be as easy as `myDelegate = log.ErrorFormat`? I would imagine there is more to it than that (pardon my ignorance on the subject -- delegates are really something I want to learn more about, but so far they have eluded my understanding).
Declare your delegate signature: ``` Public Delegate Sub Format(ByVal value As String) ``` Define your Test function: ``` Public Sub CheckDifference(ByVal A As Integer, _ ByVal B As Integer, _ ByVal format As Format) If (B - A) > 5 Then format.Invoke(String.Format( _ "Difference ({0}) is outside of acceptable range.", (B - A))) End If End Sub ``` Somewhere in your code call your Test function: ``` CheckDifference(Foo, Bar, AddressOf log.WriteWarn) ``` Or ``` CheckDifference(Foo, Bar, AddressOf log.WriteError) ```
117,665
<p>I got this bad feeling about how I insert larger amounts of HTML. Lets assume we got:</p> <p><code>var html="&lt;table&gt;..&lt;a-lot-of-other-tags /&gt;..&lt;/table&gt;"</code></p> <p>and I want to put this into</p> <p><code>$("#mydiv")</code></p> <p>previously I did something like</p> <p><code>var html_obj = $(html);</code> <code>$("#mydiv").append(html_obj);</code></p> <p>Is it correct that jQuery is parsing <code>html</code> to create DOM-Objects ? Well this is what I read somewhere <strong>(UPDATE:</strong> I meant that I have read, jQuery parses the html to create the whole DOM tree by hand - its nonsense right?!<strong>)</strong>, so I changed my code:</p> <p><code>$("#mydiv").attr("innerHTML", $("#mydiv").attr("innerHTML") + html);</code></p> <p>Feels faster, is it ? And is it correct that this is equivalent to:</p> <p><code>document.getElementById("mydiv").innerHTML += html</code> ? or is jquery doing some additional expensive stuff in the background ?</p> <p>Would love to learn alternatives as well.</p>
[ { "answer_id": 117700, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 1, "selected": false, "text": "<p>For starters, write a script that times how long it takes to do it 100 or 1,000 times with each method.</p>\n\n<p>To make sure the repeats aren't somehow optimized away--I'm no expert on JavaScript engines--vary the html you're inserting every time, say by putting '0001' then '0002' then '0003' in a certain cell of the table.</p>\n" }, { "answer_id": 117705, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 3, "selected": false, "text": "<p>What are you attempting to avoid? \"A bad feeling\" is incredibly vague. If you have heard \"the DOM is slow\" and decided to \"avoid the DOM\", then this is impossible. Every method of inserting code into a page, including innerHTML, will result in DOM objects being created. The DOM is the representation of the document in your browser's memory. You <em>want</em> DOM objects to be created.</p>\n\n<p>The reason why people say \"the DOM is slow\" is because creating elements with <code>document.createElement()</code>, which is the official DOM interface for creating elements, is slower than using the non-standard innerHTML property in some browsers. This doesn't mean that creating DOM objects is bad, it is <em>necessary</em> to create DOM objects, otherwise your code wouldn't do anything at all.</p>\n" }, { "answer_id": 117902, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": -1, "selected": false, "text": "<p>You mention being interested in alternatives. If you look at the listing of <a href=\"http://plugins.jquery.com/project/Plugins/category/55\" rel=\"nofollow noreferrer\">DOM-related jQuery plugins</a> you'll find several that are dedicated to programatically generating DOM trees. See for instance <a href=\"http://plugins.jquery.com/project/SuperFlyDOM\" rel=\"nofollow noreferrer\">SuperFlyDom</a> or <a href=\"http://plugins.jquery.com/project/DOMEC\" rel=\"nofollow noreferrer\">DOM Elements Creator</a>; but there are others.</p>\n" }, { "answer_id": 117988, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 6, "selected": true, "text": "<p>innerHTML is remarkably fast, and in many cases you will get the best results just setting that (I would just use append).</p>\n\n<p><strong>However, if there is much already in \"mydiv\" then you are forcing the browser to parse and render all of that content again (everything that was there before, plus all of your new content).</strong> You can avoid this by appending a document fragment onto \"mydiv\" instead:</p>\n\n<pre><code>var frag = document.createDocumentFragment();\nfrag.innerHTML = html;\n$(\"#mydiv\").append(frag);\n</code></pre>\n\n<p>In this way, only your new content gets parsed (unavoidable) and the existing content does not.</p>\n\n<p>EDIT: My bad... I've discovered that innerHTML isn't well supported on document fragments. You can use the same technique with any node type. For your example, you could create the root table node and insert the innerHTML into that:</p>\n\n<pre><code>var frag = document.createElement('table');\nfrag.innerHTML = tableInnerHtml;\n$(\"#mydiv\").append(frag);\n</code></pre>\n" }, { "answer_id": 142848, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 2, "selected": false, "text": "<p>The answer about using a DOM fragment is on the right track. If you have a bunch of html objects that you are constant inserting into the DOM then you will see some speed improvements using the fragment. This post by John Resig explains it pretty well:\n<a href=\"http://ejohn.org/blog/dom-documentfragments/\" rel=\"nofollow noreferrer\">http://ejohn.org/blog/dom-documentfragments/</a></p>\n" }, { "answer_id": 4421104, "author": "gblazex", "author_id": 378024, "author_profile": "https://Stackoverflow.com/users/378024", "pm_score": 5, "selected": false, "text": "<p>Try the following:</p>\n\n<pre><code>$(\"#mydiv\").append(html);\n</code></pre>\n\n<p>The other answers, including the accepted answer, are <strong>slower</strong> by <strong>2-10x</strong>: <a href=\"http://jsperf.com/jquery-append-html/1\" rel=\"nofollow noreferrer\">jsperf</a>.</p>\n\n<p>The accepted answer does not work in <strong>IE 6, 7, and 8</strong> because you can't set <code>innerHTML</code> of a <code>&lt;table&gt;</code> element, due to a bug in IE: <a href=\"http://jsbin.com/akoje4/5/\" rel=\"nofollow noreferrer\">jsbin</a>.</p>\n" }, { "answer_id": 6301746, "author": "Robert Hurst", "author_id": 243568, "author_profile": "https://Stackoverflow.com/users/243568", "pm_score": 2, "selected": false, "text": "<p><strong>The fastest way to append items</strong></p>\n\n<p>The fastest way to append to the DOM tree is to buffer all of your append in to a single DOM fragment, then append the dom fragment to the dom.</p>\n\n<p>This is the method I use in my game engine.</p>\n\n<pre><code>//Returns a new Buffer object\nfunction Buffer() {\n\n //the framgment\n var domFragment = document.createDocumentFragment();\n\n //Adds a node to the dom fragment\n function add(node) {\n domFragment.appendChild(node);\n }\n\n //Flushes the buffer to a node\n function flush(targetNode) {\n\n //if the target node is not given then use the body\n var targetNode = targetNode || document.body;\n\n //append the domFragment to the target\n targetNode.appendChild(domFragment);\n\n }\n\n //return the buffer\n return {\n \"add\": add,\n \"flush\": flush\n }\n}\n\n\n//to make a buffer do this\nvar buffer = Buffer();\n\n//to add elements to the buffer do the following\nbuffer.add(someNode1);\n\n//continue to add elements to the buffer\nbuffer.add(someNode2);\nbuffer.add(someNode3);\nbuffer.add(someNode4);\nbuffer.add(someN...);\n\n//when you are done adding nodes flush the nodes to the containing div in the dom\nbuffer.flush(myContainerNode);\n</code></pre>\n\n<p>Using this object i am able to render ~1000 items to the screen ~40 times a second in firefox 4.</p>\n\n<p>Here's a use case.</p>\n" }, { "answer_id": 12161602, "author": "Ricardo Pieper", "author_id": 1470577, "author_profile": "https://Stackoverflow.com/users/1470577", "pm_score": 0, "selected": false, "text": "<p>I create a giant string with and then append this string with jquery.\nWorks good and fast, for me.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20711/" ]
I got this bad feeling about how I insert larger amounts of HTML. Lets assume we got: `var html="<table>..<a-lot-of-other-tags />..</table>"` and I want to put this into `$("#mydiv")` previously I did something like `var html_obj = $(html);` `$("#mydiv").append(html_obj);` Is it correct that jQuery is parsing `html` to create DOM-Objects ? Well this is what I read somewhere **(UPDATE:** I meant that I have read, jQuery parses the html to create the whole DOM tree by hand - its nonsense right?!**)**, so I changed my code: `$("#mydiv").attr("innerHTML", $("#mydiv").attr("innerHTML") + html);` Feels faster, is it ? And is it correct that this is equivalent to: `document.getElementById("mydiv").innerHTML += html` ? or is jquery doing some additional expensive stuff in the background ? Would love to learn alternatives as well.
innerHTML is remarkably fast, and in many cases you will get the best results just setting that (I would just use append). **However, if there is much already in "mydiv" then you are forcing the browser to parse and render all of that content again (everything that was there before, plus all of your new content).** You can avoid this by appending a document fragment onto "mydiv" instead: ``` var frag = document.createDocumentFragment(); frag.innerHTML = html; $("#mydiv").append(frag); ``` In this way, only your new content gets parsed (unavoidable) and the existing content does not. EDIT: My bad... I've discovered that innerHTML isn't well supported on document fragments. You can use the same technique with any node type. For your example, you could create the root table node and insert the innerHTML into that: ``` var frag = document.createElement('table'); frag.innerHTML = tableInnerHtml; $("#mydiv").append(frag); ```
117,667
<p>I know this is probably the dumbest question ever, however I am a total beginner when it comes to CSS; how do you hyperlink an image on a webpage using an image which is sourced from CSS? I am trying to set the title image on my website linkable to the frontpage. Thanks!</p> <p><strong>Edit:</strong> Just to make it clear, I'm sourcing my image <em>from CSS</em>, the CSS code for the header div is as follows:-</p> <pre><code>#header { width: 1000px; margin: 0px auto; padding: 0px 15px 0px 15px; border: none; background: url(images/title.png) no-repeat bottom; width: 1000px; height: 100px; } </code></pre> <p>I want to know how to make this <em>div</em> hyperlinked on my webpage without having to make it an anchor rather than a div.</p>
[ { "answer_id": 117675, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "<p>That's really not a CSS thing. You still need your A tag to make that work. (But use CSS to make sure the image border is either removed, or designed to your required spec.)</p>\n\n<pre><code>&lt;a href=\"index.html\"&gt;&lt;img src=\"foo\" class=\"whatever\" alt=\"foo alt\" /&gt;&lt;/a&gt;\n</code></pre>\n\n<p>EDIT: Taking original intent (updated question) into account, a new code sample is below:</p>\n\n<pre><code>&lt;a href=\"index.html\"&gt;&lt;img id=\"header\" alt=\"foo alt\" /&gt;&lt;/a&gt;\n</code></pre>\n\n<p>You're still in an HTML world for links, as described by other answers on this question.</p>\n" }, { "answer_id": 117680, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 2, "selected": false, "text": "<p>You still create links in HTML with 'a' (anchor) tags just like normal. CSS does not have anything that can specify if something is a link to somewhere or not.</p>\n\n<p><strong>Edit</strong>\nThe comments of mine and others still apply. To clarify, you can use JavaScript to make a div act as a link:</p>\n\n<pre><code>&lt;div id=\"header\" onclick=\"window.location='http://google.com';\"&gt;My Header&lt;/div&gt;\n</code></pre>\n\n<p>That isn't really great for usability however as people without JavaScript enabled will be unable to click that and have it act as a link.</p>\n\n<p>Also, you may want to add a <code>cursor: pointer;</code> line to your CSS to give the header div the correct mouse cursor for a link.</p>\n" }, { "answer_id": 117695, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 4, "selected": false, "text": "<p>You control design and styles with CSS, not the behavior of your content. </p>\n\n<p>You're going to have to use something like <code>&lt;a id=\"header\" href=\"[your link]\"&gt;Logo&lt;/a&gt;</code> and then have a CSS block such as:</p>\n\n<pre><code>a#header {\n background-image: url(...);\n display: block;\n width: ..;\n height: ...;\n}\n</code></pre>\n\n<p>You cannot nest a <code>div</code> inside <code>&lt;a&gt;</code> and still have 'valid' code. <code>&lt;a&gt;</code> is an inline element that cannot legally contain a block element. The only non-Javascript way to make a link is with the <code>&lt;a&gt;</code> element. </p>\n\n<p>You can nest your <code>&lt;a&gt;</code> tag inside <code>&lt;div&gt;</code> and then put your image inside :)</p>\n\n<p>If you don't want that, you're going to have to use JavaScript to make your <code>&lt;div&gt;</code> clickable:</p>\n\n<pre><code>Document.getElementById(\"header\").onclick = function() {\n window.location='...'; \n}\n</code></pre>\n" }, { "answer_id": 117697, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 0, "selected": false, "text": "<p>CSS is for presentation only, not content. A link is content and should be put into the HTML of the site using a standard <code>&lt;a href=\"\"&gt;</code> tag. You can then style this link (or add an image to the link) using CSS.</p>\n" }, { "answer_id": 117699, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;a href=\"linkto_title_page.html\" class=\"titleLink\"&gt;&lt;/a&gt;\n</code></pre>\n\n<p>then in your css</p>\n\n<pre><code>.titleLink {\n background-image: url(imageUrl);\n}\n</code></pre>\n" }, { "answer_id": 117707, "author": "Dave Rutledge", "author_id": 2486915, "author_profile": "https://Stackoverflow.com/users/2486915", "pm_score": 3, "selected": false, "text": "<p>To link a css-sourced background-image:</p>\n\n<pre><code>#header { \ndisplay:block;\n\nmargin: 0px auto;\npadding: 0px 15px 0px 15px;\nborder: none;\nbackground: url(images/title.png) no-repeat bottom;\nwidth: 1000px;\nheight: 100px; \n} \n\n&lt;a id=\"header\" href=\"blah.html\" class=\"linkedImage\"&gt;\n</code></pre>\n\n<p>The key thing here is to turn the anchor tag into a block element, so height and width work. Otherwise it's an inline element and will ignore height.</p>\n" }, { "answer_id": 117756, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 0, "selected": false, "text": "<p>HTML is the only way to create links - it defines the structure and content of a web site.</p>\n\n<p>CSS stands for Cascading <strong>Style</strong> Sheets - it only affects how things look.</p>\n\n<p>Although normally an <code>&lt;a/&gt;</code>; tag is the only way to create a link, you can make a <code>&lt;div/&gt;</code> clickable with JavaScript. I'd use jQuery:</p>\n\n<pre><code>$(\"div#header\").click(function() {window.location=XXXXXX;});\n</code></pre>\n" }, { "answer_id": 123531, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 0, "selected": false, "text": "<p>You have to use an anchor element, wrapped in a container. On your homepage, your title would normally be an h1, but then on content pages it would probably change to a div. You should also always have text in the anchor element for people without CSS support and/or screen readers. The easiest way to hide that is through CSS. Here are both examples:</p>\n\n<pre><code>&lt;h1 id=\"title\"&gt;&lt;a title=\"Home\" href=\"index.html&gt;My Title&lt;/a&gt;&lt;/h1&gt;\n&lt;div id=\"title\"&gt;&lt;a title=\"Home\" href=\"index.html&gt;My Title&lt;/a&gt;&lt;/div&gt;\n</code></pre>\n\n<p>and the CSS:</p>\n\n<pre><code>#title {\nposition:relative; /*Makes this a containing element*/\n}\n#title a {\nbackground: transparent url(../images/logo.png) no-repeat scroll 0 0;\ndisplay:block;\ntext-indent:-9999px; /*Hides the anchor text*/\nheight:50px; /*Set height and width to the exact size of your image*/\nwidth:200px;\n}\n</code></pre>\n\n<p>Depending on the rest of your stylesheet you may need to adjus it for the h1 to make it look the same as the div, check out CSS Resets for possible solutions to this.</p>\n" }, { "answer_id": 213581, "author": "John Dunagan", "author_id": 28939, "author_profile": "https://Stackoverflow.com/users/28939", "pm_score": 0, "selected": false, "text": "<p>Try this - use an H1 as the seat of your graphic instead. Saved my butt time and time again:</p>\n\n<pre><code>&lt;h1 class=\"technique-six\"&gt;\n CSS-Tricks\n&lt;/h1&gt;\n\nh1.technique-six {\n width: 350px;\n padding: 75px 0 0 0;\n height: 0;\n background: url(\"images/header-image.jpg\") no-repeat;\n overflow: hidden;\n}\n</code></pre>\n\n<p>Accessible, and also solid across browsers IE6 and > . You could also link the H1.</p>\n" }, { "answer_id": 18246863, "author": "Spoilsport", "author_id": 2684875, "author_profile": "https://Stackoverflow.com/users/2684875", "pm_score": 2, "selected": false, "text": "<p>sorry to spoil your fun ladies and gentlemen, it is possible.</p>\n\n<pre><code>Write in your header: [link](http://\"link here\")\n\nthen in your css:\n\n#header a[href=\"https://link here\"] {\n display: inline-block;\n width: 75px;\n height: 75px;\n font-size: 0;\n }\n .side .md a[href=\"link here\"] {\n background: url(%%picture here%%) no-repeat;\n }\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3394/" ]
I know this is probably the dumbest question ever, however I am a total beginner when it comes to CSS; how do you hyperlink an image on a webpage using an image which is sourced from CSS? I am trying to set the title image on my website linkable to the frontpage. Thanks! **Edit:** Just to make it clear, I'm sourcing my image *from CSS*, the CSS code for the header div is as follows:- ``` #header { width: 1000px; margin: 0px auto; padding: 0px 15px 0px 15px; border: none; background: url(images/title.png) no-repeat bottom; width: 1000px; height: 100px; } ``` I want to know how to make this *div* hyperlinked on my webpage without having to make it an anchor rather than a div.
You control design and styles with CSS, not the behavior of your content. You're going to have to use something like `<a id="header" href="[your link]">Logo</a>` and then have a CSS block such as: ``` a#header { background-image: url(...); display: block; width: ..; height: ...; } ``` You cannot nest a `div` inside `<a>` and still have 'valid' code. `<a>` is an inline element that cannot legally contain a block element. The only non-Javascript way to make a link is with the `<a>` element. You can nest your `<a>` tag inside `<div>` and then put your image inside :) If you don't want that, you're going to have to use JavaScript to make your `<div>` clickable: ``` Document.getElementById("header").onclick = function() { window.location='...'; } ```
117,690
<p>I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I'll need to wait util M out of N tasks are finished). Currently they are presented as Future, so I need something like</p> <pre><code>/** * Blocks current thread until one of specified futures is done and returns it. */ public static &lt;T&gt; Future&lt;T&gt; waitForAny(Collection&lt;Future&lt;T&gt;&gt; futures) throws AllFuturesFailedException </code></pre> <p>Is there anything like this? Or anything similar, not necessary for Future. Currently I loop through collection of futures, check if one is finished, then sleep for some time and check again. This looks like not the best solution, because if I sleep for long period then unwanted delay is added, if I sleep for short period then it can affect performance.</p> <p>I could try using </p> <pre><code>new CountDownLatch(1) </code></pre> <p>and decrease countdown when task is complete and do </p> <pre><code>countdown.await() </code></pre> <p>, but I found it possible only if I control Future creation. It is possible, but requires system redesign, because currently logic of tasks creation (sending Callable to ExecutorService) is separated from decision to wait for which Future. I could also override </p> <pre><code>&lt;T&gt; RunnableFuture&lt;T&gt; AbstractExecutorService.newTaskFor(Callable&lt;T&gt; callable) </code></pre> <p>and create custom implementation of RunnableFuture with ability to attach listener to be notified when task is finished, then attach such listener to needed tasks and use CountDownLatch, but that means I have to override newTaskFor for every ExecutorService I use - and potentially there will be implementation which do not extend AbstractExecutorService. I could also try wrapping given ExecutorService for same purpose, but then I have to decorate all methods producing Futures.</p> <p>All these solutions may work but seem very unnatural. It looks like I'm missing something simple, like </p> <pre><code>WaitHandle.WaitAny(WaitHandle[] waitHandles) </code></pre> <p>in c#. Are there any well known solutions for such kind of problem?</p> <p>UPDATE:</p> <p>Originally I did not have access to Future creation at all, so there were no elegant solution. After redesigning system I got access to Future creation and was able to add countDownLatch.countdown() to execution process, then I can countDownLatch.await() and everything works fine. Thanks for other answers, I did not know about ExecutorCompletionService and it indeed can be helpful in similar tasks, but in this particular case it could not be used because some Futures are created without any executor - actual task is sent to another server via network, completes remotely and completion notification is received.</p>
[ { "answer_id": 117711, "author": "jdmichal", "author_id": 12275, "author_profile": "https://Stackoverflow.com/users/12275", "pm_score": 3, "selected": true, "text": "<p>As far as I know, Java has no analogous structure to the <code>WaitHandle.WaitAny</code> method.</p>\n\n<p>It seems to me that this could be achieved through a \"WaitableFuture\" decorator:</p>\n\n<pre><code>public WaitableFuture&lt;T&gt;\n extends Future&lt;T&gt;\n{\n private CountDownLatch countDownLatch;\n\n WaitableFuture(CountDownLatch countDownLatch)\n {\n super();\n\n this.countDownLatch = countDownLatch;\n }\n\n void doTask()\n {\n super.doTask();\n\n this.countDownLatch.countDown();\n }\n}\n</code></pre>\n\n<p>Though this would only work if it can be inserted before the execution code, since otherwise the execution code would not have the new <code>doTask()</code> method. But I really see no way of doing this without polling if you cannot somehow gain control of the Future object before execution.</p>\n\n<p>Or if the future always runs in its own thread, and you can somehow get that thread. Then you could spawn a new thread to join each other thread, then handle the waiting mechanism after the join returns... This would be really ugly and would induce a lot of overhead though. And if some Future objects don't finish, you could have a lot of blocked threads depending on dead threads. If you're not careful, this could leak memory and system resources.</p>\n\n<pre><code>/**\n * Extremely ugly way of implementing WaitHandle.WaitAny for Thread.Join().\n */\npublic static joinAny(Collection&lt;Thread&gt; threads, int numberToWaitFor)\n{\n CountDownLatch countDownLatch = new CountDownLatch(numberToWaitFor);\n\n foreach(Thread thread in threads)\n {\n (new Thread(new JoinThreadHelper(thread, countDownLatch))).start();\n }\n\n countDownLatch.await();\n}\n\nclass JoinThreadHelper\n implements Runnable\n{\n Thread thread;\n CountDownLatch countDownLatch;\n\n JoinThreadHelper(Thread thread, CountDownLatch countDownLatch)\n {\n this.thread = thread;\n this.countDownLatch = countDownLatch;\n }\n\n void run()\n {\n this.thread.join();\n this.countDownLatch.countDown();\n }\n}\n</code></pre>\n" }, { "answer_id": 117713, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>Since you don't care which one finishes, why not just have a single WaitHandle for all threads and wait on that? Whichever one finishes first can set the handle.</p>\n" }, { "answer_id": 118158, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 3, "selected": false, "text": "<p>This is actually pretty easy with wait() and notifyAll().</p>\n\n<p>First, define a lock object. (You can use any class for this, but I like to be explicit):</p>\n\n<pre><code>package com.javadude.sample;\n\npublic class Lock {}\n</code></pre>\n\n<p>Next, define your worker thread. He must notify that lock object when he's finished with his processing. Note that the notify must be in a synchronized block locking on the lock object.</p>\n\n<pre><code>package com.javadude.sample;\n\npublic class Worker extends Thread {\n private Lock lock_;\n private long timeToSleep_;\n private String name_;\n public Worker(Lock lock, String name, long timeToSleep) {\n lock_ = lock;\n timeToSleep_ = timeToSleep;\n name_ = name;\n }\n @Override\n public void run() {\n // do real work -- using a sleep here to simulate work\n try {\n sleep(timeToSleep_);\n } catch (InterruptedException e) {\n interrupt();\n }\n System.out.println(name_ + \" is done... notifying\");\n // notify whoever is waiting, in this case, the client\n synchronized (lock_) {\n lock_.notify();\n }\n }\n}\n</code></pre>\n\n<p>Finally, you can write your client:</p>\n\n<pre><code>package com.javadude.sample;\n\npublic class Client {\n public static void main(String[] args) {\n Lock lock = new Lock();\n Worker worker1 = new Worker(lock, \"worker1\", 15000);\n Worker worker2 = new Worker(lock, \"worker2\", 10000);\n Worker worker3 = new Worker(lock, \"worker3\", 5000);\n Worker worker4 = new Worker(lock, \"worker4\", 20000);\n\n boolean started = false;\n int numNotifies = 0;\n while (true) {\n synchronized (lock) {\n try {\n if (!started) {\n // need to do the start here so we grab the lock, just\n // in case one of the threads is fast -- if we had done the\n // starts outside the synchronized block, a fast thread could\n // get to its notification *before* the client is waiting for it\n worker1.start();\n worker2.start();\n worker3.start();\n worker4.start();\n started = true;\n }\n lock.wait();\n } catch (InterruptedException e) {\n break;\n }\n numNotifies++;\n if (numNotifies == 4) {\n break;\n }\n System.out.println(\"Notified!\");\n }\n }\n System.out.println(\"Everyone has notified me... I'm done\");\n }\n}\n</code></pre>\n" }, { "answer_id": 118255, "author": "james", "author_id": 17156, "author_profile": "https://Stackoverflow.com/users/17156", "pm_score": 6, "selected": false, "text": "<p>simple, check out <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html\" rel=\"noreferrer\">ExecutorCompletionService</a>.</p>\n" }, { "answer_id": 118670, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 3, "selected": false, "text": "<p>Why not just create a results queue and wait on the queue? Or more simply, use a CompletionService since that's what it is: an ExecutorService + result queue.</p>\n" }, { "answer_id": 118992, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html#invokeAny(java.util.Collection)\" rel=\"noreferrer\">ExecutorService.invokeAny</a></p>\n" }, { "answer_id": 423759, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>See this option:</p>\n\n<pre><code>public class WaitForAnyRedux {\n\nprivate static final int POOL_SIZE = 10;\n\npublic static &lt;T&gt; T waitForAny(Collection&lt;T&gt; collection) throws InterruptedException, ExecutionException {\n\n List&lt;Callable&lt;T&gt;&gt; callables = new ArrayList&lt;Callable&lt;T&gt;&gt;();\n for (final T t : collection) {\n Callable&lt;T&gt; callable = Executors.callable(new Thread() {\n\n @Override\n public void run() {\n synchronized (t) {\n try {\n t.wait();\n } catch (InterruptedException e) {\n }\n }\n }\n }, t);\n callables.add(callable);\n }\n\n BlockingQueue&lt;Runnable&gt; queue = new ArrayBlockingQueue&lt;Runnable&gt;(POOL_SIZE);\n ExecutorService executorService = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE, 0, TimeUnit.SECONDS, queue);\n return executorService.invokeAny(callables);\n}\n\nstatic public void main(String[] args) throws InterruptedException, ExecutionException {\n\n final List&lt;Integer&gt; integers = new ArrayList&lt;Integer&gt;();\n for (int i = 0; i &lt; POOL_SIZE; i++) {\n integers.add(i);\n }\n\n (new Thread() {\n public void run() {\n Integer notified = null;\n try {\n notified = waitForAny(integers);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (ExecutionException e) {\n e.printStackTrace();\n }\n System.out.println(\"notified=\" + notified);\n }\n\n }).start();\n\n\n synchronized (integers) {\n integers.wait(3000);\n }\n\n\n Integer randomInt = integers.get((new Random()).nextInt(POOL_SIZE));\n System.out.println(\"Waking up \" + randomInt);\n synchronized (randomInt) {\n randomInt.notify();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 64568687, "author": "Alex - GlassEditor.com", "author_id": 3179759, "author_profile": "https://Stackoverflow.com/users/3179759", "pm_score": 2, "selected": false, "text": "<p>If you can use <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/concurrent/CompletableFuture.html\" rel=\"nofollow noreferrer\"><code>CompletableFuture</code></a>s instead then there is <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/concurrent/CompletableFuture.html#anyOf(java.util.concurrent.CompletableFuture...)\" rel=\"nofollow noreferrer\"><code>CompletableFuture.anyOf</code></a> that does what you want, just call join on the result:</p>\n<pre><code>CompletableFuture.anyOf(futures).join()\n</code></pre>\n<p>You can use <code>CompletableFuture</code>s with executors by calling the <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/concurrent/CompletableFuture.html#supplyAsync(java.util.function.Supplier,java.util.concurrent.Executor)\" rel=\"nofollow noreferrer\"><code>CompletableFuture.supplyAsync</code></a> or <code>runAsync</code> methods.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5507/" ]
I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I'll need to wait util M out of N tasks are finished). Currently they are presented as Future, so I need something like ``` /** * Blocks current thread until one of specified futures is done and returns it. */ public static <T> Future<T> waitForAny(Collection<Future<T>> futures) throws AllFuturesFailedException ``` Is there anything like this? Or anything similar, not necessary for Future. Currently I loop through collection of futures, check if one is finished, then sleep for some time and check again. This looks like not the best solution, because if I sleep for long period then unwanted delay is added, if I sleep for short period then it can affect performance. I could try using ``` new CountDownLatch(1) ``` and decrease countdown when task is complete and do ``` countdown.await() ``` , but I found it possible only if I control Future creation. It is possible, but requires system redesign, because currently logic of tasks creation (sending Callable to ExecutorService) is separated from decision to wait for which Future. I could also override ``` <T> RunnableFuture<T> AbstractExecutorService.newTaskFor(Callable<T> callable) ``` and create custom implementation of RunnableFuture with ability to attach listener to be notified when task is finished, then attach such listener to needed tasks and use CountDownLatch, but that means I have to override newTaskFor for every ExecutorService I use - and potentially there will be implementation which do not extend AbstractExecutorService. I could also try wrapping given ExecutorService for same purpose, but then I have to decorate all methods producing Futures. All these solutions may work but seem very unnatural. It looks like I'm missing something simple, like ``` WaitHandle.WaitAny(WaitHandle[] waitHandles) ``` in c#. Are there any well known solutions for such kind of problem? UPDATE: Originally I did not have access to Future creation at all, so there were no elegant solution. After redesigning system I got access to Future creation and was able to add countDownLatch.countdown() to execution process, then I can countDownLatch.await() and everything works fine. Thanks for other answers, I did not know about ExecutorCompletionService and it indeed can be helpful in similar tasks, but in this particular case it could not be used because some Futures are created without any executor - actual task is sent to another server via network, completes remotely and completion notification is received.
As far as I know, Java has no analogous structure to the `WaitHandle.WaitAny` method. It seems to me that this could be achieved through a "WaitableFuture" decorator: ``` public WaitableFuture<T> extends Future<T> { private CountDownLatch countDownLatch; WaitableFuture(CountDownLatch countDownLatch) { super(); this.countDownLatch = countDownLatch; } void doTask() { super.doTask(); this.countDownLatch.countDown(); } } ``` Though this would only work if it can be inserted before the execution code, since otherwise the execution code would not have the new `doTask()` method. But I really see no way of doing this without polling if you cannot somehow gain control of the Future object before execution. Or if the future always runs in its own thread, and you can somehow get that thread. Then you could spawn a new thread to join each other thread, then handle the waiting mechanism after the join returns... This would be really ugly and would induce a lot of overhead though. And if some Future objects don't finish, you could have a lot of blocked threads depending on dead threads. If you're not careful, this could leak memory and system resources. ``` /** * Extremely ugly way of implementing WaitHandle.WaitAny for Thread.Join(). */ public static joinAny(Collection<Thread> threads, int numberToWaitFor) { CountDownLatch countDownLatch = new CountDownLatch(numberToWaitFor); foreach(Thread thread in threads) { (new Thread(new JoinThreadHelper(thread, countDownLatch))).start(); } countDownLatch.await(); } class JoinThreadHelper implements Runnable { Thread thread; CountDownLatch countDownLatch; JoinThreadHelper(Thread thread, CountDownLatch countDownLatch) { this.thread = thread; this.countDownLatch = countDownLatch; } void run() { this.thread.join(); this.countDownLatch.countDown(); } } ```
117,691
<p>Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as:</p> <pre><code>$numbers = array(1,3,4,5,6,8,11,12,14,15,16); </code></pre> <p>The ranges would be:</p> <pre><code> 1,3-6,8,11-12,14-16 </code></pre>
[ { "answer_id": 117722, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "<p>Here's a python implementation, it should be easy enough to follow</p>\n\n<pre><code>numbers = [1,3,4,5,6,8,11,12,14,15,16];\n\ndef is_predecessor(i1, i2):\n if i1 == i2 - 1:\n return True;\n else:\n return False;\n\ndef make_range(i1, i2):\n if i1 == i2:\n return str(i1);\n else:\n return str(i1) + \"-\" + str(i2);\n\nprevious_element = None;\ncurrent_start_element = None;\n\nfor number in numbers:\n if not is_predecessor(previous_element, number):\n if current_start_element is not None:\n print make_range(current_start_element, previous_element);\n current_start_element = number;\n previous_element = number;\n\n# handle last pair\nif current_start_element is not None:\n print make_range(current_start_element, previous_element);\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>1\n3-6\n8\n11-12\n14-16\n</code></pre>\n\n<p>I know, I know, it isn't an <em>algorithm</em>, but I found it harder to actually explain it without having indentation problems than to just implement a solution for it.</p>\n" }, { "answer_id": 117723, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 5, "selected": true, "text": "<p>If the array is sorted in ascending order, then the problem is easy. Define a <code>Range</code> structure or class, which has a beginning and an end. Then go through the array. If the current element is one more than the previous, update <code>Range.end</code>, otherwise create a new range with this element as <code>Range.begin</code>. Store the ranges to a dynamic array or a linked list. Or just print them out as you go.</p>\n\n<p>If the array may not be sorted, then sort it first.</p>\n" }, { "answer_id": 117724, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 2, "selected": false, "text": "<p>first: sort\nsecond: tokenise\nthen: print the first value and loop over subsequent ones. If the 'current' value is equal to the last value +1, skip it. Otherwise if you've skipped value print dash and the value, otherwise print a comma and repeat.</p>\n\n<p>That should do. Unless you wanted me to code up your homework for you? :)</p>\n" }, { "answer_id": 117730, "author": "MarcE", "author_id": 7262, "author_profile": "https://Stackoverflow.com/users/7262", "pm_score": 0, "selected": false, "text": "<p>Assuming the list is ordered you could start at the end and keep subtracting the next one down. While the difference is 1, you're in a range. When it's not, you start a new range. </p>\n\n<p>i.e </p>\n\n<p>16-15 = 1</p>\n\n<p>15-14 = 1</p>\n\n<p>14-12 = 2, the range is 16-14 - start a new range.</p>\n" }, { "answer_id": 117747, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 0, "selected": false, "text": "<pre><code>startRange = array[0]; \nfor(i=0;i&lt;array.length;i++)\n{\n if (array[i + 1] - array[i] &gt; 1)\n {\n endRange = array[i];\n pushRangeOntoArray(startRange,endRange);\n i++;\n startRange = array[i]\n // need to check for end of array here\n }\n}\n</code></pre>\n" }, { "answer_id": 117779, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 0, "selected": false, "text": "<p>Here's my Perl solution. Could be cleaner and faster, but it shows how it works:</p>\n\n<pre><code># Just in case it's not sorted...\nmy @list = sort { $a &lt;=&gt; $b } ( 1, 3, 4, 5, 6, 8, 11, 12, 14, 15, 16 );\n\nmy $range = [ $list[0] ];\n\nfor(@list[1 .. $#list]) {\n if($_ == $range-&gt;[-1] + 1) {\n push @$range, $_;\n }\n else {\n print $#$range ? $range-&gt;[0] . '-' . $range-&gt;[-1] : $range-&gt;[0], \"\\n\";\n $range = [ $_ ];\n }\n}\n</code></pre>\n" }, { "answer_id": 117796, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 0, "selected": false, "text": "<p>My solution in Java 1.5 would be:</p>\n\n<pre><code>public static List&lt;String&gt; getRanges(int... in) {\n List&lt;String&gt; result = new ArrayList&lt;String&gt;();\n int last = -1;\n for (int i : in) {\n if (i != (last + 1)) {\n if (!result.isEmpty()) {\n addRange(result, last);\n }\n result.add(String.valueOf(i));\n } \n last = i;\n }\n addRange(result, last);\n return result;\n}\n\nprivate static void addRange(List&lt;String&gt; result, int last) {\n int lastPosition = result.size() - 1;\n String lastResult = result.get(lastPosition);\n if (!lastResult.equals(String.valueOf(last))) {\n result.set(lastPosition, lastResult + \"-\" + last);\n }\n}\n\npublic static void main(String[] args) {\n List&lt;String&gt; ranges = getRanges(1, 3, 4, 5, 6, 8, 11, 12, 14, 15, 16);\n System.out.println(ranges);\n}\n</code></pre>\n\n<p>which outputs:</p>\n\n<pre><code>[1, 3-6, 8, 11-12, 14-16]\n</code></pre>\n\n<p>Greetz, GHad</p>\n" }, { "answer_id": 117809, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 0, "selected": false, "text": "<p>I believe the mergeinfo property that was introduced to Subversion in the 1.5 release has a format that is the same as what you're asking for, so you could potentially go look through the source of Subversion to find out how they do it. I'd be surprised if its any different than the other suggestions that have already been posted here.</p>\n" }, { "answer_id": 117811, "author": "Morikal", "author_id": 18272, "author_profile": "https://Stackoverflow.com/users/18272", "pm_score": 2, "selected": false, "text": "<p>If the array is sorted, as in your example, I would define buckets containing a min and a max.</p>\n\n<p>Initialize: Create a bucket with a min and a max equal to the first value.</p>\n\n<p>Loop: Compare each value with the max of the current bucket. If it is equal to or 1 more than the current max, update the max. If it is more than 1 greater than the max, save the bucket to a list of buckets and start a new bucket.</p>\n\n<p>At the end you will have a set of buckets with a min and a max in each. If the min is the same as the max, print a single number (ie: in your example, the first bucket would have a min and a max of 1). If they are different, print as a range.</p>\n\n<p>Example implementation in lisp:</p>\n\n<pre><code>CL-USER&gt; (defun print-ranges (integer-list)\n (let ((sorted-list (sort integer-list #'&lt;)))\n (loop with buckets = ()\n with current-bucket\n for int in sorted-list\n initially (setf current-bucket (cons (first sorted-list) (first sorted-list)))\n do (cond ((= int (cdr current-bucket))) ; do nothing, this number is already in range\n ((= (1- int) (cdr current-bucket)) ; number is 1 higher--update bucket's max\n (setf (cdr current-bucket) int))\n (t\n (push current-bucket buckets)\n (setf current-bucket (cons int int)))) ; set up a new bucket\n finally (push current-bucket buckets)\n (loop for firstp = t then nil\n for bucket in (nreverse buckets) do\n (cond ((= (car bucket) (cdr bucket))\n (format t \"~:[,~;~]~D\" firstp (car bucket)))\n (t\n (format t \"~:[,~;~]~D-~D\" firstp (car bucket) (cdr bucket))))))))\nPRINT-RANGES\nCL-USER&gt; (print-ranges (list 1 3 4 5 6 8 11 12 14 15 16))\n1,3-6,8,11-12,14-16\nNIL\nCL-USER&gt; \n</code></pre>\n\n<p>Basically you end up with a list of things, where each thing has (lowest-in-bucket, highest-in-bucket). Those are your ranges.</p>\n\n<p>If the list is not already sorted, sort it first.</p>\n" }, { "answer_id": 117833, "author": "Valdemarick", "author_id": 14322, "author_profile": "https://Stackoverflow.com/users/14322", "pm_score": 0, "selected": false, "text": "<p>I will assume the array X() is pre-sorted (and if not, sort the array before-hand).</p>\n\n<pre>\nfor each element of X() as $element (with $i as current array posistion)\n add $element to end of array Y()\n if (X($i) + 1 is less than X($i + 1)) AND ($i + 1 is not greater than sizeof(X())) then\n append Y(1).\"-\".Y(sizeof(Y())) to end of Z()\n unset Y()\n end if \nnext\nif anything remains in Y() append to end of Z()\n\n</pre>\n\n<p>well, that's how I would do it.</p>\n" }, { "answer_id": 117894, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 0, "selected": false, "text": "<p>Create a simple range type which contains start / end of range values. Add a constructor which takes only one value and sets start = end = value. Maintain a stack of range objects, work your way through a sorted copy of the array, extend the top range or add a new range as appropriate. More specifically, when the value in the array is 1 + the end value for the range object on the to of the stack, increment the end value for that range, when it's not, push a new range (with start = end = value at index in array) onto the stack.</p>\n" }, { "answer_id": 118113, "author": "axblount", "author_id": 1729005, "author_profile": "https://Stackoverflow.com/users/1729005", "pm_score": 0, "selected": false, "text": "<pre><code>module Main where\n\nranges :: [Int] -&gt; [[Int]]\nranges [] = []\nranges list@(x:xs) = let adj = adjacent list in\n let len = length adj in\n if length adj == 1\n then [[x]] ++ ranges xs\n else [[x,(last adj)]] ++ ranges (drop ((length adj) - 1) xs)\n where adjacent [] = []\n adjacent (x:xs) = if (xs /= []) &amp;&amp; (x + 1) == head xs\n then [x] ++ adjacent (xs)\n else [x]\n\nmain = do putStrLn $ show $ ranges [1,2,3,4,5,6,8,11,12,14,15,16]\n\n-- Output: [[1,6],[8],[11,12],[14,16]]\n</code></pre>\n\n<p>Here's my best shot in Haskell.</p>\n" }, { "answer_id": 120349, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "<p>Here's a C# 3.0'y way of doing it:</p>\n\n<p>Points of interest:</p>\n\n<ul>\n<li>automatic properties (public int Property { get; set; })</li>\n<li>using new object initializers (new Range { Begin = xxx; ... }</li>\n<li>using yield for lazy evaluation</li>\n<li>using linq extension methods (First() and Skip())</li>\n</ul>\n\n<p>-</p>\n\n<pre><code>class Demo\n{\n private class Range\n {\n public int Begin { get; set; }\n public int End { get; set; }\n\n public override string ToString()\n {\n if (Begin == End)\n return string.Format(\"{0}\", Begin);\n else\n return string.Format(\"{0}-{1}\", Begin, End);\n }\n }\n\n static void Main(string[] args)\n {\n var list = new List&lt;int&gt; { 1, 3, 4, 5, 6, 8, 11, 12, 14, 15, 16 };\n // list.Sort();\n var ranges = GetRangesForSortedList(list);\n\n PrintRange(ranges);\n\n Console.Read();\n }\n\n private static void PrintRange(IEnumerable&lt;Range&gt; ranges)\n {\n if (ranges.Count() == 0)\n return;\n\n Console.Write(\"[{0}\", ranges.First());\n\n foreach (Range range in ranges.Skip(1))\n {\n Console.Write(\", {0}\", range);\n }\n\n Console.WriteLine(\"]\");\n }\n\n private static IEnumerable&lt;Range&gt; GetRangesForSortedList(IList&lt;int&gt; sortedList)\n {\n if (sortedList.Count &lt; 1) \n yield break;\n\n int firstItem = sortedList.First();\n Range currentRange = new Range { Begin = firstItem, End = firstItem };\n\n foreach (int item in sortedList.Skip(1))\n {\n if (item == currentRange.End + 1)\n {\n currentRange.End = item;\n }\n else\n {\n yield return currentRange;\n currentRange = new Range { Begin = item, End = item };\n }\n }\n\n yield return currentRange;\n }\n}\n</code></pre>\n\n<p>Cheers, David</p>\n" }, { "answer_id": 130632, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 0, "selected": false, "text": "<h2>Perl 6</h2>\n<pre><code>sub to_ranges( Int *@data ){\n my @ranges;\n \n OUTER: for @data -&gt; $item {\n for @ranges -&gt; $range {\n # short circuit if the $item is in a range\n next OUTER if $range[0] &lt;= $item &lt;= $range[1];\n \n given( $item ){\n when( $range[0]-1 ){ $range[0] = $item }\n when( $range[1]+1 ){ $range[1] = $item }\n }\n }\n \n push @ranges, [$item,$item];\n }\n \n return @ranges;\n}\n</code></pre>\n" }, { "answer_id": 233529, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "<h1>Python (&gt;= 2.6)</h1>\n<p>This version additionally handles duplicates and unsorted sequences.</p>\n<pre><code>from __future__ import print_function\n\ndef ranges(a):\n a.sort()\n i = 0\n while i &lt; len(a):\n start = i\n while i &lt; len(a)-1 and a[i] &gt;= a[i+1]-1:\n i += 1\n print(a[start] if a[start] == a[i] else &quot;%d-%d&quot; % (a[start], a[i]),\n end=&quot;,&quot; if i &lt; len(a)-1 else &quot;\\n&quot;)\n i += 1\n</code></pre>\n<p>Example:</p>\n<pre><code>import random\nr = range(10)\nrandom.shuffle(r)\nranges(r)\nranges([1,3,4,5,6,8,11,12,14,15,16]);\nranges([])\nranges([1])\nranges([1, 2])\nranges([1, 3])\nranges([1, 3, 4])\nranges([1, 2, 4])\nranges([1, 1, 2, 4])\nranges([1, 2, 2, 4])\nranges([1, 2, 2, 3, 5, 5])\n</code></pre>\n<p>Output:</p>\n<pre><code>0-9\n1,3-6,8,11-12,14-16\n1\n1-2\n1,3\n1,3-4\n1-2,4\n1-2,4\n1-2,4\n1-3,5\n</code></pre>\n" }, { "answer_id": 233811, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "<h1>C (gcc)</h1>\n\n<p>It is similar to <a href=\"https://stackoverflow.com/questions/117691/how-would-you-display-an-array-of-integers-as-a-set-of-ranges-algorithm#233529\">the Python's version</a>.</p>\n\n<pre><code>void ranges(int n; int a[n], int n)\n{\n qsort(a, n, sizeof(*a), intcmp);\n for (int i = 0; i &lt; n; ++i) {\n const int start = i;\n while(i &lt; n-1 and a[i] &gt;= a[i+1]-1)\n ++i;\n printf(\"%d\", a[start]);\n if (a[start] != a[i])\n printf(\"-%d\", a[i]);\n if (i &lt; n-1)\n printf(\",\");\n }\n printf(\"\\n\");\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>/**\n * $ gcc -std=c99 -Wall ranges.c -o ranges &amp;&amp; ./ranges\n */\n#include &lt;iso646.h&gt; // and\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define T(args...) \\\n { \\\n int array[] = {args}; \\\n ranges(array, sizeof(array) / sizeof(*array)); \\\n }\n\nint intcmp(const void* a, const void* b)\n{\n const int *ai = a;\n const int *bi = b;\n\n if (*ai &lt; *bi)\n return -1;\n else if (*ai &gt; *bi)\n return 1;\n else\n return 0;\n}\n\nint main(void)\n{\n T(1,3,4,5,6,8,11,12,14,15,16);\n T();\n T(1);\n T(1, 2);\n T(3, 1);\n T(1, 3, 4);\n T(1, 2, 4);\n T(1, 1, 2, 4);\n T(1, 2, 2, 4);\n T(1, 2, 2, 3, 5, 5);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1,3-6,8,11-12,14-16\n\n1\n1-2\n1,3\n1,3-4\n1-2,4\n1-2,4\n1-2,4\n1-3,5\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10585/" ]
Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as: ``` $numbers = array(1,3,4,5,6,8,11,12,14,15,16); ``` The ranges would be: ``` 1,3-6,8,11-12,14-16 ```
If the array is sorted in ascending order, then the problem is easy. Define a `Range` structure or class, which has a beginning and an end. Then go through the array. If the current element is one more than the previous, update `Range.end`, otherwise create a new range with this element as `Range.begin`. Store the ranges to a dynamic array or a linked list. Or just print them out as you go. If the array may not be sorted, then sort it first.
117,708
<p>The non-virtual interface idiom describes how the virtual methods are nonpublic customisation points, and public methods are nonvirtual to allow the base class to control at all times how the customisation points are called. </p> <p>This is an elegant idiom and I like to use it, but how does it work if the derived class is a base class in itself</p>
[ { "answer_id": 117744, "author": "Mike Elkins", "author_id": 19193, "author_profile": "https://Stackoverflow.com/users/19193", "pm_score": 1, "selected": false, "text": "<p>The derived class can decide for itself:</p>\n\n<p>You can just override the method completely by implementing the virtual function.\nYou can augment the method by calling the 'middle' classes function at some point in your derived class method.</p>\n\n<p>If that's not what you want, you need to set it up explicitly in the 'middle' class. I wouldn't though. If you find yourself desiring this, it probably means you didn't give the base class enough customization points.</p>\n" }, { "answer_id": 117760, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 4, "selected": true, "text": "<p>It works, because the derived class can override a private virtual function of a base class, even if the base class function overrides its base class function.</p>\n\n<p>This is perfectly legal:</p>\n\n<pre><code>\nclass Parent\n{\npublic:\n int foo() {return bar();} // the non-virtual public interface\nprivate\n virtual int bar();\n};\n\nclass Child : public Parent\n{\nprivate:\n virtual int bar(); // overrides Parent::bar()\n};\n\nclass Grandchild : public Child\n{\nprivate:\n virtual int bar(); // overrides Child::bar();\n};\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
The non-virtual interface idiom describes how the virtual methods are nonpublic customisation points, and public methods are nonvirtual to allow the base class to control at all times how the customisation points are called. This is an elegant idiom and I like to use it, but how does it work if the derived class is a base class in itself
It works, because the derived class can override a private virtual function of a base class, even if the base class function overrides its base class function. This is perfectly legal: ``` class Parent { public: int foo() {return bar();} // the non-virtual public interface private virtual int bar(); }; class Child : public Parent { private: virtual int bar(); // overrides Parent::bar() }; class Grandchild : public Child { private: virtual int bar(); // overrides Child::bar(); }; ```
117,732
<p>Take this simple <em>C# LINQ</em> query, and imagine that <code>db.Numbers</code> is an <em>SQL</em> table with one column <code>Number</code>:</p> <pre><code>var result = from n in db.Numbers where n.Number &lt; 5 select n.Number; </code></pre> <p>This will run very efficiently in <em>C#</em>, because it generates an <em>SQL</em> query something like</p> <pre><code>select Number from Numbers where Number &lt; 5 </code></pre> <p>What it <strong>doesn't</strong> do is select <em>all</em> the numbers from the database, and then filter them in <em>C#</em>, as it might appear to do at first.</p> <p><em>Python</em> supports a similar syntax:</p> <pre><code>result = [n.Number for n in Numbers if n.Number &lt; 5] </code></pre> <p>But it the <code>if</code> clause here does the filtering on the client side, rather than the server side, which is much less efficient.</p> <p>Is there something as efficient as <em>LINQ</em> in <em>Python</em>? (I'm currently evaluating <em>Python</em> vs. <em>IronPython</em> vs. <em>Boo</em>, so an answer that works in any of those languages is fine.)</p>
[ { "answer_id": 117794, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "<p>Look closely at <a href=\"http://www.sqlalchemy.org/\" rel=\"nofollow noreferrer\">SQLAlchemy</a>. This can probably do much of what you want. It gives you Python syntax for plain-old SQL that runs on the server.</p>\n" }, { "answer_id": 117818, "author": "Chris Ammerman", "author_id": 2729, "author_profile": "https://Stackoverflow.com/users/2729", "pm_score": 2, "selected": false, "text": "<p>LINQ is a language feature of C# and VB.NET. It is a special syntax recognized by the compiler and treated specially. It is also dependent on another language feature called expression trees.</p>\n\n<p>Expression trees are a <strong>little</strong> different in that they are not special syntax. They are written just like any other class instantiation, but the compiler does treat them specially under the covers by turning a lambda into an instantiation of a run-time <a href=\"http://en.wikipedia.org/wiki/Abstract_syntax_tree\" rel=\"nofollow noreferrer\">abstract syntax tree</a>. These can be manipulated at run-time to produce a command in another language (i.e. SQL).</p>\n\n<p>The C# and VB.NET compilers take LINQ syntax, and turn it into lambdas, then pass those into expression tree instantiations. Then there are a bunch of framework classes that manipulate these trees to produce SQL. You can also find other libraries, both MS-produced and third party, that offer \"LINQ providers\", which basically pop a different AST processer in to produce something from the LINQ other than SQL.</p>\n\n<p>So one obstacle to doing these things in another language is the question whether they support run-time AST building/manipulation. I don't know whether any implementations of Python or Boo do, but I haven't heard of any such features.</p>\n" }, { "answer_id": 118350, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 3, "selected": true, "text": "<p>I believe that when IronPython 2.0 is complete, it will have LINQ support (see <a href=\"http://groups.google.com/group/ironpy/browse_thread/thread/eb6b9eb2241cc68e\" rel=\"nofollow noreferrer\">this thread</a> for some example discussion). Right now you should be able to write something like:</p>\n\n<pre><code>Queryable.Select(Queryable.Where(someInputSequence, somePredicate), someFuncThatReturnsTheSequenceElement) \n</code></pre>\n\n<p>Something better might have made it into IronPython 2.0b4 - there's a lot of <a href=\"http://ironpython-urls.blogspot.com/2008/09/dlr-namespace-change-fire-drill.html\" rel=\"nofollow noreferrer\">current discussion</a> about how naming conflicts were handled.</p>\n" }, { "answer_id": 118496, "author": "David Raznick", "author_id": 20842, "author_profile": "https://Stackoverflow.com/users/20842", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.sqlalchemy.org/trac/wiki/SqlSoup\" rel=\"nofollow noreferrer\">sqlsoup</a> in sqlalchemy gives you the quickest solution in python I think if you want a clear(ish) one liner . Look at the page to see.</p>\n\n<p>It should be something like...</p>\n\n<pre><code>result = [n.Number for n in db.Numbers.filter(db.Numbers.Number &lt; 5).all()]\n</code></pre>\n" }, { "answer_id": 235727, "author": "Andrew Davey", "author_id": 7011, "author_profile": "https://Stackoverflow.com/users/7011", "pm_score": 0, "selected": false, "text": "<p>A key factor for LINQ is the ability of the compiler to generate expression trees.\nI am using a macro in Nemerle that converts a given Nemerle expression into an Expression tree object.\nI can then pass this to the Where/Select/etc extension methods on IQueryables.\nIt's not quite the syntax of C# and VB, but it's close enough for me. </p>\n\n<p>I got the Nemerle macro via a link on this post: \n<a href=\"http://groups.google.com/group/nemerle-dev/browse_thread/thread/99b9dcfe204a578e\" rel=\"nofollow noreferrer\">http://groups.google.com/group/nemerle-dev/browse_thread/thread/99b9dcfe204a578e</a></p>\n\n<p>It should be possible to create a similar macro for Boo. It's quite a bit of work however, given the large set of possible expressions you need to support.\nAyende has given a proof of concept here:\n<a href=\"http://ayende.com/Blog/archive/2008/08/05/Ugly-Linq.aspx\" rel=\"nofollow noreferrer\">http://ayende.com/Blog/archive/2008/08/05/Ugly-Linq.aspx</a></p>\n" }, { "answer_id": 254524, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 1, "selected": false, "text": "<p>Boo supports list generator expressions using the same syntax as python. For more information on that, check out the Boo documentation on <a href=\"http://boo.codehaus.org/Generator+Expressions\" rel=\"nofollow noreferrer\">Generator expressions</a> and <a href=\"http://boo.codehaus.org/List+Generators\" rel=\"nofollow noreferrer\">List comprehensions</a>.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42219/" ]
Take this simple *C# LINQ* query, and imagine that `db.Numbers` is an *SQL* table with one column `Number`: ``` var result = from n in db.Numbers where n.Number < 5 select n.Number; ``` This will run very efficiently in *C#*, because it generates an *SQL* query something like ``` select Number from Numbers where Number < 5 ``` What it **doesn't** do is select *all* the numbers from the database, and then filter them in *C#*, as it might appear to do at first. *Python* supports a similar syntax: ``` result = [n.Number for n in Numbers if n.Number < 5] ``` But it the `if` clause here does the filtering on the client side, rather than the server side, which is much less efficient. Is there something as efficient as *LINQ* in *Python*? (I'm currently evaluating *Python* vs. *IronPython* vs. *Boo*, so an answer that works in any of those languages is fine.)
I believe that when IronPython 2.0 is complete, it will have LINQ support (see [this thread](http://groups.google.com/group/ironpy/browse_thread/thread/eb6b9eb2241cc68e) for some example discussion). Right now you should be able to write something like: ``` Queryable.Select(Queryable.Where(someInputSequence, somePredicate), someFuncThatReturnsTheSequenceElement) ``` Something better might have made it into IronPython 2.0b4 - there's a lot of [current discussion](http://ironpython-urls.blogspot.com/2008/09/dlr-namespace-change-fire-drill.html) about how naming conflicts were handled.
117,751
<p>I have a web application using JPA and JTA with Spring. I would like to support both JBoss and Tomcat. When running on JBoss, I'd like to use JBoss' own TransactionManager, and when running on Tomcat, I'd like to use JOTM.</p> <p>I have both scenarios working, but I now find that I seem to need two separate Spring configurations for the two cases. With JOTM, I need to use Spring's <code>JotmFactoryBean</code>:</p> <pre><code>&lt;bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"&gt; &lt;property name="userTransaction"&gt; &lt;bean class="org.springframework.transaction.jta.JotmFactoryBean"/&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>In JBoss, though, I just need to fetch "TransactionManager" from JNDI:</p> <pre><code>&lt;bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"&gt; &lt;property name="transactionManager"&gt; &lt;bean class="org.springframework.jndi.JndiObjectFactoryBean"&gt; &lt;property name="resourceRef" value="true" /&gt; &lt;property name="jndiName" value="TransactionManager" /&gt; &lt;property name="expectedType" value="javax.transaction.TransactionManager" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>Is there a way to configure this so that the appropriate TransactionManager - JBoss or JOTM - is used, without the need for two different configuration files?</p>
[ { "answer_id": 117871, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "<p>You can use PropertyConfigurerPlaceholder to inject bean references as well as simple values.</p>\n\n<p>For example if you call your beans 'jotm' and 'jboss' then you could inject your TM like:</p>\n\n<pre><code>&lt;bean class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\"&gt;\n &lt;property name=\"systemPropertiesModeName\" value=\"SYSTEM_PROPERTIES_MODE_OVERRIDE\"&gt;\n &lt;property name=\"location\" value=\"classpath:/path/to/application.properties\"/&gt;\n&lt;/bean&gt;\n&lt;bean id=\"jotm\"&gt;...&lt;/bean&gt;\n&lt;bean id=\"jboss\"&gt;...&lt;/bean&gt;\n&lt;bean id=\"bean-requiring-transaction-manager\"&gt;\n &lt;property name=\"transactionManager\" ref=\"${transaction.strategy}\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>Then you can swap transaction managers using</p>\n\n<ul>\n<li><em>transaction.strategy=jotm</em> in a properties file</li>\n<li><em>-Dtransaction.strategy=jotm</em> as a system property</li>\n</ul>\n\n<p>This is one possible approach. See my <a href=\"http://toolkits.blogspot.com/2008/04/changing-spring-beans-using-properties.html\" rel=\"nofollow noreferrer\">blog</a> for a more complete example.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 117933, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 2, "selected": false, "text": "<p>If you are using Spring 2.5 you can use &lt;tx:jta-transaction-manager/&gt;. I have not used it with JBoss but it should work for you according to section <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/transaction.html#transaction-application-server-integration\" rel=\"nofollow noreferrer\">9.8 Application server-specific integration</a> from the Spring reference manual.</p>\n" }, { "answer_id": 263157, "author": "Chochos", "author_id": 10165, "author_profile": "https://Stackoverflow.com/users/10165", "pm_score": 2, "selected": false, "text": "<p>The <code>&lt;tx:jta-transaction-manager/&gt;</code> approach will look for a transaction manager in several default locations <a href=\"http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/transaction/jta/JtaTransactionManager.html\" rel=\"nofollow noreferrer\">listed here</a>. If your JBoss transaction manager is not in one of those locations, I suggest you move it, if possible, or move it in Tomcat so that both containers have their TM in the same JNDI location.</p>\n" }, { "answer_id": 416975, "author": "David Newcomb", "author_id": 52070, "author_profile": "https://Stackoverflow.com/users/52070", "pm_score": 5, "selected": true, "text": "<p>I think you have missed the point of JNDI. JNDI was pretty much written to solve the problem you have!</p>\n\n<p>I think you can take it up a level, so instead of using the \"userTransaction\" or \"transactionManager from JNDI\" depending on your situation. Why not add the \"JtaTransactionManager\" to JNDI. That way you push the configuration to the JNDI where it is supposed to be instead of creating even more configuration files [ like there aren't enough already ;) ].</p>\n" }, { "answer_id": 5080761, "author": "Darren Bishop", "author_id": 133330, "author_profile": "https://Stackoverflow.com/users/133330", "pm_score": 1, "selected": false, "text": "<p>Just adding my experience here so I don't have to re-suffer the experience again.</p>\n\n<p>As bmatthews68, Chochos and <a href=\"https://stackoverflow.com/questions/1783540/spring-jta-configuration-how-to-set-transactionmanager\">these posters</a> have said, use <code>&lt;tx:jta-transaction-manager/&gt;</code> in your Spring bean file; it definitely provides the appropriate level of abstraction and there's no need to do anything extra on the Spring side.</p>\n\n<p>As for Tomcat, I declared <code>&lt;Transaction factory=\"org.objectweb.jotm.UserTransactionFactory\" jotm.timeout=\"60\" /&gt;</code> in the default/shared <code>conf/context.xml</code> file, which binds to <code>java:comp/UserTransaction</code>. As this is one of the places searched for by Spring, you shouldn't need to do anything else.</p>\n\n<p>One gotcha though: if like me you use Maven, make sure you exclude any dependencies on the <code>javax.transaction:jta</code> jar or set the scope to <code>provided</code>. Otherwise you will experience classloader issues.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7034/" ]
I have a web application using JPA and JTA with Spring. I would like to support both JBoss and Tomcat. When running on JBoss, I'd like to use JBoss' own TransactionManager, and when running on Tomcat, I'd like to use JOTM. I have both scenarios working, but I now find that I seem to need two separate Spring configurations for the two cases. With JOTM, I need to use Spring's `JotmFactoryBean`: ``` <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="userTransaction"> <bean class="org.springframework.transaction.jta.JotmFactoryBean"/> </property> </bean> ``` In JBoss, though, I just need to fetch "TransactionManager" from JNDI: ``` <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="transactionManager"> <bean class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="resourceRef" value="true" /> <property name="jndiName" value="TransactionManager" /> <property name="expectedType" value="javax.transaction.TransactionManager" /> </bean> </property> </bean> ``` Is there a way to configure this so that the appropriate TransactionManager - JBoss or JOTM - is used, without the need for two different configuration files?
I think you have missed the point of JNDI. JNDI was pretty much written to solve the problem you have! I think you can take it up a level, so instead of using the "userTransaction" or "transactionManager from JNDI" depending on your situation. Why not add the "JtaTransactionManager" to JNDI. That way you push the configuration to the JNDI where it is supposed to be instead of creating even more configuration files [ like there aren't enough already ;) ].
117,755
<p>Here's the code I want to speed up. It's getting a value from an ADO recordset and converting it to a char*. But this is slow. Can I skip the creation of the _bstr_t?</p> <pre><code> _variant_t var = pRs-&gt;Fields-&gt;GetItem(i)-&gt;GetValue(); if (V_VT(&amp;var) == VT_BSTR) { char* p = (const char*) (_bstr_t) var; </code></pre>
[ { "answer_id": 117780, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>This creates a temporary on the stack:</p>\n\n<pre><code>USES_CONVERSION;\nchar *p=W2A(var.bstrVal);\n</code></pre>\n\n<p>This uses a slightly newer syntax and is probably more robust. It has a configurable size, beyond which it will use the heap so it avoids putting massive strings onto the stack:</p>\n\n<pre><code>char *p=CW2AEX&lt;&gt;(var.bstrVal);\n</code></pre>\n" }, { "answer_id": 117781, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 2, "selected": false, "text": "<p>Your problem (other than the possibility of a memory copy inside _bstr_t) is that you're converting the UNICODE BSTR into an ANSI char*.</p>\n\n<p>You can use the USES_CONVERSION macros which perform the conversion on the stack, so they might be faster. Alternatively, keep the BSTR value as unicode if possible.</p>\n\n<p>to convert:</p>\n\n<pre><code>USES_CONVERSION;\nchar* p = strdup(OLE2A(var.bstrVal));\n\n// ...\n\nfree(p);\n</code></pre>\n\n<p>remember - the string returned from OLE2A (and its sister macros) return a string that is allocated on the stack - return from the enclosing scope and you have garbage string unless you copy it (and free it eventually, obviously)</p>\n" }, { "answer_id": 117785, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": -1, "selected": false, "text": "<p>Ok, my C++ is getting a little rusty... but I don't think the conversion is your problem. That conversion doesn't really do anything except tell the compiler to consider _bstr_t a char*. Then you're just assigning the address of that pointer to p. Nothing's actually being \"done.\"</p>\n\n<p>Are you sure it's not just slow getting stuff from GetValue?</p>\n\n<p>Or is my C++ rustier than I think...</p>\n" }, { "answer_id": 118442, "author": "PiNoYBoY82", "author_id": 13646, "author_profile": "https://Stackoverflow.com/users/13646", "pm_score": 3, "selected": true, "text": "<p>The first 4 bytes of the BSTR contain the length. You can loop through and get every other character if unicode or every character if multibyte. Some sort of memcpy or other method would work too. IIRC, this can be faster than <code>W2A</code> or casting <code>(LPCSTR)(_bstr_t)</code></p>\n" }, { "answer_id": 2379121, "author": "Peter Nimmo", "author_id": 176690, "author_profile": "https://Stackoverflow.com/users/176690", "pm_score": 0, "selected": false, "text": "<pre><code>_variant_t var = pRs-&gt;Fields-&gt;GetItem(i)-&gt;GetValue(); \n</code></pre>\n\n<p>You can also make this assignment quicker by avoiding the fields collection all together. You should only use the Fields collection when you need to retrieve the item by name. If you know the fields by index you can instead use this.</p>\n\n<pre><code>_variant_t vara = pRs-&gt;Collect[i]-&gt;Value;\n</code></pre>\n\n<p>Note i cannot be an integer as ADO does not support VT_INTEGER, so you might as well use a long variable.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
Here's the code I want to speed up. It's getting a value from an ADO recordset and converting it to a char\*. But this is slow. Can I skip the creation of the \_bstr\_t? ``` _variant_t var = pRs->Fields->GetItem(i)->GetValue(); if (V_VT(&var) == VT_BSTR) { char* p = (const char*) (_bstr_t) var; ```
The first 4 bytes of the BSTR contain the length. You can loop through and get every other character if unicode or every character if multibyte. Some sort of memcpy or other method would work too. IIRC, this can be faster than `W2A` or casting `(LPCSTR)(_bstr_t)`
117,772
<p>I'm trying to use the page-break-inside CSS directive, the class of which is to be attached to a div tag or a table tag (I think this may only work on block elements, in which case it would have to be the table).</p> <p>I've tried all the tutorials that supposedly describe exactly how to do this, but nothing works. Is this an issue of browser support or has anyone actually gotten this working, the exact bit of CSS looks like this:</p> <pre><code>@media print { .noPageBreak { page-break-inside : avoid; } } </code></pre>
[ { "answer_id": 117834, "author": "phloopy", "author_id": 8507, "author_profile": "https://Stackoverflow.com/users/8507", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://developer.apple.com/documentation/AppleApplications/Reference/SafariCSSRef/Articles/StandardCSSProperties.html#//apple_ref/doc/uid/TP30001266-PagedMedia\" rel=\"nofollow noreferrer\"><strong>Safari</strong> 1.3+</a>, <a href=\"http://reference.sitepoint.com/css/page-break-inside\" rel=\"nofollow noreferrer\"><strong>Opera</strong> 9.2+</a>, <a href=\"http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(CSS)#Properties\" rel=\"nofollow noreferrer\">Konquerer</a>, and <a href=\"http://msdn.microsoft.com/en-us/library/cc304067(VS.85).aspx\" rel=\"nofollow noreferrer\"><strong>IE8</strong></a> all support it, at least to some degree.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(CSS)#Properties\" rel=\"nofollow noreferrer\">Firefox</a> apparently still does not.</p>\n" }, { "answer_id": 117878, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>I'm trying to use the page-break-inside CSS directive, the class of which is to be attached to a div tag or a table tag (I think this may only work on block elements, in which case it would have to be the table).</p>\n</blockquote>\n\n<p>Firstly, there's no need to guess. Just look at <a href=\"http://www.w3.org/TR/CSS21/page.html#propdef-page-break-inside\" rel=\"nofollow noreferrer\">the specification</a>, and you'll see that it does indeed only apply to block-level elements.</p>\n\n<p>Secondly, <code>&lt;div&gt;</code> elements are usually block-level elements, so there's no problem applying <code>page-break-inside</code> to a <code>&lt;div&gt;</code> element.</p>\n\n<p>Finally, you don't need to wrap it in <code>@media</code>. You only need <code>@media</code> if you want to apply media-independent rules to only one medium, for instance, if you want to use <code>display: block</code> only for one medium. In this case, you don't need to hide those rules from other media, because they'll only apply to paged media anyway.</p>\n" }, { "answer_id": 117908, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://developer.apple.com/documentation/AppleApplications/Reference/SafariCSSRef/Articles/StandardCSSProperties.html#//apple_ref/doc/uid/TP30001266-PagedMedia\" rel=\"nofollow noreferrer\">Safari 1.3 and later</a> support <code>page-break-inside</code>.</p>\n\n<p><a href=\"http://bugs.kde.org/68930\" rel=\"nofollow noreferrer\">So does Konqueror</a>.</p>\n" }, { "answer_id": 1213479, "author": "Stop Slandering Monica Cellio", "author_id": 146406, "author_profile": "https://Stackoverflow.com/users/146406", "pm_score": 3, "selected": false, "text": "<p>Safari 1.3 and later (don't know about 4) do <strong>not</strong> support page-break-inside (try it, or see here: <a href=\"http://reference.sitepoint.com/css/page-break-inside\" rel=\"nofollow noreferrer\">http://reference.sitepoint.com/css/page-break-inside</a>). Neither do Firefox 3 or IE7 (don't know about 8).</p>\n\n<p>In a practical sense, support for this attribute is SO spotty, it doesn't make sense to use it at all at this point. You'd be lucky if even 10% of your visitors have browsers that can support this.</p>\n\n<p>The solution I used was to add</p>\n\n<p><code>page-break-after:always</code></p>\n\n<p>to certain divs, or add a \"page-breaker\" div in where you want breaks. This is quite ham-handed, I know, because it doesn't do quite what you want, and causes content to not reach the bottom of the printed page, but unfortunately there isn't a better solution (prove me wrong!).</p>\n\n<p>Another approach is to create a stylesheet that removes all extraneous elements (<code>display:none</code>) and causes the main content to flow in one main column. Basically, turn it into a single column, text-only document.</p>\n\n<p>Finally, avoid floats and columns when styling for printers, it can make IE (and FF) act wacky.</p>\n" }, { "answer_id": 4029846, "author": "chadoh", "author_id": 249801, "author_profile": "https://Stackoverflow.com/users/249801", "pm_score": 0, "selected": false, "text": "<p>From preliminary searches, it's hard to find up-to-date statistics on browser support for this, but it seems that Firefox 4beta6 supports it and Chrome 7 does not. Chrome also breaks pages halfway through a line of text, so that part of the text appears on one page and part appears on the next. Uncharacteristic lack of attention to detail, but I guess neither Google nor Apple care about printing things.</p>\n\n<p>Firefox 4 also adds some nice headers and footers to your prints with url, page title, site title, number of pages, and time. Nice.</p>\n" }, { "answer_id": 4312187, "author": "Eamon Nerbonne", "author_id": 42921, "author_profile": "https://Stackoverflow.com/users/42921", "pm_score": 2, "selected": false, "text": "<ul>\n<li>Firefox <a href=\"https://developer.mozilla.org/en/CSS/page-break-inside\" rel=\"nofollow\">does not support this</a> as of 2010-11-30, and thus won't in Firefox 4.</li>\n<li>IE8 <a href=\"http://msdn.microsoft.com/en-us/library/cc304067.aspx\" rel=\"nofollow\">does support page-break-inside: avoid</a> - but when I tried this on IE9, it's not very successful at avoiding page-breaks (this may be a regression, or perhaps IE8 is also only capable of avoiding page breaks in very simple cases).</li>\n<li>AFAIK it doesn't work in any webkit browser; certainly not in chrome.</li>\n<li>It actually works in Opera, even on real sites.</li>\n</ul>\n" }, { "answer_id": 6859968, "author": "AJ.", "author_id": 287151, "author_profile": "https://Stackoverflow.com/users/287151", "pm_score": 0, "selected": false, "text": "<p>As a bit more information further to <a href=\"https://stackoverflow.com/questions/117772/which-browsers-support-page-break-manipulation-using-css-and-the-page-break-insid/4312187#4312187\">Eamon Nerbonne's answer</a> on the IE rendering (IE8+), you need to make sure the browser is in standards mode. <a href=\"http://msdn.microsoft.com/en-us/library/dd433064.aspx\" rel=\"nofollow noreferrer\">This article on MSDN</a> shows what is necessary - including a meta tag in your html to force the issue:</p>\n\n<pre><code>&lt;meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\" /&gt;\n</code></pre>\n\n<p>Feels kludgy, but there you have it... seems to work more consistently.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20762/" ]
I'm trying to use the page-break-inside CSS directive, the class of which is to be attached to a div tag or a table tag (I think this may only work on block elements, in which case it would have to be the table). I've tried all the tutorials that supposedly describe exactly how to do this, but nothing works. Is this an issue of browser support or has anyone actually gotten this working, the exact bit of CSS looks like this: ``` @media print { .noPageBreak { page-break-inside : avoid; } } ```
Safari 1.3 and later (don't know about 4) do **not** support page-break-inside (try it, or see here: <http://reference.sitepoint.com/css/page-break-inside>). Neither do Firefox 3 or IE7 (don't know about 8). In a practical sense, support for this attribute is SO spotty, it doesn't make sense to use it at all at this point. You'd be lucky if even 10% of your visitors have browsers that can support this. The solution I used was to add `page-break-after:always` to certain divs, or add a "page-breaker" div in where you want breaks. This is quite ham-handed, I know, because it doesn't do quite what you want, and causes content to not reach the bottom of the printed page, but unfortunately there isn't a better solution (prove me wrong!). Another approach is to create a stylesheet that removes all extraneous elements (`display:none`) and causes the main content to flow in one main column. Basically, turn it into a single column, text-only document. Finally, avoid floats and columns when styling for printers, it can make IE (and FF) act wacky.
117,792
<p>I'm interested to know the best / common way of storing a <code>this</code> pointer for use in the <code>WndProc</code>. I know of several approaches, but each as I understand it have their own drawbacks. My questions are:</p> <p>What different ways are there of producing this kind of code:</p> <pre><code>CWindow::WndProc(UINT msg, WPARAM wParam, LPARAM) { this-&gt;DoSomething(); } </code></pre> <p>I can think of Thunks, HashMaps, Thread Local Storage and the Window User Data struct.</p> <p>What are the pros / cons of each of these approaches?</p> <p>Points awarded for code examples and recommendations.</p> <p>This is purely for curiosities sake. After using MFC I've just been wondering how that works and then got to thinking about ATL etc.</p> <p><strong>Edit:</strong> What is the earliest place I can validly use the <code>HWND</code> in the window proc? It is documented as <code>WM_NCCREATE</code> - but if you actually experiment, that's <em>not</em> the first message to be sent to a window.</p> <p><strong>Edit:</strong> ATL uses a thunk for accessing the this pointer. MFC uses a hashtable lookup of <code>HWND</code>s.</p>
[ { "answer_id": 117828, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 3, "selected": false, "text": "<p>I've used SetProp/GetProp to store a pointer to data with the window itself. I'm not sure how it stacks up to the other items you mentioned.</p>\n" }, { "answer_id": 117832, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>You should use <code>GetWindowLongPtr()</code>/<code>SetWindowLongPtr()</code> (or the deprecated <code>GetWindowLong()</code>/<code>SetWindowLong()</code>). They are fast and do exactly what you want to do. The only tricky part is figuring out when to call <code>SetWindowLongPtr()</code> - You need to do this when the first window message is sent, which is <code>WM_NCCREATE</code>.<br>\nSee <a href=\"http://www.gamedev.net/reference/articles/article1810.asp\" rel=\"nofollow noreferrer\">this article</a> for sample code and a more in-depth discussion.</p>\n\n<p>Thread-local storage is a bad idea, since you may have multiple windows running in one thread.</p>\n\n<p>A hash map would also work, but computing the hash function for every window message (and there are a <em>LOT</em>) can get expensive.</p>\n\n<p>I'm not sure how you mean to use thunks; how are you passing around the thunks?</p>\n" }, { "answer_id": 117876, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>In your constructor, call <strong>CreateWindowEx</strong> with \"this\" as the lpParam argument.</p>\n\n<p>Then, on WM_NCCREATE, call the following code:</p>\n\n<pre><code>SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) ((CREATESTRUCT*)lParam)-&gt;lpCreateParams);\nSetWindowPos(hwnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);\n</code></pre>\n\n<p>Then, at the top of your window procedure you could do the following:</p>\n\n<pre><code>MyWindowClass *wndptr = (MyWindowClass*) GetWindowLongPtr(hwnd, GWL_USERDATA);\n</code></pre>\n\n<p>Which allows you to do this:</p>\n\n<pre><code>wndptr-&gt;DoSomething();\n</code></pre>\n\n<p>Of course, you could use the same technique to call something like your function above:</p>\n\n<pre><code>wndptr-&gt;WndProc(msg, wparam, lparam);\n</code></pre>\n\n<p>... which can then use its \"this\" pointer as expected.</p>\n" }, { "answer_id": 118412, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 4, "selected": false, "text": "<p>While using the <strong>SetWindowLongPtr</strong> and <strong>GetWindowLongPtr</strong> to access the <strong>GWL_USERDATA</strong> might sound like a good idea, I would strongly recommend <strong>not</strong> using this approach.</p>\n\n<p>This is the exactly the approached used by the <a href=\"http://www.zeusedit.com/ccpp.html\" rel=\"noreferrer\">Zeus</a> editor and in recent years it has caused nothing but pain.</p>\n\n<p>I think what happens is third party windows messages are sent to <a href=\"http://www.zeusedit.com/ccpp.html\" rel=\"noreferrer\">Zeus</a> that also have their <strong>GWL_USERDATA</strong> value set. One application in particular was a Microsoft tool that provied an alternative way to enter Asian characters in any windows application (i.e. some sort of software keyboard utility).</p>\n\n<p>The problem is <a href=\"http://www.zeusedit.com/ccpp.html\" rel=\"noreferrer\">Zeus</a> always assumes the <strong>GWL_USERDATA</strong> data was set by it and tries to use the data as a <em>this pointer</em>, which then results in a crash.</p>\n\n<p>If I was to do it all again with, what I know now, I would go for a cached hash lookup approach where the window handle is used as the key.</p>\n" }, { "answer_id": 125684, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>With regard to SetWindowLong() / GetWindowLong() security, according to Microsoft:</p>\n\n<blockquote>\n <p>The SetWindowLong function fails if\n the window specified by the hWnd\n parameter does not belong to the same\n process as the calling thread.</p>\n</blockquote>\n\n<p>Unfortunately, until the release of a <a href=\"http://www.microsoft.com/technet/security/bulletin/ms04-032.mspx\" rel=\"nofollow noreferrer\">Security Update</a> on October 12, 2004, Windows <a href=\"http://osdir.com/ml/security.vulnerabilities/2004-10/msg00009.html\" rel=\"nofollow noreferrer\">would not enforce this rule</a>, allowing an application to set any other application's GWL_USERDATA. Therefore, applications running on unpatched systems are vulnerable to attack through calls to SetWindowLong().</p>\n" }, { "answer_id": 7386287, "author": "Vishal", "author_id": 796017, "author_profile": "https://Stackoverflow.com/users/796017", "pm_score": 2, "selected": false, "text": "<p>You can use <code>GetWindowLongPtr</code> and <code>SetWindowLongPtr</code>; use <code>GWLP_USERDATA</code> to attach the pointer to the window. However, if you are writing a custom control I would suggest to use extra window bytes to get the job done. While registering the window class set the <code>WNDCLASS::cbWndExtra</code> to the size of the data like this, <code>wc.cbWndExtra = sizeof(Ctrl*);</code>.</p>\n\n<p>You can get and set the value using <code>GetWindowLongPtr</code> and <code>SetWindowLongPtr</code> with <code>nIndex</code> parameter set to <code>0</code>. This method can save <code>GWLP_USERDATA</code> for other purposes.</p>\n\n<p>The disadvantage with <code>GetProp</code> and <code>SetProp</code>, there will be a string comparison to get/set a property. </p>\n" }, { "answer_id": 23944337, "author": "paulm", "author_id": 1124744, "author_profile": "https://Stackoverflow.com/users/1124744", "pm_score": 0, "selected": false, "text": "<p>In the past I've used the lpParam parameter of <code>CreateWindowEx</code>:</p>\n\n<blockquote>\n <p>lpParam [in, optional] Type: LPVOID</p>\n \n <p>Pointer to a value to be passed to the window through the CREATESTRUCT\n structure (lpCreateParams member) pointed to by the lParam param of\n the WM_CREATE message. This message is sent to the created window by\n this function before it returns. If an application calls CreateWindow\n to create a MDI client window, lpParam should point to a\n CLIENTCREATESTRUCT structure. If an MDI client window calls\n CreateWindow to create an MDI child window, lpParam should point to a\n MDICREATESTRUCT structure. lpParam may be NULL if no additional data\n is needed.</p>\n</blockquote>\n\n<p>The trick here is to have a <code>static</code> <code>std::map</code> of HWND to class instance pointers. Its possible that the <code>std::map::find</code> might be more performant than the <code>SetWindowLongPtr</code> method. Its certainly easier to write test code using this method though.</p>\n\n<p>Btw if you are using a win32 dialog then you'll need to use the <code>DialogBoxParam</code> function.</p>\n" }, { "answer_id": 32916389, "author": "adigostin", "author_id": 451036, "author_profile": "https://Stackoverflow.com/users/451036", "pm_score": 2, "selected": false, "text": "<p>I recommend setting a <code>thread_local</code> variable just before calling <code>CreateWindow</code>, and reading it in your <code>WindowProc</code> to find out the <code>this</code> variable (I presume you have control over <code>WindowProc</code>).</p>\n\n<p>This way you'll have the <code>this</code>/<code>HWND</code> association on the very first message sent to you window.</p>\n\n<p>With the other approaches suggested here chances are you'll miss on some messages: those sent before <code>WM_CREATE</code> / <code>WM_NCCREATE</code> / <code>WM_GETMINMAXINFO</code>.</p>\n\n<pre><code>class Window\n{\n // ...\n static thread_local Window* _windowBeingCreated;\n static thread_local std::unordered_map&lt;HWND, Window*&gt; _hwndMap;\n // ...\n HWND _hwnd;\n // ...\n // all error checking omitted\n // ...\n void Create (HWND parentHWnd, UINT nID, HINSTANCE hinstance)\n {\n // ...\n _windowBeingCreated = this;\n ::CreateWindow (YourWndClassName, L\"\", WS_CHILD | WS_VISIBLE, x, y, w, h, parentHWnd, (HMENU) nID, hinstance, NULL);\n }\n\n static LRESULT CALLBACK Window::WindowProcStatic (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)\n {\n Window* _this;\n if (_windowBeingCreated != nullptr)\n {\n _hwndMap[hwnd] = _windowBeingCreated;\n _windowBeingCreated-&gt;_hwnd = hwnd;\n _this = _windowBeingCreated;\n windowBeingCreated = NULL;\n }\n else\n {\n auto existing = _hwndMap.find (hwnd);\n _this = existing-&gt;second;\n }\n\n return _this-&gt;WindowProc (msg, wparam, lparam);\n }\n\n LRESULT Window::WindowProc (UINT msg, WPARAM wparam, LPARAM lparam)\n {\n switch (msg)\n {\n // ....\n</code></pre>\n" }, { "answer_id": 53358637, "author": "johnathan", "author_id": 772515, "author_profile": "https://Stackoverflow.com/users/772515", "pm_score": 1, "selected": false, "text": "<p>ATL's thunk is the most efficent. the thunk executes once and replaces the callback function for the WINPROC to the classes own message processing member function. subsiquent messages are passed by a direct call to the classes member function by windows. it doesnt get any faster than that.</p>\n" }, { "answer_id": 63434487, "author": "SuperSim135", "author_id": 8338615, "author_profile": "https://Stackoverflow.com/users/8338615", "pm_score": 0, "selected": false, "text": "<p>In order to prevent the problem that occurred in the Zeus editor, simply specify the window in the GetMessage function:</p>\n<pre><code>BOOL GetMessage(\nLPMSG lpMsg,\nHWND hWnd, /*A handle to the window whose messages are to be retrieved.*/\nUINT wMsgFilterMin,\nUINT wMsgFilterMax\n);\n</code></pre>\n<p><strong>NOTE</strong>\nThe window must belong to the current thread.</p>\n<p><a href=\"https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage\" rel=\"nofollow noreferrer\">Easy to read Documentation of the function </a></p>\n" }, { "answer_id": 65876605, "author": "dialer", "author_id": 653473, "author_profile": "https://Stackoverflow.com/users/653473", "pm_score": 4, "selected": false, "text": "<p>This question has many duplicates and almost-duplicates on SO, yet almost none of the answers I've seen explore the pitfalls of their chosen solutions.</p>\n<p>There are several ways how to associate an arbitrary data pointer with a window, and there are 2 different situations to consider. Depending on the situation, the possibilities are different.</p>\n<p>Situation 1 is when you are authoring the window class. This means you are implementing the <code>WNDPROC</code>, and it is your intention that other people use your window class in their applications. You generally do not know who will use your window class, and for what.</p>\n<p>Situation 2 is when you are using a window class that already exists in your own application. In general, you do not have access to the window class source code, and you cannot modify it.</p>\n<p>I'm assuming that the problem <em>isn't</em> getting the data pointer into the <code>WNDPROC</code> initially (that would just be the through the <code>CREATESTRUCT</code> with the <code>lpParam</code> parameter in <code>CreateWindow[ExW]</code>), but rather, how to store it for subsequent calls.</p>\n<h2>Method 1: cbWndExtra</h2>\n<p>When Windows creates an instance of a window, it internally allocates a <code>WND</code> struct. This struct has a certain size, contains all sorts of window-related things, like its position, its window class, and its current WNDPROC. At the end of this struct, Windows optionally allocates a number of additional bytes that belong to the struct. The number is specified in <code>WNDCLASSEX.cbWndExtra</code>, which is used in <code>RegisterWindowClassEx</code>.</p>\n<p>This implies that this method can only be used if you are the person who registers the window class, i.e. you are <em>authoring the window class</em>.</p>\n<p>Applications cannot directly access the <code>WND</code> struct. Instead, use <code>GetWindowLong[Ptr]</code>. Non-negative indices access memory inside the extra bytes at the end of the struct. &quot;0&quot; will access the first extra bytes.</p>\n<p>This is a clean, and fast way of doing it, if you are authoring the window class. Most Windows internal controls seem to use this method.</p>\n<p>Unfortunately, this method does not play so well with dialogs (<code>DialogBox</code> family). You would have a dialog window class in addition to providing the dialog template, which can become cumbersome to maintain (unless you need to do so for other reasons anyway). If you do want to use it with dialogs, you must specify the window class name in the dialog template, make sure this window class is registered before showing the dialog, and you need to implement a <code>WNDPROC</code> for the dialog (or use <code>DefDlgProc</code>). Furthermore, all dialogs already reserve a certain amount of bytes in <code>cbWndExtra</code> for the dialog manager to function properly. The number of extra bytes needed is the <code>DLGWINDOWEXTRA</code> constant. This means <em>your</em> stuff needs to come <em>after</em> the extra bytes which are already reserved by the dialog. Offset all accesses to the extra memory by <code>DLGWINDOWEXTRA</code> (including the value of <code>cbWndExtra</code> which you specify in your window class).</p>\n<p>See also below for an extra method exclusive to dialogs.</p>\n<h2>Method 2: GWLP_USERDATA</h2>\n<p>The aforementioned <code>WND</code> struct happens to contain one pointer-sized field, which is not used by the system. It is accessed using <code>GetWindowLongPtr</code> with a negative index (namely, <code>GWLP_USERDATA</code>). A negative index will access fields inside the <code>WND</code> structure. Note that according to <a href=\"https://winterdom.com/dev/ui/wnd/\" rel=\"nofollow noreferrer\">this</a>, the negative indices do not seem to represent memory offsets, but are arbitrary.</p>\n<p>The problem with <code>GWLP_USERDATA</code> is that it is not clear, and it has not been clear in the past, what <em>exactly</em> the purpose of this field is, and hence, who the owner of this field is. See also <a href=\"https://stackoverflow.com/questions/41521809/who-is-owner-of-gwlp-userdata-cell\">this question</a>. <em>The general consensus is that there is no consensus.</em> It is likely that <code>GWLP_USERDATA</code> was meant to be used by <em>users of the window</em>, and not <em>authors of the window class</em>. This implies that using it inside of the WNDPROC is strictly incorrect, as the WNDPROC is always provided by the window class author.</p>\n<p>I am personally convinced that this is the intention of the engineers that came up with <code>GWLP_USERDATA</code> simply because if it is true, then the API as a whole is sound, extensible, and future-proof. But if it is not true, then the API is neither of those, and it would be redundant with <code>cbWndExtra</code>.</p>\n<p>All standard windows controls that I am aware of (e.g. <code>BUTTON</code>, <code>EDIT</code>, etc.) adhere to this and do not use <code>GWLP_USERDATA</code> internally, leaving it free for the window which <em>uses</em> these controls. The problem is that there are WAY too many examples, including on MSDN and on SO, which break this rule and use <code>GWLP_USERDATA</code> for implementation of the window class. This effectively takes away the cleanest and simplest method for a control <em>user</em> to associate a context pointer with it, simply because way too many people are doing it &quot;wrong&quot; (according to my definition of &quot;wrong&quot;). At worst, the user code does not know that <code>GWLP_USERDATA</code> is occupied, and may overwrite it, which would likely crash the application.</p>\n<p>Because of this longstanding dispute about the ownership of <code>GWLP_USERDATA</code>, it is not generally safe to use it. If you are <em>authoring</em> a window class, you probably never should have used it anyway. If you are <em>using</em> a window, you should only do so if you are certain that it is not used by the window class.</p>\n<h2>Method 3: SetProp</h2>\n<p>The <code>SetProp</code> family of functions implements access to a property table. Each window has its own, independent properties. The key of this table is a string at API surface level, but internally it is really an ATOM.</p>\n<p><code>SetProp</code> can be used by window class <em>authors</em>, and window <em>users</em>, and it has issues too, but they are different from <code>GWLP_USERDATA</code>. You must make sure that the strings used as the property keys do not collide. The window user may not necessarily know what strings the window class author is using internally. Even though conflicts are unlikely, you can avoid them entirely by using a GUID as string, for example. As is evident when looking at the contents of the global ATOM table, many programs use GUIDs this way.</p>\n<p><code>SetProp</code> must be used with care. Most resources do not explain the pitfalls of this function. Internally, it uses <code>GlobalAddAtom</code>. This has several implications, which need to be considered when using this function:</p>\n<ul>\n<li><p>When calling <code>SetProp</code> (or any other API that uses the global ATOM table), instead of a string, you can use an <code>ATOM</code>, which you get when you register a new string <code>GlobalAddAtom</code>. An ATOM is just an integer which refers to one entry in the ATOM table. This will improve performance; <code>SetProp</code> internally always uses <code>ATOM</code>s as property keys, never strings. Passing a string causes <code>SetProp</code> and similar functions to internally search the ATOM table for a match first. Passing an <code>ATOM</code> directly skips searching the string in the global atom table.</p>\n</li>\n<li><p>The number of possible string atoms in the global atom table is limited to 16384, system-wide. This is because atoms are 16-bit uints ranging from <code>0xC000</code> to <code>0xFFFF</code> (all values below <code>0xC000</code> are pseudo-atoms pointing to fixed strings (which are perfectly fine to use, but you cannot guarantee that nobody else is using them)). It is a bad idea to use many different property names, let alone if those names are dynamically generated at runtime. Instead, you can use a single property to store a pointer to a structure that contains all the data you need.</p>\n</li>\n<li><p>If you are using a GUID, it is safe to use the same GUID for <em>every</em> window you are working with, even across different software projects, since every window has its own properties. This way, all of your software will only use up at most <em>two</em> entries in the global atom table (you'll need at most one GUID as a window class author, and at most one GUID as a window class user). In fact, it might make sense to define two de-facto standard GUIDs everyone can use for their context pointers (realistically not going to happen).</p>\n</li>\n<li><p>Because properties use <code>GlobalAddAtom</code>, you must make sure that the atoms are unregistered. Global atoms are not cleaned up when the process exists and will clog up the global atom table until the operating system is restarted. To do this, you must make sure that <code>RemoveProp</code> is called. A good place for this is usually <code>WM_NCDESTROY</code>.</p>\n</li>\n<li><p>Global atoms are reference-counted. This implies that the counter can overflow at some point. To protect against overflows, once the reference count of an atom reaches 65536, the atom will stay in the atom table forever, and no amount of <code>GlobalDeleteAtom</code> can get rid of it. The operating system must be restarted to free the atom table in this case.</p>\n</li>\n</ul>\n<p>Avoid having many different atom names if you want to use <code>SetProp</code>. Other than that, <code>SetProp</code>/<code>GetProp</code> is a very clean and defensive approach. The dangers of atom leaks could be greatly mitigated if developers agreed upon using the same 2 atom names for all windows, but that is not going to happen.</p>\n<h2>Method 4: SetWindowSubclass</h2>\n<p><code>SetWindowSubclass</code> is meant to allow overriding the <code>WNDPROC</code> of a specific window, so that you can handle some messages in your own callback, and delegate the rest of the messages to the original <code>WNDPROC</code>. For example, this can be used to listen for specific key combinations in an <code>EDIT</code> control, while leaving the rest of the messages to its original implementation.</p>\n<p>A convenient side effect of <code>SetWindowSubclass</code> is that the <em>new</em>, replacement <code>WNDPROC</code> is not actually a <code>WNDPROC</code>, but a <code>SUBCLASSPROC</code>.</p>\n<p><code>SUBCLASSPROC</code> has 2 additional parameters, one of them is <code>DWORD_PTR dwRefData</code>. This is arbitrary pointer-sized data. The data comes from you, through the last parameter to <code>SetWindowSubclass</code>. The data is then passed to <em>every invocation</em> of the replacement <code>SUBCLASSPROC</code>. If only <em>every</em> <code>WNDPROC</code> had this parameter, then we wouldn't be in this horrible situation!</p>\n<p>This method only helps the window class author.<sup>(1)</sup> During the initial creation of the window (e.g. <code>WM_CREATE</code>), the window subclasses itself (it can allocate memory for the <code>dwRefData</code> right there if that's appropriate). Deallocation probably best in <code>WM_NCDESTROY</code>. The rest of the code that would normally go in <code>WNDPROC</code> is moved to the replacement <code>SUBCLASSPROC</code> instead.</p>\n<p>It can even be used in a dialog's own <code>WM_INITDIALOG</code> message. If the dialog is shown with <code>DialogParamW</code>, the last parameter can be used as <code>dwRefData</code> in a <code>SetWindowSubclass</code> call in the <code>WM_INITDIALOG</code> message. Then, all the rest of the dialog logic goes in the new <code>SUBCLASSPROC</code>, which will receive this <code>dwRefData</code> for every message. Note that this changes semantics slightly. You are now writing at the level of the dialog's <em>window</em> procedure, not the dialog procedure.</p>\n<p>Internally, <code>SetWindowSubclass</code> uses a property (using <code>SetProp</code>) whose atom name is <code>UxSubclassInfo</code>. Every instance of <code>SetWindowSubclass</code> uses this name, so it will already be in the global atom table on practically any system. It replaces the window's original <code>WNDPROC</code> with a <code>WNDPROC</code> called <code>MasterSubclassProc</code>. That function uses the data in the <code>UxSubclassInfo</code> property to get the <code>dwRefData</code> and call all registered <code>SUBCLASSPROC</code> functions. This also implies that you should probably not use <code>UxSubclassInfo</code> as your own property name for anything.</p>\n<h2>Method 5: Thunk</h2>\n<p>A thunk is a small function whose machine code is dynamically generated at run-time in memory. Its purpose is to call another function, but with additional parameters that seem to magically come out of nowhere.</p>\n<p>This would let you define a function which is like <code>WNDPROC</code>, but it has one additional parameter. This parameter could be the equivalent of a &quot;this&quot; pointer. Then, when creating the window, you replace the original stub <code>WNDPROC</code> with a thunk that calls the real, pseudo-<code>WNDPROC</code> with an additional parameter.</p>\n<p>The way this works is that when the thunk is created, it generates machine code in memory for a load instruction, loading the value of the extra parameter as a <em>constant</em>, and then a jump instruction to the address of the function which would normally require an additional parameter. The thunk itself can then be called as if it were a regular <code>WNDPROC</code>.</p>\n<p>This method can be used by window class authors and is extremely fast. However, the implementation is not trivial. The <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/atlthunk/nf-atlthunk-atlthunk_initdata\" rel=\"nofollow noreferrer\"><code>AtlThunk</code></a> family of functions implements this, but with a quirk. It does not add an <em>extra</em> parameter. Instead, it <em>replaces</em> the <code>HWND</code> parameter of <code>WNDPROC</code> with your arbitrary piece of data (pointer-sized). However, that is not a big problem since your arbitrary data may be a pointer to a struct containing the <code>HWND</code> of the window.</p>\n<p>Similarly to the <code>SetWindowSubclass</code> method, you would create the thunk during window creation, using an arbitrary data pointer. Then, replace the window's <code>WNDPROC</code> with the thunk. All the real work goes in the new, pseudo-<code>WNDPROC</code> which is targeted by the thunk.</p>\n<p>Thunks do not mess with the global atom table at all, and there are no string uniqueness considerations either. However, like everything else that is allocated in heap memory, they must be freed, and after that, the thunk may no longer be called. Since <code>WM_NCDESTROY</code> is the last message a window receives, this is the place to do that. Otherwise, you must make sure to reinstall the original <code>WNDPROC</code> when freeing the thunk.</p>\n<p>Note that this method of smuggling a &quot;this&quot; pointer into a callback function is practically ubiquitous in many ecosystems, including C# interop with native C functions.</p>\n<h2>Method 6: Global lookup table</h2>\n<p>No long explanation needed. In your application, implement a global table where you store <code>HWND</code>s as keys and context data as values. You are responsible for cleaning up the table, and, if needed, to make it sufficiently fast.</p>\n<p>Window class authors can use private tables for their implementations, and window users can use their own tables to store application-specific information. There are no concerns about atoms or string uniqueness.</p>\n<h2>Bottom line</h2>\n<p>These methods work if you are the <em>Window Class Author</em>:</p>\n<p>cbWndExtra, (GWLP_USERDATA), SetProp, SetWindowSubclass, Thunk, Global lookup table.</p>\n<p>Window Class Author means that you are writing the <code>WNDPROC</code> function. For example, you may be implementing a custom picture box control, which allows the user to pan and zoom. You may need additional data to store pan/zoom data (e.g. as a 2D transformation matrix), so that you can implement your <code>WM_PAINT</code> code correctly.</p>\n<p>Recommendation: Avoid GWLP_USERDATA because the user code may rely on it; use cbWndExtra if possible.</p>\n<p>These methods work if you are the <em>Window User</em>:</p>\n<p>GWLP_USERDATA, SetProp, Global lookup table.</p>\n<p>Window User means you are creating one or more of the windows and use them in your own application. For example, you may be creating a variable number of buttons dynamically, and each of them is associated with a different piece of data that is relevant when it is being clicked.</p>\n<p>Recommendation: Use GWLP_USERDATA if it's a standard Windows control, or you are sure that the control doesn't use it internally. Otherwise, <code>SetProp</code>.</p>\n<h2>Extra mention when using dialogs</h2>\n<p>Dialogs, by default, use a window class that has <code>cbWndExtra</code> set to <code>DLGWINDOWEXTRA</code>. It is possible to define your own window class for a dialog, where you allocate, say, <code>DLGWINDOWEXTRA + sizeof(void*)</code>, and then access <code>GetWindowLongPtrW(hDlg, DLGWINDOWEXTRA)</code>. But while doing so you will find yourself having to answer questions you won't like. For example, which <code>WNDPROC</code> do you use (answer: you can use <code>DefDlgProc</code>), or which class styles do you use (the default dialogs happen to use <code>CS_SAVEBITS | CS_DBLCLKS</code>, but good luck finding an authoritative reference).</p>\n<p>Within the <code>DLGWINDOEXTRA</code> bytes, dialogs happen to reserve a pointer-sized field, which can be accessed using <code>GetWindowLongPtr</code> with index <code>DWLP_USER</code>. This is kind of an additional <code>GWLP_USERDATA</code>, and, in theory, has the same problems. In practice I have only ever seen this used inside the <code>DLGPROC</code> which ends up being passed to <code>DialogBox[Param]</code>. After all, the <em>window user</em> still has <code>GWLP_USERDATA</code>. So it is probably safe to use for the <em>window class implementation</em> in practically every situation.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
I'm interested to know the best / common way of storing a `this` pointer for use in the `WndProc`. I know of several approaches, but each as I understand it have their own drawbacks. My questions are: What different ways are there of producing this kind of code: ``` CWindow::WndProc(UINT msg, WPARAM wParam, LPARAM) { this->DoSomething(); } ``` I can think of Thunks, HashMaps, Thread Local Storage and the Window User Data struct. What are the pros / cons of each of these approaches? Points awarded for code examples and recommendations. This is purely for curiosities sake. After using MFC I've just been wondering how that works and then got to thinking about ATL etc. **Edit:** What is the earliest place I can validly use the `HWND` in the window proc? It is documented as `WM_NCCREATE` - but if you actually experiment, that's *not* the first message to be sent to a window. **Edit:** ATL uses a thunk for accessing the this pointer. MFC uses a hashtable lookup of `HWND`s.
In your constructor, call **CreateWindowEx** with "this" as the lpParam argument. Then, on WM\_NCCREATE, call the following code: ``` SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) ((CREATESTRUCT*)lParam)->lpCreateParams); SetWindowPos(hwnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER); ``` Then, at the top of your window procedure you could do the following: ``` MyWindowClass *wndptr = (MyWindowClass*) GetWindowLongPtr(hwnd, GWL_USERDATA); ``` Which allows you to do this: ``` wndptr->DoSomething(); ``` Of course, you could use the same technique to call something like your function above: ``` wndptr->WndProc(msg, wparam, lparam); ``` ... which can then use its "this" pointer as expected.
117,844
<p>I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation?</p>
[ { "answer_id": 117862, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 3, "selected": false, "text": "<p>You can use strtol</p>\n\n<pre><code>char string[] = \"1101110100110100100000\";\nchar * end;\nlong int value = strtol (string,&amp;end,2);\n</code></pre>\n" }, { "answer_id": 117870, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 6, "selected": true, "text": "<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(void) {\n char * ptr;\n long parsed = strtol(\"11110111\", &amp; ptr, 2);\n printf(\"%lX\\n\", parsed);\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>For larger numbers, there as a <code>long long</code> version, <code>strtoll</code>.</p>\n" }, { "answer_id": 118009, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 4, "selected": false, "text": "<p>You can use std::bitset (if then length of your bits is known at compile time)<br>\nThough with some program you could break it up into chunks and combine.</p>\n\n<pre><code>#include &lt;bitset&gt;\n#include &lt;iostream&gt;\n\nint main()\n{\n std::bitset&lt;5&gt; x(std::string(\"01011\"));\n\n std::cout &lt;&lt; x &lt;&lt; \":\" &lt;&lt; x.to_ulong() &lt;&lt; std::endl;\n}\n</code></pre>\n" }, { "answer_id": 119446, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 3, "selected": false, "text": "<p>You can use Boost Dynamic Bitset:</p>\n\n<pre><code>boost::dynamic_bitset&lt;&gt; x(std::string(\"01011\"));\nstd::cout &lt;&lt; x &lt;&lt; \":\" &lt;&lt; x.to_ulong() &lt;&lt; std::endl;\n</code></pre>\n" }, { "answer_id": 63068058, "author": "PentiumPro200", "author_id": 3100538, "author_profile": "https://Stackoverflow.com/users/3100538", "pm_score": 0, "selected": false, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\nstring getBinaryString(int value, unsigned int length, bool reverse) {\n string output = string(length, '0');\n if (!reverse) {\n for (unsigned int i = 0; i &lt; length; i++) {\n if ((value &amp; (1 &lt;&lt; i)) != 0) {\n output[i] = '1';\n }\n }\n }\n else {\n for (unsigned int i = 0; i &lt; length; i++) {\n if ((value &amp; (1 &lt;&lt; (length - i - 1))) != 0) {\n output[i] = '1';\n }\n }\n }\n return output;\n}\n\nunsigned long getInteger(const string&amp; input, size_t lsbindex, size_t msbindex) {\n unsigned long val = 0;\n unsigned int offset = 0;\n if (lsbindex &gt; msbindex) {\n size_t length = lsbindex - msbindex;\n for (size_t i = msbindex; i &lt;= lsbindex; i++, offset++) {\n if (input[i] == '1') {\n val |= (1 &lt;&lt; (length - offset));\n }\n }\n }\n else { //lsbindex &lt; msbindex\n for (size_t i = lsbindex; i &lt;= msbindex; i++, offset++) {\n if (input[i] == '1') {\n val |= (1 &lt;&lt; offset);\n }\n }\n }\n return val;\n}\n\nint main() {\n int value = 23;\n cout &lt;&lt; value &lt;&lt; &quot;: &quot; &lt;&lt; getBinaryString(value, 5, false) &lt;&lt; endl;\n string str = &quot;01011&quot;;\n cout &lt;&lt; str &lt;&lt; &quot;: &quot; &lt;&lt; getInteger(str, 1, 3) &lt;&lt; endl;\n}\n</code></pre>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1582/" ]
I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation?
``` #include <stdio.h> #include <stdlib.h> int main(void) { char * ptr; long parsed = strtol("11110111", & ptr, 2); printf("%lX\n", parsed); return EXIT_SUCCESS; } ``` For larger numbers, there as a `long long` version, `strtoll`.
117,851
<p>For example if I'm working on Visual Studio 2008, I want the values devenv and 2008 or 9.</p> <p>The version number is very important...</p>
[ { "answer_id": 117971, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 0, "selected": false, "text": "<p>This <a href=\"http://www.codeproject.com/KB/cs/windowhider.aspx\" rel=\"nofollow noreferrer\">project</a> demonstrates the two functions you need: <a href=\"http://msdn.microsoft.com/en-us/library/ms633497(VS.85).aspx\" rel=\"nofollow noreferrer\">EnumWindows</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms633520(VS.85).aspx\" rel=\"nofollow noreferrer\">GetWindowtext</a></p>\n" }, { "answer_id": 117976, "author": "jdmichal", "author_id": 12275, "author_profile": "https://Stackoverflow.com/users/12275", "pm_score": 0, "selected": false, "text": "<p>Can you clarify your question? Do you mean you want a program running, which will tell you data about the program in the active window? Or that you want your program to report out its own version?</p>\n\n<p>What you're looking for to get the information either way is <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.aspx\" rel=\"nofollow noreferrer\">System.Reflection.Assembly</a>. (See code examples in the link.)</p>\n\n<p>How to get the assembly from an external program? That one I'm not sure about...</p>\n" }, { "answer_id": 117980, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 4, "selected": true, "text": "<p>This is going to be PInvoke city...</p>\n\n<p>You'll need to PInvoke the following API's in User32.dll</p>\n\n<p>Win32::GetForegroundWindow() in returns the HWND of the currently active window.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// The GetForegroundWindow function returns a handle to the foreground window.\n/// &lt;/summary&gt;\n[DllImport(\"user32.dll\")]\nstatic extern IntPtr GetForegroundWindow();\n</code></pre>\n\n<p>Win32::GetWindowThreadProcessId(HWND,LPDWORD) returns the PID of a given HWND</p>\n\n<pre><code>[DllImport(\"user32.dll\", SetLastError=true)]\nstatic extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n</code></pre>\n\n<p>In C#</p>\n\n<p>Process.GetProcessByID() takes the PID to create a C# process object</p>\n\n<p>processInstance.MainModule returns a ProcessModule with FileVersionInfo attached.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44972/" ]
For example if I'm working on Visual Studio 2008, I want the values devenv and 2008 or 9. The version number is very important...
This is going to be PInvoke city... You'll need to PInvoke the following API's in User32.dll Win32::GetForegroundWindow() in returns the HWND of the currently active window. ``` /// <summary> /// The GetForegroundWindow function returns a handle to the foreground window. /// </summary> [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); ``` Win32::GetWindowThreadProcessId(HWND,LPDWORD) returns the PID of a given HWND ``` [DllImport("user32.dll", SetLastError=true)] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); ``` In C# Process.GetProcessByID() takes the PID to create a C# process object processInstance.MainModule returns a ProcessModule with FileVersionInfo attached.
117,900
<p>I have an application that loads external SWF files and plays them inside a Adobe Flex / Air application via the <a href="http://livedocs.adobe.com/flex/3/html/controls_15.html" rel="nofollow noreferrer">SWFLoader Flex component</a>. I have been trying to find a way to unload them from a button click event. I have Google'd far and wide and no one seems to have been able to do it without a hack. The combination of code I see people use is:</p> <pre><code>swfLoader.source = ""; // Removes the external link to the SWF. swfLoader.load(null); // Forces the loader to try to load nothing. // Note: At this point sound from the SWF is still playing, and // seems to still be playing in memory. flash.media.SoundMixer.stopAll(); // Stops the sound. This works on my development machine, but not // on the client's. </code></pre> <p>If the SWFs are closed (hidden) this way, eventually the program crashes.</p> <p>Any ideas? I have found tons of posts in various forums with people having the same problem. I assume I will get one wrong/incomplete answer here, and than my post will sink into nothingness as usual, but either way, thanks in advance!</p> <p><em>Edit 1</em>: I can't edit the actual SWF movies, they're created by the client. If I can't close any SWF opened through Flex, isn't that a problem with the Flex architecture? Is my only option sending the SWFs to the web browser?</p>
[ { "answer_id": 118026, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 1, "selected": false, "text": "<p>The problem resides in the loaded swf, it simply does not clean up the audio after itself.\nTry attaching an unload event onto movieclips like this:</p>\n\n<pre><code>MovieClip(event.target.content).loaderInfo.addEventListener(Event.UNLOAD, unloadMovieClipHandler);\nprivate function unloadMovieClipHandler(event:Event) : void\n{\n SoundMixer.stopAll(); \n} \n</code></pre>\n" }, { "answer_id": 118461, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 0, "selected": false, "text": "<p>Try the following:</p>\n\n<pre><code>try {\n new LocalConnection().connect('foo');\n new LocalConnection().connect('foo');\n} catch (e:*) {}\n</code></pre>\n\n<p>That will force a Garbage Collection routine. If your SWF is still attached, then you've missed some sort of connection, like the audio. </p>\n\n<p>There are a couple ways to force GC, which all kind of suck because they spike CPU, but the good news is that an official way is coming in Flash Player 10:</p>\n\n<pre><code>unloadAndStop\n</code></pre>\n\n<p>link: <a href=\"http://www.gskinner.com/blog/archives/2008/07/unloadandstop_i.html\" rel=\"nofollow noreferrer\">http://www.gskinner.com/blog/archives/2008/07/unloadandstop_i.html</a></p>\n\n<p>Until then, I'm afraid you'll have to force it with hacks like I showed above.</p>\n" }, { "answer_id": 118640, "author": "Brian Hodge", "author_id": 20628, "author_profile": "https://Stackoverflow.com/users/20628", "pm_score": 0, "selected": false, "text": "<p>You have not shown all of your code so I am going to assume you didn't use the unload method of the Loader class. Also swfLoader.load(null) seems wrong to me as the load method is expecting a URLRequest object. When you want to clean things up at the end, set the object's value to null instead of calling a null load. The fact that your still hearing audio indicates that your data wasn't unloaded, or the audio file does not reside inside the content that was unloaded. Lets walk through this.</p>\n\n<p>Example below<pre><code>\nvar loader:Loader = new Loader();\nvar request:URLRequest = new URLRequest('test.swf');\nloader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSwfLoad, false, 0, true);</p>\n\n<p>function onSwfLoad(e:Event):void\n{\n addChild(loader);\n loader.contentLoaderInfo.addEventListener(Event.UNLOAD, onLoaderUnload, false, 0, true);</p>\n\n<p>loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onSwfLoad, false);\n}\nfunction onLoaderUnload(e:Event):void\n{\n trace('LOADER WAS SUCCESSFULLY UNLOADED.');\n}\n//Now to remove this with the click of a button, assuming the buttons name is button_mc\nbutton_mc.addEventListener(MouseEvent.MOUSE_DOWN, onButtonDown, false, 0, true);</p>\n\n<p>function onButtonDown(e:MouseEvent):void\n{\n loader.unload();\n loader.contentLoaderInfo.removeEventListener(Event.UNLOAD, onLoaderUnload);\n //When you want to remove things completely from memory you simply set their value to null.\n loader = null;\n <code>button_mc.removeEventListener(MouseEvent.MOUSE_DOWN, onButtonDown);</code>\n}\n</code>\n</pre>\nI do hope that this was helpful, and I am sorry if it was redundant, but without seeing your code I have no way of knowing exactly how you approached this.</p>\n" }, { "answer_id": 119481, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "<p>It is a problem that a badly created SWF can sink your application, and many of the issues with this will be fixed in Flash Player 10, as others have mentioned. However, regardless of platform you will always risk having problems if you load third party code, there's always the possibility that it contains bugs, memory leaks or downright malicious code. Unless you can load content into a sandbox (and you can't in Flash, at least not yet), loading bad things will sink your app, it's as simple as that.</p>\n\n<p>I'm sorry to say that unless you can guarantee the quality of the loaded content you can't guarantee the quality of your own application. Flash developers are notorious for writing things that leak, or can't be unloaded, because Flash makes it easy to do the wrong thing, especially for things that live on the time line. Loading any Flash content that you don't have control over directly is very perilous.</p>\n" }, { "answer_id": 224447, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>... isn't that a problem with the Flex architecture?</p>\n</blockquote>\n\n<p>Yes it is, and it also affects Flash in general. Until you can take advantage of the <a href=\"http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/Loader.html\" rel=\"noreferrer\">Loader.unloadAndStop()</a> method in FP10 (AIR 1.5), you can't guarantee that externally loaded content will not continue to consume memory and cpu resources, even if you use the <code>Loader.unload()</code> method. (To be honest, I'm not 100% sure that even that will guarantee freeing of resources, but maybe I'm a pessimist.)</p>\n\n<p>The next best thing is for you to insist that the creators of the content you load adhere to a set of guidelines, including exposing something like a <code>dispose()</code> method which your app can call to ask it to release as many resources as possible before you <code>unload()</code> it. If this isn't possible, then your application will almost definitely bloat in memory and cpu usage each time you load an external swf. Sorry. </p>\n\n<p>If it makes you feel any better, you're not alone. ;)</p>\n" }, { "answer_id": 448992, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I'd generally stay away from SWFLoader and use the classes in the mx.modules package. </p>\n\n<p>Flex has a module system that enables this type of behavior. You can check it out here : <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=modular_3.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/html/help.html?content=modular_3.html</a> . In general, dynamically loading and unloading swf components is tricky, especially if those modules modify any global state in the application (styles, etc..). But if you create an interface for your modules, and then each class you load/unload implement that interface as well as extend the flex module class, you can load and unload them cleanly. </p>\n" }, { "answer_id": 15096611, "author": "Yury Euceda", "author_id": 706435, "author_profile": "https://Stackoverflow.com/users/706435", "pm_score": 2, "selected": false, "text": "<p>The best solution is </p>\n\n<pre><code>swfLoader.autoLoad = false;\nswfLoader.unloadAndStop();\nswfLoader.autoLoad = true;\n</code></pre>\n\n<p>In this way you stop the player, unload the content from memory and avoid the sound to remain playing..\nCheers</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
I have an application that loads external SWF files and plays them inside a Adobe Flex / Air application via the [SWFLoader Flex component](http://livedocs.adobe.com/flex/3/html/controls_15.html). I have been trying to find a way to unload them from a button click event. I have Google'd far and wide and no one seems to have been able to do it without a hack. The combination of code I see people use is: ``` swfLoader.source = ""; // Removes the external link to the SWF. swfLoader.load(null); // Forces the loader to try to load nothing. // Note: At this point sound from the SWF is still playing, and // seems to still be playing in memory. flash.media.SoundMixer.stopAll(); // Stops the sound. This works on my development machine, but not // on the client's. ``` If the SWFs are closed (hidden) this way, eventually the program crashes. Any ideas? I have found tons of posts in various forums with people having the same problem. I assume I will get one wrong/incomplete answer here, and than my post will sink into nothingness as usual, but either way, thanks in advance! *Edit 1*: I can't edit the actual SWF movies, they're created by the client. If I can't close any SWF opened through Flex, isn't that a problem with the Flex architecture? Is my only option sending the SWFs to the web browser?
> > ... isn't that a problem with the Flex architecture? > > > Yes it is, and it also affects Flash in general. Until you can take advantage of the [Loader.unloadAndStop()](http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/Loader.html) method in FP10 (AIR 1.5), you can't guarantee that externally loaded content will not continue to consume memory and cpu resources, even if you use the `Loader.unload()` method. (To be honest, I'm not 100% sure that even that will guarantee freeing of resources, but maybe I'm a pessimist.) The next best thing is for you to insist that the creators of the content you load adhere to a set of guidelines, including exposing something like a `dispose()` method which your app can call to ask it to release as many resources as possible before you `unload()` it. If this isn't possible, then your application will almost definitely bloat in memory and cpu usage each time you load an external swf. Sorry. If it makes you feel any better, you're not alone. ;)
117,931
<p>I'm building a fairly large website and my .htaccess is starting to feel a bit bloated, is there a way of replacing my current system of - one rule for each of the possibile number of vars that could be passed, to one catch all expression that can account for varying numbers of inputs ?</p> <p>for example I currently have:</p> <pre><code>RewriteRule ^([a-z]+)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)$ /index.php?mode=$1&amp;id=$2&amp;$3=$4&amp;$5=$6 RewriteRule ^([a-z]+)/([^/]*)/([^/]*)/([^/]*)$ /index.php?mode=$1&amp;id=$2&amp;$3=$4 RewriteRule ^([a-z]+)/([^/]*)$ /index.php?mode=$1&amp;id=$2 RewriteRule ^([a-z]+)$ /index.php?mode=$1 </code></pre> <p>the first backreference is always the <em>mode</em> and (if any more exist) the second is always <em>id</em>, thereafter any further backreferences alternate between the name of the input and its value</p> <pre><code>http://www.example.com/search http://www.example.com/search/3039/sort_by/name_asc/page/23 </code></pre> <p>I would love to be able to have one expression to gracefully handle all the inputs.</p>
[ { "answer_id": 117968, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 4, "selected": true, "text": "<p>Do like Drupal:</p>\n\n<pre><code> RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]\n</code></pre>\n\n<p>And then handle all the stuff in your script using php code something like this</p>\n\n<pre><code>$pathmap = ();\nif ($_GET[\"q\"]){\n $path = split(\"/\", $_GET[\"q\"]);\n for ($i=0; $i+1&lt;count($path); $i++){\n $pathmap[$path[$i]] = $path[$i+1];\n $i++;\n }\n}\n</code></pre>\n" }, { "answer_id": 117978, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 2, "selected": false, "text": "<p>I don't believe that their is a way - but I'd say that your best bet would be to have the script \"index.php\" process a path instead of having to do so many back references.</p>\n\n<p>So for example, your rewriterule would be </p>\n\n<pre><code>RewriteBase /\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</code></pre>\n\n<p>Or similar... This would then make the $_SERVER['REQUEST_URI'] variable contain the path information, which you can split and parse.</p>\n\n<pre><code>$path = split('/', $_SERVER['REQUEST_URI']);\narray_shift($path); // We always have a first null value\n$mode = array_shift($path);\n</code></pre>\n\n<p>This ends up with $mode containing the mode, and $path containing an array of elements that are the rest of your path, so</p>\n\n<pre><code>http://example.com/foo/bar/baz\n</code></pre>\n\n<p>Would leave you with $mode being 'foo' and $path being an array containing 'bar' and 'baz'</p>\n" }, { "answer_id": 119306, "author": "bmb", "author_id": 5298, "author_profile": "https://Stackoverflow.com/users/5298", "pm_score": 3, "selected": false, "text": "<p>I don't know if it can be done with a single expression, but it can be done with a fixed number of expressions, no matter how long the query string.</p>\n\n<p>Your mod_rewrite rules will be called repeatedly, giving you what is sometimes called mod_rewrite recursion. There are techniques for avoiding it, but I think you want to use it.</p>\n\n<p>Set up a rule that replaces the last pair with name=value&amp;</p>\n\n<p>Keep tacking on the input query string to the output. Every time through, your query string will get longer and your URL will get shorter. </p>\n\n<p>Eventually you have only a single value that matches your last rule.</p>\n\n<p>You have to capture the query string with</p>\n\n<pre><code>RewriteCond %{QUERY_STRING} ^(.*)$\n</code></pre>\n\n<p>And then you add it back to the output with %1</p>\n\n<p>You'd end up with four lines.</p>\n\n<p>I know four lines is what you started with, but you'd match as many parameters as you want without having to add a fifth line.</p>\n\n<pre><code>RewriteCond %{QUERY_STRING} ^(.*)$\nRewriteRule ^(.*/)([^/]+)/([^/]+) $1?$2=$3&amp;%1 [L]\nRewriteCond %{QUERY_STRING} ^(.*)$\nRewriteRule ^([^/]+)/ $1.php?%1 [L]\n</code></pre>\n\n<p>This will rewrite the following</p>\n\n<pre><code>/mypage/param1/val1/param2/val2/param3/val3/... ---&gt;\n/mypage.php?param1=val1&amp;param2=val2&amp;param3=val3&amp;...\n</code></pre>\n\n<p>It stops when there is only one parameter remaining. It will take the first \"parameter\" and call the .php file with that name. There is no limit to the number of param/val pairs.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2083/" ]
I'm building a fairly large website and my .htaccess is starting to feel a bit bloated, is there a way of replacing my current system of - one rule for each of the possibile number of vars that could be passed, to one catch all expression that can account for varying numbers of inputs ? for example I currently have: ``` RewriteRule ^([a-z]+)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)$ /index.php?mode=$1&id=$2&$3=$4&$5=$6 RewriteRule ^([a-z]+)/([^/]*)/([^/]*)/([^/]*)$ /index.php?mode=$1&id=$2&$3=$4 RewriteRule ^([a-z]+)/([^/]*)$ /index.php?mode=$1&id=$2 RewriteRule ^([a-z]+)$ /index.php?mode=$1 ``` the first backreference is always the *mode* and (if any more exist) the second is always *id*, thereafter any further backreferences alternate between the name of the input and its value ``` http://www.example.com/search http://www.example.com/search/3039/sort_by/name_asc/page/23 ``` I would love to be able to have one expression to gracefully handle all the inputs.
Do like Drupal: ``` RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?q=$1 [L,QSA] ``` And then handle all the stuff in your script using php code something like this ``` $pathmap = (); if ($_GET["q"]){ $path = split("/", $_GET["q"]); for ($i=0; $i+1<count($path); $i++){ $pathmap[$path[$i]] = $path[$i+1]; $i++; } } ```
117,952
<p>I have two tables containing Tasks and Notes, and want to retrieve a list of tasks with the number of associated notes for each one. These two queries do the job:</p> <pre>select t.TaskId, (select count(n.TaskNoteId) from TaskNote n where n.TaskId = t.TaskId) 'Notes' from Task t -- or select t.TaskId, count(n.TaskNoteId) 'Notes' from Task t left join TaskNote n on t.TaskId = n.TaskId group by t.TaskId</pre> <p>Is there a difference between them and should I be using one over the other, or are they just two ways of doing the same job? Thanks.</p>
[ { "answer_id": 117981, "author": "Sean Reilly", "author_id": 8313, "author_profile": "https://Stackoverflow.com/users/8313", "pm_score": 0, "selected": false, "text": "<p>You can use either, and they are semantically identical. In general, the rule of thumb is to use whichever form is easier for you to read, unless performance is an issue.</p>\n\n<p>If performance is an issue, then experiment with rewriting the query using the other form. Sometimes the optimizer will use an index for one form, and not the other.</p>\n" }, { "answer_id": 117990, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 1, "selected": false, "text": "<p>There's no clear-cut answer on this. You should view the SQL Plan. In terms of relational algebra, they are essentially equivalent.</p>\n" }, { "answer_id": 118014, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 5, "selected": true, "text": "<p>On small datasets they are wash when it comes to performance. When indexed, the LOJ is a little better.</p>\n\n<p>I've found on large datasets that an inner join (an inner join will work too.) will outperform the subquery by a very large factor (sorry, no numbers).</p>\n" }, { "answer_id": 118016, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "<p>In most cases, the optimizer will treat them the same.</p>\n\n<p>I tend to prefer the second, because it has less nesting, which makes it easier to read and easier to maintain. I have started to use SQL Server's common table expressions to reduce nesting as well for the same reason.</p>\n\n<p>In addition, the second syntax is more flexible if there are further aggregates which may be added in the future in addition to COUNT, like MIN(some_scalar), MAX(), AVG() etc.</p>\n" }, { "answer_id": 118069, "author": "Simon Forrest", "author_id": 4733, "author_profile": "https://Stackoverflow.com/users/4733", "pm_score": 2, "selected": false, "text": "<p>If you're using SQL Server Management Studio, you can enter both versions into the Query Editor and then right-click and choose Display Estimated Execution Plan. It will give you two percentage costs relative to the batch. If they're expected to take the same time, they'll both show as 50% - in which case, choose whichever you prefer for other reasons (easier to read, easier to maintain, better fit with your coding standards etc). Otherwise, you can pick the one with the lower percentage cost relative to the batch.</p>\n\n<p>You can use the same technique to look at changing any query to improve performance by comparing two versions that do the same thing. </p>\n\n<p>Of course, because it's a cost relative to the batch, it doesn't mean that either query is as fast as it could be - it just tells you how they compare to each other, not to some notional optimum query to get the same results.</p>\n" }, { "answer_id": 128009, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": false, "text": "<p>The subquery will be slower as it is being executed for every row in the outer query. The join will be faster as it is done once. I believe that the query optimiser will not rewrite this query plan as it can't recognize the equivalence.</p>\n\n<p>Normally you would do a join and group by for this sort of count. Correlated subqueries of the sort you show are mainly of interest if they have to do some grouping or more complex predicate on a table that is not participating in another join.</p>\n" }, { "answer_id": 135054, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>I make it a point to avoid subqueries wherever possible. The join will generally be more efficient. </p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
I have two tables containing Tasks and Notes, and want to retrieve a list of tasks with the number of associated notes for each one. These two queries do the job: ``` select t.TaskId, (select count(n.TaskNoteId) from TaskNote n where n.TaskId = t.TaskId) 'Notes' from Task t -- or select t.TaskId, count(n.TaskNoteId) 'Notes' from Task t left join TaskNote n on t.TaskId = n.TaskId group by t.TaskId ``` Is there a difference between them and should I be using one over the other, or are they just two ways of doing the same job? Thanks.
On small datasets they are wash when it comes to performance. When indexed, the LOJ is a little better. I've found on large datasets that an inner join (an inner join will work too.) will outperform the subquery by a very large factor (sorry, no numbers).
117,962
<p>I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect.</p> <p>For example:</p> <pre><code> &lt;-----row 1 interval-------&gt; &lt;---find this--&gt; &lt;--and this--&gt; &lt;--and this--&gt; </code></pre> <p>Please phrase your answer in the form of a SQL <code>WHERE</code>-clause, AND consider the case where the end time in the second table may be <code>NULL</code>.</p> <p>Target platform is SQL Server 2005, but solutions from other platforms may be of interest also.</p>
[ { "answer_id": 117977, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 7, "selected": true, "text": "<pre><code>SELECT * \nFROM table1,table2 \nWHERE table2.start &lt;= table1.end \nAND (table2.end IS NULL OR table2.end &gt;= table1.start)\n</code></pre>\n" }, { "answer_id": 117999, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 1, "selected": false, "text": "<pre><code>select * from table_1 \nright join \ntable_2 on \n(\ntable_1.start between table_2.start and table_2.[end]\nor\ntable_1.[end] between table_2.start and table_2.[end]\nor\n(table_1.[end] &gt; table_2.start and table_2.[end] is null)\n)\n</code></pre>\n\n<p><strong>EDIT:</strong> Ok, don't go for my solution, it perfoms like shit. The \"where\" solution is 14x faster. Oops...</p>\n\n<p>Some statistics: running on a db with ~ 65000 records for both table 1 and 2 (no indexing), having intervals of 2 days between start and end for each row, running for 2 minutes in SQLSMSE (don't have the patience to wait)</p>\n\n<p>Using join: 8356 rows in 2 minutes</p>\n\n<p>Using where: 115436 rows in 2 minutes </p>\n" }, { "answer_id": 44767600, "author": "Mike S", "author_id": 6158286, "author_profile": "https://Stackoverflow.com/users/6158286", "pm_score": 2, "selected": false, "text": "<p>It's sound very complicated until you start working from reverse.\nBelow I illustrated ONLY GOOD CASES (no overlaps)! defined by those 2 simple conditions, we have no overlap ranges if condA OR condB is TRUE, so we going to reverse those:\nNOT condA AND NOT CondB, in our case I just reversed signs (> became &lt;=)</p>\n\n<pre><code>/*\n|--------| A \\___ CondA: b.ddStart &gt; a.ddEnd\n |=========| B / \\____ CondB: a.ddS &gt; b.ddE\n |+++++++++| A /\n*/\n--DROP TABLE ran\ncreate table ran ( mem_nbr int, ID int, ddS date, ddE date)\ninsert ran values \n(100, 1, '2012-1-1','2012-12-30'), ----\\ ovl\n(100, 11, '2012-12-12','2012-12-24'), ----/\n(100, 2, '2012-12-31','2014-1-1'),\n(100, 3, '2014-5-1','2014-12-14') ,\n\n(220, 1, '2015-5-5','2015-12-14') , ---\\ovl\n(220, 22, '2014-4-1','2015-5-25') , ---/\n(220, 3, '2016-6-1','2016-12-16') \n\nselect DISTINCT a.mem_nbr , a.* , '-' [ ], b.dds, b.dde, b.id \nFROM ran a\njoin ran b on a.mem_nbr = b.mem_nbr -- match by mem#\n AND a.ID &lt;&gt; b.ID -- itself\n AND b.ddS &lt;= a.ddE -- NOT b.ddS &gt; a.ddE \n AND a.ddS &lt;= b.ddE -- NOT a.ddS &gt; b.ddE \n</code></pre>\n" }, { "answer_id": 60317867, "author": "Sven", "author_id": 12931599, "author_profile": "https://Stackoverflow.com/users/12931599", "pm_score": 0, "selected": false, "text": "<p>And what, if you want to analyse such an overlap on a minute precision with 70m+ rows?\nthe only solution i could make up myself was a time dimension table for the join </p>\n\n<p>else the dublicate-handling became a headache .. and the processing cost where astronomical</p>\n" }, { "answer_id": 61834782, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p>&quot;solutions from other platforms may be of interest also.&quot;</p>\n</blockquote>\n<p>SQL Standard defines <strong><a href=\"https://jakewheat.github.io/sql-overview/sql-92-grammar.html#_8_11_overlaps_predicate\" rel=\"nofollow noreferrer\">OVERLAPS</a></strong> predicate:</p>\n<blockquote>\n<p>Specify a test for an overlap between two events.</p>\n<pre><code>&lt;overlaps predicate&gt; ::=\n &lt;row value constructor 1&gt; OVERLAPS &lt;row value constructor 2&gt; \n</code></pre>\n</blockquote>\n<p>Example:</p>\n<pre><code>SELECT 1\nWHERE ('2020-03-01'::DATE, '2020-04-15'::DATE) OVERLAPS \n ('2020-02-01'::DATE, '2020-03-15'::DATE) \n-- 1\n</code></pre>\n<p><strong><a href=\"https://dbfiddle.uk/?rdbms=postgres_12&amp;fiddle=ef2dde20e25c2ff0c15b4df23509a650\" rel=\"nofollow noreferrer\">db&lt;&gt;fiddle demo</a></strong></p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect. For example: ``` <-----row 1 interval-------> <---find this--> <--and this--> <--and this--> ``` Please phrase your answer in the form of a SQL `WHERE`-clause, AND consider the case where the end time in the second table may be `NULL`. Target platform is SQL Server 2005, but solutions from other platforms may be of interest also.
``` SELECT * FROM table1,table2 WHERE table2.start <= table1.end AND (table2.end IS NULL OR table2.end >= table1.start) ```
117,986
<p>I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields.</p> <p>Something like firefox live headers, but for the server side.</p>
[ { "answer_id": 118037, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "<p>That shouldn't be too hard to write yourself as long as you only need the headers. Try that:</p>\n\n<pre><code>import sys\n\ndef log_headers(app, stream=None):\n if stream is None:\n stream = sys.stdout\n def proxy(environ, start_response):\n for key, value in environ.iteritems():\n if key.startswith('HTTP_'):\n stream.write('%s: %s\\n' % (key[5:].title().replace('_', '-'), value))\n return app(environ, start_response)\n return proxy\n</code></pre>\n" }, { "answer_id": 118142, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 3, "selected": true, "text": "<p>The middleware</p>\n\n<pre><code>from wsgiref.util import request_uri\nimport sys\n\ndef logging_middleware(application, stream=sys.stdout):\n def _logger(environ, start_response):\n stream.write('REQUEST\\n')\n stream.write('%s %s\\n' %(\n environ['REQUEST_METHOD'],\n request_uri(environ),\n ))\n\n for name, value in environ.items():\n if name.startswith('HTTP_'):\n stream.write(' %s: %s\\n' %(\n name[5:].title().replace('_', '-'),\n value,\n ))\n stream.flush()\n def _start_response(code, headers):\n stream.write('RESPONSE\\n')\n stream.write('%s\\n' % code)\n for data in headers:\n stream.write(' %s: %s\\n' % data)\n stream.flush()\n start_response(code, headers)\n return application(environ, _start_response)\n return _logger\n</code></pre>\n\n<p>The test</p>\n\n<pre><code>def application(environ, start_response):\n start_response('200 OK', [\n ('Content-Type', 'text/html')\n ])\n return ['Hello World']\n\nif __name__ == '__main__':\n logger = logging_middleware(application)\n from wsgiref.simple_server import make_server\n httpd = make_server('', 1234, logger)\n httpd.serve_forever()\n</code></pre>\n\n<p>See also the <a href=\"http://werkzeug.pocoo.org/documentation/debug\" rel=\"nofollow noreferrer\">werkzeug debugger</a> Armin wrote, it's usefull for interactive debugging.</p>\n" }, { "answer_id": 307547, "author": "ianb", "author_id": 20218, "author_profile": "https://Stackoverflow.com/users/20218", "pm_score": 2, "selected": false, "text": "<p>If you want Apache-style logs, try <a href=\"http://svn.pythonpaste.org/Paste/trunk/paste/translogger.py\" rel=\"nofollow noreferrer\">paste.translogger</a></p>\n\n<p>But for something more complete, though not in a very handy or stable location (maybe copy it into your source) is <a href=\"http://svn.pythonpaste.org/Paste/WSGIFilter/trunk/wsgifilter/proxyapp.py\" rel=\"nofollow noreferrer\">wsgifilter.proxyapp.DebugHeaders</a></p>\n\n<p>And writing one using <a href=\"http://pythonpaste.org/webob\" rel=\"nofollow noreferrer\">WebOb</a>:</p>\n\n<pre><code>import webob, sys\nclass LogHeaders(object):\n def __init__(self, app, stream=sys.stderr):\n self.app = app\n self.stream = stream\n def __call__(self, environ, start_response):\n req = webob.Request(environ)\n resp = req.get_response(self.app)\n print &gt;&gt; self.stream, 'Request:\\n%s\\n\\nResponse:\\n%s\\n\\n\\n' % (req, resp)\n return resp(environ, start_response)\n</code></pre>\n" }, { "answer_id": 1041821, "author": "Graham Dumpleton", "author_id": 128141, "author_profile": "https://Stackoverflow.com/users/128141", "pm_score": 1, "selected": false, "text": "<p>The mod_wsgi documentation provides various tips on debugging which are applicable to any WSGI hosting mechanism and not just mod_wsgi. See:</p>\n\n<p><a href=\"http://code.google.com/p/modwsgi/wiki/DebuggingTechniques\" rel=\"nofollow noreferrer\">http://code.google.com/p/modwsgi/wiki/DebuggingTechniques</a></p>\n\n<p>This includes an example WSGI middleware that captures request and response.</p>\n" }, { "answer_id": 2384940, "author": "amcgregor", "author_id": 211827, "author_profile": "https://Stackoverflow.com/users/211827", "pm_score": 1, "selected": false, "text": "<p>My WebCore project has a bit of middleware that logs the entire WSGI environment (thus Beaker sessions, headers, etc.) for the incoming request, headers for outbound responses, as well as performance information to a MongoDB database. Average overhead is around 4ms.</p>\n\n<p>The module has been removed from the core package, but hasn’t yet been integrated into its own. The current version as of this answer is available in the Git history:</p>\n\n<p><a href=\"http://github.com/GothAlice/WebCore/blob/cd1d6dcbd081323869968c51a78eceb1a32007d8/web/extras/cprofile.py\" rel=\"nofollow noreferrer\">http://github.com/GothAlice/WebCore/blob/cd1d6dcbd081323869968c51a78eceb1a32007d8/web/extras/cprofile.py</a></p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/117986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720/" ]
I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields. Something like firefox live headers, but for the server side.
The middleware ``` from wsgiref.util import request_uri import sys def logging_middleware(application, stream=sys.stdout): def _logger(environ, start_response): stream.write('REQUEST\n') stream.write('%s %s\n' %( environ['REQUEST_METHOD'], request_uri(environ), )) for name, value in environ.items(): if name.startswith('HTTP_'): stream.write(' %s: %s\n' %( name[5:].title().replace('_', '-'), value, )) stream.flush() def _start_response(code, headers): stream.write('RESPONSE\n') stream.write('%s\n' % code) for data in headers: stream.write(' %s: %s\n' % data) stream.flush() start_response(code, headers) return application(environ, _start_response) return _logger ``` The test ``` def application(environ, start_response): start_response('200 OK', [ ('Content-Type', 'text/html') ]) return ['Hello World'] if __name__ == '__main__': logger = logging_middleware(application) from wsgiref.simple_server import make_server httpd = make_server('', 1234, logger) httpd.serve_forever() ``` See also the [werkzeug debugger](http://werkzeug.pocoo.org/documentation/debug) Armin wrote, it's usefull for interactive debugging.
118,040
<p>I had this questions since the time I learnt about object-oriented programming. Now, I have got a wonderful forum I thought of asking this.</p> <p>Lets say we are implementing an employee management application using EJB.</p> <p>Now, there are 2 ways of doing this.</p> <ol> <li><p>Normally, we create entities (POJOs) which represent an employee. Then we create an EJB interface 'EmployeeManager' with add, delete, update, retrieve, retrieveAll methods. This way I could use 'employee' entity as a data transfer object.</p></li> <li><p>We call the EJB interface itself 'Employee'. Implementation could be called 'EmployeeImpl' which has <em>fields</em> as well as method implementation (add, delete, update, retrieve, retrieveAll). If I am using a layered approach where my business logic needs access to employee details, I need to pass 'EmployeeImpl' (because it contains values).</p></li> </ol> <p>Which one do you think is the better way?</p> <p>I prefer the first one, because it 'looks' fine and does not feel awkward. like</p> <pre><code>EmployeeMgr empMgr = // JNDI lookup; Employee emp = new Employee(); empMgr.add(emp); Employee employees[] = empMgr.retrieveAll(); </code></pre> <p>Where as the second one would look like (though I am not sure),</p> <pre><code>Employee emp = // JNDI lookup; emp.setName(); //set the properties emp.add(); Employee employees[] = emp.retrieveAll(); </code></pre> <p>As you can see, the second one looks awkward.</p> <p>I request you guys to advise me on this.</p> <p>Thanks manju</p>
[ { "answer_id": 118057, "author": "Smashery", "author_id": 14902, "author_profile": "https://Stackoverflow.com/users/14902", "pm_score": 2, "selected": false, "text": "<p>The first one is certainly clearer, and clarity should certainly be an aim of your code. However, in terms of the first one, I'll direct you <a href=\"http://www.codinghorror.com/blog/archives/000553.html\" rel=\"nofollow noreferrer\">here</a>: Jeff Atwood's take on calling things \"SomethingManager\" - not recommended.</p>\n" }, { "answer_id": 118083, "author": "SteinNorheim", "author_id": 19220, "author_profile": "https://Stackoverflow.com/users/19220", "pm_score": 2, "selected": false, "text": "<p>Of your examples, I would not recommend #2, because it gives the Employee class too many responsibilities.</p>\n\n<p>Although not giving a straight answer, I can cordially recommend Martin Fowler's book <a href=\"http://www.martinfowler.com/books.html#eaa\" rel=\"nofollow noreferrer\">Patterns of Enterprise Application Architecture</a>. It has been a great eye-opener for me personally, and describes several different approaches to this.</p>\n\n<p>I also think the open-source <a href=\"http://www.hibernate.org/\" rel=\"nofollow noreferrer\">Hibernate</a> is a great tool for persisting entities. I'm sure you will find lots of good input there.</p>\n" }, { "answer_id": 118125, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 0, "selected": false, "text": "<p>Having separare class for persisting Employee looks more OO. And more flexible, because you potentially may want to have DBEmployeeMrg, FileSystemEmployeeMrg, InMemoryEmployeeMgr and MockEmployeeMgr for testing - all those classes may implement inteface EmployeeMrg in different way.</p>\n\n<p>For your code to be shorter you may want to have employee being able to save itself - employee.save() instead of employeeMrg.save(employee)\nI can understand design when employee saves itself, updates and even deletes, but definitely one employee is not needed to load another employee by id and to load list of employees.</p>\n" }, { "answer_id": 123262, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 2, "selected": false, "text": "<p>Strive for appropriate design and not \"OO Compliance\".</p>\n\n<p>Incidentally, EJB is not Object Oriented at all.</p>\n\n<p>The best practice for using EJB is:</p>\n\n<ul>\n<li>DataContainer classes hold data you got from the DB or the user; \"POJOs\"</li>\n<li>EJBs have methods that operate on your DataContainers</li>\n<li>DAOs handle persisting/retrieving DataContainers from the database.</li>\n</ul>\n\n<p>EJBs typically do not have fields unless they are to be deployed as Stateless, which is needed only rarely.</p>\n\n<p>If you are using EJBs that would be the design most people would expect. It is clearly not OO, as the DataContainers contain no real methods and the EJBs/DAOs contain no real data.</p>\n\n<p>This is not a bad thing; it separates concerns and makes your system more changeable and maintainable. </p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19034/" ]
I had this questions since the time I learnt about object-oriented programming. Now, I have got a wonderful forum I thought of asking this. Lets say we are implementing an employee management application using EJB. Now, there are 2 ways of doing this. 1. Normally, we create entities (POJOs) which represent an employee. Then we create an EJB interface 'EmployeeManager' with add, delete, update, retrieve, retrieveAll methods. This way I could use 'employee' entity as a data transfer object. 2. We call the EJB interface itself 'Employee'. Implementation could be called 'EmployeeImpl' which has *fields* as well as method implementation (add, delete, update, retrieve, retrieveAll). If I am using a layered approach where my business logic needs access to employee details, I need to pass 'EmployeeImpl' (because it contains values). Which one do you think is the better way? I prefer the first one, because it 'looks' fine and does not feel awkward. like ``` EmployeeMgr empMgr = // JNDI lookup; Employee emp = new Employee(); empMgr.add(emp); Employee employees[] = empMgr.retrieveAll(); ``` Where as the second one would look like (though I am not sure), ``` Employee emp = // JNDI lookup; emp.setName(); //set the properties emp.add(); Employee employees[] = emp.retrieveAll(); ``` As you can see, the second one looks awkward. I request you guys to advise me on this. Thanks manju
The first one is certainly clearer, and clarity should certainly be an aim of your code. However, in terms of the first one, I'll direct you [here](http://www.codinghorror.com/blog/archives/000553.html): Jeff Atwood's take on calling things "SomethingManager" - not recommended.
118,051
<p>I have a grid that is binded to a collection. For some reason that I do not know, now when I do some action in the grid, the grid doesn't update.</p> <p>Situation : When I click a button in the grid, it increase a value that is in the same line. When I click, I can debug and see the value increment but the value doesn't change in the grid. <strong>BUT</strong> when I click the button, minimize and restore the windows, the value are updated... what do I have to do to have the value updated like it was before?</p> <p><strong>UPDATE</strong> This is NOT SOLVED but I accepted the best answer around here.</p> <p>It's not solved because it works as usuall when the data is from the database but not from the cache. Objects are serialized and threw the process the event are lost. This is why I build them back and it works for what I know because I can interact with them BUT it seem that it doesn't work for the update of the grid for an unkown reason.</p>
[ { "answer_id": 118121, "author": "µBio", "author_id": 9796, "author_profile": "https://Stackoverflow.com/users/9796", "pm_score": 0, "selected": false, "text": "<p>It sounds like you need to call DataBind in your update code.</p>\n" }, { "answer_id": 118156, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 0, "selected": false, "text": "<p>I am using the BindingSource object between my Collection and my Grid. Usually I do not have to call anything.</p>\n" }, { "answer_id": 118438, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 3, "selected": true, "text": "<p>In order for the binding to be bidirectional, from control to datasource and from datasource to control the datasource must implement property changing notification events, in one of the 2 possible ways:</p>\n\n<ul>\n<li><p>Implement the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged\" rel=\"nofollow noreferrer\">INotifyPropertyChanged</a> interface, and raise the event when the properties change :</p>\n\n<pre><code>public string Name \n{\n get\n {\n return this._Name;\n }\n set\n {\n if (value != this._Name)\n {\n this._Name= value;\n NotifyPropertyChanged(\"Name\");\n }\n }\n}\n</code></pre></li>\n<li><p>Inplement a changed event for every property that must notify the controls when it changes. The event name must be in the form <em>PropertyName</em>Changed :</p>\n\n<pre><code>public event EventHandler NameChanged;\n\npublic string Name \n{\n get\n {\n return this._Name;\n }\n set\n {\n if (value != this._Name)\n {\n this._Name= value;\n if (NameChanged != null) NameChanged(this, EventArgs.Empty);\n }\n }\n}\n</code></pre>\n\n<p>*as a note your property values are the correct ones after window maximize, because the control rereads the values from the datasource.</p></li>\n</ul>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
I have a grid that is binded to a collection. For some reason that I do not know, now when I do some action in the grid, the grid doesn't update. Situation : When I click a button in the grid, it increase a value that is in the same line. When I click, I can debug and see the value increment but the value doesn't change in the grid. **BUT** when I click the button, minimize and restore the windows, the value are updated... what do I have to do to have the value updated like it was before? **UPDATE** This is NOT SOLVED but I accepted the best answer around here. It's not solved because it works as usuall when the data is from the database but not from the cache. Objects are serialized and threw the process the event are lost. This is why I build them back and it works for what I know because I can interact with them BUT it seem that it doesn't work for the update of the grid for an unkown reason.
In order for the binding to be bidirectional, from control to datasource and from datasource to control the datasource must implement property changing notification events, in one of the 2 possible ways: * Implement the [INotifyPropertyChanged](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged) interface, and raise the event when the properties change : ``` public string Name { get { return this._Name; } set { if (value != this._Name) { this._Name= value; NotifyPropertyChanged("Name"); } } } ``` * Inplement a changed event for every property that must notify the controls when it changes. The event name must be in the form *PropertyName*Changed : ``` public event EventHandler NameChanged; public string Name { get { return this._Name; } set { if (value != this._Name) { this._Name= value; if (NameChanged != null) NameChanged(this, EventArgs.Empty); } } } ``` \*as a note your property values are the correct ones after window maximize, because the control rereads the values from the datasource.
118,091
<p>I am trying to learn how to use MSBuild so we can use it to build our project. There's what seems to be a very big hole in the documentation, and I find the hole everywhere I look, the hole being how do you name or otherwise designate the MSBuild project file? </p> <p>For example, the tutorial on MSBuild that can be downloaded from Microsoft goes into some detail on the contents of the build file. For example, here's a little bit of their Hello World project file.</p> <pre><code>&lt;Project MSBuildVersion = "1.0" DefaultTargets = "Compile"&gt; &lt;Property appname = "HelloWorldCS"/&gt; &lt;Item Type = "CSFile" Include = "consolehwcs1.cs"/&gt; &lt;Target Name = "Compile"&gt; &lt;Task Name = "CSC" Sources = "@(CSFile)"&gt; &lt;OutputItem TaskParameter = "OutputAssembly" Type = "EXEFile" Include = "$(appname).exe"/&gt; &lt;/Task&gt; &lt;Message Text="The output file is @(EXEFile)"/&gt; &lt;/Target&gt; &lt;/Project&gt; </code></pre> <p>And it goes on blah, blah, blah Items blah blah blah tasks, here's how you do this and here's how you do that. Useless, completely useless. Because they never get around to saying how this xml file is supposed to be recognized by the MSBuild app. Is it supposed to be named in a particular way? Is it supposed to be placed in a particular directory? Both? Neither? </p> <p>It isn't just the MS tutorial where they don't tell about it. I haven't been able to find it on MSDN, or on any link I can wring out of Groups.Google, either.</p> <p>Does someone here know? I sure hope so.</p> <blockquote> <p><strong>Edited to add:</strong> I mistook the .proj file included in the tutorial to be the .csproj file and that is what one fed to MSBuild, but it took the answer below before I saw this. It should have been rather obvious, but I missed it.</p> </blockquote>
[ { "answer_id": 118118, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 4, "selected": true, "text": "<p>You can name the file as you see fit. From the help for MSBuild</p>\n\n<pre><code>msbuild.exe /?\n\nMicrosoft (R) Build Engine Version 2.0.50727.3053\n[Microsoft .NET Framework, Version 2.0.50727.3053]\nCopyright (C) Microsoft Corporation 2005. All rights reserved.\n\nSyntax: MSBuild.exe [options] [project file]\n</code></pre>\n\n<p>So if you save the file as mybuildfile.xml you would use the syntax:</p>\n\n<pre><code>msbuild.exe mybuildfile.xml\n</code></pre>\n" }, { "answer_id": 233813, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<p>Or for the truly lazy, like me.</p>\n\n<pre><code>msbuild.exe project-file-name.vcproj /t:Rebuild /p:Configuration=Release\n</code></pre>\n" }, { "answer_id": 249765, "author": "Thomas Freudenberg", "author_id": 4747, "author_profile": "https://Stackoverflow.com/users/4747", "pm_score": 2, "selected": false, "text": "<p>You don't have to specify the build file if you respect following strategy:</p>\n\n<blockquote>\n <p>Today, when you invoke msbuild.exe\n from the command line and don't\n specify any project files as\n arguments, then we do some auto\n inferral and scanning and decide if we\n should build anything. If we find\n either a msbuild project (anything\n that has an extension of *proj) or a\n solution file (.sln), we will build\n either the project or the solution as\n long as there is only one solution or\n one project in the directory. If there\n is a solution and a project, we will\n give preference to the solution. If\n there's more than one project or more\n than one solution, we issue an error\n message because we can't decide which\n one to build.</p>\n</blockquote>\n\n<p>This is taken from <a href=\"http://blogs.msdn.com/msbuild/archive/2006/03/24/559547.aspx\" rel=\"nofollow noreferrer\">New Feature Feedback Request: /IgnoreProjectExtensions - A new command-line switch</a>.</p>\n\n<p>I always name my manually written scripts <em>build.proj</em>.</p>\n" }, { "answer_id": 7039953, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 2, "selected": false, "text": "<p>Not a direct answer, but related; if you use <code>.msproj</code> as your extension, Visual Studio gives you intellisense.</p>\n" }, { "answer_id": 15303704, "author": "kkahl", "author_id": 473014, "author_profile": "https://Stackoverflow.com/users/473014", "pm_score": 0, "selected": false, "text": "<p>Visual Studio 2012 recognizes the <code>.msbuildproj</code> as an extension and will treat it as a \"project\" in the Solution Explorer.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16964/" ]
I am trying to learn how to use MSBuild so we can use it to build our project. There's what seems to be a very big hole in the documentation, and I find the hole everywhere I look, the hole being how do you name or otherwise designate the MSBuild project file? For example, the tutorial on MSBuild that can be downloaded from Microsoft goes into some detail on the contents of the build file. For example, here's a little bit of their Hello World project file. ``` <Project MSBuildVersion = "1.0" DefaultTargets = "Compile"> <Property appname = "HelloWorldCS"/> <Item Type = "CSFile" Include = "consolehwcs1.cs"/> <Target Name = "Compile"> <Task Name = "CSC" Sources = "@(CSFile)"> <OutputItem TaskParameter = "OutputAssembly" Type = "EXEFile" Include = "$(appname).exe"/> </Task> <Message Text="The output file is @(EXEFile)"/> </Target> </Project> ``` And it goes on blah, blah, blah Items blah blah blah tasks, here's how you do this and here's how you do that. Useless, completely useless. Because they never get around to saying how this xml file is supposed to be recognized by the MSBuild app. Is it supposed to be named in a particular way? Is it supposed to be placed in a particular directory? Both? Neither? It isn't just the MS tutorial where they don't tell about it. I haven't been able to find it on MSDN, or on any link I can wring out of Groups.Google, either. Does someone here know? I sure hope so. > > **Edited to add:** I mistook the > .proj file included in the tutorial > to be the .csproj file and that is what > one fed to MSBuild, but it took the answer below before I saw this. > It should have been rather obvious, but I missed it. > > >
You can name the file as you see fit. From the help for MSBuild ``` msbuild.exe /? Microsoft (R) Build Engine Version 2.0.50727.3053 [Microsoft .NET Framework, Version 2.0.50727.3053] Copyright (C) Microsoft Corporation 2005. All rights reserved. Syntax: MSBuild.exe [options] [project file] ``` So if you save the file as mybuildfile.xml you would use the syntax: ``` msbuild.exe mybuildfile.xml ```
118,092
<p>In PHP, replace one URL with another within a string e.g. </p> <pre><code>New post on the site &lt;a href="http://stackoverflow.com/xyz1"&gt;http://stackoverflow.com/xyz1&lt;/a&gt;&lt;/p&gt; </code></pre> <p>becomes:</p> <pre><code>New post on the site &lt;a href="http://yahoo.com/abc1"&gt;http://yahoo.com/abc1&lt;/a&gt;&lt;/p&gt; </code></pre> <p>Must work for repeating strings as above. Appreciate this is simple but struggling!</p>
[ { "answer_id": 118099, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"http://php.net/str_replace\" rel=\"nofollow noreferrer\">str_replace()</a>:</p>\n\n<pre><code>$text = str_replace('http://stackoverflow.com/xyz1', 'http://yahoo.com/abc1', $text);\n</code></pre>\n\n<p>That will replace the first URL with the second URL in $text.</p>\n" }, { "answer_id": 118101, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>preg_replace('#(https?://)(www\\.)?stackoverflow.com\\b#', '\\1\\2yahoo.com', $text);\n</code></pre>\n\n<p>If you want to change the path after the url, add another group and use <code>preg_replace_callabck</code>. More information in the PHP documentation.</p>\n" }, { "answer_id": 118112, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 2, "selected": false, "text": "<pre><code>function replace_url($text, $newurl) {\n $text = preg_replace('@(https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?)@', $newurl, $text);\n return $text;\n}\n</code></pre>\n<p>Should work.\nRegex stolen from <a href=\"http://snipplr.com/view/2371/regex-regular-expression-to-match-a-url/\" rel=\"nofollow noreferrer\">here</a>. This will replace all URLs in the string with the new one.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In PHP, replace one URL with another within a string e.g. ``` New post on the site <a href="http://stackoverflow.com/xyz1">http://stackoverflow.com/xyz1</a></p> ``` becomes: ``` New post on the site <a href="http://yahoo.com/abc1">http://yahoo.com/abc1</a></p> ``` Must work for repeating strings as above. Appreciate this is simple but struggling!
``` function replace_url($text, $newurl) { $text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', $newurl, $text); return $text; } ``` Should work. Regex stolen from [here](http://snipplr.com/view/2371/regex-regular-expression-to-match-a-url/). This will replace all URLs in the string with the new one.
118,096
<p>I need to be able to take a string like:</p> <pre><code>'''foo, bar, "one, two", three four''' </code></pre> <p>into:</p> <pre><code>['foo', 'bar', 'one, two', 'three four'] </code></pre> <p>I have an feeling (with hints from #python) that the solution is going to involve the shlex module.</p>
[ { "answer_id": 118110, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>You may also want to consider the <a href=\"http://docs.python.org/lib/module-csv.html\" rel=\"noreferrer\">csv</a> module. I haven't tried it, but it looks like your input data is closer to CSV than to shell syntax (which is what shlex parses).</p>\n" }, { "answer_id": 118132, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 1, "selected": false, "text": "<p>You could do something like this:</p>\n\n<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; pattern = re.compile(r'\\s*(\"[^\"]*\"|.*?)\\s*,')\n&gt;&gt;&gt; def split(line):\n... return [x[1:-1] if x[:1] == x[-1:] == '\"' else x\n... for x in pattern.findall(line.rstrip(',') + ',')]\n... \n&gt;&gt;&gt; split(\"foo, bar, baz\")\n['foo', 'bar', 'baz']\n&gt;&gt;&gt; split('foo, bar, baz, \"blub blah\"')\n['foo', 'bar', 'baz', 'blub blah']\n</code></pre>\n" }, { "answer_id": 118161, "author": "Rodrigo Queiro", "author_id": 20330, "author_profile": "https://Stackoverflow.com/users/20330", "pm_score": -1, "selected": false, "text": "<p>If it doesn't need to be pretty, this might get you on your way:</p>\n\n<pre><code>def f(s, splitifeven):\n if splitifeven &amp; 1:\n return [s]\n return [x.strip() for x in s.split(\",\") if x.strip() != '']\n\nss = 'foo, bar, \"one, two\", three four'\n\nprint sum([f(s, sie) for sie, s in enumerate(ss.split('\"'))], [])\n</code></pre>\n" }, { "answer_id": 118162, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 5, "selected": false, "text": "<p>It depends how complicated you want to get... do you want to allow more than one type of quoting. How about escaped quotes?</p>\n\n<p>Your syntax looks very much like the common CSV file format, which is supported by the Python standard library:</p>\n\n<pre><code>import csv\nreader = csv.reader(['''foo, bar, \"one, two\", three four'''], skipinitialspace=True)\nfor r in reader:\n print r\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>['foo', 'bar', 'one, two', 'three four']\n</code></pre>\n\n<p>HTH!</p>\n" }, { "answer_id": 118187, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 6, "selected": true, "text": "<p>The shlex module solution allows escaped quotes, one quote escape another, and all fancy stuff shell supports.</p>\n\n<pre><code>&gt;&gt;&gt; import shlex\n&gt;&gt;&gt; my_splitter = shlex.shlex('''foo, bar, \"one, two\", three four''', posix=True)\n&gt;&gt;&gt; my_splitter.whitespace += ','\n&gt;&gt;&gt; my_splitter.whitespace_split = True\n&gt;&gt;&gt; print list(my_splitter)\n['foo', 'bar', 'one, two', 'three', 'four']\n</code></pre>\n\n<p>escaped quotes example:</p>\n\n<pre><code>&gt;&gt;&gt; my_splitter = shlex.shlex('''\"test, a\",'foo,bar\",baz',bar \\xc3\\xa4 baz''',\n posix=True) \n&gt;&gt;&gt; my_splitter.whitespace = ',' ; my_splitter.whitespace_split = True \n&gt;&gt;&gt; print list(my_splitter)\n['test, a', 'foo,bar\",baz', 'bar \\xc3\\xa4 baz']\n</code></pre>\n" }, { "answer_id": 157771, "author": "Jeff", "author_id": 23902, "author_profile": "https://Stackoverflow.com/users/23902", "pm_score": 0, "selected": false, "text": "<p>I'd say a regular expression would be what you're looking for here, though I'm not terribly familiar with Python's Regex engine.</p>\n\n<p>Assuming you use lazy matches, you can get a set of matches on a string which you can put into your array.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18866/" ]
I need to be able to take a string like: ``` '''foo, bar, "one, two", three four''' ``` into: ``` ['foo', 'bar', 'one, two', 'three four'] ``` I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
The shlex module solution allows escaped quotes, one quote escape another, and all fancy stuff shell supports. ``` >>> import shlex >>> my_splitter = shlex.shlex('''foo, bar, "one, two", three four''', posix=True) >>> my_splitter.whitespace += ',' >>> my_splitter.whitespace_split = True >>> print list(my_splitter) ['foo', 'bar', 'one, two', 'three', 'four'] ``` escaped quotes example: ``` >>> my_splitter = shlex.shlex('''"test, a",'foo,bar",baz',bar \xc3\xa4 baz''', posix=True) >>> my_splitter.whitespace = ',' ; my_splitter.whitespace_split = True >>> print list(my_splitter) ['test, a', 'foo,bar",baz', 'bar \xc3\xa4 baz'] ```
118,100
<p>do you use a tool? or just manually make them?</p>
[ { "answer_id": 118106, "author": "David Leonard", "author_id": 19502, "author_profile": "https://Stackoverflow.com/users/19502", "pm_score": 0, "selected": false, "text": "<p>We use something locally based on <a href=\"http://opentcdb.org/\" rel=\"nofollow noreferrer\">http://opentcdb.org/</a> but that does scrum tracking, and draws pretty graphs.</p>\n" }, { "answer_id": 118147, "author": "Darren", "author_id": 6065, "author_profile": "https://Stackoverflow.com/users/6065", "pm_score": 1, "selected": false, "text": "<p>I did use TargetProcess but I now prefer a more tactile method so I draw it manually on a whiteboard.</p>\n" }, { "answer_id": 118164, "author": "Hortitude", "author_id": 16584, "author_profile": "https://Stackoverflow.com/users/16584", "pm_score": 2, "selected": false, "text": "<p>We tend to just use a simple shared excel sheet with a graph on one tab and a pivot table on another.</p>\n" }, { "answer_id": 118220, "author": "CR.", "author_id": 20387, "author_profile": "https://Stackoverflow.com/users/20387", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.versionone.com/\" rel=\"nofollow noreferrer\">VersionOne</a> makes the burndown sheets nicely.</p>\n" }, { "answer_id": 118521, "author": "Daniel Honig", "author_id": 1129162, "author_profile": "https://Stackoverflow.com/users/1129162", "pm_score": 0, "selected": false, "text": "<p>We use the community edition of RallyDev and it makes nice burndown charts. The problem is that our team has not yet been able to do a solid job of entering in data to keep the burndown information meaningful.</p>\n" }, { "answer_id": 118546, "author": "Bazman", "author_id": 18521, "author_profile": "https://Stackoverflow.com/users/18521", "pm_score": 0, "selected": false, "text": "<p>We also use the community edition of <a href=\"http://www.rallydev.com/\" rel=\"nofollow noreferrer\">RallyDev</a> that has nice charts. I find it to be an excellent tool once you work out which bits of it you really want to use. There is a huge amount of fields and functionality that most people wouldn't use which could be a confusing problem for bigger teams.</p>\n" }, { "answer_id": 122458, "author": "Michael Groner", "author_id": 10233, "author_profile": "https://Stackoverflow.com/users/10233", "pm_score": 0, "selected": false, "text": "<p>We used to use the tools at rallydev.com, but in time we found the tool to simply be to cumbersome for what we wanted.</p>\n\n<p>In time, I moved to just a simple Excel spreadsheet. Every morning before stand up I counted the hours remaining and added the trend line next to an \"ideal\" burndown line on the chart. I posted it on the wall where we held our morning standups. </p>\n" }, { "answer_id": 692737, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://code.google.com/apis/chart/basics.html\" rel=\"nofollow noreferrer\">Google charts api/server</a> can make one fairly easily</p>\n\n<p><img src=\"https://chart.apis.google.com/chart?chs=600x250&amp;cht=lxy&amp;chtt=Burndown&amp;chxt=x,y&amp;chxl=days&amp;chdl=Estimated|Actual&amp;chco=FF0000,00FF00&amp;chd=t:-1|40,36,32,28,24,20,16,12,8,4,0|-1|40,38,36,35,20,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1&amp;chxr=0,0,30,2|1,0,40,2&amp;chds=0,40&amp;chm=s,FF0000,0,-1,5|s,0000ff,1,-1,5|s,00aa00,2,-1,5\" alt=\"Burndown 2\">\n<img src=\"https://chart.apis.google.com/chart?chs=600x250&amp;chtt=Burndown&amp;cht=lc&amp;chxt=x,y&amp;chxl=days&amp;chdl=Estimated|Actual&amp;chco=FF0000,00FF00&amp;chd=t:40,36,32,28,24,20,16,12,8,4,0|40,39,38,37,36,35,30,25,23,21,18,14,4,0,0&amp;chxr=0,0,30,2|1,0,40,2&amp;chds=0,40\" alt=\"Burn down\"></p>\n\n<p>You specify everything in the URL so it's easy to update:</p>\n\n<pre><code>http://chart.apis.google.com/chart?\nchs=600x250&amp; // the size of the chart\nchtt=Burndown&amp; // Title\ncht=lc&amp; // The chart type - \"lc\" means a line chart that only needs Y values\nchdl=estimated|actual&amp; // The two legends\nchco=FF0000,00FF00&amp; // The colours in hex of the two lines\nchxr=0,0,30,2|1,0,40,2&amp; // The data range for the x,y (index,min,max,interval)\nchds=0,40 // The min and max values for the data. i.e. amount of features\nchd=t:40,36,32,28,24,20,16,12,8,4,0|40,39,38,37,36,35,30,25,23,21,18,14,12,9,1 // Data\n</code></pre>\n\n<p>The URL above plots in intervals of 2 - so work every 2 days. You'll need a bigger size chart for every day. To do this make the data have 30 values for estimated and actual, and change the \"chxr\" so the interval is 1, not two.</p>\n\n<p>You can plot only the days done more clearly with the \"lxy\" chart type (the first image). This needs you to enter the X data values too (so a vector). Use -1 for unknown.</p>\n" }, { "answer_id": 692751, "author": "Emil C", "author_id": 1648989, "author_profile": "https://Stackoverflow.com/users/1648989", "pm_score": 0, "selected": false, "text": "<p>We you Team Foundation Server and with conchango's scrum templates using the built in burndown through this nice little scrum dashboard</p>\n\n<p><a href=\"http://www.codeplex.com/scrumdashboard\" rel=\"nofollow noreferrer\">http://www.codeplex.com/scrumdashboard</a></p>\n" }, { "answer_id": 6351426, "author": "i8abug", "author_id": 129609, "author_profile": "https://Stackoverflow.com/users/129609", "pm_score": 0, "selected": false, "text": "<p>I used google docs and excel. Templates for both are available at the bottom of this article (and include a number of nice features like automatic calculation of the efficiency factor)</p>\n\n<p><a href=\"http://joel.inpointform.net/software-development/burn-down-charts-tutorial-simple-agile-project-tracking/\" rel=\"nofollow\">Burn Down Chart Tutorial: Simple Agile Project Tracking</a></p>\n" }, { "answer_id": 7290547, "author": "hlovdal", "author_id": 23118, "author_profile": "https://Stackoverflow.com/users/23118", "pm_score": 2, "selected": false, "text": "<p>I have not used myself, but <a href=\"http://apps.vanpuffelen.net/charts/burndown.jsp\" rel=\"nofollow noreferrer\">http://apps.vanpuffelen.net/charts/burndown.jsp</a> presents an api that is even simpler than the google charts api. Example:</p>\n\n<pre><code>http://apps.vanpuffelen.net/charts/burndown.jsp?days=17,18,19,22,23,24,25,26,29,30&amp;work=125,112,104,99,95\n</code></pre>\n\n<p>gives the following graph:</p>\n\n<p><img src=\"https://i.stack.imgur.com/uy5SF.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 8736802, "author": "Emanuel", "author_id": 646542, "author_profile": "https://Stackoverflow.com/users/646542", "pm_score": 1, "selected": false, "text": "<p>Like answered in this post <a href=\"https://stackoverflow.com/questions/528519/what-tools-provide-burndown-charts-to-bugzilla-or-mylyn/8736768#8736768\">What tools provide burndown charts to Bugzilla or Mylyn?</a></p>\n\n<p><a href=\"http://www.burndown-charts.com/\" rel=\"nofollow noreferrer\">www.in-sight.io</a> (previously burndowncharts) is a great SCRUM analytics tool.</p>\n\n<p>Here are some dashboard examples:</p>\n\n<p><a href=\"http://www.burndown-charts.com/teams/family-petre-bach/sprints/baby-shower\" rel=\"nofollow noreferrer\">Sprint metrics</a></p>\n\n<p><a href=\"http://www.burndown-charts.com/teams/family-petre-bach\" rel=\"nofollow noreferrer\">Team metrics</a></p>\n\n<p><img src=\"https://i.stack.imgur.com/I01lT.png\" alt=\"enter image description here\"></p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10431/" ]
do you use a tool? or just manually make them?
[Google charts api/server](http://code.google.com/apis/chart/basics.html) can make one fairly easily ![Burndown 2](https://chart.apis.google.com/chart?chs=600x250&cht=lxy&chtt=Burndown&chxt=x,y&chxl=days&chdl=Estimated|Actual&chco=FF0000,00FF00&chd=t:-1|40,36,32,28,24,20,16,12,8,4,0|-1|40,38,36,35,20,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1&chxr=0,0,30,2|1,0,40,2&chds=0,40&chm=s,FF0000,0,-1,5|s,0000ff,1,-1,5|s,00aa00,2,-1,5) ![Burn down](https://chart.apis.google.com/chart?chs=600x250&chtt=Burndown&cht=lc&chxt=x,y&chxl=days&chdl=Estimated|Actual&chco=FF0000,00FF00&chd=t:40,36,32,28,24,20,16,12,8,4,0|40,39,38,37,36,35,30,25,23,21,18,14,4,0,0&chxr=0,0,30,2|1,0,40,2&chds=0,40) You specify everything in the URL so it's easy to update: ``` http://chart.apis.google.com/chart? chs=600x250& // the size of the chart chtt=Burndown& // Title cht=lc& // The chart type - "lc" means a line chart that only needs Y values chdl=estimated|actual& // The two legends chco=FF0000,00FF00& // The colours in hex of the two lines chxr=0,0,30,2|1,0,40,2& // The data range for the x,y (index,min,max,interval) chds=0,40 // The min and max values for the data. i.e. amount of features chd=t:40,36,32,28,24,20,16,12,8,4,0|40,39,38,37,36,35,30,25,23,21,18,14,12,9,1 // Data ``` The URL above plots in intervals of 2 - so work every 2 days. You'll need a bigger size chart for every day. To do this make the data have 30 values for estimated and actual, and change the "chxr" so the interval is 1, not two. You can plot only the days done more clearly with the "lxy" chart type (the first image). This needs you to enter the X data values too (so a vector). Use -1 for unknown.
118,130
<p>I'm using Windows Vista and C#.net 3.5, but I had my friend run the program on XP and has the same problem.</p> <p>So I have a C# program that I have running in the background with an icon in the SystemTray. I have a low level keyboard hook so when I press two keys (Ctr+windows in this case) it'll pull of the application's main form. The form is set to be full screen in the combo key press even handler:</p> <pre><code>this.FormBorderStyle = FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; </code></pre> <p>So it basically works. When I hit CTR+Windows it brings up the form, no matter what program I have given focus to. But sometimes, the taskbar will still show up over the form, which I don't want. I want it to always be full screen when I hit that key combo.</p> <p>I figure it has something to do with what application has focus originally. But even when I click on my main form, the taskbar sometimes stays there. So I wonder if focus really is the problem. It just seems like sometimes the taskbar is being stubborn and doesn't want to sit behind my program.</p> <p>Anyone have any ideas how I can fix this?</p> <p>EDIT: More details- I'm trying to achieve the same effect that a web browser has when you put it into fullscreen mode, or when you put powerpoint into presentation mode.</p> <p>In a windows form you do that by putting the border style to none and maximizing the window. But sometimes the window won't cover the taskbar for some reason. Half the time it will.</p> <p>If I have the main window topmost, the others will fall behind it when I click on it, which I don't want if the taskbar is hidden.</p>
[ { "answer_id": 118155, "author": "jdmichal", "author_id": 12275, "author_profile": "https://Stackoverflow.com/users/12275", "pm_score": 0, "selected": false, "text": "<p>As far as I know, the taskbar is either above or below windows based on the \"Keep the taskbar on top of other windows\" setting. (At least, that's the wording in XP.) I suppose you could try to see if you can detect this setting and toggle it if needed?</p>\n" }, { "answer_id": 118159, "author": "Paul Beesley", "author_id": 14333, "author_profile": "https://Stackoverflow.com/users/14333", "pm_score": 0, "selected": false, "text": "<p>Try resizing the form and bringing it to the front of the z-order like so:</p>\n\n<pre><code> Rectangle screenRect = Screen.GetBounds(this);\n this.Location = screenRect.Location;\n this.Size = screenRect.Size;\n this.BringToFront();\n</code></pre>\n" }, { "answer_id": 118170, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 5, "selected": true, "text": "<p>Try this (where <code>this</code> is your form):</p>\n\n<pre><code>this.Bounds = Screen.PrimaryScreen.Bounds;\nthis.TopMost = true;\n</code></pre>\n\n<p>That'll set the form to fullscreen, and it'll cover the taskbar.</p>\n" }, { "answer_id": 3577991, "author": "Ronen", "author_id": 432171, "author_profile": "https://Stackoverflow.com/users/432171", "pm_score": 1, "selected": false, "text": "<pre><code>private void Form1_KeyDown(object sender, KeyEventArgs e)\n{\n if (e.KeyCode == Keys.F11)\n if (FormBorderStyle == FormBorderStyle.None)\n {\n FormBorderStyle = FormBorderStyle.Sizable;\n WindowState = FormWindowState.Normal;\n }\n else\n {\n SuspendLayout();\n FormBorderStyle = FormBorderStyle.None;\n WindowState = FormWindowState.Maximized;\n ResumeLayout();\n }\n}\n</code></pre>\n" }, { "answer_id": 8868785, "author": "mammadalius", "author_id": 91055, "author_profile": "https://Stackoverflow.com/users/91055", "pm_score": 2, "selected": false, "text": "<p>I've tried so many solutions, some of them works on Windows XP and all of them did NOT work on Windows 7. After all I write a simple method to do so.</p>\n\n<pre><code>private void GoFullscreen(bool fullscreen)\n {\n if (fullscreen)\n {\n this.WindowState = FormWindowState.Normal;\n this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;\n this.Bounds = Screen.PrimaryScreen.Bounds;\n }\n else\n {\n this.WindowState = FormWindowState.Maximized;\n this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;\n }\n }\n</code></pre>\n\n<p>the order of code is important and will not work if you change the place of WindwosState and FormBorderStyle.</p>\n\n<p>One of the advantages of this method is leaving the TOPMOST on false that allow other forms to come over the main form.</p>\n\n<p>It absolutely solved my problem.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13713/" ]
I'm using Windows Vista and C#.net 3.5, but I had my friend run the program on XP and has the same problem. So I have a C# program that I have running in the background with an icon in the SystemTray. I have a low level keyboard hook so when I press two keys (Ctr+windows in this case) it'll pull of the application's main form. The form is set to be full screen in the combo key press even handler: ``` this.FormBorderStyle = FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; ``` So it basically works. When I hit CTR+Windows it brings up the form, no matter what program I have given focus to. But sometimes, the taskbar will still show up over the form, which I don't want. I want it to always be full screen when I hit that key combo. I figure it has something to do with what application has focus originally. But even when I click on my main form, the taskbar sometimes stays there. So I wonder if focus really is the problem. It just seems like sometimes the taskbar is being stubborn and doesn't want to sit behind my program. Anyone have any ideas how I can fix this? EDIT: More details- I'm trying to achieve the same effect that a web browser has when you put it into fullscreen mode, or when you put powerpoint into presentation mode. In a windows form you do that by putting the border style to none and maximizing the window. But sometimes the window won't cover the taskbar for some reason. Half the time it will. If I have the main window topmost, the others will fall behind it when I click on it, which I don't want if the taskbar is hidden.
Try this (where `this` is your form): ``` this.Bounds = Screen.PrimaryScreen.Bounds; this.TopMost = true; ``` That'll set the form to fullscreen, and it'll cover the taskbar.
118,143
<p>Not a competition, it is instead me trying to find why a certain regex works in one but not the other.</p> <pre><code>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) </code></pre> <p>That's my Regex and I'm trying to run it on</p> <pre><code>127.255.0.0 </code></pre> <p>Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python.</p> <pre><code>re.findall(regex, string) preg_match_all($regex, $string, $matches); </code></pre> <p><hr> Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated.</p>
[ { "answer_id": 118163, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 4, "selected": true, "text": "<p>It works for me. You must be doing something wrong.</p>\n\n<pre><code>&gt;&gt;&gt; re.match(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', '127.255.0.0').groups()\n('127', '255', '0', '0')\n</code></pre>\n\n<p>Don't forget to escape the regex using raw strings: <code>r'regex_here'</code> as stated in the <a href=\"http://docs.python.org/dev/howto/regex.html\" rel=\"nofollow noreferrer\">Regex Howto</a></p>\n" }, { "answer_id": 118165, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 1, "selected": false, "text": "<p>That regular expression matches here, no idea what you are doing wrong:</p>\n\n<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; x = re.compile(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|'\n... r'2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]'\n... r'[0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)')\n&gt;&gt;&gt; x.match(\"127.0.0.1\")\n&lt;_sre.SRE_Match object at 0x5a8860&gt;\n&gt;&gt;&gt; x.match(\"127.255.0.1\")\n&lt;_sre.SRE_Match object at 0x5a8910&gt;\n&gt;&gt;&gt; x.match(\"127.255.0.0\")\n&lt;_sre.SRE_Match object at 0x5a8860&gt;\n</code></pre>\n\n<p>Please note that <code>preg_match</code> translates to <code>re.search</code> in Python and not <code>re.match</code>. <code>re.match</code> is for useful for lexing because it's anchored.</p>\n" }, { "answer_id": 118180, "author": "WolfmanDragon", "author_id": 13491, "author_profile": "https://Stackoverflow.com/users/13491", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.regular-expressions.info/php.html\" rel=\"nofollow noreferrer\">PHP</a> uses 3 different flavors of regex, while python uses only one. I don't code in python, so I make no expert claims on how it uses REGEX. <a href=\"http://oreilly.com/catalog/9781565922570/\" rel=\"nofollow noreferrer\">O'Reilly Mastering Regular Expressions</a> is a great book, as most of their works are.</p>\n" }, { "answer_id": 118181, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>I would suggest that using a regex for decimal range validation is not necessarily the correct answer for this problem. This is far more readable:</p>\n\n<pre><code>def valid_ip(s):\n m = re.match(r\"(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$\", s)\n if m is None:\n return False\n parts = [int(m.group(1+x)) for x in range(4)]\n if max(parts) &gt; 255:\n return False\n return True\n</code></pre>\n" }, { "answer_id": 118182, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "<p>Without further details, I'd guess it's quote escaping of some kind. Both PHP and python's RegEX objects take strings as arguments. These strings will be escaped by the languge before being passed on to the RegEx engine.</p>\n\n<p>I always using Python's \"raw\" string format when working with regular expressions. It ensure that \"<a href=\"http://www.amk.ca/python/howto/regex/\" rel=\"nofollow noreferrer\">backslashes are not handled in any special way</a>\"</p>\n\n<pre><code>r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'\n</code></pre>\n" }, { "answer_id": 198882, "author": "david", "author_id": 27600, "author_profile": "https://Stackoverflow.com/users/27600", "pm_score": 2, "selected": false, "text": "<p>Just because you <em>can</em> do it with regex, doesn't mean you should. It would be much better to write instructions like: split the string on the period, make sure each group is numeric and within a certain range of numbers.</p>\n\n<p>If you want to use a regex, just verify that it kind of \"looks like\" an IP address, as with Greg's regex.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
Not a competition, it is instead me trying to find why a certain regex works in one but not the other. ``` (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) ``` That's my Regex and I'm trying to run it on ``` 127.255.0.0 ``` Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python. ``` re.findall(regex, string) preg_match_all($regex, $string, $matches); ``` --- Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated.
It works for me. You must be doing something wrong. ``` >>> re.match(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', '127.255.0.0').groups() ('127', '255', '0', '0') ``` Don't forget to escape the regex using raw strings: `r'regex_here'` as stated in the [Regex Howto](http://docs.python.org/dev/howto/regex.html)
118,144
<p>What's the most efficient way to select the last n number of rows in a table using mySQL? The table contains millions of rows, and at any given time I don't know how large the table is (it is constantly growing). The table does have a column that is automatically incremented and used as a unique identifier for each row.</p>
[ { "answer_id": 118169, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 7, "selected": true, "text": "<pre class=\"lang-sql prettyprint-override\"><code>SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT n\n</code></pre>\n" }, { "answer_id": 118171, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 2, "selected": false, "text": "<p>Use ORDER BY to sort by the identifier column in DESC order, and use LIMIT to specify how many results you want.</p>\n" }, { "answer_id": 118172, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>Maybe order it by the unique id descending:</p>\n\n<pre><code>SELECT * FROM table ORDER BY id DESC LIMIT n\n</code></pre>\n\n<p>The only problem with this is that you might want to select in a different order, and this problem has made me have to select the last rows by counting the number of rows and then selecting them using LIMIT, but obviously that's probably not a good solution in your case.</p>\n" }, { "answer_id": 118178, "author": "Ray", "author_id": 233, "author_profile": "https://Stackoverflow.com/users/233", "pm_score": 2, "selected": false, "text": "<p>You would probably also want to add a descending index (or whatever they're called in mysql) as well to make the select fast if it's something you're going to do often.</p>\n" }, { "answer_id": 11083649, "author": "Sergey Telshevsky", "author_id": 836646, "author_profile": "https://Stackoverflow.com/users/836646", "pm_score": 4, "selected": false, "text": "<p>Actually the right way to get last n rows in order is to use a subquery:</p>\n\n<pre><code>(SELECT id, title, description FROM my_table ORDER BY id DESC LIMIT 5) \nORDER BY tbl.id ASC\n</code></pre>\n\n<p>As this way is the only I know that will return them in right order. The accepted answer is actually a solution for \"<em>Select first 5 rows from a set ordered by descending ID</em>\", but that is most probably what you need.</p>\n" }, { "answer_id": 27200520, "author": "Marco", "author_id": 4305959, "author_profile": "https://Stackoverflow.com/users/4305959", "pm_score": 1, "selected": false, "text": "<p>This is a lot faster when you have big tables because you don't have to order an entire table.\nYou just use id as a unique row identifier. \nThis is also more eficient when you have big amounts of data in some colum(s) as images for example (blobs). The order by in this case can be very time and data consuming.</p>\n\n<pre><code>select * \nfrom TableName \nwhere id &gt; ((select max(id) from TableName)-(NumberOfRowsYouWant+1)) \norder by id desc|asc\n</code></pre>\n\n<p>The only problem is if you delete rows in the interval you want. In this case you would't get the real \"NumberOfRowsYouWant\".</p>\n\n<p>You can also easily use this to select n rows for each page just by multiplying (NumberOfRowsYouWant+1) by page number when you need to show the table backwards in multiple web pages.</p>\n" }, { "answer_id": 35505304, "author": "tron5", "author_id": 2700360, "author_profile": "https://Stackoverflow.com/users/2700360", "pm_score": 3, "selected": false, "text": "<p>(Similar to \"marco\"s answer,)<br>\nmy fav is the max()-function of MySQL too, in a simple <strong>one-liner</strong>, but there are other ways of sure:</p>\n\n<pre><code>SELECT whatever FROM mytable WHERE id &gt; (SELECT max(id)-10 FROM mytable);\n</code></pre>\n\n<p>... and you get \"last id minus 10\", normally the last 10 entries of that table.<br>\n<br>\nIt's a short way, to avoid the a error 1111 (\"Invalid use of group function\") not only if there is a auto_increment-row (here id).<br>\nThe max()-function can be used many ways.</p>\n" }, { "answer_id": 41952323, "author": "Vipin Pandey", "author_id": 6883436, "author_profile": "https://Stackoverflow.com/users/6883436", "pm_score": 0, "selected": false, "text": "<p>Here you can change table name and column name according your requirement . if you want to show last 10 row then put n=10,or n=20 ,or n=30 ...etc according your requirement.</p>\n\n<p>select * from\n(select * from employee \nOrder by emp_id desc limit n) \na Order by emp_id asc;</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9076/" ]
What's the most efficient way to select the last n number of rows in a table using mySQL? The table contains millions of rows, and at any given time I don't know how large the table is (it is constantly growing). The table does have a column that is automatically incremented and used as a unique identifier for each row.
```sql SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT n ```
118,190
<p>I have a SQL script that creates a package with a comment containing an ampersand (&amp;). When I run the script from SQL Plus, I am prompted to enter a substitute value for the string starting with &amp;. How do I disable this feature so that SQL Plus ignores the ampersand?</p>
[ { "answer_id": 118210, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 9, "selected": true, "text": "<p>This may work for you:</p>\n\n<pre><code>set define off\n</code></pre>\n\n<p>Otherwise the ampersand needs to be at the end of a string, </p>\n\n<pre><code>'StackOverflow &amp;' || ' you'\n</code></pre>\n\n<p>EDIT: I was click-happy when saving... This was referenced from a <a href=\"http://blog.andrewbeacock.com/2008/09/using-ampersands-without-variable_15.html\" rel=\"noreferrer\">blog</a>.</p>\n" }, { "answer_id": 118217, "author": "user19387", "author_id": 19387, "author_profile": "https://Stackoverflow.com/users/19387", "pm_score": 2, "selected": false, "text": "<p>According to <a href=\"http://www.orafaq.com/wiki/SQL*Plus_FAQ#How_does_one_disable_interactive_prompting_in_SQL.2APlus.3F\" rel=\"nofollow noreferrer\">this nice FAQ</a> there are a couple solutions.</p>\n\n<p>You might also be able to escape the ampersand with the backslash character <code>\\</code> if you can modify the comment.</p>\n" }, { "answer_id": 4393005, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 5, "selected": false, "text": "<p>If you sometimes use substitution variables you might not want to turn define off. In these cases you could convert the ampersand from its numeric equivalent as in <code>|| Chr(38) ||</code> or append it as a single character as in <code>|| '&amp;' ||</code>.</p>\n" }, { "answer_id": 13511214, "author": "Cauca", "author_id": 1451781, "author_profile": "https://Stackoverflow.com/users/1451781", "pm_score": 4, "selected": false, "text": "<p>I resolved with the code below:</p>\n\n<pre><code>set escape on\n</code></pre>\n\n<p>and put a \\ beside &amp; in the left <code>'value_\\&amp;_intert'</code></p>\n\n<p>Att</p>\n" }, { "answer_id": 27345583, "author": "tvCa", "author_id": 4282156, "author_profile": "https://Stackoverflow.com/users/4282156", "pm_score": 3, "selected": false, "text": "<p>You can set the special character, which is looked for upon execution of a script, to another value by means of using the <code>SET DEFINE &lt;1_CHARACTER&gt;</code></p>\n\n<p>By default, the DEFINE function itself is on, and it is set to <strong>&amp;</strong></p>\n\n<p>It can be turned off - as mentioned already - but it can be avoided as well by means of setting it to a different value. Be very aware of what sign you set it to. In the below example, I've chose the # character, but that choice is just an example.</p>\n\n<pre><code>SQL&gt; select '&amp;var_ampersand #var_hash' from dual;\nEnter value for var_ampersand: a value\n\n'AVALUE#VAR_HASH'\n-----------------\na value #var_hash\n\nSQL&gt; set define #\nSQL&gt; r\n 1* select '&amp;var_ampersand #var_hash' from dual\nEnter value for var_hash: another value\n\n'&amp;VAR_AMPERSANDANOTHERVALUE'\n----------------------------\n&amp;var_ampersand another value\n\nSQL&gt;\n</code></pre>\n" }, { "answer_id": 30333520, "author": "ora", "author_id": 4917530, "author_profile": "https://Stackoverflow.com/users/4917530", "pm_score": 3, "selected": false, "text": "<p>set define off &lt;- This is the best solution I found</p>\n\n<p>I also tried...</p>\n\n<p>set define } </p>\n\n<p>I was able to insert several records containing ampersand characters '&amp;' but I cannot use the '}' character into the text\nSo I decided to use \"set define off\" and everything works as it should.</p>\n" }, { "answer_id": 51257086, "author": "AWOLKiwi", "author_id": 8685916, "author_profile": "https://Stackoverflow.com/users/8685916", "pm_score": 0, "selected": false, "text": "<p>I had a CASE statement with WHEN column = 'sometext &amp; more text' THEN ....</p>\n\n<p>I replaced it with\nWHEN column = 'sometext ' || CHR(38) || ' more text' THEN ...</p>\n\n<p>you could also use\nWHEN column LIKE 'sometext _ more text' THEN ...</p>\n\n<p>(_ is the wildcard for a single character)</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20625/" ]
I have a SQL script that creates a package with a comment containing an ampersand (&). When I run the script from SQL Plus, I am prompted to enter a substitute value for the string starting with &. How do I disable this feature so that SQL Plus ignores the ampersand?
This may work for you: ``` set define off ``` Otherwise the ampersand needs to be at the end of a string, ``` 'StackOverflow &' || ' you' ``` EDIT: I was click-happy when saving... This was referenced from a [blog](http://blog.andrewbeacock.com/2008/09/using-ampersands-without-variable_15.html).
118,199
<p>I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change? I don't have any syncronization or Mutual exclusion system in place... but should this code work all the time (imagine a global <strong>bool</strong> named <strong>dataUpdated</strong>):</p> <p>Thread 1:</p> <pre><code>while(1) { if (dataUpdated) updateScreen(); doSomethingElse(); } </code></pre> <p>Thread 2:</p> <pre><code>while(1) { if (doSomething()) dataUpdated = TRUE; } </code></pre> <p>Does a compiler like gcc optimize this code in a way that it doesn't check for the global value, only considering it value at compile time (because it nevers get changed at the same thred)?</p> <p>PS: Being this for a game-like application, it really doen't matter if there will be a read while the value is being written... all that matters is that the change gets noticed by the other thread.</p>
[ { "answer_id": 118204, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "<p>Use the <strong>volatile</strong> keyword to hint to the compiler that the value can change at any time.</p>\n\n<pre><code>volatile int myInteger;\n</code></pre>\n" }, { "answer_id": 118208, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>No, it's not certain. If you declare the variable volatile, then the complier is supposed to generate code that always loads the variable from memory on a read.</p>\n" }, { "answer_id": 118211, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Your solution will use 100% CPU, among other problems. Google for \"condition variable\".</p>\n" }, { "answer_id": 118238, "author": "fabiopedrosa", "author_id": 2731698, "author_profile": "https://Stackoverflow.com/users/2731698", "pm_score": 2, "selected": false, "text": "<p>Chris Jester-Young pointed out that:</p>\n\n<blockquote>\n <p>This only work under Java 1.5+'s memory model. The C++ standard does not address threading, and volatile does not guarantee memory coherency between processors. You do need a memory barrier for this</p>\n</blockquote>\n\n<p>being so, the only true answer is implementing a synchronization system, right?</p>\n" }, { "answer_id": 118266, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": false, "text": "<p>Here is an example that uses boost condition variables:</p>\n\n<pre><code>bool _updated=false;\nboost::mutex _access;\nboost::condition _condition;\n\nbool updated()\n{\n return _updated;\n}\n\nvoid thread1()\n{\n boost::mutex::scoped_lock lock(_access);\n while (true)\n {\n boost::xtime xt;\n boost::xtime_get(&amp;xt, boost::TIME_UTC);\n // note that the second parameter to timed_wait is a predicate function that is called - not the address of a variable to check\n if (_condition.timed_wait(lock, &amp;updated, xt))\n updateScreen();\n doSomethingElse();\n }\n}\n\nvoid thread2()\n{\n while(true)\n {\n if (doSomething())\n _updated=true;\n }\n}\n</code></pre>\n" }, { "answer_id": 118269, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 1, "selected": false, "text": "<p>If the scope is right ( \"extern\", global, etc. ) then the change will be noticed. The question is when? And in what order?</p>\n\n<p>The problem is that the compiler <strong>can</strong> and frequently <strong>will</strong> re-order your logic to fill all it's concurrent pipelines as a performance optimization.</p>\n\n<p>It doesn't really show in your specific example because there aren't any other instructions around your assignment, but imagine functions declared after your bool assign execute <strong>before</strong> the assignment.</p>\n\n<p>Check-out <a href=\"http://en.wikipedia.org/wiki/Pipeline_stall#Eliminating_hazards\" rel=\"nofollow noreferrer\">Pipeline Hazard</a> on wikipedia or search google for \"compiler instruction reordering\"</p>\n" }, { "answer_id": 118283, "author": "Niall", "author_id": 6049, "author_profile": "https://Stackoverflow.com/users/6049", "pm_score": 3, "selected": false, "text": "<p>Use a lock. Always always use a lock to access shared data. Marking the variable as volatile will prevent the compiler from optimizing away the memory read, but will not prevent other problems such as <a href=\"http://en.wikipedia.org/wiki/Memory_ordering\" rel=\"noreferrer\">memory re-ordering</a>. Without a lock there is no guarantee that the memory writes in doSomething() will be visible in the updateScreen() function.</p>\n\n<p>The only other safe way is to use a <a href=\"http://en.wikipedia.org/wiki/Memory_barrier\" rel=\"noreferrer\">memory fence</a>, either explicitly or an implicitly using an Interlocked* function for example.</p>\n" }, { "answer_id": 118296, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "<p>As others have said the <code>volatile</code> keyword is your friend. :-)</p>\n\n<p>You'll most likely find that your code would work when you had all of the optimisation options disabled in gcc. In this case (I believe) it treats everything as volatile and as a result the variable is accessed in memory for every operation.</p>\n\n<p>With any sort of optimisation turned on the compiler will attempt to use a local copy held in a register. Depending on your functions this may mean that you only see the change in variable intermittently or, at worst, never.</p>\n\n<p>Using the keyword <code>volatile</code> indicates to the compiler that the contents of this variable can change at any time and that it should <em>not</em> use a locally cached copy.</p>\n\n<p>With all of that said you may find better results (as alluded to by <a href=\"https://stackoverflow.com/questions/118199/c-thread-shared-data#118211\">Jeff</a>) through the use of a semaphore or condition variable.</p>\n\n<p><a href=\"http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html\" rel=\"nofollow noreferrer\">This</a> is a reasonable introduction to the subject.</p>\n" }, { "answer_id": 118311, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 6, "selected": true, "text": "<p>Yes. No. Maybe.</p>\n\n<p>First, as others have mentioned you need to make dataUpdated volatile; otherwise the compiler may be free to lift reading it out of the loop (depending on whether or not it can see that doSomethingElse doesn't touch it).</p>\n\n<p>Secondly, depending on your processor and ordering needs, you may need memory barriers. volatile is enough to guarentee that the other processor will see the change eventually, but not enough to guarentee that the changes will be seen in the order they were performed. Your example only has one flag, so it doesn't really show this phenomena. If you need and use memory barriers, you should no longer need volatile</p>\n\n<p><a href=\"http://www.kernel.org/doc/Documentation/volatile-considered-harmful.txt\" rel=\"noreferrer\">Volatile considered harmful</a> and <a href=\"http://www.kernel.org/doc/Documentation/memory-barriers.txt\" rel=\"noreferrer\">Linux Kernel Memory Barriers</a> are good background on the underlying issues; I don't really know of anything similar written specifically for threading. Thankfully threads don't raise these concerns nearly as often as hardware peripherals do, though the sort of case you describe (a flag indicating completion, with other data presumed to be valid if the flag is set) is exactly the sort of thing where ordering matterns...</p>\n" }, { "answer_id": 118345, "author": "Tall Jeff", "author_id": 1553, "author_profile": "https://Stackoverflow.com/users/1553", "pm_score": 3, "selected": false, "text": "<p>Use the <strong><em>volatile</em></strong> keyword to hint to the compiler that the value can change at any time.</p>\n\n<pre><code>volatile int myInteger;\n</code></pre>\n\n<p>The above will guarantee that any access to the variable will be to and from memory without any specific optimizations and as a result all threads running on the same processor will \"see\" changes to the variable with the same semantics as the code reads.</p>\n\n<p>Chris Jester-Young pointed out that coherency concerns to such a variable value change may arise in a multi-processor systems. This is a consideration and it depends on the platform.</p>\n\n<p>Actually, there are really two considerations to think about relative to platform. They are coherency and atomicity of the memory transactions.</p>\n\n<p>Atomicity is actually a consideration for both single and multi-processor platforms. The issue arises because the variable is likely multi-byte in nature and the question is if one thread could see a partial update to the value or not. ie: Some bytes changed, context switch, invalid value read by interrupting thread. For a single variable that is at the natural machine word size or smaller and naturally aligned should not be a concern. Specifically, an <strong><em>int</em></strong> type should always be OK in this regard as long as it is aligned - which should be the default case for the compiler.</p>\n\n<p>Relative to coherency, this is a potential concern in a multi-processor system. The question is if the system implements full cache coherency or not between processors. If implemented, this is typically done with the MESI protocol in hardware. The question didn't state platforms, but both Intel x86 platforms and PowerPC platforms are cache coherent across processors for normally mapped program data regions. Therefore this type of issue should not be a concern for ordinary data memory accesses between threads even if there are multiple processors.</p>\n\n<p>The final issue relative to atomicity that arises is specific to read-modify-write atomicity. That is, how do you guarantee that if a value is read updated in value and the written, that this happen atomically, even across processors if more than one. So, for this to work without specific synchronization objects, would require that all potential threads accessing the variable are readers ONLY but expect for only one thread can ever be a writer at one time. If this is not the case, then you do need a sync object available to be able to ensure atomic actions on read-modify-write actions to the variable.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2731698/" ]
I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change? I don't have any syncronization or Mutual exclusion system in place... but should this code work all the time (imagine a global **bool** named **dataUpdated**): Thread 1: ``` while(1) { if (dataUpdated) updateScreen(); doSomethingElse(); } ``` Thread 2: ``` while(1) { if (doSomething()) dataUpdated = TRUE; } ``` Does a compiler like gcc optimize this code in a way that it doesn't check for the global value, only considering it value at compile time (because it nevers get changed at the same thred)? PS: Being this for a game-like application, it really doen't matter if there will be a read while the value is being written... all that matters is that the change gets noticed by the other thread.
Yes. No. Maybe. First, as others have mentioned you need to make dataUpdated volatile; otherwise the compiler may be free to lift reading it out of the loop (depending on whether or not it can see that doSomethingElse doesn't touch it). Secondly, depending on your processor and ordering needs, you may need memory barriers. volatile is enough to guarentee that the other processor will see the change eventually, but not enough to guarentee that the changes will be seen in the order they were performed. Your example only has one flag, so it doesn't really show this phenomena. If you need and use memory barriers, you should no longer need volatile [Volatile considered harmful](http://www.kernel.org/doc/Documentation/volatile-considered-harmful.txt) and [Linux Kernel Memory Barriers](http://www.kernel.org/doc/Documentation/memory-barriers.txt) are good background on the underlying issues; I don't really know of anything similar written specifically for threading. Thankfully threads don't raise these concerns nearly as often as hardware peripherals do, though the sort of case you describe (a flag indicating completion, with other data presumed to be valid if the flag is set) is exactly the sort of thing where ordering matterns...
118,205
<p>At work, we have a windows server 2003 with IIS and Subversion installed. We use it to publish and test locally our ASP.NET websites. Every programmer has Tortoise installed on his PC and can update/commit content to the server. Hosting the repositories is working fine. But the files kept in those repositories needs then to be copied to our local IIS (virtual directories). </p> <p>What is an easy way to publish those subversion repositories to our local IIS?</p> <p>Edit:<br /> Thanks to <a href="https://stackoverflow.com/users/14312/puetzk">puetzk</a> I added a simple bat file that gets executed every time a commit occurs (check the <a href="http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html" rel="nofollow noreferrer">subversion documentation</a> about hooks). My bat file only contains: </p> <pre><code>echo off setlocal :: Localize the working copy where IIS points) pushd E:\wwwroot\yourapp\trunk :: Update your working copy svn update endlocal exit </code></pre>
[ { "answer_id": 118229, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 3, "selected": false, "text": "<p>SVN doesn't support IIS; you can however <a href=\"http://svn.collab.net/repos/svn/trunk/notes/windows-service.txt\" rel=\"nofollow noreferrer\">run the standalone svnserve server as a windows service</a>. </p>\n\n<p>There's the <a href=\"http://subversion.tigris.org/faq.html#svnserve-win-service\" rel=\"nofollow noreferrer\">SVN FAQ entry</a> about it, and this blog post on <a href=\"http://blogs.vertigosoftware.com/teamsystem/archive/2006/01/16/Setting_up_a_Subversion_Server_under_Windows.aspx\" rel=\"nofollow noreferrer\">Vertigo Software blog</a> may be helpful too.</p>\n\n<p>UPDATE:\nAfter your clarification, I see that what you are looking for is a way to automatically update the code on the server after it's checked in. Look into <a href=\"http://ccnet.thoughtworks.com/\" rel=\"nofollow noreferrer\">CruiseControl.NET</a>, after looking at the <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Subversion+Source+Control+Block\" rel=\"nofollow noreferrer\">subversion integration tutorial</a> it looks like it should do what you want.</p>\n\n<p>UPDATE 2: This tutorial describes <a href=\"http://www.testearly.com/2006/05/01/integrating-ccnet-with-nant-and-subversion-on-windows/\" rel=\"nofollow noreferrer\">integrating Subversion, CruiseControl.NET and Nant</a>.</p>\n" }, { "answer_id": 118246, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 5, "selected": true, "text": "<ol>\n<li><p>Just keep the web server's file area as a working copy, and perform an svn up in it whenever you want to \"publish\". Configure it to hide the contents of the .svn folders if they seem untidy to you (I don't specifically know how to do this, but I assume it can be done). They will already have the filesystem hidden bit, which may take care of this.</p></li>\n<li><p>If you want it really automatic (updates as soon as someone commits), use a post-commit hook script on the SVN server to kick off the first process.</p></li>\n</ol>\n\n<p>Others in the comments have suggested using export instead of checkout. That can work too, and avoids the .svn clutter, but has two drawbacks. One, it has to redownload the entire contents every time, not just the modified files (since it didn't keep the .svn dir to remember what it has). If you have a lot of files, this will be much slower. Two, update replaces the file atomically (writes the new version in .svn/tmp, then moves it into place). Export writes the file gradually into it's destination as it downloads. That means export could deliver an incomplete file to someone who browsed it at just the wrong time.</p>\n" }, { "answer_id": 118309, "author": "zvikara", "author_id": 9937, "author_profile": "https://Stackoverflow.com/users/9937", "pm_score": 1, "selected": false, "text": "<p>Use can use the free <a href=\"http://www.visualsvn.com/server/\" rel=\"nofollow noreferrer\">Visual-SVN Server</a> to quickly install Subversion with Apache front end. It also have a nice MMC snap-in for managing the server and repositories.</p>\n\n<p>You will than be able to access subversion with HTTP or HTTPS, but the port number must be different from the one your local IIS uses (default port for Visual-SVN server is 8080).</p>\n\n<p>If you really need to access the repositories using your local IIS port 80, you can try <a href=\"http://www.svniis.org/\" rel=\"nofollow noreferrer\">SVN-IIS</a> which acts as a bridge between your IIS and Apache. I haven't tried this one myself though.</p>\n" }, { "answer_id": 1900125, "author": "user231161", "author_id": 231161, "author_profile": "https://Stackoverflow.com/users/231161", "pm_score": 2, "selected": false, "text": "<p>maybe SVNIsapi can solve the problem (<a href=\"http://www.svnisapi.com\" rel=\"nofollow noreferrer\">http://www.svnisapi.com</a>). Cause it only utilizes an IIS installation, therefore you don't need an APACHE server or an SVNSERVER service. Secondly it should be possible to stack the ASP.NET ISAPI plugin onto the processing of SVNISAPI, so that a ASP.NET (.aspx) page will interpreted after read from the repository.</p>\n\n<p>Cheers\nPaolo</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/296/" ]
At work, we have a windows server 2003 with IIS and Subversion installed. We use it to publish and test locally our ASP.NET websites. Every programmer has Tortoise installed on his PC and can update/commit content to the server. Hosting the repositories is working fine. But the files kept in those repositories needs then to be copied to our local IIS (virtual directories). What is an easy way to publish those subversion repositories to our local IIS? Edit: Thanks to [puetzk](https://stackoverflow.com/users/14312/puetzk) I added a simple bat file that gets executed every time a commit occurs (check the [subversion documentation](http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html) about hooks). My bat file only contains: ``` echo off setlocal :: Localize the working copy where IIS points) pushd E:\wwwroot\yourapp\trunk :: Update your working copy svn update endlocal exit ```
1. Just keep the web server's file area as a working copy, and perform an svn up in it whenever you want to "publish". Configure it to hide the contents of the .svn folders if they seem untidy to you (I don't specifically know how to do this, but I assume it can be done). They will already have the filesystem hidden bit, which may take care of this. 2. If you want it really automatic (updates as soon as someone commits), use a post-commit hook script on the SVN server to kick off the first process. Others in the comments have suggested using export instead of checkout. That can work too, and avoids the .svn clutter, but has two drawbacks. One, it has to redownload the entire contents every time, not just the modified files (since it didn't keep the .svn dir to remember what it has). If you have a lot of files, this will be much slower. Two, update replaces the file atomically (writes the new version in .svn/tmp, then moves it into place). Export writes the file gradually into it's destination as it downloads. That means export could deliver an incomplete file to someone who browsed it at just the wrong time.
118,241
<p>I'd like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?</p> <p>If it's not built-in, my only idea is to create a table of widths for each character, but this is pretty unreasonable especially supporting <a href="http://en.wikipedia.org/wiki/Unicode" rel="noreferrer">Unicode</a> and different type sizes (and all browsers for that matter).</p>
[ { "answer_id": 118251, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": 10, "selected": true, "text": "<p>Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var fontSize = 12;\r\nvar test = document.getElementById(\"Test\");\r\ntest.style.fontSize = fontSize;\r\nvar height = (test.clientHeight + 1) + \"px\";\r\nvar width = (test.clientWidth + 1) + \"px\"\r\n\r\nconsole.log(height, width);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#Test\r\n{\r\n position: absolute;\r\n visibility: hidden;\r\n height: auto;\r\n width: auto;\r\n white-space: nowrap; /* Thanks to Herb Caudill comment */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"Test\"&gt;\r\n abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 118268, "author": "Bryan Friedman", "author_id": 16985, "author_profile": "https://Stackoverflow.com/users/16985", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;span id=\"text\"&gt;Text&lt;/span&gt;\n\n&lt;script&gt;\nvar textWidth = document.getElementById(\"text\").offsetWidth;\n&lt;/script&gt;\n</code></pre>\n\n<p>This should work as long as the &lt;span&gt; tag has no other styles applied to it.\noffsetWidth will include the width of any borders, horizontal padding, vertical scrollbar width, etc. </p>\n" }, { "answer_id": 122370, "author": "big lep", "author_id": 16318, "author_profile": "https://Stackoverflow.com/users/16318", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"https://www.sencha.com/products/extjs/\" rel=\"nofollow noreferrer\">ExtJS javascript library</a> has a great class called Ext.util.TextMetrics that \"provides precise pixel measurements for blocks of text so that you can determine exactly how high and wide, in pixels, a given block of text will be\". You can either use it directly or view its source to code to see how this is done.</p>\n\n<p><a href=\"http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html\" rel=\"nofollow noreferrer\">http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html</a></p>\n" }, { "answer_id": 2117698, "author": "Deepak Nadar", "author_id": 256784, "author_profile": "https://Stackoverflow.com/users/256784", "pm_score": 5, "selected": false, "text": "<p>jQuery:</p>\n\n<pre><code>(function($) {\n\n $.textMetrics = function(el) {\n\n var h = 0, w = 0;\n\n var div = document.createElement('div');\n document.body.appendChild(div);\n $(div).css({\n position: 'absolute',\n left: -1000,\n top: -1000,\n display: 'none'\n });\n\n $(div).html($(el).html());\n var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];\n $(styles).each(function() {\n var s = this.toString();\n $(div).css(s, $(el).css(s));\n });\n\n h = $(div).outerHeight();\n w = $(div).outerWidth();\n\n $(div).remove();\n\n var ret = {\n height: h,\n width: w\n };\n\n return ret;\n }\n\n})(jQuery);\n</code></pre>\n" }, { "answer_id": 3140086, "author": "Techek", "author_id": 231144, "author_profile": "https://Stackoverflow.com/users/231144", "pm_score": 2, "selected": false, "text": "<p>The code-snips below, \"calculate\" the width of the span-tag, appends \"...\" to it if its too long and reduces the text-length, until it fits in its parent (or until it has tried more than a thousand times)</p>\n\n<p>CSS</p>\n\n<pre><code>div.places {\n width : 100px;\n}\ndiv.places span {\n white-space:nowrap;\n overflow:hidden;\n}\n</code></pre>\n\n<p>HTML</p>\n\n<pre><code>&lt;div class=\"places\"&gt;\n &lt;span&gt;This is my house&lt;/span&gt;\n&lt;/div&gt;\n&lt;div class=\"places\"&gt;\n &lt;span&gt;And my house are your house&lt;/span&gt;\n&lt;/div&gt;\n&lt;div class=\"places\"&gt;\n &lt;span&gt;This placename is most certainly too wide to fit&lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>JavaScript (with jQuery)</p>\n\n<pre><code>// loops elements classed \"places\" and checks if their child \"span\" is too long to fit\n$(\".places\").each(function (index, item) {\n var obj = $(item).find(\"span\");\n if (obj.length) {\n var placename = $(obj).text();\n if ($(obj).width() &gt; $(item).width() &amp;&amp; placename.trim().length &gt; 0) {\n var limit = 0;\n do {\n limit++;\n placename = placename.substring(0, placename.length - 1);\n $(obj).text(placename + \"...\");\n } while ($(obj).width() &gt; $(item).width() &amp;&amp; limit &lt; 1000)\n }\n }\n});\n</code></pre>\n" }, { "answer_id": 4032497, "author": "Pete", "author_id": 488707, "author_profile": "https://Stackoverflow.com/users/488707", "pm_score": 5, "selected": false, "text": "<p>This works for me...</p>\n<pre><code>// Handy JavaScript to measure the size taken to render the supplied text;\n// you can supply additional style information too if you have it.\n\nfunction measureText(pText, pFontSize, pStyle) {\n var lDiv = document.createElement('div');\n\n document.body.appendChild(lDiv);\n\n if (pStyle != null) {\n lDiv.style = pStyle;\n }\n lDiv.style.fontSize = &quot;&quot; + pFontSize + &quot;px&quot;;\n lDiv.style.position = &quot;absolute&quot;;\n lDiv.style.left = -1000;\n lDiv.style.top = -1000;\n\n lDiv.textContent = pText;\n\n var lResult = {\n width: lDiv.clientWidth,\n height: lDiv.clientHeight\n };\n\n document.body.removeChild(lDiv);\n lDiv = null;\n\n return lResult;\n}\n</code></pre>\n" }, { "answer_id": 5047712, "author": "Bob Monteverde", "author_id": 623933, "author_profile": "https://Stackoverflow.com/users/623933", "pm_score": 7, "selected": false, "text": "<p>Here's one I whipped together without example. It looks like we are all on the same page.</p>\n\n<pre><code>String.prototype.width = function(font) {\n var f = font || '12px arial',\n o = $('&lt;div&gt;&lt;/div&gt;')\n .text(this)\n .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})\n .appendTo($('body')),\n w = o.width();\n\n o.remove();\n\n return w;\n}\n</code></pre>\n\n<p>Using it is simple: <code>\"a string\".width()</code></p>\n\n<p>**Added <code>white-space: nowrap</code> so strings with width larger than the window width can be calculated.</p>\n" }, { "answer_id": 14291586, "author": "rysama", "author_id": 200363, "author_profile": "https://Stackoverflow.com/users/200363", "pm_score": 3, "selected": false, "text": "<p>You can use the canvas so you don't have to deal so much with css properties:</p>\n\n<pre><code>var canvas = document.createElement(\"canvas\");\nvar ctx = canvas.getContext(\"2d\");\nctx.font = \"20pt Arial\"; // This can be set programmaticly from the element's font-style if desired\nvar textWidth = ctx.measureText($(\"#myElement\").text()).width;\n</code></pre>\n" }, { "answer_id": 14411323, "author": "Jason Bracey", "author_id": 1992316, "author_profile": "https://Stackoverflow.com/users/1992316", "pm_score": 1, "selected": false, "text": "<p>Try this code:</p>\n\n<pre><code>function GetTextRectToPixels(obj)\n{\nvar tmpRect = obj.getBoundingClientRect();\nobj.style.width = \"auto\"; \nobj.style.height = \"auto\"; \nvar Ret = obj.getBoundingClientRect(); \nobj.style.width = (tmpRect.right - tmpRect.left).toString() + \"px\";\nobj.style.height = (tmpRect.bottom - tmpRect.top).toString() + \"px\"; \nreturn Ret;\n}\n</code></pre>\n" }, { "answer_id": 17118176, "author": "Gjaa", "author_id": 2171254, "author_profile": "https://Stackoverflow.com/users/2171254", "pm_score": 1, "selected": false, "text": "<p>The width and heigth of a text can be obtained with <code>clientWidth</code> and <code>clientHeight</code></p>\n\n<pre><code>var element = document.getElementById (\"mytext\");\n\nvar width = element.clientWidth;\nvar height = element.clientHeight;\n</code></pre>\n\n<p>make sure that style position property is set to absolute</p>\n\n<pre><code>element.style.position = \"absolute\";\n</code></pre>\n\n<p>not required to be inside a <code>div</code>, can be inside a <code>p</code> or a <code>span</code></p>\n" }, { "answer_id": 18789999, "author": "artnikpro", "author_id": 1955709, "author_profile": "https://Stackoverflow.com/users/1955709", "pm_score": 2, "selected": false, "text": "<p>The better of is to detect whether text will fits right before you display the element. So you can use this function which doesn't requires the element to be on screen.</p>\n\n<pre><code>function textWidth(text, fontProp) {\n var tag = document.createElement(\"div\");\n tag.style.position = \"absolute\";\n tag.style.left = \"-999em\";\n tag.style.whiteSpace = \"nowrap\";\n tag.style.font = fontProp;\n tag.innerHTML = text;\n\n document.body.appendChild(tag);\n\n var result = tag.clientWidth;\n\n document.body.removeChild(tag);\n\n return result;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>if ( textWidth(\"Text\", \"bold 13px Verdana\") &gt; elementWidth) {\n ...\n}\n</code></pre>\n" }, { "answer_id": 19994364, "author": "kavun", "author_id": 789893, "author_profile": "https://Stackoverflow.com/users/789893", "pm_score": -1, "selected": false, "text": "<pre><code>var textWidth = (function (el) {\n el.style.position = 'absolute';\n el.style.top = '-1000px';\n document.body.appendChild(el);\n\n return function (text) {\n el.innerHTML = text;\n return el.clientWidth;\n };\n})(document.createElement('div'));\n</code></pre>\n" }, { "answer_id": 21015393, "author": "Domi", "author_id": 2228771, "author_profile": "https://Stackoverflow.com/users/2228771", "pm_score": 9, "selected": false, "text": "<p>In <strong>HTML 5</strong>, you can just use the <a href=\"http://www.w3schools.com/tags/canvas_measuretext.asp\" rel=\"noreferrer\">Canvas.measureText method</a> (further explanation <a href=\"http://www.html5canvastutorials.com/tutorials/html5-canvas-text-metrics/\" rel=\"noreferrer\">here</a>).</p>\n<p><a href=\"http://jsfiddle.net/eNzjZ/34/\" rel=\"noreferrer\">Try this fiddle</a>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * Uses canvas.measureText to compute and return the width of the given text of given font in pixels.\n * \n * @param {String} text The text to be rendered.\n * @param {String} font The css font descriptor that text is to be rendered with (e.g. &quot;bold 14px verdana&quot;).\n * \n * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393\n */\nfunction getTextWidth(text, font) {\n // re-use canvas object for better performance\n const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement(&quot;canvas&quot;));\n const context = canvas.getContext(&quot;2d&quot;);\n context.font = font;\n const metrics = context.measureText(text);\n return metrics.width;\n}\n\nfunction getCssStyle(element, prop) {\n return window.getComputedStyle(element, null).getPropertyValue(prop);\n}\n\nfunction getCanvasFont(el = document.body) {\n const fontWeight = getCssStyle(el, 'font-weight') || 'normal';\n const fontSize = getCssStyle(el, 'font-size') || '16px';\n const fontFamily = getCssStyle(el, 'font-family') || 'Times New Roman';\n \n return `${fontWeight} ${fontSize} ${fontFamily}`;\n}\n\nconsole.log(getTextWidth(&quot;hello there!&quot;, &quot;bold 12pt arial&quot;)); // close to 86\n</code></pre>\n<p>If you want to use the font-size of some specific element <code>myEl</code>, you can make use of the <code>getCanvasFont</code> utility function:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const fontSize = getTextWidth(text, getCanvasFont(myEl));\n// do something with fontSize here...\n</code></pre>\n<p>Explanation: The <code>getCanvasFontSize</code> function takes some element's (by default: the <code>body</code>'s) font and converts it into a format compatible with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font\" rel=\"noreferrer\">Context.font property</a>. Of course any element must first be added to the DOM before usage, else it gives you bogus values.</p>\n<h2>More Notes</h2>\n<p>There are several advantages to this approach, including:</p>\n<ul>\n<li>More concise and safer than the other (DOM-based) methods because it does not change global state, such as your DOM.</li>\n<li>Further customization is possible by <a href=\"http://diveintohtml5.info/canvas.html#text\" rel=\"noreferrer\">modifying more canvas text properties</a>, such as <code>textAlign</code> and <code>textBaseline</code>.</li>\n</ul>\n<p>NOTE: When you add the text to your DOM, remember to also take account of <a href=\"http://api.jquery.com/outerwidth/\" rel=\"noreferrer\">padding, margin and border</a>.</p>\n<p>NOTE 2: On some browsers, this method yields sub-pixel accuracy (result is a floating point number), on others it does not (result is only an int). You might want to run <code>Math.floor</code> (or <code>Math.ceil</code>) on the result, to avoid inconsistencies. Since the DOM-based method is never sub-pixel accurate, this method has even higher precision than the other methods here.</p>\n<p>According to <a href=\"http://jsperf.com/measure-text-width/4\" rel=\"noreferrer\">this jsperf</a> (thanks to the contributors in comments), the <em>Canvas method</em> and the <em>DOM-based method</em> are about equally fast, if caching is added to the <em>DOM-based method</em> and you are not using Firefox. In Firefox, for some reason, this <em>Canvas method</em> is much much faster than the <em>DOM-based method</em> (as of September 2014).</p>\n<h2>Performance</h2>\n<p><a href=\"http://jsfiddle.net/eNzjZ/70/\" rel=\"noreferrer\">This fiddle</a> compares this Canvas method to a variation of <a href=\"https://stackoverflow.com/a/5047712/2228771\">Bob Monteverde's DOM-based method</a>, so you can analyze and compare accuracy of the results.</p>\n" }, { "answer_id": 21961146, "author": "schickling", "author_id": 2418739, "author_profile": "https://Stackoverflow.com/users/2418739", "pm_score": 4, "selected": false, "text": "<p>I wrote a little tool for that. Perhaps it's useful to somebody. It works <strong>without jQuery</strong>.</p>\n\n<p><strong><a href=\"https://github.com/schickling/calculate-size\" rel=\"noreferrer\">https://github.com/schickling/calculate-size</a></strong></p>\n\n<p>Usage:</p>\n\n<pre><code>var size = calculateSize(\"Hello world!\", {\n font: 'Arial',\n fontSize: '12px'\n});\n\nconsole.log(size.width); // 65\nconsole.log(size.height); // 14\n</code></pre>\n\n<p>Fiddle: <a href=\"http://jsfiddle.net/PEvL8/\" rel=\"noreferrer\">http://jsfiddle.net/PEvL8/</a></p>\n" }, { "answer_id": 23665686, "author": "Mauricio Mora", "author_id": 1863494, "author_profile": "https://Stackoverflow.com/users/1863494", "pm_score": 0, "selected": false, "text": "<p>I guess this is prety similar to Depak entry, but is based on the work of Louis Lazaris published at an article in <a href=\"http://www.impressivewebs.com/textarea-auto-resize/\" rel=\"nofollow\">impressivewebs page</a></p>\n\n<pre><code>(function($){\n\n $.fn.autofit = function() { \n\n var hiddenDiv = $(document.createElement('div')),\n content = null;\n\n hiddenDiv.css('display','none');\n\n $('body').append(hiddenDiv);\n\n $(this).bind('fit keyup keydown blur update focus',function () {\n content = $(this).val();\n\n content = content.replace(/\\n/g, '&lt;br&gt;');\n hiddenDiv.html(content);\n\n $(this).css('width', hiddenDiv.width());\n\n });\n\n return this;\n\n };\n })(jQuery);\n</code></pre>\n\n<p>The fit event is used to execute the function call inmediatly after the function is asociated to the control.</p>\n\n<p>e.g.: $('input').autofit().trigger(\"fit\");</p>\n" }, { "answer_id": 28199324, "author": "v1r00z", "author_id": 821888, "author_profile": "https://Stackoverflow.com/users/821888", "pm_score": 0, "selected": false, "text": "<p>Without jQuery:</p>\n\n<pre><code>String.prototype.width = function (fontSize) {\n var el,\n f = fontSize + \" px arial\" || '12px arial';\n el = document.createElement('div');\n el.style.position = 'absolute';\n el.style.float = \"left\";\n el.style.whiteSpace = 'nowrap';\n el.style.visibility = 'hidden';\n el.style.font = f;\n el.innerHTML = this;\n el = document.body.appendChild(el);\n w = el.offsetWidth;\n el.parentNode.removeChild(el);\n return w;\n}\n\n// Usage\n\"MyString\".width(12);\n</code></pre>\n" }, { "answer_id": 30945077, "author": "Jason Williams", "author_id": 2733283, "author_profile": "https://Stackoverflow.com/users/2733283", "pm_score": 0, "selected": false, "text": "<p>Fiddle of working example: <a href=\"http://jsfiddle.net/tdpLdqpo/1/\" rel=\"nofollow\">http://jsfiddle.net/tdpLdqpo/1/</a></p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;h1 id=\"test1\"&gt;\n How wide is this text?\n&lt;/h1&gt;\n&lt;div id=\"result1\"&gt;&lt;/div&gt;\n&lt;hr/&gt;\n&lt;p id=\"test2\"&gt;\n How wide is this text?\n&lt;/p&gt;\n&lt;div id=\"result2\"&gt;&lt;/div&gt;\n&lt;hr/&gt;\n&lt;p id=\"test3\"&gt;\n How wide is this text?&lt;br/&gt;&lt;br/&gt;\n f sdfj f sdlfj lfj lsdk jflsjd fljsd flj sflj sldfj lsdfjlsdjkf sfjoifoewj flsdjfl jofjlgjdlsfjsdofjisdojfsdmfnnfoisjfoi ojfo dsjfo jdsofjsodnfo sjfoj ifjjfoewj fofew jfos fojo foew jofj s f j\n&lt;/p&gt;\n&lt;div id=\"result3\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>JavaScript code:</p>\n\n<pre><code>function getTextWidth(text, font) {\n var canvas = getTextWidth.canvas ||\n (getTextWidth.canvas = document.createElement(\"canvas\"));\n var context = canvas.getContext(\"2d\");\n context.font = font;\n var metrics = context.measureText(text);\n return metrics.width;\n};\n\n$(\"#result1\")\n.text(\"answer: \" +\n getTextWidth(\n $(\"#test1\").text(),\n $(\"#test1\").css(\"font\")) + \" px\");\n\n$(\"#result2\")\n .text(\"answer: \" +\n getTextWidth(\n $(\"#test2\").text(),\n $(\"#test2\").css(\"font\")) + \" px\");\n\n$(\"#result3\")\n .text(\"answer: \" +\n getTextWidth(\n $(\"#test3\").text(),\n $(\"#test3\").css(\"font\")) + \" px\");\n</code></pre>\n" }, { "answer_id": 36403029, "author": "Mr. Polywhirl", "author_id": 1762224, "author_profile": "https://Stackoverflow.com/users/1762224", "pm_score": 1, "selected": false, "text": "<p>Building off of <a href=\"https://stackoverflow.com/a/2117698/1762224\">Deepak Nadar's answer</a>, I changed the functions parameter's to accept text and font styles. You do not need to reference an element. Also, the <code>fontOptions</code> have defaults, so you to not need to supply all of them.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(function($) {\r\n $.format = function(format) {\r\n return (function(format, args) {\r\n return format.replace(/{(\\d+)}/g, function(val, pos) {\r\n return typeof args[pos] !== 'undefined' ? args[pos] : val;\r\n });\r\n }(format, [].slice.call(arguments, 1)));\r\n };\r\n $.measureText = function(html, fontOptions) {\r\n fontOptions = $.extend({\r\n fontSize: '1em',\r\n fontStyle: 'normal',\r\n fontWeight: 'normal',\r\n fontFamily: 'arial'\r\n }, fontOptions);\r\n var $el = $('&lt;div&gt;', {\r\n html: html,\r\n css: {\r\n position: 'absolute',\r\n left: -1000,\r\n top: -1000,\r\n display: 'none'\r\n }\r\n }).appendTo('body');\r\n $(fontOptions).each(function(index, option) {\r\n $el.css(option, fontOptions[option]);\r\n });\r\n var h = $el.outerHeight(), w = $el.outerWidth();\r\n $el.remove();\r\n return { height: h, width: w };\r\n };\r\n}(jQuery));\r\n\r\nvar dimensions = $.measureText(\"Hello World!\", { fontWeight: 'bold', fontFamily: 'arial' });\r\n\r\n// Font Dimensions: 94px x 18px\r\n$('body').append('&lt;p&gt;').text($.format('Font Dimensions: {0}px x {1}px', dimensions.width, dimensions.height));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 48172630, "author": "Toph", "author_id": 120290, "author_profile": "https://Stackoverflow.com/users/120290", "pm_score": 5, "selected": false, "text": "<p>I like your &quot;only idea&quot; of just doing a static character width map! It actually works well for my purposes. Sometimes, for performance reasons or because you don't have easy access to a DOM, you may just want a quick hacky standalone calculator calibrated to a single font. So here's one calibrated to Helvetica; pass a string and a font size:</p>\n<pre><code>const widths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.2796875,0.2765625,0.3546875,0.5546875,0.5546875,0.8890625,0.665625,0.190625,0.3328125,0.3328125,0.3890625,0.5828125,0.2765625,0.3328125,0.2765625,0.3015625,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.2765625,0.2765625,0.584375,0.5828125,0.584375,0.5546875,1.0140625,0.665625,0.665625,0.721875,0.721875,0.665625,0.609375,0.7765625,0.721875,0.2765625,0.5,0.665625,0.5546875,0.8328125,0.721875,0.7765625,0.665625,0.7765625,0.721875,0.665625,0.609375,0.721875,0.665625,0.94375,0.665625,0.665625,0.609375,0.2765625,0.3546875,0.2765625,0.4765625,0.5546875,0.3328125,0.5546875,0.5546875,0.5,0.5546875,0.5546875,0.2765625,0.5546875,0.5546875,0.221875,0.240625,0.5,0.221875,0.8328125,0.5546875,0.5546875,0.5546875,0.5546875,0.3328125,0.5,0.2765625,0.5546875,0.5,0.721875,0.5,0.5,0.5,0.3546875,0.259375,0.353125,0.5890625]\nconst avg = 0.5279276315789471\n\nfunction measureText(str, fontSize) {\n return Array.from(str).reduce(\n (acc, cur) =&gt; acc + (widths[cur.charCodeAt(0)] ?? avg), 0\n ) * fontSize\n}\n</code></pre>\n<p>That giant ugly array is ASCII character widths indexed by character code. So this just supports ASCII (otherwise it assumes an average character width). Fortunately, width basically scales linearly with font size, so it works pretty well at any font size. It's noticeably lacking any awareness of kerning or ligatures or whatever.</p>\n<p>To &quot;calibrate&quot; I just rendered every character up to charCode 126 (the mighty tilde) on an svg and got the bounding box and saved it to this array; <a href=\"https://bl.ocks.org/tophtucker/62f93a4658387bb61e4510c37e2e97cf\" rel=\"noreferrer\">more code and explanation and demo here</a>.</p>\n" }, { "answer_id": 50661478, "author": "transistor09", "author_id": 420597, "author_profile": "https://Stackoverflow.com/users/420597", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>The <code>Element.getClientRects()</code> method returns a collection of <code>DOMRect</code> objects that indicate the bounding rectangles for each CSS border box in a client. The returned value is a collection of <code>DOMRect</code> objects, one for each CSS border box associated with the element. Each <code>DOMRect</code> object contains read-only <code>left</code>, <code>top</code>, <code>right</code> and <code>bottom</code> properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport.</p>\n</blockquote>\n\n<blockquote><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/getClientRects\" rel=\"nofollow noreferrer\">Element.getClientRects()</a> by <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/getClientRects$history\" rel=\"nofollow noreferrer\">Mozilla Contributors</a> is licensed under <a href=\"http://creativecommons.org/licenses/by-sa/2.5/\" rel=\"nofollow noreferrer\">CC-BY-SA 2.5</a>.</blockquote>\n\n<p>Summing up all returned rectangle widths yields the total text width in pixels.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.getElementById('in').addEventListener('input', function (event) {\r\n var span = document.getElementById('text-render')\r\n span.innerText = event.target.value\r\n var rects = span.getClientRects()\r\n var widthSum = 0\r\n for (var i = 0; i &lt; rects.length; i++) {\r\n widthSum += rects[i].right - rects[i].left\r\n }\r\n document.getElementById('width-sum').value = widthSum\r\n})</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;&lt;textarea id='in'&gt;&lt;/textarea&gt;&lt;/p&gt;\r\n&lt;p&gt;&lt;span id='text-render'&gt;&lt;/span&gt;&lt;/p&gt;\r\n&lt;p&gt;Sum of all widths: &lt;output id='width-sum'&gt;0&lt;/output&gt;px&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 50813259, "author": "M Katz", "author_id": 384670, "author_profile": "https://Stackoverflow.com/users/384670", "pm_score": 2, "selected": false, "text": "<p>In case anyone else got here looking both for a way to measure the width of a string <em>and</em> a way to know what's the largest font size that will fit in a particular width, here is a function that builds on <a href=\"https://stackoverflow.com/a/21015393\">@Domi's solution</a> with a binary search:</p>\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * Find the largest font size (in pixels) that allows the string to fit in the given width.\n * \n * @param {String} text - The text to be rendered.\n * @param {String} font - The css font descriptor that text is to be rendered with (e.g. &quot;bold ?px verdana&quot;) -- note the use of ? in place of the font size.\n * @param {Number} width - The width in pixels the string must fit in\n * @param {Number} minFontPx - The smallest acceptable font size in pixels\n * @param {Number} maxFontPx - The largest acceptable font size in pixels\n **/\nfunction GetTextSizeForWidth(text, font, width, minFontPx, maxFontPx) {\n for (;;) {\n var s = font.replace(&quot;?&quot;, maxFontPx);\n var w = GetTextWidth(text, s);\n if (w &lt;= width) {\n return maxFontPx;\n }\n\n var g = (minFontPx + maxFontPx) / 2;\n\n if (Math.round(g) == Math.round(minFontPx) || Math.round(g) == Math.round(maxFontPx)) {\n return g;\n }\n\n s = font.replace(&quot;?&quot;, g);\n w = GetTextWidth(text, s);\n if (w &gt;= width) {\n maxFontPx = g;\n } else {\n minFontPx = g;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 53958056, "author": "Roman86", "author_id": 4892968, "author_profile": "https://Stackoverflow.com/users/4892968", "pm_score": 1, "selected": false, "text": "<p>Rewritten my answer from scratch (thanks for that minus).\nNow function accepts a text and css rules to be applied (and doesn't use jQuery anymore). So it will respect paddings too. Resulting values are being rounded (you can see Math.round there, remove if you want more that precise values)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getSpan(){\n const span = document.createElement('span')\n span.style.position = 'fixed';\n span.style.visibility = 'hidden';\n document.body.appendChild(span);\n return span;\n}\n\nfunction textWidth(str, css) {\n const span = getSpan();\n Object.assign(span.style, css || {});\n span.innerText = str;\n const w = Math.round(span.getBoundingClientRect().width);\n \n span.remove();\n \n return w;\n}\n\n\nconst testStyles = [\n {fontSize: '10px'},\n {fontSize: '12px'},\n {fontSize: '60px'},\n {fontSize: '120px'},\n {fontSize: '120px', padding: '10px'},\n {fontSize: '120px', fontFamily: 'arial'},\n {fontSize: '120px', fontFamily: 'tahoma'},\n {fontSize: '120px', fontFamily: 'tahoma', padding: '5px'},\n];\n\nconst ul = document.getElementById('output');\ntestStyles.forEach(style =&gt; {\n const li = document.createElement('li');\n li.innerText = `${JSON.stringify(style)} &gt; ${textWidth('abc', style)}`;\n ul.appendChild(li);\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;ul id=\"output\"&gt;&lt;/ul&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 59647192, "author": "Inc33", "author_id": 986419, "author_profile": "https://Stackoverflow.com/users/986419", "pm_score": 2, "selected": false, "text": "<p>You can also do this with createRange, which is more accurate, than the text cloning technique:</p>\n\n<pre><code>function getNodeTextWidth(nodeWithText) {\n var textNode = $(nodeWithText).contents().filter(function () {\n return this.nodeType == Node.TEXT_NODE;\n })[0];\n var range = document.createRange();\n range.selectNode(textNode);\n return range.getBoundingClientRect().width;\n}\n</code></pre>\n" }, { "answer_id": 63309811, "author": "Darex1991", "author_id": 3012785, "author_profile": "https://Stackoverflow.com/users/3012785", "pm_score": 0, "selected": false, "text": "<p>I'm using <a href=\"https://www.npmjs.com/package/text-metrics\" rel=\"nofollow noreferrer\">text-metrics</a> package. Works really nice, I tried this <a href=\"https://stackoverflow.com/a/21961146/3012785\">solution</a> but in some reasons, it counts it wrong.</p>\n<pre><code>textMetrics.init(document.querySelector('h1'), { fontSize: '20px' });\n\ntextMetrics.init({\n fontSize: '14px',\n lineHeight: '20px',\n fontFamily: 'Helvetica, Arial, sans-serif',\n fontWeight: 400,\n width: 100,\n});\n</code></pre>\n" }, { "answer_id": 70178495, "author": "Red Mercury", "author_id": 2133888, "author_profile": "https://Stackoverflow.com/users/2133888", "pm_score": 1, "selected": false, "text": "<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/max-content\" rel=\"nofollow noreferrer\"><code>max-content</code></a> to measure the pixel width of text.</p>\n<p>Here is a utility function that does that. It optionally takes any node as a context to calculate the width in, taking into account any CSS like <code>font-size</code>, <code>letter-spacing</code>, etc.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function measureTextPxWidth(\n text,\n template = document.createElement(\"span\")\n) {\n const measurer = template.cloneNode();\n measurer.style.setProperty(\"all\", \"revert\", \"important\");\n measurer.style.setProperty(\"position\", \"position\", \"important\");\n measurer.style.setProperty(\"visibility\", \"hidden\", \"important\");\n measurer.style.setProperty(\"width\", \"max-content\", \"important\");\n measurer.innerText = text;\n\n document.body.appendChild(measurer);\n const { width } = measurer.getBoundingClientRect();\n document.body.removeChild(measurer);\n return width;\n}\n\ndocument.querySelector('.spanTextWidth').innerText = \n `${measureTextPxWidth('one two three')}px`\n \ndocument.querySelector('.h1TextWidth').innerText = \n `${measureTextPxWidth('one two three', document.querySelector('h1'))}px`</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>h1 {\n letter-spacing: 3px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;span&gt;one two three&lt;/span&gt;\n&lt;div class=\"spanTextWidth\"&gt;&lt;/div&gt;\n \n&lt;h1&gt;one two three&lt;/h1&gt;\n&lt;div class=\"h1TextWidth\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 72148318, "author": "V. Rubinetti", "author_id": 2180570, "author_profile": "https://Stackoverflow.com/users/2180570", "pm_score": 2, "selected": false, "text": "<p>If you're okay with installing a package, and you want perhaps a more authoritative or precise answer, you can use <a href=\"https://github.com/opentypejs/opentype.js\" rel=\"nofollow noreferrer\">opentype.js</a> (surprised no one has mentioned this yet):</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { load } from &quot;opentype.js&quot;;\n\nconst getWidth = async (text = &quot;Hello World&quot;) =&gt; {\n const font = await load(&quot;path/to/some/font&quot;);\n const { x1, x2 } = font.getPath(text, 0, 0, 12).getBoundingBox();\n return x2 - x1;\n};\n</code></pre>\n<p>Naturally you'd want to only call <code>load</code> once per font, so you should pull that line out to a higher scope based on your circumstances.</p>\n<p>Here's a Code Sandbox comparing this OpenType method to the Canvas and DOM methods:\n<a href=\"https://codesandbox.io/s/measure-width-of-text-in-javascript-vctst2\" rel=\"nofollow noreferrer\">https://codesandbox.io/s/measure-width-of-text-in-javascript-vctst2</a></p>\n<p>On my machine, for 100 samples each, the typical results are:</p>\n<ul>\n<li>OpenType: <code>5ms</code></li>\n<li>Canvas: <code>3ms</code></li>\n<li>DOM: <code>4ms</code></li>\n</ul>\n<p>Another package I found is this one: <a href=\"https://github.com/sffc/word-wrappr\" rel=\"nofollow noreferrer\">https://github.com/sffc/word-wrappr</a></p>\n" }, { "answer_id": 72222681, "author": "Felipe Chernicharo", "author_id": 13111779, "author_profile": "https://Stackoverflow.com/users/13111779", "pm_score": 1, "selected": false, "text": "<h1>For any one out there using React and/or Typescript...</h1>\n<p><a href=\"https://codesandbox.io/s/react-ts-get-text-width-in-pixels-e1dj3o\" rel=\"nofollow noreferrer\">Try this Codepen!</a></p>\n<pre><code>export default function App() {\n const spanRef = useRef&lt;HTMLSpanElement&gt;(null);\n const [textWidth, setTextWidth] = useState(0);\n\n const getTextWidthInPixels = (ref: HTMLSpanElement) =&gt;\n ref.getBoundingClientRect().width;\n\n useEffect(() =&gt; {\n setTextWidth(getTextWidthInPixels(spanRef.current!));\n }, [spanRef]);\n\n return (\n &lt;div className=&quot;App&quot;&gt;\n &lt;span\n ref={spanRef}\n contentEditable\n suppressContentEditableWarning\n onInput={() =&gt; setTextWidth(getTextWidthInPixels(spanRef.current!))}\n &gt;\n Edit Me!!!\n &lt;/span&gt;\n {`textWidth: ${textWidth}px`}\n &lt;/div&gt;\n );\n}\n\n</code></pre>\n<ul>\n<li>It's a good idea to wrap our text in an inline-positioned element (like a <code>&lt;span&gt;</code>)</li>\n<li><code>useRef</code> is the React way to access a DOM element, the <code>&lt;span&gt;</code> in our case</li>\n<li><code>getBoundingClientRect</code> can get the total width of any DOM element.</li>\n<li><code>contentEditable</code> allows users to change the contents of an element ...which is a little unsafe (React will throw warnings!)</li>\n<li><code>suppressContentEditableWarning</code> will help us prevent these warnings</li>\n</ul>\n" }, { "answer_id": 73213192, "author": "JOHNNY SHAHIN", "author_id": 17499951, "author_profile": "https://Stackoverflow.com/users/17499951", "pm_score": 0, "selected": false, "text": "<p>Hey Everyone I know I'm a little late to the party but here we go</p>\n<pre><code>window.addEventListener(&quot;error&quot;,function(e){ alert(e.message); });\nvar canvas = new OffscreenCanvas(400, 50);\nvar ctx = canvas.getContext(&quot;2d&quot;);\nctx.font = &quot;16px Ariel&quot;; //this can be dynamic using getComputedStyle\nconst chars = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot; &quot;,&quot; &quot;];\nconst charWidths = new Map();\nwhile(chars.length &gt; 0){\n var char = chars.shift();\n var wide = ctx.measureText(char).width;\n charWidths.set(char,wide);\n}\n</code></pre>\n<p>and then you can use it with something like:</p>\n<pre><code>var pixelWidth = charWidths.get(&quot;0&quot;);\n//fyi css properties like letter-spacing need to be accounted for\n</code></pre>\n" }, { "answer_id": 73342405, "author": "Vikash Madhow", "author_id": 576437, "author_profile": "https://Stackoverflow.com/users/576437", "pm_score": 1, "selected": false, "text": "<p>Use <code>scrollWidth</code> on the containing element of the text to get the minimum width of the element including hidden parts due to overflow. More information at <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth</a></p>\n<p>If the element is not in the DOM, add it to some hidden area to do the measurement. For example:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function measureText(text) {\n let div = document.createElement(&quot;div&quot;);\n div.innerText = text;\n div.style.whiteSpace = 'nowrap';\n body.appendChild(div);\n let width = div.scrollWidth;\n body.removeChild(div);\n return width;\n}\n</code></pre>\n<p>The style (font-size, weight, etc.) will be inherited by the element and thus accounted in the width. You could also measure the size of more complex content with <code>scrollWidth</code> and <code>scrollHeight</code>.</p>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/118241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8119/" ]
I'd like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface? If it's not built-in, my only idea is to create a table of widths for each character, but this is pretty unreasonable especially supporting [Unicode](http://en.wikipedia.org/wiki/Unicode) and different type sizes (and all browsers for that matter).
Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size. ```js var fontSize = 12; var test = document.getElementById("Test"); test.style.fontSize = fontSize; var height = (test.clientHeight + 1) + "px"; var width = (test.clientWidth + 1) + "px" console.log(height, width); ``` ```css #Test { position: absolute; visibility: hidden; height: auto; width: auto; white-space: nowrap; /* Thanks to Herb Caudill comment */ } ``` ```html <div id="Test"> abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ </div> ```