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 ...
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...
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...
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]) + ......
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>\...
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>...
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 mos...
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....
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'r...
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...
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\">t...
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 com...
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 protoco...
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, y...
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<...
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.prototyp...
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...
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 noreferr...
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 ...
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/artic...
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 recu...
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 beco...
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 buil...
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), ...
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 wan...
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=\"noreferr...
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...
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 ...
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=...
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...
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>...
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&...
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" }, { "ans...
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....
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 gro...
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": "john.doe@example.com" } 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...
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.</...
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 ...
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<l...
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 de...
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 ...
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 f...
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<pr...
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 sc...
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, "auth...
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_prof...
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 ...
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 in...
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...
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 t...
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, ...
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,...
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...
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/w...
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 ...
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" }...
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 ...
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...
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...
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 tha...
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 ...
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...
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" }...
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\...
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....
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 ...
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...
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...
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...
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...
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 s...
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 borde...
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 ...
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,...
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 ...
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...
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 yo...
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></p...
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/StandardCSSPropertie...
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 oth...
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 (s...
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 ...
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 e...
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 RewriteR...
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 ea...
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;= ...
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>...
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 firs...
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": "Patric...
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 E...
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...
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> mo...
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.or...
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...
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]?[...
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...
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...
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>...
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=\...
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 tryin...
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> ```