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
114,211
<p>Let's say I have a container (std::vector) of pointers used by a multi-threaded application. When adding new pointers to the container, the code is protected using a critical section (boost::mutex). All well and good. The code should be able to return one of these pointers to a thread for processing, but another separate thread could choose to delete one of these pointers, which might still be in use. e.g.:</p> <pre><code>thread1() { foo* p = get_pointer(); ... p-&gt;do_something(); } thread2() { foo* p = get_pointer(); ... delete p; } </code></pre> <p>So thread2 could delete the pointer whilst thread1 is using it. Nasty.</p> <p>So instead I want to use a container of Boost shared ptrs. IIRC these pointers will be reference counted, so as long as I return shared ptrs instead of raw pointers, removing one from the container WON'T actually free it until the last use of it goes out of scope. i.e.</p> <pre><code>std::vector&lt;boost::shared_ptr&lt;foo&gt; &gt; my_vec; thread1() { boost::shared_ptr&lt;foo&gt; sp = get_ptr[0]; ... sp-&gt;do_something(); } thread2() { boost::shared_ptr&lt;foo&gt; sp = get_ptr[0]; ... my_vec.erase(my_vec.begin()); } boost::shared_ptr&lt;foo&gt; get_ptr(int index) { lock_my_vec(); return my_vec[index]; } </code></pre> <p>In the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes? <strong>Note that access to the global vector will be via a critical section.</strong></p> <p>I think this is how shared_ptrs work but I need to be sure.</p>
[ { "answer_id": 114221, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": true, "text": "<p>For the threading safety of boost::shared_ptr you should check <a href=\"http://www.boost.org/doc/libs/1_36_0/libs...
2008/09/22
[ "https://Stackoverflow.com/questions/114211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
Let's say I have a container (std::vector) of pointers used by a multi-threaded application. When adding new pointers to the container, the code is protected using a critical section (boost::mutex). All well and good. The code should be able to return one of these pointers to a thread for processing, but another separate thread could choose to delete one of these pointers, which might still be in use. e.g.: ``` thread1() { foo* p = get_pointer(); ... p->do_something(); } thread2() { foo* p = get_pointer(); ... delete p; } ``` So thread2 could delete the pointer whilst thread1 is using it. Nasty. So instead I want to use a container of Boost shared ptrs. IIRC these pointers will be reference counted, so as long as I return shared ptrs instead of raw pointers, removing one from the container WON'T actually free it until the last use of it goes out of scope. i.e. ``` std::vector<boost::shared_ptr<foo> > my_vec; thread1() { boost::shared_ptr<foo> sp = get_ptr[0]; ... sp->do_something(); } thread2() { boost::shared_ptr<foo> sp = get_ptr[0]; ... my_vec.erase(my_vec.begin()); } boost::shared_ptr<foo> get_ptr(int index) { lock_my_vec(); return my_vec[index]; } ``` In the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes? **Note that access to the global vector will be via a critical section.** I think this is how shared\_ptrs work but I need to be sure.
For the threading safety of boost::shared\_ptr you should check [this link](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety). It's not guarantied to be safe, but on many platforms it works. Modifying the std::vector is not safe AFAIK.
114,214
<p>What is the difference between the following class methods?</p> <p>Is it that one is static and the other is not?</p> <pre><code>class Test(object): def method_one(self): print "Called method_one" def method_two(): print "Called method_two" a_test = Test() a_test.method_one() a_test.method_two() </code></pre>
[ { "answer_id": 114232, "author": "Justin Poliey", "author_id": 6967, "author_profile": "https://Stackoverflow.com/users/6967", "pm_score": 4, "selected": false, "text": "<p>When you call a class member, Python automatically uses a reference to the object as the first parameter. The varia...
2008/09/22
[ "https://Stackoverflow.com/questions/114214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16070/" ]
What is the difference between the following class methods? Is it that one is static and the other is not? ``` class Test(object): def method_one(self): print "Called method_one" def method_two(): print "Called method_two" a_test = Test() a_test.method_one() a_test.method_two() ```
In Python, there is a distinction between *bound* and *unbound* methods. Basically, a call to a member function (like `method_one`), a bound function ``` a_test.method_one() ``` is translated to ``` Test.method_one(a_test) ``` i.e. a call to an unbound method. Because of that, a call to your version of `method_two` will fail with a `TypeError` ``` >>> a_test = Test() >>> a_test.method_two() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: method_two() takes no arguments (1 given) ``` You can change the behavior of a method using a decorator ``` class Test(object): def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method two" ``` The decorator tells the built-in default metaclass `type` (the class of a class, cf. [this question](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python)) to not create bound methods for `method_two`. Now, you can invoke static method both on an instance or on the class directly: ``` >>> a_test = Test() >>> a_test.method_one() Called method_one >>> a_test.method_two() Called method_two >>> Test.method_two() Called method_two ```
114,222
<p>With the introduction of .NET 3.5 and the <code>IQueryable&lt;T&gt;</code> interface, new patterns will emerge. While I have seen a number of implementations of the Specification pattern, I have not seen many other patterns using this technology. Rob Conery's Storefront application is another concrete example using <code>IQueryable&lt;T&gt;</code> which may lead to some new patterns.</p> <p><strong>What patterns have emerged from the useful <code>IQueryable&lt;T&gt;</code> interface?</strong></p>
[ { "answer_id": 114609, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 3, "selected": false, "text": "<p>It has certainly made the repository pattern much simpler to implement as well. You can essentially create a gene...
2008/09/22
[ "https://Stackoverflow.com/questions/114222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/708/" ]
With the introduction of .NET 3.5 and the `IQueryable<T>` interface, new patterns will emerge. While I have seen a number of implementations of the Specification pattern, I have not seen many other patterns using this technology. Rob Conery's Storefront application is another concrete example using `IQueryable<T>` which may lead to some new patterns. **What patterns have emerged from the useful `IQueryable<T>` interface?**
It has certainly made the repository pattern much simpler to implement as well. You can essentially create a generic repository: ``` public class LinqToSqlRepository : IRepository { private readonly DataContext _context; public LinqToSqlRepository(DataContext context) { _context = context; } public IQueryable<T> Find<T>() { return _dataContext.GetTable<T>(); // linq 2 sql } /** snip: Insert, Update etc.. **/ } ``` and then use it with linq: ``` var query = from customers in _repository.Find<Customer>() select customers; ```
114,242
<p>Previously I have asked to strip text from a field and convert it to an int, this works successfully. But now, I would like to do an INNER JOIN on this new value.</p> <p>So I have this:</p> <pre><code>SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname FROM accountingTab INNER JOIN (SELECT id, title, first, last FROM memDetTab) AS userDetails ON memID = userDetails.id </code></pre> <p>And then I get the Invalid Column Name <code>memID</code> error.</p> <p>How can I fix this?</p>
[ { "answer_id": 114253, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "<p>Instead of memId, repeat the whole expression.</p>\n" }, { "answer_id": 114265, "author": "Remi Desp...
2008/09/22
[ "https://Stackoverflow.com/questions/114242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1841427/" ]
Previously I have asked to strip text from a field and convert it to an int, this works successfully. But now, I would like to do an INNER JOIN on this new value. So I have this: ``` SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname FROM accountingTab INNER JOIN (SELECT id, title, first, last FROM memDetTab) AS userDetails ON memID = userDetails.id ``` And then I get the Invalid Column Name `memID` error. How can I fix this?
If you have to do this, you have design problems. If you're able, I would suggest you need to refactor your table or relationships.
114,266
<p>I am getting the following error whenever I click on a postbacking control</p> <pre><code>HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. </code></pre> <p>I am not using a Web Farm or cluster server. I have even tried setting the page property <strong><em>EnableViewStateMac</em></strong> to false but it changes the error message stating</p> <pre><code>The state information is invalid for this page and might be corrupted. </code></pre> <p>What could possibly be wrong?</p>
[ { "answer_id": 114292, "author": "user20259", "author_id": 20259, "author_profile": "https://Stackoverflow.com/users/20259", "pm_score": 3, "selected": true, "text": "<p>There is an article about this here: <a href=\"http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-ma...
2008/09/22
[ "https://Stackoverflow.com/questions/114266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4021/" ]
I am getting the following error whenever I click on a postbacking control ``` HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. ``` I am not using a Web Farm or cluster server. I have even tried setting the page property ***EnableViewStateMac*** to false but it changes the error message stating ``` The state information is invalid for this page and might be corrupted. ``` What could possibly be wrong?
There is an article about this here: <http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx> . The basic problem is that Your page hasn't completed loading before You perform the postback. A few different solutions are in the article listed above: 1. Set enableEventValidation to false and viewStateEncryptionMode to Never 2. Mark the form as disabled and then enable it in script once the load is complete. 3. override the Render Event of the page to place the hidden fields for Encrypted Viewstate and Event validation on the top of the form. But the main problem is that the page load slow, which should be fixed (if possible ASAP). It can also be good to apply solution 2 above as well as there will always be trigger happy users that will click faster that the page loads no matter how fast it loads :-). /Andreas
114,284
<p>First of all, this question regards MySQL 3.23.58, so be advised.</p> <p>I have 2 tables with the following definition:</p> <pre><code>Table A: id INT (primary), customer_id INT, offlineid INT Table B: id INT (primary), name VARCHAR(255) </code></pre> <p>Now, table A contains in the range of 65k+ records, while table B contains ~40 records. In addition to the 2 primary key indexes, there is also an index on the <em>offlineid</em> field in table A. There are more fields in each table, but they are not relevant (as I see it, ask if necessary) for this query.</p> <p>I was first presented with the following query (<em>query time: ~22 seconds</em>):</p> <pre><code>SELECT b.name, COUNT(*) AS orders, COUNT(DISTINCT(a.kundeid)) AS leads FROM katalogbestilling_katalog a, medie b WHERE a.offlineid = b.id GROUP BY b.name </code></pre> <p>Now, each id in medie is associated with a different name, meaning you could group by id as well as name. A bit of testing back and forth settled me on this (<em>query time: ~6 seconds</em>):</p> <pre><code>SELECT a.name, COUNT(*) AS orders, COUNT(DISTINCT(b.kundeid)) AS leads FROM medie a INNER JOIN katalogbestilling_katalog b ON a.id = b.offline GROUP BY b.offline; </code></pre> <p>Is there any way to crank it down to "instant" time (max 1 second at worst)? I added the index on offlineid, but besides that and the re-arrangement of the query, I am at a loss for what to do. The EXPLAIN query shows me the query is using fileshort (the original query also used temp tables). All suggestions are welcome!</p>
[ { "answer_id": 114345, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 1, "selected": false, "text": "<p>I'm going to guess that your main problem is that you are using such an old version of MySQL. Maybe MySQL 3 doesn't like the ...
2008/09/22
[ "https://Stackoverflow.com/questions/114284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9479/" ]
First of all, this question regards MySQL 3.23.58, so be advised. I have 2 tables with the following definition: ``` Table A: id INT (primary), customer_id INT, offlineid INT Table B: id INT (primary), name VARCHAR(255) ``` Now, table A contains in the range of 65k+ records, while table B contains ~40 records. In addition to the 2 primary key indexes, there is also an index on the *offlineid* field in table A. There are more fields in each table, but they are not relevant (as I see it, ask if necessary) for this query. I was first presented with the following query (*query time: ~22 seconds*): ``` SELECT b.name, COUNT(*) AS orders, COUNT(DISTINCT(a.kundeid)) AS leads FROM katalogbestilling_katalog a, medie b WHERE a.offlineid = b.id GROUP BY b.name ``` Now, each id in medie is associated with a different name, meaning you could group by id as well as name. A bit of testing back and forth settled me on this (*query time: ~6 seconds*): ``` SELECT a.name, COUNT(*) AS orders, COUNT(DISTINCT(b.kundeid)) AS leads FROM medie a INNER JOIN katalogbestilling_katalog b ON a.id = b.offline GROUP BY b.offline; ``` Is there any way to crank it down to "instant" time (max 1 second at worst)? I added the index on offlineid, but besides that and the re-arrangement of the query, I am at a loss for what to do. The EXPLAIN query shows me the query is using fileshort (the original query also used temp tables). All suggestions are welcome!
You could try making sure there are covering indexes defined on each table. A covering index is just an index where each column requested in the select or used in a join is included in the index. This way, the engine only has to read the index entry and doesn't have to also do the corresponding row lookup to get any requested columns not included in the index. I've used this technique with great success in Oracle and MS SqlServer. Looking at your query, you could try: one index for medie.id, medie.name one index for katalogbestilling\_katalog.offlineid, katalogbestilling\_katalog.kundeid The columns should be defined in these orders for the index. That makes a difference whether the index can be used or not. More info here: [Covering Index Info](http://peter-zaitsev.livejournal.com/6949.html)
114,302
<p>I'm looking for a list of win32 API in some "database"/XML format. </p> <p>I'd need it to easily create a "conversion layer" between win32 API and the higher level language I'm using (harbour/xharbour). Since this runs Pcode, it is necessary to transform parameters to C standard...</p> <p>Instead of doing manual code write, I'd like to automate the process...</p> <p>just for example, the windows API definition (taken from MSDN)</p> <pre><code>DWORD WINAPI GetSysColor( __in int nIndex ); </code></pre> <p>should be transformed in</p> <pre><code>HB_FUNC( GETSYSCOLOR ) { hb_retnl( (LONG) GetSysColor( hb_parni( 1 ) ) ); } </code></pre>
[ { "answer_id": 114307, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "<p>About the closest thing I know of would be: <a href=\"http://pinvoke.net/\" rel=\"nofollow noreferrer\">http://pinvoke.ne...
2008/09/22
[ "https://Stackoverflow.com/questions/114302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking for a list of win32 API in some "database"/XML format. I'd need it to easily create a "conversion layer" between win32 API and the higher level language I'm using (harbour/xharbour). Since this runs Pcode, it is necessary to transform parameters to C standard... Instead of doing manual code write, I'd like to automate the process... just for example, the windows API definition (taken from MSDN) ``` DWORD WINAPI GetSysColor( __in int nIndex ); ``` should be transformed in ``` HB_FUNC( GETSYSCOLOR ) { hb_retnl( (LONG) GetSysColor( hb_parni( 1 ) ) ); } ```
AFAIK, pinvoke.net only stores text data with the PInvoke definition for the call. Not very useful if what you want is something to use as a pre-parsed database of APIs. Probably you could create an small parser that will take the include file and translate it to what you need. In that case, I'd recommend using [lcc-win32](http://www.cs.virginia.edu/~lcc-win32/)'s include files, as they are pretty much fat-free/no-BS version of the SDK headers (they don't come with a bunch of special reserved words you'd have to ignore, etc.)
114,339
<p>If I want to manipulate an HTML tag's properties on the server within an aspx page based on a master page i.e. </p> <pre><code>&lt;a href="#" runat="server" ID="myLink"&gt;My Link&lt;/a&gt; </code></pre> <p>For example to give the link a different class depending on the current page i.e.</p> <pre><code>if (Path.GetFileName(Request.PhysicalPath) == "MyPage") { myLink.Attributes.Add("class","active"); } </code></pre> <p>.NET changes the ID property of the link to something like</p> <pre><code>&lt;a href="#" ID="ct100-foo-myLink"&gt;My Link&lt;/a&gt; </code></pre> <p>Is there any way of stopping this from happening and keeping the original ID?</p> <p>Thanks in advance</p>
[ { "answer_id": 114357, "author": "Giovanni Galbo", "author_id": 4050, "author_profile": "https://Stackoverflow.com/users/4050", "pm_score": 0, "selected": false, "text": "<p>I don't think so. </p>\n\n<p>However, you probably want to keep the original name so that you can manipulate the ...
2008/09/22
[ "https://Stackoverflow.com/questions/114339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12918/" ]
If I want to manipulate an HTML tag's properties on the server within an aspx page based on a master page i.e. ``` <a href="#" runat="server" ID="myLink">My Link</a> ``` For example to give the link a different class depending on the current page i.e. ``` if (Path.GetFileName(Request.PhysicalPath) == "MyPage") { myLink.Attributes.Add("class","active"); } ``` .NET changes the ID property of the link to something like ``` <a href="#" ID="ct100-foo-myLink">My Link</a> ``` Is there any way of stopping this from happening and keeping the original ID? Thanks in advance
AFAIK there is no way. It shows the actual control tree, which is in this case masterpage-content-control. However if you add an ID to the masterpage (this.ID = "whatever") then you will see "whatever" instead of ctl00 (which means control index 0).
114,419
<p>The following two C# code snippets produce different results (assuming the variable level is used both before and after the recursive call). Why?</p> <pre><code>public DoStuff(int level) { // ... DoStuff(level++); // ... } </code></pre> <p>,</p> <pre><code>public DoStuff(int level) { // ... DoStuff(level+1); // ... } </code></pre> <p>After reading some of the responses below I thought it would be worthwhile posting the stack traces for level++, ++level and level+1 to highlight how deceiving this problem is.</p> <p>I've simplified them for this post. The recursive call sequence starts with DoStuff(1). </p> <p>// level++</p> <pre><code>DoStuff(int level = 1) DoStuff(int level = 2) DoStuff(int level = 2) DoStuff(int level = 2) </code></pre> <p>// ++level</p> <pre><code>DoStuff(int level = 4) DoStuff(int level = 4) DoStuff(int level = 3) DoStuff(int level = 2) </code></pre> <p>// level+1</p> <pre><code>DoStuff(int level = 4) DoStuff(int level = 3) DoStuff(int level = 2) DoStuff(int level = 1) </code></pre>
[ { "answer_id": 114427, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 5, "selected": false, "text": "<p><strong>level++</strong> will pass <strong>level</strong> into <strong>DoStuff</strong> and then increment <strong>lev...
2008/09/22
[ "https://Stackoverflow.com/questions/114419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199234/" ]
The following two C# code snippets produce different results (assuming the variable level is used both before and after the recursive call). Why? ``` public DoStuff(int level) { // ... DoStuff(level++); // ... } ``` , ``` public DoStuff(int level) { // ... DoStuff(level+1); // ... } ``` After reading some of the responses below I thought it would be worthwhile posting the stack traces for level++, ++level and level+1 to highlight how deceiving this problem is. I've simplified them for this post. The recursive call sequence starts with DoStuff(1). // level++ ``` DoStuff(int level = 1) DoStuff(int level = 2) DoStuff(int level = 2) DoStuff(int level = 2) ``` // ++level ``` DoStuff(int level = 4) DoStuff(int level = 4) DoStuff(int level = 3) DoStuff(int level = 2) ``` // level+1 ``` DoStuff(int level = 4) DoStuff(int level = 3) DoStuff(int level = 2) DoStuff(int level = 1) ```
**level++** will pass **level** into **DoStuff** and then increment **level** for use in the rest of the function. This could be a fairly nasty bug as the recursion will never end (from what is shown **DoStuff** is always being passed the same value). Perhaps **++level** is meant instead, as this is the opposite of **level++** (increments level and passes the incremented value into **DoStuff**)? **level+1** will pass **level+1** into **DoStuff** and leave **level** unchanged for the rest of the function.
114,431
<p>I am trying to display a live word count in the vim statusline. I do this by setting my status line in my .vimrc and inserting a function into it. The idea of this function is to return the number of words in the current buffer. This number is then displayed on the status line. This should work nicely as the statusline is updated at just about every possible opportunity so the count will always remain 'live'. </p> <p>The problem is that the function I have currently defined is slow and so vim is obviously sluggish when it is used for all but the smallest files; due to this function being executed so frequently.</p> <p>In summary, does anyone have a clever trick for producing a function that is blazingly fast at calculating the number of words in the current buffer and returning the result?</p>
[ { "answer_id": 114474, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 3, "selected": false, "text": "<p>Keep a count for the current line and a separate count for the rest of the buffer. As you type (or delete) words o...
2008/09/22
[ "https://Stackoverflow.com/questions/114431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20388/" ]
I am trying to display a live word count in the vim statusline. I do this by setting my status line in my .vimrc and inserting a function into it. The idea of this function is to return the number of words in the current buffer. This number is then displayed on the status line. This should work nicely as the statusline is updated at just about every possible opportunity so the count will always remain 'live'. The problem is that the function I have currently defined is slow and so vim is obviously sluggish when it is used for all but the smallest files; due to this function being executed so frequently. In summary, does anyone have a clever trick for producing a function that is blazingly fast at calculating the number of words in the current buffer and returning the result?
Here's a usable version of Rodrigo Queiro's idea. It doesn't change the status bar, and it restores the statusmsg variable. ``` function WordCount() let s:old_status = v:statusmsg exe "silent normal g\<c-g>" let s:word_count = str2nr(split(v:statusmsg)[11]) let v:statusmsg = s:old_status return s:word_count endfunction ``` This seems to be fast enough to include directly in the status line, e.g.: ``` :set statusline=wc:%{WordCount()} ```
114,493
<p>I know the range name of the start of a list - <code>1</code> column wide and <code>x</code> rows deep.</p> <p>How do I calculate <code>x</code>?</p> <p>There is more data in the column than just this list. However, this list is contiguous - there is nothing in any of the cells above or below or either side beside it.</p>
[ { "answer_id": 114513, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 5, "selected": true, "text": "<pre><code>Function ListRowCount(ByVal FirstCellName as String) as Long\n With thisworkbook.Names(FirstCellName).RefersToR...
2008/09/22
[ "https://Stackoverflow.com/questions/114493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10326/" ]
I know the range name of the start of a list - `1` column wide and `x` rows deep. How do I calculate `x`? There is more data in the column than just this list. However, this list is contiguous - there is nothing in any of the cells above or below or either side beside it.
``` Function ListRowCount(ByVal FirstCellName as String) as Long With thisworkbook.Names(FirstCellName).RefersToRange If isempty(.Offset(1,0).value) Then ListRowCount = 1 Else ListRowCount = .End(xlDown).row - .row + 1 End If End With End Function ``` But if you are damn sure there's nothing around the list, then just `thisworkbook.Names(FirstCellName).RefersToRange.CurrentRegion.rows.count`
114,501
<p>I want to set a background image for a div, in a way that it is in the upper <strong>RIGHT</strong> of the div, but with a fixed <code>10px</code> distance from top and right.</p> <p>Here is how I would do that if wanted it in the upper <strong>LEFT</strong> of the div:</p> <pre>background: url(images/img06.gif) no-repeat 10px 10px;</pre> <p>Is there anyway to achieve the same result, but showing the background on the upper <strong>RIGHT</strong>?</p>
[ { "answer_id": 114517, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 3, "selected": false, "text": "<p>I don't know if it is possible in pure css, so you can try </p>\n\n<pre><code>background: url(images/img06.gif) no-repeat t...
2008/09/22
[ "https://Stackoverflow.com/questions/114501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6476/" ]
I want to set a background image for a div, in a way that it is in the upper **RIGHT** of the div, but with a fixed `10px` distance from top and right. Here is how I would do that if wanted it in the upper **LEFT** of the div: ``` background: url(images/img06.gif) no-repeat 10px 10px; ``` Is there anyway to achieve the same result, but showing the background on the upper **RIGHT**?
Use the previously mentioned rule along with a top and right margin: ``` background: url(images/img06.gif) no-repeat top right; margin-top: 10px; margin-right: 10px; ``` Background images only appear within padding, not margins. If adding the margin isn't an option you may have to resort to another div, although I'd recommend you only use that as a last resort to try and keep your markup as lean and sementic as possible.
114,504
<p>Eg. can I write something like this code:</p> <pre><code>public void InactiveCustomers(IEnumerable&lt;Guid&gt; customerIDs) { //... myAdoCommand.CommandText = "UPDATE Customer SET Active = 0 WHERE CustomerID in (@CustomerIDs)"; myAdoCommand.Parameters["@CustomerIDs"].Value = customerIDs; //... } </code></pre> <p>The only way I know is to Join my IEnumerable and then use string concatenation to build my SQL string.</p>
[ { "answer_id": 114548, "author": "Pontus Gagge", "author_id": 20402, "author_profile": "https://Stackoverflow.com/users/20402", "pm_score": -1, "selected": false, "text": "<p>Nope. Parameters are like SQL values in obeying <a href=\"http://www.anaesthetist.com/mnm/sql/normal.htm\" rel=\"...
2008/09/22
[ "https://Stackoverflow.com/questions/114504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
Eg. can I write something like this code: ``` public void InactiveCustomers(IEnumerable<Guid> customerIDs) { //... myAdoCommand.CommandText = "UPDATE Customer SET Active = 0 WHERE CustomerID in (@CustomerIDs)"; myAdoCommand.Parameters["@CustomerIDs"].Value = customerIDs; //... } ``` The only way I know is to Join my IEnumerable and then use string concatenation to build my SQL string.
Generally the way that you do this is to pass in a comma-separated list of values, and within your stored procedure, parse the list out and insert it into a temp table, which you can then use for joins. As of **Sql Server 2005**, this is standard practice for dealing with parameters that need to hold arrays. Here's a good article on various ways to deal with this problem: [Passing a list/array to an SQL Server stored procedure](http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm) But for **Sql Server 2008**, we finally get to pass table variables into procedures, by first defining the table as a custom type. There is a good description of this (and more 2008 features) in this article: [Introduction to New T-SQL Programmability Features in SQL Server 2008](http://technet.microsoft.com/en-us/library/cc721270.aspx)
114,521
<p>I am creating a <code>gridView</code> that allows adding new rows by adding the controls necessary for the insert into the <code>FooterTemplate</code>, but when the <code>ObjectDataSource</code> has no records, I add a dummy row as the <code>FooterTemplate</code> is only displayed when there is data.</p> <p>How can I hide this dummy row? I have tried setting <code>e.row.visible = false</code> on <code>RowDataBound</code> but the row is still visible.</p>
[ { "answer_id": 114589, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "<p>This is the incorrect usage of the GridView control. The GridView control has a special InsertRow which is where you...
2008/09/22
[ "https://Stackoverflow.com/questions/114521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2808/" ]
I am creating a `gridView` that allows adding new rows by adding the controls necessary for the insert into the `FooterTemplate`, but when the `ObjectDataSource` has no records, I add a dummy row as the `FooterTemplate` is only displayed when there is data. How can I hide this dummy row? I have tried setting `e.row.visible = false` on `RowDataBound` but the row is still visible.
You could handle the gridview's databound event and hide the dummy row. (Don't forget to assign the event property in the aspx code): ``` protected void GridView1_DataBound(object sender, EventArgs e) { if (GridView1.Rows.Count == 1) GridView1.Rows[0].Visible = false; } ```
114,525
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname">JavaScript: var functionName = function() {} vs function functionName() {}</a> </p> </blockquote> <p>What's the difference between:</p> <pre><code>function sum(x, y) { return x+y; } // and var sum = function (x, y) { return x+y; } </code></pre> <p>Why is one used over the other?</p>
[ { "answer_id": 114573, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 3, "selected": false, "text": "<p>The first one is a named function statement, the second one assigns an anonymous function expression to a variable.<...
2008/09/22
[ "https://Stackoverflow.com/questions/114525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3983/" ]
> > **Possible Duplicate:** > > [JavaScript: var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname) > > > What's the difference between: ``` function sum(x, y) { return x+y; } // and var sum = function (x, y) { return x+y; } ``` Why is one used over the other?
The first is known as a named function where the second is known as an anonymous function. The key practical difference is in when you can use the sum function. For example:- ``` var z = sum(2, 3); function sum(x, y) { return x+y; } ``` `z` is assigned 5 whereas this:- ``` var z = sum(2, 3); var sum = function(x, y) { return x+y; } ``` Will fail since at the time the first line has executed the variable sum has not yet been assigned the function. Named functions are parsed and assigned to their names before execution begins which is why a named function can be utilized in code that precedes its definition. Variables assigned a function by code can clearly only be used as function once execution has proceeded past the assignment.
114,527
<p>I'm really new to .NET, and I still didn't get the hang about how configuration files work.</p> <p>Every time I search on Google about it I get results about web.config, but I'm writing a Windows Forms application.</p> <p>I figured out that I need to use the System.Configuration namespace, but the documentation isn't helping.</p> <p>How do I define that my configuration file is XYZ.xml? Or does it have a "default" name for the configuration file? I still didn't get that.</p> <p>Also, how do I define a new section? Do I really need to create a class which inherits from ConfigurationSection?</p> <p>I would like to just have a configuration file with some values like this:</p> <pre><code>&lt;MyCustomValue&gt;1&lt;/MyCustomValue&gt; &lt;MyCustomPath&gt;C:\Some\Path\Here&lt;/MyCustomPath&gt; </code></pre> <p>Is there a simple way to do it? Can you explain in a simple way how to read and write from/to a simple configuration file?</p>
[ { "answer_id": 114551, "author": "Geoff", "author_id": 1097, "author_profile": "https://Stackoverflow.com/users/1097", "pm_score": 0, "selected": false, "text": "<p>What version of .NET and Visual&nbsp;Studio are you using?</p>\n\n<p>When you created the new project, you should have a fi...
2008/09/22
[ "https://Stackoverflow.com/questions/114527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/727/" ]
I'm really new to .NET, and I still didn't get the hang about how configuration files work. Every time I search on Google about it I get results about web.config, but I'm writing a Windows Forms application. I figured out that I need to use the System.Configuration namespace, but the documentation isn't helping. How do I define that my configuration file is XYZ.xml? Or does it have a "default" name for the configuration file? I still didn't get that. Also, how do I define a new section? Do I really need to create a class which inherits from ConfigurationSection? I would like to just have a configuration file with some values like this: ``` <MyCustomValue>1</MyCustomValue> <MyCustomPath>C:\Some\Path\Here</MyCustomPath> ``` Is there a simple way to do it? Can you explain in a simple way how to read and write from/to a simple configuration file?
You want to use an App.Config. When you add a new item to a project there is something called Applications Configuration file. Add that. Then you add keys in the configuration/appsettings section Like: ``` <configuration> <appSettings> <add key="MyKey" value="false"/> ``` Access the members by doing ``` System.Configuration.ConfigurationSettings.AppSettings["MyKey"]; ``` This works in .NET 2 and above.
114,541
<p>I want to write a <a href="http://getsongbird.com/" rel="noreferrer">Songbird</a> extension binds the multimedia keys available on all Apple Mac OS X platforms. Unfortunately this isn't an easy google search and I can't find any docs.</p> <p>Can anyone point me resources on accessing these keys or tell me how to do it?</p> <p>I have extensive programming experience, but this will be my first time coding in both MacOSX and <a href="http://wiki.songbirdnest.com/Developer/Developer_Intro/Extensions" rel="noreferrer">XUL</a> (Firefox, etc), so any tips on either are welcome.</p> <p>Please note that these are not regular key events. I assume it must be a different type of system event that I will need to hook or subscribe to.</p>
[ { "answer_id": 115333, "author": "rami", "author_id": 9629, "author_profile": "https://Stackoverflow.com/users/9629", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.manpagez.com/man/1/xev/\" rel=\"nofollow noreferrer\"><code>xev</code></a> might help you if you want t...
2008/09/22
[ "https://Stackoverflow.com/questions/114541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15948/" ]
I want to write a [Songbird](http://getsongbird.com/) extension binds the multimedia keys available on all Apple Mac OS X platforms. Unfortunately this isn't an easy google search and I can't find any docs. Can anyone point me resources on accessing these keys or tell me how to do it? I have extensive programming experience, but this will be my first time coding in both MacOSX and [XUL](http://wiki.songbirdnest.com/Developer/Developer_Intro/Extensions) (Firefox, etc), so any tips on either are welcome. Please note that these are not regular key events. I assume it must be a different type of system event that I will need to hook or subscribe to.
This blog post has a solution: <http://www.rogueamoeba.com/utm/posts/Article/mediaKeys-2007-09-29-17-00.html> You basically need to subclass `NSApplication` and override `sendEvent`, looking for special scan codes. I don't know what songbird is, but if it's not a real application then I doubt you'll be able to do this. Or maybe you can, a simple category may suffice: ``` @implementation NSApplication(WantMediaKeysCategoryKBye) - (void)sendEvent: (NSEvent*)event { // intercept media keys here } @end ```
114,543
<p>How can I horizontally center a <code>&lt;div&gt;</code> within another <code>&lt;div&gt;</code> using CSS?</p> <pre class="lang-html prettyprint-override"><code>&lt;div id=&quot;outer&quot;&gt; &lt;div id=&quot;inner&quot;&gt;Foo foo&lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 114549, "author": "Justin Poliey", "author_id": 6967, "author_profile": "https://Stackoverflow.com/users/6967", "pm_score": 13, "selected": true, "text": "<p>You can apply this CSS to the inner <code>&lt;div&gt;</code>:</p>\n<pre class=\"lang-css prettyprint-override\"><co...
2008/09/22
[ "https://Stackoverflow.com/questions/114543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20403/" ]
How can I horizontally center a `<div>` within another `<div>` using CSS? ```html <div id="outer"> <div id="inner">Foo foo</div> </div> ```
You can apply this CSS to the inner `<div>`: ```css #inner { width: 50%; margin: 0 auto; } ``` Of course, you don't have to set the `width` to `50%`. Any width less than the containing `<div>` will work. The `margin: 0 auto` is what does the actual centering. If you are targeting [Internet Explorer 8](https://en.wikipedia.org/wiki/Internet_Explorer_8) (and later), it might be better to have this instead: ```css #inner { display: table; margin: 0 auto; } ``` It will make the inner element center horizontally and it works without setting a specific `width`. Working example here: ```css #inner { display: table; margin: 0 auto; border: 1px solid black; } #outer { border: 1px solid red; width:100% } ``` ```html <div id="outer"> <div id="inner">Foo foo</div> </div> ``` --- EDIT ---- With `flexbox` it is very easy to style the div horizontally and vertically centered. ```css #inner { border: 0.05em solid black; } #outer { border: 0.05em solid red; width:100%; display: flex; justify-content: center; } ``` ```html <div id="outer"> <div id="inner">Foo foo</div> </div> ``` To align the div vertically centered, use the property `align-items: center`.
114,619
<p>I have defined a Delphi TTable object with calculated fields, and it is used in a grid on a form. I would like to make a copy of the TTable object, including the calculated fields, open that copy, do some changes to the data with the copy, close the copy, and then refresh the original copy and thusly the grid view. Is there an easy way to get a copy of a TTable object to be used in such a way?</p> <p>The ideal answer would be one that solves the problem as generically as possible, i.e., a way of getting something like this:</p> <pre><code>newTable:=getACopyOf(existingTable); </code></pre>
[ { "answer_id": 114803, "author": "mj2008", "author_id": 5544, "author_profile": "https://Stackoverflow.com/users/5544", "pm_score": 0, "selected": false, "text": "<p>You should be able to select the table on the form, copy it using <kbd>Ctrl</kbd>-<kbd>C</kbd>, then paste it into any tex...
2008/09/22
[ "https://Stackoverflow.com/questions/114619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20408/" ]
I have defined a Delphi TTable object with calculated fields, and it is used in a grid on a form. I would like to make a copy of the TTable object, including the calculated fields, open that copy, do some changes to the data with the copy, close the copy, and then refresh the original copy and thusly the grid view. Is there an easy way to get a copy of a TTable object to be used in such a way? The ideal answer would be one that solves the problem as generically as possible, i.e., a way of getting something like this: ``` newTable:=getACopyOf(existingTable); ```
You can use the **TBatchMove** component to copy a table and its structure. Set the Mode property to specify the desired operation. The Source and Destination properties indicate the datasets whose records are added, deleted, or copied. The online help has additional details. (Although I reckon you should investigate a TClientDataSet approach - it's certainly more scalable and faster).
114,658
<p>I keep hearing that </p> <pre><code>catch (Exception ex) </code></pre> <p>Is bad practise, however, I often use it in event handlers where an operation may for example go to network, allowing the possibility of many different types of failure. In this case, I catch all exceptions and display the error message to the user in a message box.</p> <p>Is this considered bad practise? There's nothing more I can do with the exception: I don't want it to halt the application, the user needs to know what happened, and I'm at the top level of my code. What else should I be doing?</p> <p>EDIT:</p> <p>People are saying that I should look through the stack of calls and handle errors specifically, because for example a StackOverflow exception cannot be handled meaningfully. However, halting the process is the <b>worst</b> outcome, I want to prevent that at all costs. If I can't handle a StackOverflow, so be it - the outcome will be no worse than not catching exceptions at all, and in 99% of cases, informing the user is the least bad option as far as I'm concerned.</p> <p>Also, despite my best efforts to work out all of the possible exceptions that can be thrown, in a large code-base it's likely that I would miss some. And for most of them the best defense is still to inform the user.</p>
[ { "answer_id": 114678, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "<p>It's perfectly okay if you re-raise exceptions you can't handle properly. If you just catch the exceptions you ...
2008/09/22
[ "https://Stackoverflow.com/questions/114658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6448/" ]
I keep hearing that ``` catch (Exception ex) ``` Is bad practise, however, I often use it in event handlers where an operation may for example go to network, allowing the possibility of many different types of failure. In this case, I catch all exceptions and display the error message to the user in a message box. Is this considered bad practise? There's nothing more I can do with the exception: I don't want it to halt the application, the user needs to know what happened, and I'm at the top level of my code. What else should I be doing? EDIT: People are saying that I should look through the stack of calls and handle errors specifically, because for example a StackOverflow exception cannot be handled meaningfully. However, halting the process is the **worst** outcome, I want to prevent that at all costs. If I can't handle a StackOverflow, so be it - the outcome will be no worse than not catching exceptions at all, and in 99% of cases, informing the user is the least bad option as far as I'm concerned. Also, despite my best efforts to work out all of the possible exceptions that can be thrown, in a large code-base it's likely that I would miss some. And for most of them the best defense is still to inform the user.
The bad practice is ``` catch (Exception ex){} ``` and variants: ``` catch (Exception ex){ return false; } ``` etc. Catching all exceptions on the top-level and passing them on to the user (by either logging them or displaying them in a message-box, depending on whether you are writing a server- or a client-application), is exactly the right thing to do.
114,725
<p>I’ve got a problem with Visual Basic (6) in combination with LDAP. When I try to connect to an LDAP store, I always get errors like ‘Bad Pathname’ or ‘Table does not exist’ (depending on what the code looks like).</p> <p>This is the part of the code I wrote to connect:</p> <pre><code>path = "LDAP://xx.xxx.xxx.xxx:xxx/" Logging.WriteToLogFile "Test1", logINFO Set conn = CreateObject("ADODB.Connection") conn.Provider = "ADsDSOObject" conn.Properties("User ID") = "USER_ID" conn.Properties("Password") = "PASSWORD" conn.Properties("Encrypt Password") = True conn.Properties("ADSI Flag") = 34 Logging.WriteToLogFile "Test2", logINFO conn.Open "Active Directory Provider" Logging.WriteToLogFile "Test3", logINFO Set rs = conn.Execute("&lt;" &amp; path &amp; "ou=Some,ou=Kindof,o=Searchbase&gt;;(objectclass=*);name;subtree") Logging.WriteToLogFile "Test4", logINFO </code></pre> <p>The logfile shows “Test1” , “Test2”, “Test3” and then “Table does not exist”, so it’s the line “Set rs = conn.Execute(…)” where things go wrong (pretty obvious…).</p> <p>In my code, I try to connect in a secure way. I found out it has nothing to do with SSL/certificates though, because it’s also not possible to establish an anonymous unsecured connection. Funny thing is: I wrote a small test app in .NET in five minutes. With that app I was able to connect (anonymously) and read results from the LDAP store, no problems at all.</p> <p>Does anyone have any experience with the combination LDAP and VB6 and maybe know what could be the problem? I googled and saw some example code snippets, but unfortunately none of them worked (same error messages as result). Thanks in advance!</p>
[ { "answer_id": 114790, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 2, "selected": false, "text": "<p>I'm not sure how much help this will be, but I use this code to access Active Directory objects.</p>\n\n<pre><code>...
2008/09/22
[ "https://Stackoverflow.com/questions/114725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I’ve got a problem with Visual Basic (6) in combination with LDAP. When I try to connect to an LDAP store, I always get errors like ‘Bad Pathname’ or ‘Table does not exist’ (depending on what the code looks like). This is the part of the code I wrote to connect: ``` path = "LDAP://xx.xxx.xxx.xxx:xxx/" Logging.WriteToLogFile "Test1", logINFO Set conn = CreateObject("ADODB.Connection") conn.Provider = "ADsDSOObject" conn.Properties("User ID") = "USER_ID" conn.Properties("Password") = "PASSWORD" conn.Properties("Encrypt Password") = True conn.Properties("ADSI Flag") = 34 Logging.WriteToLogFile "Test2", logINFO conn.Open "Active Directory Provider" Logging.WriteToLogFile "Test3", logINFO Set rs = conn.Execute("<" & path & "ou=Some,ou=Kindof,o=Searchbase>;(objectclass=*);name;subtree") Logging.WriteToLogFile "Test4", logINFO ``` The logfile shows “Test1” , “Test2”, “Test3” and then “Table does not exist”, so it’s the line “Set rs = conn.Execute(…)” where things go wrong (pretty obvious…). In my code, I try to connect in a secure way. I found out it has nothing to do with SSL/certificates though, because it’s also not possible to establish an anonymous unsecured connection. Funny thing is: I wrote a small test app in .NET in five minutes. With that app I was able to connect (anonymously) and read results from the LDAP store, no problems at all. Does anyone have any experience with the combination LDAP and VB6 and maybe know what could be the problem? I googled and saw some example code snippets, but unfortunately none of them worked (same error messages as result). Thanks in advance!
I'm not sure how much help this will be, but I use this code to access Active Directory objects. ``` Set oinfo = New ADSystemInfo sDomain = Split(oinfo.DomainDNSName, ".") '-- Get Datasets from the Active Directory '-- Connect to Active Directory in logged in domain con.Open "Provider=ADsDSOObject;Encrypt Password=False;Integrated Security=SSPI;Data Source=ADSDSOObject;Mode=Read;Bind Flags=0;ADSI Flag=-2147483648" '-- Query all serviceConnectionPoints in the Active Directory '-- that contain the keyword "urn://tavis.net/TM/Database" '-- and return the full path to the object Set rst = con.Execute("<LDAP://DC=" & sDomain(0) & ",DC=" & sDomain(1) & ">;(&(objectCategory=serviceConnectionPoint)(keywords=urn://tavis.net/TM/Database));Name, AdsPath;subTree") ```
114,728
<p>One of my DBs have grown closer to permitted size.</p> <p>Inorder to find out the table containing the max data, i used the following query:</p> <pre><code>exec sp_MSforeachtable @command1="print '?' exec sp_spaceused '?'" </code></pre> <p>It returned the culprit table comprising the max data.</p> <p>As a next step, i want to cleanup the rows based on the size. For this, i would like to order the rows based on size.</p> <p>How to achieve this using a query? Are there any tools to do this?</p>
[ { "answer_id": 114827, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 1, "selected": false, "text": "<p>An easier approach for all table sizes is to use the stored procedure at <a href=\"http://www.mitchelsellers.com/blogs/a...
2008/09/22
[ "https://Stackoverflow.com/questions/114728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15425/" ]
One of my DBs have grown closer to permitted size. Inorder to find out the table containing the max data, i used the following query: ``` exec sp_MSforeachtable @command1="print '?' exec sp_spaceused '?'" ``` It returned the culprit table comprising the max data. As a next step, i want to cleanup the rows based on the size. For this, i would like to order the rows based on size. How to achieve this using a query? Are there any tools to do this?
This will give you a list of rows by size, just set @table and @idcol accordingly (as written it'll run against the Northwind sample) ``` declare @table varchar(20) declare @idcol varchar(10) declare @sql varchar(1000) set @table = 'Employees' set @idcol = 'EmployeeId' set @sql = 'select ' + @idcol +' , (0' select @sql = @sql + ' + isnull(datalength(' + name + '), 1)' from syscolumns where id = object_id(@table) set @sql = @sql + ') as rowsize from ' + @table + ' order by rowsize desc' exec (@sql) ```
114,733
<p>Do anyone have good ideas of how to modify the toolbar for the WinForms version of the ReportViewer Toolbar? That is, I want to remove some buttons and varius, but it looks like the solution is to create a brand new toolbar instead of modifying the one that is there.</p> <p>Like, I had to remove export to excel, and did it this way:</p> <pre><code> // Disable excel export foreach (RenderingExtension extension in lr.ListRenderingExtensions()) { if (extension.Name == "Excel") { //extension.Visible = false; // Property is readonly... FieldInfo fi = extension.GetType().GetField("m_isVisible", BindingFlags.Instance | BindingFlags.NonPublic); fi.SetValue(extension, false); } } </code></pre> <p>A bit trickysh if you ask me.. For removing toolbarbuttons, an possible way was to iterate through the Control array inside the ReportViewer and change the Visible property for the buttons to hide, but it gets reset all the time, so it is not an good way..</p> <p>WHEN do MS come with an new version btw?</p>
[ { "answer_id": 114766, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "<p>Generally you are suppose to create your own toolbar if you want to modify it. Your solution for removing buttons will p...
2008/09/22
[ "https://Stackoverflow.com/questions/114733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3308/" ]
Do anyone have good ideas of how to modify the toolbar for the WinForms version of the ReportViewer Toolbar? That is, I want to remove some buttons and varius, but it looks like the solution is to create a brand new toolbar instead of modifying the one that is there. Like, I had to remove export to excel, and did it this way: ``` // Disable excel export foreach (RenderingExtension extension in lr.ListRenderingExtensions()) { if (extension.Name == "Excel") { //extension.Visible = false; // Property is readonly... FieldInfo fi = extension.GetType().GetField("m_isVisible", BindingFlags.Instance | BindingFlags.NonPublic); fi.SetValue(extension, false); } } ``` A bit trickysh if you ask me.. For removing toolbarbuttons, an possible way was to iterate through the Control array inside the ReportViewer and change the Visible property for the buttons to hide, but it gets reset all the time, so it is not an good way.. WHEN do MS come with an new version btw?
There are a lot of properties to set which buttons would you like to see. For example [ShowBackButton](http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer.showbackbutton(VS.80).aspx), [ShowExportButton](http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer.showexportbutton(VS.80).aspx), [ShowFindControls](http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer.showfindcontrols(VS.80).aspx), and so on. Check them in the [help](http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer_members(VS.80).aspx), all starts with "Show". But you are right, you cannot add new buttons. You have to create your own toolbar in order to do this. What do you mean about new version? There is already a [2008 SP1](http://www.microsoft.com/downloads/details.aspx?FamilyID=bb196d5d-76c2-4a0e-9458-267d22b6aac6&DisplayLang=en) version of it.
114,787
<p>I'm trying to setup a stress/load test using the WCAT toolkit included in the IIS Resources.</p> <p>Using LogParser, I've processed a UBR file with configuration. It looks something like this:</p> <pre><code> [Configuration] NumClientMachines: 1 # number of distinct client machines to use NumClientThreads: 100 # number of threads per machine AsynchronousWait: TRUE # asynchronous wait for think and delay Duration: 5m # length of experiment (m = minutes, s = seconds) MaxRecvBuffer: 8192K # suggested maximum received buffer ThinkTime: 0s # maximum think-time before next request WarmupTime: 5s # time to warm up before taking statistics CooldownTime: 6s # time to cool down at the end of the experiment [Performance] [Script] SET RequestHeader = "Accept: */*\r\n" APP RequestHeader = "Accept-Language: en-us\r\n" APP RequestHeader = "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705)\r\n" APP RequestHeader = "Host: %HOST%\r\n" NEW TRANSACTION classId = 1 NEW REQUEST HTTP ResponseStatusCode = 200 Weight = 45117 verb = "GET" URL = "http://Url1.com" NEW TRANSACTION classId = 3 NEW REQUEST HTTP ResponseStatusCode = 200 Weight = 13662 verb = "GET" URL = "http://Url1.com/test.aspx" </code></pre> <p>Does it look OK?</p> <p>I execute the controller with this command: <code>wcctl -z StressTest.ubr -a localhost</code></p> <p>The Client(s) is executed like this: <code>wcclient localhost</code></p> <p>When the client is executed, I get this error: <code>main client thread Connect Attempt 0 Failed. Error = 10061</code></p> <p>Has anyone in this world ever used WCAT?</p>
[ { "answer_id": 114863, "author": "Corey Goldberg", "author_id": 16148, "author_profile": "https://Stackoverflow.com/users/16148", "pm_score": 0, "selected": false, "text": "<p>I don't have an answer for you, but have you considered using other tools for your testing? The WCAT tools seem...
2008/09/22
[ "https://Stackoverflow.com/questions/114787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2972/" ]
I'm trying to setup a stress/load test using the WCAT toolkit included in the IIS Resources. Using LogParser, I've processed a UBR file with configuration. It looks something like this: ``` [Configuration] NumClientMachines: 1 # number of distinct client machines to use NumClientThreads: 100 # number of threads per machine AsynchronousWait: TRUE # asynchronous wait for think and delay Duration: 5m # length of experiment (m = minutes, s = seconds) MaxRecvBuffer: 8192K # suggested maximum received buffer ThinkTime: 0s # maximum think-time before next request WarmupTime: 5s # time to warm up before taking statistics CooldownTime: 6s # time to cool down at the end of the experiment [Performance] [Script] SET RequestHeader = "Accept: */*\r\n" APP RequestHeader = "Accept-Language: en-us\r\n" APP RequestHeader = "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705)\r\n" APP RequestHeader = "Host: %HOST%\r\n" NEW TRANSACTION classId = 1 NEW REQUEST HTTP ResponseStatusCode = 200 Weight = 45117 verb = "GET" URL = "http://Url1.com" NEW TRANSACTION classId = 3 NEW REQUEST HTTP ResponseStatusCode = 200 Weight = 13662 verb = "GET" URL = "http://Url1.com/test.aspx" ``` Does it look OK? I execute the controller with this command: `wcctl -z StressTest.ubr -a localhost` The Client(s) is executed like this: `wcclient localhost` When the client is executed, I get this error: `main client thread Connect Attempt 0 Failed. Error = 10061` Has anyone in this world ever used WCAT?
I'd look at updating to WCat 6.3 - available [here for x86](http://www.iis.net/downloads/default.aspx?tabid=34&i=1466&g=6) and [here for x64](http://www.iis.net/downloads/default.aspx?tabid=34&i=1467&g=6) They've changed the settings/scenario file strucutures, which is a little painful, but should suit your needs.
114,804
<p>I want to write a real-time analysis tool for wireless traffic.</p> <p>Does anyone know how to read from a promiscuous (or sniffing) device in C? </p> <p>I know that you need to have root access to do it. I was wondering if anyone knows what functions are necessary to do this. Normal sockets don't seem to make sense here.</p>
[ { "answer_id": 114820, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "<p>Why wouldn't you use something like <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">WireShark</a>?</p>\...
2008/09/22
[ "https://Stackoverflow.com/questions/114804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/542226/" ]
I want to write a real-time analysis tool for wireless traffic. Does anyone know how to read from a promiscuous (or sniffing) device in C? I know that you need to have root access to do it. I was wondering if anyone knows what functions are necessary to do this. Normal sockets don't seem to make sense here.
On Linux you use a PF\_PACKET socket to read data from a raw device, such as an ethernet interface running in promiscuous mode: ``` s = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)) ``` This will send copies of every packet received up to your socket. It is quite likely that you don't really want every packet, though. The kernel can perform a first level of filtering using BPF, the [Berkeley Packet Filter](http://en.wikipedia.org/wiki/Berkeley_Packet_Filter). BPF is essentially a stack-based virtual machine: it handles a small set of instructions such as: ``` ldh = load halfword (from packet) jeq = jump if equal ret = return with exit code ``` BPF's exit code tells the kernel whether to copy the packet to the socket or not. It is possible to write relatively small BPF programs directly, using setsockopt(s, SOL\_SOCKET, SO\_ATTACH\_FILTER, ). (WARNING: The kernel takes a struct sock\_fprog, not a struct bpf\_program, do not mix those up or your program will not work on some platforms). For anything reasonably complex, you really want to use libpcap. BPF is limited in what it can do, in particular in the number of instructions it can execute per packet. [libpcap](http://www.tcpdump.org/pcap.htm) will take care of splitting a complex filter up into two pieces, with the kernel performing a first level of filtering and the more-capable user-space code dropping the packets it didn't actually want to see. libpcap also abstracts the kernel interface out of your application code. Linux and BSD use similar APIs, but Solaris requires DLPI and Windows uses something else.
114,814
<p>In Bash, how do I count the number of non-blank lines of code in a project?</p>
[ { "answer_id": 114835, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 2, "selected": false, "text": "<pre><code>awk '/^[[:space:]]*$/ {++x} END {print x}' \"$testfile\"\n</code></pre>\n" }, { "answer_id": 114836...
2008/09/22
[ "https://Stackoverflow.com/questions/114814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10176/" ]
In Bash, how do I count the number of non-blank lines of code in a project?
``` cat foo.c | sed '/^\s*$/d' | wc -l ``` And if you consider comments blank lines: ``` cat foo.pl | sed '/^\s*#/d;/^\s*$/d' | wc -l ``` Although, that's language dependent.
114,819
<p>Consider these classes.</p> <pre><code>class Base { ... }; class Derived : public Base { ... }; </code></pre> <p>this function</p> <pre><code>void BaseFoo( std::vector&lt;Base*&gt;vec ) { ... } </code></pre> <p>And finally my vector</p> <pre><code>std::vector&lt;Derived*&gt;derived; </code></pre> <p>I want to pass <code>derived</code> to function <code>BaseFoo</code>, but the compiler doesn't let me. How do I solve this, without copying the whole vector to a <code>std::vector&lt;Base*&gt;</code>?</p>
[ { "answer_id": 114833, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 3, "selected": false, "text": "<p>one option is to use a template</p>\n\n<pre><code>template&lt;typename T&gt;\nvoid BaseFoo( const std::vector&lt;T*&gt;&...
2008/09/22
[ "https://Stackoverflow.com/questions/114819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
Consider these classes. ``` class Base { ... }; class Derived : public Base { ... }; ``` this function ``` void BaseFoo( std::vector<Base*>vec ) { ... } ``` And finally my vector ``` std::vector<Derived*>derived; ``` I want to pass `derived` to function `BaseFoo`, but the compiler doesn't let me. How do I solve this, without copying the whole vector to a `std::vector<Base*>`?
`vector<Base*>` and `vector<Derived*>` are unrelated types, so you can't do this. This is explained in the C++ FAQ [here](http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.3). You need to change your variable from a `vector<Derived*>` to a `vector<Base*>` and insert `Derived` objects into it. Also, to avoid copying the `vector` unnecessarily, you should pass it by const-reference, not by value: ``` void BaseFoo( const std::vector<Base*>& vec ) { ... } ``` Finally, to avoid memory leaks, and make your code exception-safe, consider using a container designed to handle heap-allocated objects, e.g: ``` #include <boost/ptr_container/ptr_vector.hpp> boost::ptr_vector<Base> vec; ``` Alternatively, change the vector to hold a smart pointer instead of using raw pointers: ``` #include <memory> std::vector< std::shared_ptr<Base*> > vec; ``` or ``` #include <boost/shared_ptr.hpp> std::vector< boost::shared_ptr<Base*> > vec; ``` In each case, you would need to modify your `BaseFoo` function accordingly.
114,830
<p>One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?</p>
[ { "answer_id": 114831, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 9, "selected": true, "text": "<p>Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Pe...
2008/09/22
[ "https://Stackoverflow.com/questions/114830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]
One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?
Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, [here](http://mail.python.org/pipermail/python-list/2000-March/048085.html "Tim Peters"). That's why you can't use something 'not hashable' as a dict key, like a list: ``` >>> a = {} >>> b = ['some', 'list'] >>> hash(b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list objects are unhashable >>> a[b] = 'some' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list objects are unhashable ``` You can [read more about hash tables](http://en.wikipedia.org/wiki/Hash_table "Hash table on wikipedia") or [check how it has been implemented in python](https://hg.python.org/cpython/file/10eea15880db/Objects/dictobject.c "Dict Object in Python source code") and [why it is implemented that way](https://hg.python.org/cpython/file/10eea15880db/Objects/dictnotes.txt "Notes on optimizing dictionaries in the CPython distribution").
114,851
<p>I have the following code:</p> <pre><code>ListBox.DataSource = DataSet.Tables("table_name").Select("some_criteria = match") ListBox.DisplayMember = "name" </code></pre> <p>The <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.select(VS.80).aspx" rel="noreferrer"><code>DataTable.Select()</code> method</a> returns an array of <a href="http://msdn.microsoft.com/en-us/library/system.data.datarow(VS.80).aspx" rel="noreferrer"><code>System.Data.DataRow</code></a> objects.</p> <p>No matter what I specify in the <code>ListBox.DisplayMember</code> property, all I see is the ListBox with the correct number of items all showing as <code>System.Data.DataRow</code> instead of the value I want which is in the <code>"name"</code> column!</p> <p>Is it possible to bind to the resulting array from <code>DataTable.Select()</code>, instead of looping through it and adding each one to the <code>ListBox</code>?</p> <p>(I've no problem with looping, but doesn't seem an elegant ending!)</p>
[ { "answer_id": 114887, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 6, "selected": true, "text": "<p>Use a <a href=\"http://msdn.microsoft.com/en-us/library/hy5b8exc(VS.71).aspx\" rel=\"noreferrer\">DataView</a> instead.</p>...
2008/09/22
[ "https://Stackoverflow.com/questions/114851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
I have the following code: ``` ListBox.DataSource = DataSet.Tables("table_name").Select("some_criteria = match") ListBox.DisplayMember = "name" ``` The [`DataTable.Select()` method](http://msdn.microsoft.com/en-us/library/system.data.datatable.select(VS.80).aspx) returns an array of [`System.Data.DataRow`](http://msdn.microsoft.com/en-us/library/system.data.datarow(VS.80).aspx) objects. No matter what I specify in the `ListBox.DisplayMember` property, all I see is the ListBox with the correct number of items all showing as `System.Data.DataRow` instead of the value I want which is in the `"name"` column! Is it possible to bind to the resulting array from `DataTable.Select()`, instead of looping through it and adding each one to the `ListBox`? (I've no problem with looping, but doesn't seem an elegant ending!)
Use a [DataView](http://msdn.microsoft.com/en-us/library/hy5b8exc(VS.71).aspx) instead. ``` ListBox.DataSource = new DataView(DataSet.Tables("table_name"), "some_criteria = match", "name", DataViewRowState.CurrentRows); ListBox.DisplayMember = "name" ```
114,859
<p>I use a custom Matrix class in my application, and I frequently add multiple matrices:</p> <pre><code>Matrix result = a + b + c + d; // a, b, c and d are also Matrices </code></pre> <p>However, this creates an intermediate matrix for each addition operation. Since this is simple addition, it is possible to avoid the intermediate objects and create the result by adding the elements of all 4 matrices at once. How can I accomplish this?</p> <p>NOTE: I know I can define multiple functions like <code>Add3Matrices(a, b, c)</code>, <code>Add4Matrices(a, b, c, d)</code>, etc. but I want to keep the elegancy of <code>result = a + b + c + d</code>.</p>
[ { "answer_id": 114881, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 0, "selected": false, "text": "<p>It is not possible, using operators.</p>\n" }, { "answer_id": 114894, "author": "David Dibben", "a...
2008/09/22
[ "https://Stackoverflow.com/questions/114859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/976/" ]
I use a custom Matrix class in my application, and I frequently add multiple matrices: ``` Matrix result = a + b + c + d; // a, b, c and d are also Matrices ``` However, this creates an intermediate matrix for each addition operation. Since this is simple addition, it is possible to avoid the intermediate objects and create the result by adding the elements of all 4 matrices at once. How can I accomplish this? NOTE: I know I can define multiple functions like `Add3Matrices(a, b, c)`, `Add4Matrices(a, b, c, d)`, etc. but I want to keep the elegancy of `result = a + b + c + d`.
You could limit yourself to a single small intermediate by using lazy evaluation. Something like ``` public class LazyMatrix { public static implicit operator Matrix(LazyMatrix l) { Matrix m = new Matrix(); foreach (Matrix x in l.Pending) { for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) m.Contents[i, j] += x.Contents[i, j]; } return m; } public List<Matrix> Pending = new List<Matrix>(); } public class Matrix { public int[,] Contents = { { 0, 0 }, { 0, 0 } }; public static LazyMatrix operator+(Matrix a, Matrix b) { LazyMatrix l = new LazyMatrix(); l.Pending.Add(a); l.Pending.Add(b); return l; } public static LazyMatrix operator+(Matrix a, LazyMatrix b) { b.Pending.Add(a); return b; } } class Program { static void Main(string[] args) { Matrix a = new Matrix(); Matrix b = new Matrix(); Matrix c = new Matrix(); Matrix d = new Matrix(); a.Contents[0, 0] = 1; b.Contents[1, 0] = 4; c.Contents[0, 1] = 9; d.Contents[1, 1] = 16; Matrix m = a + b + c + d; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { System.Console.Write(m.Contents[i, j]); System.Console.Write(" "); } System.Console.WriteLine(); } System.Console.ReadLine(); } } ```
114,872
<p>Given some JS code like that one here:</p> <pre><code> for (var i = 0; i &lt; document.getElementsByName('scale_select').length; i++) { document.getElementsByName('scale_select')[i].onclick = vSetScale; } </code></pre> <p>Would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that?</p> <p>I am not sure how large the effect is in real life, with the result from <code>getElementsByName</code> typically having &lt; 10 items. I'd like to understand the underlying mechanics anyway.</p> <p>Also, if there's anything else noteworthy about the two options, please tell me.</p>
[ { "answer_id": 114891, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>In principle, would the code be faster if we put the result of getElementsByName into a variable before the...
2008/09/22
[ "https://Stackoverflow.com/questions/114872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
Given some JS code like that one here: ``` for (var i = 0; i < document.getElementsByName('scale_select').length; i++) { document.getElementsByName('scale_select')[i].onclick = vSetScale; } ``` Would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that? I am not sure how large the effect is in real life, with the result from `getElementsByName` typically having < 10 items. I'd like to understand the underlying mechanics anyway. Also, if there's anything else noteworthy about the two options, please tell me.
Definitely. The memory required to store that would only be a pointer to a DOM object and that's ***significantly*** less painful than doing a DOM search each time you need to use something! Idealish code: ``` var scale_select = document.getElementsByName('scale_select'); for (var i = 0; i < scale_select.length; i++) scale_select[i].onclick = vSetScale; ```
114,914
<p>We use <a href="http://hudson-ci.org/" rel="noreferrer">Hudson</a> as a continuous integration system to execute automated builds (nightly and based on CVS polling) of a lot of our projects.</p> <p>Some projects poll CVS every 15 minutes, some others poll every 5 minutes and some poll every hour.</p> <p>Every few weeks we'll get a build that fails with the following output:</p> <pre><code>FATAL: java.io.IOException: Too many open files java.io.IOException: java.io.IOException: Too many open files at java.lang.UNIXProcess.&lt;init&gt;(UNIXProcess.java:148) </code></pre> <p>The next build always worked (with 0 changes) so we always chalked it up to 2 build jobs being run at the same time and happening to have too many files open during the process.</p> <p>This weekend we had a build fail Friday night (automatic nightly build) with the message and every other nightly build also failed. Somehow this triggered Hudson to continuously build every project which failed until the issue was resolved. This resulted in a build every 30 minutes or so of every project until sometime Saturday night when the issue magically disappeared. </p>
[ { "answer_id": 114932, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>Change system limits for per-process maximum open file descriptors? As in <code>ulimit -n</code> for the Java process?</p>\n...
2008/09/22
[ "https://Stackoverflow.com/questions/114914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9518/" ]
We use [Hudson](http://hudson-ci.org/) as a continuous integration system to execute automated builds (nightly and based on CVS polling) of a lot of our projects. Some projects poll CVS every 15 minutes, some others poll every 5 minutes and some poll every hour. Every few weeks we'll get a build that fails with the following output: ``` FATAL: java.io.IOException: Too many open files java.io.IOException: java.io.IOException: Too many open files at java.lang.UNIXProcess.<init>(UNIXProcess.java:148) ``` The next build always worked (with 0 changes) so we always chalked it up to 2 build jobs being run at the same time and happening to have too many files open during the process. This weekend we had a build fail Friday night (automatic nightly build) with the message and every other nightly build also failed. Somehow this triggered Hudson to continuously build every project which failed until the issue was resolved. This resulted in a build every 30 minutes or so of every project until sometime Saturday night when the issue magically disappeared.
This is Hudson issue 715 (~~<http://issues.hudson-ci.org/browse/HUDSON-715>~~). The current recommendation is to set the 'maximum number of simultaneous polling threads' to keep the polling activity down.
114,928
<p>I'm firing off a Java application from inside of a C# <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> console application. It works fine for the case where the Java application doesn't care what the "default" directory is, but fails for a Java application that only searches the current directory for support files.</p> <p>Is there a process parameter that can be set to specify the default directory that a process is started in?</p>
[ { "answer_id": 114937, "author": "Dror Helper", "author_id": 11361, "author_profile": "https://Stackoverflow.com/users/11361", "pm_score": 9, "selected": true, "text": "<p>Yes!\nProcessStartInfo Has a property called <em>WorkingDirectory</em>, just use:</p>\n\n<pre><code>...\nusing Syste...
2008/09/22
[ "https://Stackoverflow.com/questions/114928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15689/" ]
I'm firing off a Java application from inside of a C# [.NET](http://en.wikipedia.org/wiki/.NET_Framework) console application. It works fine for the case where the Java application doesn't care what the "default" directory is, but fails for a Java application that only searches the current directory for support files. Is there a process parameter that can be set to specify the default directory that a process is started in?
Yes! ProcessStartInfo Has a property called *WorkingDirectory*, just use: ``` ... using System.Diagnostics; ... var startInfo = new ProcessStartInfo(); startInfo.WorkingDirectory = // working directory // set additional properties Process proc = Process.Start(startInfo); ```
114,983
<p>Given:</p> <pre><code>DateTime.UtcNow </code></pre> <p>How do I get a string which represents the same value in an <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a>-compliant format?</p> <p>Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:</p> <pre><code>yyyy-MM-ddTHH:mm:ssZ </code></pre>
[ { "answer_id": 114997, "author": "Iain", "author_id": 20457, "author_profile": "https://Stackoverflow.com/users/20457", "pm_score": 7, "selected": false, "text": "<pre><code>DateTime.UtcNow.ToString(\"s\")\n</code></pre>\n\n<p>Returns something like 2008-04-10T06:30:00</p>\n\n<p><code>Ut...
2008/09/22
[ "https://Stackoverflow.com/questions/114983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457/" ]
Given: ``` DateTime.UtcNow ``` How do I get a string which represents the same value in an [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601)-compliant format? Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is: ``` yyyy-MM-ddTHH:mm:ssZ ```
> > **Note to readers:** Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information. > > > ``` DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz", CultureInfo.InvariantCulture); ``` Using [custom date-time formatting](https://learn.microsoft.com/dotnet/standard/base-types/custom-date-and-time-format-strings), this gives you a date similar to **2008-09-22T13:57:31.2311892-04:00**. Another way is: ``` DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture); ``` which uses the standard ["round-trip" style](https://learn.microsoft.com/dotnet/standard/base-types/standard-date-and-time-format-strings#Roundtrip) (ISO 8601) to give you **2008-09-22T14:01:54.9571247Z**. To get the specified format, you can use: ``` DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture) ```
114,996
<p>How can we connect a <code>PHP</code> script to <code>MS Access (.mdb)</code> file?</p> <p>I tried by including following <code>PHP</code> code:</p> <pre><code>$db_path = $_SERVER['DOCUMENT_ROOT'] . '\WebUpdate\\' . $file_name . '.mdb'; $cfg_dsn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" . $db_path; $odbcconnect = odbc_connect($cfg_dsn, '', ''); </code></pre> <p>But it failed and I received following error message:</p> <pre><code> Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect in C:\web\WebUpdate\index.php on line 41 </code></pre>
[ { "answer_id": 115009, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": true, "text": "<p>Here's a sample for a connect and a simple select...</p>\n\n<pre><code>&lt;?php\n$db_conn = new COM(\"ADODB.Connection\"...
2008/09/22
[ "https://Stackoverflow.com/questions/114996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6561/" ]
How can we connect a `PHP` script to `MS Access (.mdb)` file? I tried by including following `PHP` code: ``` $db_path = $_SERVER['DOCUMENT_ROOT'] . '\WebUpdate\\' . $file_name . '.mdb'; $cfg_dsn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" . $db_path; $odbcconnect = odbc_connect($cfg_dsn, '', ''); ``` But it failed and I received following error message: ``` Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect in C:\web\WebUpdate\index.php on line 41 ```
Here's a sample for a connect and a simple select... ``` <?php $db_conn = new COM("ADODB.Connection"); $connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("./Northwind.mdb").";"; $db_conn->open($connstr); $rS = $db_conn->execute("SELECT * FROM Employees"); $f1 = $rS->Fields(0); $f2 = $rS->Fields(1); while (!$rS->EOF) { print $f1->value." ".$f2->value."<br />\n"; $rS->MoveNext(); } $rS->Close(); $db_conn->Close(); ?> ```
115,008
<p>How to print line numbers to the log. Say when outputting some information to the log, I also want to print the line number where that output is in the source code. As we can see in the stack trace, it displays the line number where the exception has occurred. Stack trace is available on the exception object.</p> <p>Other alternative could be like manually including the line number when printing to the log. Is there any other way?</p>
[ { "answer_id": 115027, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 7, "selected": false, "text": "<p>From <a href=\"https://web.archive.org/web/20100818065334/http://blog.taragana.com:80/index.php/archive/core-java-...
2008/09/22
[ "https://Stackoverflow.com/questions/115008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15177/" ]
How to print line numbers to the log. Say when outputting some information to the log, I also want to print the line number where that output is in the source code. As we can see in the stack trace, it displays the line number where the exception has occurred. Stack trace is available on the exception object. Other alternative could be like manually including the line number when printing to the log. Is there any other way?
From [Angsuman Chakraborty](https://web.archive.org/web/20100818065334/http://blog.taragana.com:80/index.php/archive/core-java-how-to-get-java-source-code-line-number-file-name-in-code/) (archived) : ``` /** Get the current line number. * @return int - Current line number. */ public static int getLineNumber() { return Thread.currentThread().getStackTrace()[2].getLineNumber(); } ```
115,031
<p>I have an assembly, written in C++\CLI, which uses some of enumerations, provided by .Net. It has such kind of properties: </p> <pre><code>property System::ServiceProcess::ServiceControllerStatus ^ Status { ServiceControllerStatus ^ get() { return (ServiceControllerStatus)_status-&gt;dwCurrentState; } } </code></pre> <p>it works fine, but when i use this assembly from my C# code, type of this property is </p> <pre><code>System.Enum </code></pre> <p>and i have to make type-cast</p> <pre><code> if ((ServiceControllerStatus)currentService.Status == ServiceControllerStatus.Running) //do smth </code></pre> <p>The question is simple: why is it so, and how to fix it ?</p>
[ { "answer_id": 115054, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>I think enums don't use the ^ -- try removing it from the property declaration and get().</p>\n" }, { "answer_...
2008/09/22
[ "https://Stackoverflow.com/questions/115031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6698/" ]
I have an assembly, written in C++\CLI, which uses some of enumerations, provided by .Net. It has such kind of properties: ``` property System::ServiceProcess::ServiceControllerStatus ^ Status { ServiceControllerStatus ^ get() { return (ServiceControllerStatus)_status->dwCurrentState; } } ``` it works fine, but when i use this assembly from my C# code, type of this property is ``` System.Enum ``` and i have to make type-cast ``` if ((ServiceControllerStatus)currentService.Status == ServiceControllerStatus.Running) //do smth ``` The question is simple: why is it so, and how to fix it ?
In C++/CLI **^** is like the analagous \* in standard C++. Because enumerations are value types the **^** should not be included otherwise you will see them as **System.Enum**. Remove the ^ and you will see the correct enumeration on C# side. ``` property System::ServiceProcess::ServiceControllerStatus Status { System::ServiceProcess::ServiceControllerStatus get() { return (System::ServiceProcess::ServiceControllerStatus)_status->dwCurrentState; } } ```
115,039
<p>Suppose that the <strong>ApplicationSettings</strong> class is a general repository of settings that apply to my application such as TimeoutPeriod, DefaultUnitOfMeasure, HistoryWindowSize, etc... And let's say MyClass makes use of one of those settings - DefaultUnitOfMeasure.</p> <p>My reading of proper use of Inversion of Control Containers - and please correct me if I'm wrong on this - is that you define the dependencies of a class in its constructor:</p> <pre><code>public class MyClass { public MyClass(IDataSource ds, UnitOfMeasure default_uom) {...} } </code></pre> <p>and then call instantiate your class with something like</p> <pre><code>var mc = IoC.Container.Resolve&lt;MyClass&gt;(); </code></pre> <p>Where <strong>IDataSource</strong> has been assigned a concrete implementation and default_uom has been wired up to instantiate from the <strong>ApplicationSettings.DefaultUnitOfMeasure</strong> property. I've got to wonder however, if all these hoops are really that necessary to jump through. What trouble am I setting myself up for should I do</p> <pre><code>public class MyClass { public MyClass(IDataSource ds) { UnitOfMeasure duom = IoC.Container.Resolve&lt;UnitOfMeasure&gt;("default_uom"); } } </code></pre> <p>Yes, many of my classes end up with a dependency on <strong>IoC.Container</strong> but that is a dependency that most of my classes will have anyways. It seems like I maybe should make full use of it as long as the classes are coupled. Please Agile gurus, tell me where I'm wrong.</p>
[ { "answer_id": 115183, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Yes, many of my classes end up with a dependency on IoC.Container but that is a dependency that most of...
2008/09/22
[ "https://Stackoverflow.com/questions/115039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
Suppose that the **ApplicationSettings** class is a general repository of settings that apply to my application such as TimeoutPeriod, DefaultUnitOfMeasure, HistoryWindowSize, etc... And let's say MyClass makes use of one of those settings - DefaultUnitOfMeasure. My reading of proper use of Inversion of Control Containers - and please correct me if I'm wrong on this - is that you define the dependencies of a class in its constructor: ``` public class MyClass { public MyClass(IDataSource ds, UnitOfMeasure default_uom) {...} } ``` and then call instantiate your class with something like ``` var mc = IoC.Container.Resolve<MyClass>(); ``` Where **IDataSource** has been assigned a concrete implementation and default\_uom has been wired up to instantiate from the **ApplicationSettings.DefaultUnitOfMeasure** property. I've got to wonder however, if all these hoops are really that necessary to jump through. What trouble am I setting myself up for should I do ``` public class MyClass { public MyClass(IDataSource ds) { UnitOfMeasure duom = IoC.Container.Resolve<UnitOfMeasure>("default_uom"); } } ``` Yes, many of my classes end up with a dependency on **IoC.Container** but that is a dependency that most of my classes will have anyways. It seems like I maybe should make full use of it as long as the classes are coupled. Please Agile gurus, tell me where I'm wrong.
> > IoC.Container.Resolve("default\_uom"); > > > I see this as a classic anti-pattern, where you are using the IoC container as a service locater - the key issues that result are: * Your application no longer fails-fast if your container is misconfigured (you'll only know about it the first time it tries to resolve that particular service in code, which might not occur except for a specific set of logic/circumstances). * Harder to test - not impossible of course, but you either have to create a real (and semi-configured) instance of the windsor container for your tests or inject the singleton with a mock of IWindsorContainer - this adds a lot of friction to testing, compared to just being able to pass the mock/stub services directly into your class under test via constructors/properties. * Harder to maintain this kind of application (configuration isn't centralized in one location) * Violates a number of other software development principles (DRY, SOC etc.) The concerning part of your original statement is the implication that most of your classes will have a dependency on your IoC singleton - if they're getting all the services injected in via constructors/dependencies then having some tight coupling to IoC should be the exception to the rule - In general the only time I take a dependency on the container is when I'm doing something tricky i.e. trying to avoid a circular dependency problems, or wish to create components at run-time for some reason, and even then I can often avoid taking a dependency on anything more then a generic IServiceProvider interface, allowing me to swap in a home-bake IoC or service locater implementation if I need to reuse the components in an environment outside of the original project.
115,103
<p>I am trying to implement position-sensitive zooming inside a <code>JScrollPane</code>. The <code>JScrollPane</code> contains a component with a customized <code>paint</code> that will draw itself inside whatever space it is allocated - so zooming is as easy as using a <code>MouseWheelListener</code> that resizes the inner component as required.</p> <p>But I also want zooming into (or out of) a point to keep that point as central as possible within the resulting zoomed-in (or -out) view (this is what I refer to as 'position-sensitive' zooming), similar to how zooming works in google maps. I am sure this has been done many times before - does anybody know the "right" way to do it under Java Swing?. Would it be better to play with <code>Graphic2D</code>'s transformations instead of using <code>JScrollPanes</code>?</p> <p>Sample code follows:</p> <pre><code>package test; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; public class FPanel extends javax.swing.JPanel { private Dimension preferredSize = new Dimension(400, 400); private Rectangle2D[] rects = new Rectangle2D[50]; public static void main(String[] args) { JFrame jf = new JFrame("test"); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(400, 400); jf.add(new JScrollPane(new FPanel())); jf.setVisible(true); } public FPanel() { // generate rectangles with pseudo-random coords for (int i=0; i&lt;rects.length; i++) { rects[i] = new Rectangle2D.Double( Math.random()*.8, Math.random()*.8, Math.random()*.2, Math.random()*.2); } // mouse listener to detect scrollwheel events addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { updatePreferredSize(e.getWheelRotation(), e.getPoint()); } }); } private void updatePreferredSize(int n, Point p) { double d = (double) n * 1.08; d = (n &gt; 0) ? 1 / d : -d; int w = (int) (getWidth() * d); int h = (int) (getHeight() * d); preferredSize.setSize(w, h); getParent().doLayout(); // Question: how do I keep 'p' centered in the resulting view? } public Dimension getPreferredSize() { return preferredSize; } private Rectangle2D r = new Rectangle2D.Float(); public void paint(Graphics g) { super.paint(g); g.setColor(Color.red); int w = getWidth(); int h = getHeight(); for (Rectangle2D rect : rects) { r.setRect(rect.getX() * w, rect.getY() * h, rect.getWidth() * w, rect.getHeight() * h); ((Graphics2D)g).draw(r); } } } </code></pre>
[ { "answer_id": 115179, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 1, "selected": false, "text": "<p>Your MouseWheelListener also has to locate the cursor, move it to the center of the JScrollPane and adjust the xmin...
2008/09/22
[ "https://Stackoverflow.com/questions/115103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15472/" ]
I am trying to implement position-sensitive zooming inside a `JScrollPane`. The `JScrollPane` contains a component with a customized `paint` that will draw itself inside whatever space it is allocated - so zooming is as easy as using a `MouseWheelListener` that resizes the inner component as required. But I also want zooming into (or out of) a point to keep that point as central as possible within the resulting zoomed-in (or -out) view (this is what I refer to as 'position-sensitive' zooming), similar to how zooming works in google maps. I am sure this has been done many times before - does anybody know the "right" way to do it under Java Swing?. Would it be better to play with `Graphic2D`'s transformations instead of using `JScrollPanes`? Sample code follows: ``` package test; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; public class FPanel extends javax.swing.JPanel { private Dimension preferredSize = new Dimension(400, 400); private Rectangle2D[] rects = new Rectangle2D[50]; public static void main(String[] args) { JFrame jf = new JFrame("test"); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(400, 400); jf.add(new JScrollPane(new FPanel())); jf.setVisible(true); } public FPanel() { // generate rectangles with pseudo-random coords for (int i=0; i<rects.length; i++) { rects[i] = new Rectangle2D.Double( Math.random()*.8, Math.random()*.8, Math.random()*.2, Math.random()*.2); } // mouse listener to detect scrollwheel events addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { updatePreferredSize(e.getWheelRotation(), e.getPoint()); } }); } private void updatePreferredSize(int n, Point p) { double d = (double) n * 1.08; d = (n > 0) ? 1 / d : -d; int w = (int) (getWidth() * d); int h = (int) (getHeight() * d); preferredSize.setSize(w, h); getParent().doLayout(); // Question: how do I keep 'p' centered in the resulting view? } public Dimension getPreferredSize() { return preferredSize; } private Rectangle2D r = new Rectangle2D.Float(); public void paint(Graphics g) { super.paint(g); g.setColor(Color.red); int w = getWidth(); int h = getHeight(); for (Rectangle2D rect : rects) { r.setRect(rect.getX() * w, rect.getY() * h, rect.getWidth() * w, rect.getHeight() * h); ((Graphics2D)g).draw(r); } } } ```
Tested this, seems to work... ``` private void updatePreferredSize(int n, Point p) { double d = (double) n * 1.08; d = (n > 0) ? 1 / d : -d; int w = (int) (getWidth() * d); int h = (int) (getHeight() * d); preferredSize.setSize(w, h); int offX = (int)(p.x * d) - p.x; int offY = (int)(p.y * d) - p.y; setLocation(getLocation().x-offX,getLocation().y-offY); getParent().doLayout(); } ``` **Update** Here is an explanation: the point `p` is the location of the mouse relative to the `FPanel`. Since you are scaling the size of the panel, the location of `p` (relative to the size of the panel) will scale by the same factor. By subtracting the current location from the scaled location, you get how much the point 'shifts' when the panel is resized. Then it is simply a matter of shifting the panel location in the scroll pane by the same amount in the opposite direction to put `p` back under the mouse cursor.
115,121
<p>Does anyone know why there is no <code>respond_to</code> block for generated <code>edit</code> actions? Every other action in typical scaffold controllers has a <code>respond_to</code> block in order to output <code>html</code> and <code>xml</code> formats. Why is the <code>edit</code> action an exception?</p> <p>I'm using the latest version of Ruby on Rails (2.1.1).</p>
[ { "answer_id": 115201, "author": "Andrew", "author_id": 17408, "author_profile": "https://Stackoverflow.com/users/17408", "pm_score": 1, "selected": false, "text": "<p>Because the edit action will only be called from HTML\nThere is no need for the edit form to be returned in an XML conte...
2008/09/22
[ "https://Stackoverflow.com/questions/115121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20467/" ]
Does anyone know why there is no `respond_to` block for generated `edit` actions? Every other action in typical scaffold controllers has a `respond_to` block in order to output `html` and `xml` formats. Why is the `edit` action an exception? I'm using the latest version of Ruby on Rails (2.1.1).
Rails handles the 99% case: It's fairly unlikely you'd ever need to do any XML or JSON translations in your Edit action, because non-visually, the Edit action is pretty much just like the Show action. Nonvisual clients that want to update a model in your application can call the controller this way ``` GET /my_models/[:id].xml (Show) ``` Then, the client app can make any transformations or edits and post (or put) the results to ``` PUT /my_models/[:id].xml (Update) ``` When you call this, you usually are doing it to get an editable form of the Show action: ``` GET /my_models/[:id]/edit ``` And it is intended for human use. 99% of the time, that is. Since it's unusual to transform the data in the Edit action, Rails assumes you aren't going to, and DRYs up your code by leaving respond\_to out of the scaffold.
115,159
<p>I have been using ASP.NET for years, but I can never remember when using the # and = are appropriate.</p> <p>For example:</p> <pre><code>&lt;%= Grid.ClientID %&gt; </code></pre> <p>or</p> <pre><code>&lt;%# Eval("FullName")%&gt; </code></pre> <p>Can someone explain when each should be used so I can keep it straight in my mind? Is # only used in controls that support databinding?</p>
[ { "answer_id": 115199, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 6, "selected": true, "text": "<p>&lt;%= %> is the equivalent of doing Response.Write(\"\") wherever you place it.</p>\n\n<p>&lt;%# %> is for Databindi...
2008/09/22
[ "https://Stackoverflow.com/questions/115159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417/" ]
I have been using ASP.NET for years, but I can never remember when using the # and = are appropriate. For example: ``` <%= Grid.ClientID %> ``` or ``` <%# Eval("FullName")%> ``` Can someone explain when each should be used so I can keep it straight in my mind? Is # only used in controls that support databinding?
<%= %> is the equivalent of doing Response.Write("") wherever you place it. <%# %> is for Databinding and can only be used where databinding is supported (you can use these on the page-level outside a control if you call Page.DataBind() in your codebehind) [Databinding Expressions Overview](http://msdn.microsoft.com/en-us/library/ms178366.aspx)
115,167
<p>I've been developing a site over the past few weeks using CodeIgniter as the framework. I've been thinking of the best way to accomplish something, which in a lot of other frameworks in other languages is relatively simple: sortable tables. CodeIgniter switches off query strings by default, because your URLs contain method parameters. So a URL might look like:</p> <pre><code>/controller/method/param1/param2 </code></pre> <p>You might think that you could just add in <code>sortBy</code> and <code>sortOrder</code> as two additional parameters to the controller method. I don't particularly want to do that, mainly because I want to have a re-usable controller. When you use query string parameters, PHP can easily tell you whether there is a parameter called <code>sortBy</code>. However, when you're using URL based parameters, it will vary with each controller.</p> <p>I was wondering what my options were. As far as I can see they are something like:</p> <ul> <li>Pass in my <code>sortBy</code> and <code>sortOrder</code> parameters, just suck it up, and develop some less-than-reusable component for it.</li> <li>Have an additional controller, which will store the <code>sortBy</code> and <code>sortOrder</code> in the session (although it would have to know where you came from, and send you back to the original page).</li> <li>Have some kind of AJAX function, which would call the controller above; then reload the page.</li> <li>Hack CodeIgniter to turn query strings back on. Actually, if this is the only option, any links to how to do this would be appreciated.</li> </ul> <p>I just can't quite believe such a simple task would present such a problem! Am I missing something? Does anyone have any recommendations?</p> <p>While I love jQuery, and I'm already using it on the site, so TableSorter is a good option. However, I would like to do server-side sorting as there are some pages with potentially large numbers of results, including pagination.</p>
[ { "answer_id": 115259, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<p>I recently added this <a href=\"http://tetlaw.id.au/view/blog/table-sorting-with-prototype/\" rel=\"nofollow noreferrer\"...
2008/09/22
[ "https://Stackoverflow.com/questions/115167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've been developing a site over the past few weeks using CodeIgniter as the framework. I've been thinking of the best way to accomplish something, which in a lot of other frameworks in other languages is relatively simple: sortable tables. CodeIgniter switches off query strings by default, because your URLs contain method parameters. So a URL might look like: ``` /controller/method/param1/param2 ``` You might think that you could just add in `sortBy` and `sortOrder` as two additional parameters to the controller method. I don't particularly want to do that, mainly because I want to have a re-usable controller. When you use query string parameters, PHP can easily tell you whether there is a parameter called `sortBy`. However, when you're using URL based parameters, it will vary with each controller. I was wondering what my options were. As far as I can see they are something like: * Pass in my `sortBy` and `sortOrder` parameters, just suck it up, and develop some less-than-reusable component for it. * Have an additional controller, which will store the `sortBy` and `sortOrder` in the session (although it would have to know where you came from, and send you back to the original page). * Have some kind of AJAX function, which would call the controller above; then reload the page. * Hack CodeIgniter to turn query strings back on. Actually, if this is the only option, any links to how to do this would be appreciated. I just can't quite believe such a simple task would present such a problem! Am I missing something? Does anyone have any recommendations? While I love jQuery, and I'm already using it on the site, so TableSorter is a good option. However, I would like to do server-side sorting as there are some pages with potentially large numbers of results, including pagination.
If you're OK with sorting on the client side, [the Tablesorter plugin for jQuery](http://tablesorter.com/docs) is pretty nice.
115,210
<p>I'm processing some data files that are supposed to be valid UTF-8 but aren't, which causes the parser (not under my control) to fail. I'd like to add a stage of pre-validating the data for UTF-8 well-formedness, but I've not yet found a utility to help do this.</p> <p>There's a <a href="http://www.w3.org/2005/01/yacker/uploads/utf8-validator" rel="noreferrer">web service</a> at W3C which appears to be dead, and I've found a Windows-only validation <a href="http://web.archive.org/web/20081101142036/http://bolek.techno.cz:80/UTF8-Validator/" rel="noreferrer">tool</a> that reports invalid UTF-8 files but doesn't report which lines/characters to fix.</p> <p>I'd be happy with either a tool I can drop in and use (ideally cross-platform), or a ruby/perl script I can make part of my data loading process. </p>
[ { "answer_id": 115241, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "<p>Use python and str.encode|decode functions.</p>\n\n<pre><code>&gt;&gt;&gt; a=\"γεια\"\n&gt;&gt;&gt; a\n'\\xce\\xb3\\xce\\xb5...
2008/09/22
[ "https://Stackoverflow.com/questions/115210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6716/" ]
I'm processing some data files that are supposed to be valid UTF-8 but aren't, which causes the parser (not under my control) to fail. I'd like to add a stage of pre-validating the data for UTF-8 well-formedness, but I've not yet found a utility to help do this. There's a [web service](http://www.w3.org/2005/01/yacker/uploads/utf8-validator) at W3C which appears to be dead, and I've found a Windows-only validation [tool](http://web.archive.org/web/20081101142036/http://bolek.techno.cz:80/UTF8-Validator/) that reports invalid UTF-8 files but doesn't report which lines/characters to fix. I'd be happy with either a tool I can drop in and use (ideally cross-platform), or a ruby/perl script I can make part of my data loading process.
You can use GNU iconv: ``` $ iconv -f UTF-8 your_file -o /dev/null; echo $? ``` Or with older versions of iconv, such as on macOS: ``` $ iconv -f UTF-8 your_file > /dev/null; echo $? ``` The command will return 0 if the file could be converted successfully, and 1 if not. Additionally, it will print out the byte offset where the invalid byte sequence occurred. **Edit**: The output encoding doesn't have to be specified, it will be assumed to be UTF-8.
115,249
<p>I am trying to have a logout page where is displays a messages and then redirects to the login page. This is in ASP.net 2.0.</p> <p>I have this in my <code>Page_Load</code>:</p> <pre><code>ClientScript.RegisterStartupScript(typeof(Page), "pageredirect", JavascriptRedirect() ); </code></pre> <p>This is my redirect function:</p> <pre><code>private string JavascriptRedirect() { StringBuilder sb = new StringBuilder(); sb.Append("&lt;script type=\"text/javascript\" language=\"javascript\"&gt;"); sb.Append("var x = 5;"); sb.Append("var y = 1;"); sb.Append("function startClock(){"); sb.Append("x = x-y;"); sb.Append("t=setTimeout(\"startClock()\", 1000);"); sb.Append("if(x==0){"); sb.Append("window.location='login.aspx';"); sb.Append("clearTimeout(t);"); sb.Append(" }"); sb.Append(" }"); sb.Append("startClock();"); sb.Append("&lt;/script&gt;"); return sb.ToString(); } </code></pre> <p>When I test there is no javascript in my resulting logout page. Anyone have an idea on what is happening. Is <code>Page_Load</code> to late to register this?</p>
[ { "answer_id": 115279, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>Instead of typeof(Page), try typeof(YOURPAGECLASS) -- with YOURPAGECLASS set the name of your page's classname. Page_...
2008/09/22
[ "https://Stackoverflow.com/questions/115249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I am trying to have a logout page where is displays a messages and then redirects to the login page. This is in ASP.net 2.0. I have this in my `Page_Load`: ``` ClientScript.RegisterStartupScript(typeof(Page), "pageredirect", JavascriptRedirect() ); ``` This is my redirect function: ``` private string JavascriptRedirect() { StringBuilder sb = new StringBuilder(); sb.Append("<script type=\"text/javascript\" language=\"javascript\">"); sb.Append("var x = 5;"); sb.Append("var y = 1;"); sb.Append("function startClock(){"); sb.Append("x = x-y;"); sb.Append("t=setTimeout(\"startClock()\", 1000);"); sb.Append("if(x==0){"); sb.Append("window.location='login.aspx';"); sb.Append("clearTimeout(t);"); sb.Append(" }"); sb.Append(" }"); sb.Append("startClock();"); sb.Append("</script>"); return sb.ToString(); } ``` When I test there is no javascript in my resulting logout page. Anyone have an idea on what is happening. Is `Page_Load` to late to register this?
By the way: You don't need Javascript to redirect the browser to a page after a certain amount of time. Just use a plain HTML meta Tag in your `<HEAD>` section. ``` <meta http-equiv="refresh" content="5; URL=login.aspx"> ``` The number stands for the time in seconds, the URL for the target.
115,269
<p>There's something very unsatisfactory about this code:</p> <pre><code>/* Given a command string in which the first 8 characters are the command name padded on the right with whitespace, construct the appropriate kind of Command object. */ public class CommandFactory { public Command getCommand(String cmd) { cmdName = cmd.subString(0,8).trim(); if(cmdName.equals("START")) { return new StartCommand(cmd); } if(cmdName.equals("END")) { return new EndCommand(cmd); } // ... more commands in more if blocks here // else it's a bad command. return new InvalidCommand(cmd); } } </code></pre> <p>I'm unrepentant about the multiple exit points - the structure is clear. But I'm not happy about the series of near-identical if statements. I've considered making a Map of Strings to Commands:</p> <pre><code>commandMap = new HashMap(); commandMap.put("START",StartCommand.class); // ... etc. </code></pre> <p>... then using Reflection to make instances of the appropriate class looked up from the Map. However while conceptually elegant, this involves a fair amount of Reflection code that whoever inherits this code might not appreciate - although that cost might be offset by the benefits. All the lines hardcoding values into the commandMap smell almost as bad as the if block.</p> <p>Even better would be if the factory's constructor could scan the classpath for subclasses of Command, query them for String representations, and automatically add them them to its repertoire.</p> <p>So - how should I go about refactoring this?</p> <p>I guess some of the frameworks out there give me this kind of thing for free. Let's assume I'm not in a position to migrate this stuff into such a framework.</p>
[ { "answer_id": 115289, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": -1, "selected": false, "text": "<p>At the very least, your command should have a getCommandString() -- where StartCommand overrides to return \"START\"....
2008/09/22
[ "https://Stackoverflow.com/questions/115269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7512/" ]
There's something very unsatisfactory about this code: ``` /* Given a command string in which the first 8 characters are the command name padded on the right with whitespace, construct the appropriate kind of Command object. */ public class CommandFactory { public Command getCommand(String cmd) { cmdName = cmd.subString(0,8).trim(); if(cmdName.equals("START")) { return new StartCommand(cmd); } if(cmdName.equals("END")) { return new EndCommand(cmd); } // ... more commands in more if blocks here // else it's a bad command. return new InvalidCommand(cmd); } } ``` I'm unrepentant about the multiple exit points - the structure is clear. But I'm not happy about the series of near-identical if statements. I've considered making a Map of Strings to Commands: ``` commandMap = new HashMap(); commandMap.put("START",StartCommand.class); // ... etc. ``` ... then using Reflection to make instances of the appropriate class looked up from the Map. However while conceptually elegant, this involves a fair amount of Reflection code that whoever inherits this code might not appreciate - although that cost might be offset by the benefits. All the lines hardcoding values into the commandMap smell almost as bad as the if block. Even better would be if the factory's constructor could scan the classpath for subclasses of Command, query them for String representations, and automatically add them them to its repertoire. So - how should I go about refactoring this? I guess some of the frameworks out there give me this kind of thing for free. Let's assume I'm not in a position to migrate this stuff into such a framework.
Your map of strings to commands I think is good. You could even factor out the string command name to the constructor (i.e. shouldn't StartCommand know that its command is "START"?) If you could do this, instantiation of your command objects is much simpler: ``` Class c = commandMap.get(cmdName); if (c != null) return c.newInstance(); else throw new IllegalArgumentException(cmdName + " is not as valid command"); ``` Another option is to create an `enum` of all your commands with links to the classes (assume all your command objects implement `CommandInterface`): ``` public enum Command { START(StartCommand.class), END(EndCommand.class); private Class<? extends CommandInterface> mappedClass; private Command(Class<? extends CommandInterface> c) { mappedClass = c; } public CommandInterface getInstance() { return mappedClass.newInstance(); } } ``` since the toString of an enum is its name, you can use `EnumSet` to locate the right object and get the class from within.
115,319
<p>I'm using C# and connecting to a WebService via an auto-generated C# proxy object. The method I'm calling can be long running, and sometimes times out. I get different errors back, sometimes I get a <code>System.Net.WebException</code> or a <code>System.Web.Services.Protocols.SoapException</code>. These exceptions have properties I can interrogate to find the specific type of error from which I can display a human-friendly version of to the user.</p> <p>But sometimes I just get an <code>InvalidOperationException</code>, and it has the following Message. Is there any way I can interpret what this is without digging through the string for things I recognize, that feels very dirty, and isn't internationalization agnostic, the error message might come back in a different language.</p> <pre><code>Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'. The request failed with the error message: -- &lt;html&gt; &lt;head&gt; &lt;title&gt;Request timed out.&lt;/title&gt; &lt;style&gt; body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Lucida Console";font-size: .9em} .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } &lt;/style&gt; &lt;/head&gt; &lt;body bgcolor="white"&gt; &lt;span&gt;&lt;H1&gt;Server Error in '/PerformanceManager' Application.&lt;hr width=100% size=1 color=silver&gt;&lt;/H1&gt; &lt;h2&gt; &lt;i&gt;Request timed out.&lt;/i&gt; &lt;/h2&gt;&lt;/span&gt; &lt;font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif "&gt; &lt;b&gt; Description: &lt;/b&gt;An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. &lt;br&gt;&lt;br&gt; &lt;b&gt; Exception Details: &lt;/b&gt;System.Web.HttpException: Request timed out.&lt;br&gt;&lt;br&gt; &lt;b&gt;Source Error:&lt;/b&gt; &lt;br&gt;&lt;br&gt; &lt;table width=100% bgcolor="#ffffcc"&gt; &lt;tr&gt; &lt;td&gt; &lt;code&gt; An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.&lt;/code&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;br&gt; &lt;b&gt;Stack Trace:&lt;/b&gt; &lt;br&gt;&lt;br&gt; &lt;table width=100% bgcolor="#ffffcc"&gt; &lt;tr&gt; &lt;td&gt; &lt;code&gt;&lt;pre&gt; [HttpException (0x80004005): Request timed out.] &lt;/pre&gt;&lt;/code&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;br&gt; &lt;hr width=100% size=1 color=silver&gt; &lt;b&gt;Version Information:&lt;/b&gt; Microsoft .NET Framework Version:2.0.50727.312; ASP.NET Version:2.0.50727.833 &lt;/font&gt; &lt;/body&gt; &lt;/html&gt; &lt;!-- [HttpException]: Request timed out. --&gt; --. </code></pre> <p>Edit: I have a try-catch around the method on the web-server. I have debugged it, and the web-server method returns (after a minute or so) without any exception. I also added an unhandled exception handler in the web service and a breakpoint there wasn't hit. As soon as the web-service returns, I get this error in the client instead of the result I expected.</p>
[ { "answer_id": 115337, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<p>That means that your consumer is expecting XML from the webservice but the webservice, as your error shows, retur...
2008/09/22
[ "https://Stackoverflow.com/questions/115319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898/" ]
I'm using C# and connecting to a WebService via an auto-generated C# proxy object. The method I'm calling can be long running, and sometimes times out. I get different errors back, sometimes I get a `System.Net.WebException` or a `System.Web.Services.Protocols.SoapException`. These exceptions have properties I can interrogate to find the specific type of error from which I can display a human-friendly version of to the user. But sometimes I just get an `InvalidOperationException`, and it has the following Message. Is there any way I can interpret what this is without digging through the string for things I recognize, that feels very dirty, and isn't internationalization agnostic, the error message might come back in a different language. ``` Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'. The request failed with the error message: -- <html> <head> <title>Request timed out.</title> <style> body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Lucida Console";font-size: .9em} .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } </style> </head> <body bgcolor="white"> <span><H1>Server Error in '/PerformanceManager' Application.<hr width=100% size=1 color=silver></H1> <h2> <i>Request timed out.</i> </h2></span> <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif "> <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. <br><br> <b> Exception Details: </b>System.Web.HttpException: Request timed out.<br><br> <b>Source Error:</b> <br><br> <table width=100% bgcolor="#ffffcc"> <tr> <td> <code> An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code> </td> </tr> </table> <br> <b>Stack Trace:</b> <br><br> <table width=100% bgcolor="#ffffcc"> <tr> <td> <code><pre> [HttpException (0x80004005): Request timed out.] </pre></code> </td> </tr> </table> <br> <hr width=100% size=1 color=silver> <b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.312; ASP.NET Version:2.0.50727.833 </font> </body> </html> <!-- [HttpException]: Request timed out. --> --. ``` Edit: I have a try-catch around the method on the web-server. I have debugged it, and the web-server method returns (after a minute or so) without any exception. I also added an unhandled exception handler in the web service and a breakpoint there wasn't hit. As soon as the web-service returns, I get this error in the client instead of the result I expected.
This is happening because there is an unhandled exception in your Web service, and the .NET runtime is spitting out its HTML yellow screen of death server error/exception dump page, instead of XML. Since the consumer of your Web service was expecting a text/xml header and instead got text/html, it throws that error. You should address the cause of your timeouts (perhaps a lengthy SQL query?). Also, checkout [this blog post](http://blog.codinghorror.com/throwing-better-soap-exceptions/) on Jeff Atwood's blog that explains implementing a global unhandled exception handler and using SOAP exceptions.
115,328
<p>I have the following class</p> <pre> public class Car { public Name {get; set;} } </pre> <p>and I want to bind this programmatically to a text box.</p> <p>How do I do that?</p> <p>Shooting in the dark:</p> <pre> ... Car car = new Car(); TextEdit editBox = new TextEdit(); editBox.DataBinding.Add("Name", car, "Car - Name"); ... </pre> <p>I get the following error</p> <blockquote> <p>"Cannot bind to the propery 'Name' on the target control.</p> </blockquote> <p>What am I doing wrong and how should I be doing this? I am finding the databinding concept a bit difficult to grasp coming from web-development.</p>
[ { "answer_id": 115346, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 4, "selected": false, "text": "<p>Without looking at the syntax, I'm pretty sure it's:</p>\n\n<pre><code>editBox.DataBinding.Add(\"Text\", car, \"Name\");\...
2008/09/22
[ "https://Stackoverflow.com/questions/115328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ]
I have the following class ``` public class Car { public Name {get; set;} } ``` and I want to bind this programmatically to a text box. How do I do that? Shooting in the dark: ``` ... Car car = new Car(); TextEdit editBox = new TextEdit(); editBox.DataBinding.Add("Name", car, "Car - Name"); ... ``` I get the following error > > "Cannot bind to the propery 'Name' on the target control. > > > What am I doing wrong and how should I be doing this? I am finding the databinding concept a bit difficult to grasp coming from web-development.
You want ``` editBox.DataBindings.Add("Text", car, "Name"); ``` The first parameter is the name of the property on the control that you want to be databound, the second is the data source, the third parameter is the property on the data source that you want to bind to.
115,399
<p>My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing:</p> <ol> <li>I put a <code>DropDownList</code> of the 4-digit year on the page.</li> <li>I validate the expiration date in a <code>DateTime</code> field to be sure that the expiration date being passed to the CC processor isn't expired.</li> <li>I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL.</li> </ol> <p>Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the <code>DateTime</code> object. Or should I just keep processing it as I am?</p>
[ { "answer_id": 115419, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 1, "selected": false, "text": "<p>At this point, the simplest way is to just truncate the last two digits of the year. For credit cards, having a date in th...
2008/09/22
[ "https://Stackoverflow.com/questions/115399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535/" ]
My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing: 1. I put a `DropDownList` of the 4-digit year on the page. 2. I validate the expiration date in a `DateTime` field to be sure that the expiration date being passed to the CC processor isn't expired. 3. I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL. Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the `DateTime` object. Or should I just keep processing it as I am?
If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so: ``` DateTime expirationDate = new DateTime(2008, 1, 31); // random date string lastTwoDigitsOfYear = expirationDate.ToString("yy"); ``` Edit: Be careful with your dates though if you use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first.
115,425
<p>Aside from trying</p> <pre><code>perldoc &lt;module name&gt; </code></pre> <p>individually for any CPAN module that takes my fancy or going through the file system and looking at the directories I have no idea what modules we have installed. </p> <p>What's the easiest way to just get a big list of every CPAN module installed? From the command line or otherwise.</p>
[ { "answer_id": 115439, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 5, "selected": false, "text": "<pre><code>perldoc perllocal\n</code></pre>\n\n<p>Edit: There's a (little) more info about it in the <a href=\"http://www.cpan...
2008/09/22
[ "https://Stackoverflow.com/questions/115425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3404/" ]
Aside from trying ``` perldoc <module name> ``` individually for any CPAN module that takes my fancy or going through the file system and looking at the directories I have no idea what modules we have installed. What's the easiest way to just get a big list of every CPAN module installed? From the command line or otherwise.
This is answered in the Perl FAQ, the answer which can be quickly found with `perldoc -q installed`. In short, it comes down to using `ExtUtils::Installed` or using `File::Find`, variants of both of which have been covered previously in this thread. You can also find the FAQ entry ["How do I find which modules are installed on my system?"](http://perldoc.perl.org/perlfaq3.html#How-do-I-find-which-modules-are-installed-on-my-system%3f) in perlfaq3. You can see a list of all FAQ answers by looking in [perlfaq](http://perldoc.perl.org/perlfaq.html)
115,426
<p>I'm looking for an algorithm to detect if two rectangles intersect (one at an arbitrary angle, the other with only vertical/horizontal lines).</p> <p>Testing if a corner of one is in the other ALMOST works. It fails if the rectangles form a cross-like shape.</p> <p>It seems like a good idea to avoid using slopes of the lines, which would require special cases for vertical lines.</p>
[ { "answer_id": 115476, "author": "Brendan Cashman", "author_id": 5814, "author_profile": "https://Stackoverflow.com/users/5814", "pm_score": 0, "selected": false, "text": "<p>If you're using Java, all implementations of the Shape interface have an <a href=\"http://java.sun.com/javase/6/d...
2008/09/22
[ "https://Stackoverflow.com/questions/115426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20493/" ]
I'm looking for an algorithm to detect if two rectangles intersect (one at an arbitrary angle, the other with only vertical/horizontal lines). Testing if a corner of one is in the other ALMOST works. It fails if the rectangles form a cross-like shape. It seems like a good idea to avoid using slopes of the lines, which would require special cases for vertical lines.
The standard method would be to do the **separating axis test** (do a google search on that). In short: * Two objects don't intersect if you can find a line that separates the two objects. e.g. the objects / all points of an object are on different sides of the line. The fun thing is, that it's sufficient to just check all edges of the two rectangles. If the rectangles don't overlap one of the edges will be the separating axis. In 2D you can do this without using slopes. An edge is simply defined as the difference between two vertices, e.g. ``` edge = v(n) - v(n-1) ``` You can get a perpendicular to this by rotating it by 90°. In 2D this is easy as: ``` rotated.x = -unrotated.y rotated.y = unrotated.x ``` So no trigonometry or slopes involved. Normalizing the vector to unit-length is not required either. If you want to test if a point is on one or another side of the line you can just use the dot-product. the sign will tell you which side you're on: ``` // rotated: your rotated edge // v(n-1) any point from the edge. // testpoint: the point you want to find out which side it's on. side = sign (rotated.x * (testpoint.x - v(n-1).x) + rotated.y * (testpoint.y - v(n-1).y); ``` Now test all points of rectangle A against the edges of rectangle B and vice versa. If you find a separating edge the objects don't intersect (providing all other points in B are on the other side of the edge being tested for - see drawing below). If you find no separating edge either the rectangles are intersecting or one rectangle is contained in the other. The test works with any convex polygons btw.. **Amendment:** To identify a separating edge, it is not enough to test all points of one rectangle against each edge of the other. The candidate-edge E (below) would as such be identified as a separating edge, as all points in A are in the same half-plane of E. However, it isn't a separating edge because the vertices Vb1 and Vb2 of B are also in that half-plane. It would only have been a separating edge if that had not been the case <http://www.iassess.com/collision.png>
115,428
<p>I am looking to convert a <code>MySQL timestamp</code> to a epoch time in seconds using <code>PHP</code>, and vice versa. </p> <p>What's the cleanest way to do this?</p>
[ { "answer_id": 115506, "author": "Harrison Fisk", "author_id": 16111, "author_profile": "https://Stackoverflow.com/users/16111", "pm_score": 3, "selected": false, "text": "<p>There are two functions in MySQL which are useful for converting back and forth from the unix epoch time that PHP...
2008/09/22
[ "https://Stackoverflow.com/questions/115428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am looking to convert a `MySQL timestamp` to a epoch time in seconds using `PHP`, and vice versa. What's the cleanest way to do this?
There are two functions in MySQL which are useful for converting back and forth from the unix epoch time that PHP likes: [from\_unixtime()](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_from-unixtime) [unix\_timestamp()](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_unix-timestamp) For example, to get it back in PHP unix time, you could do: ``` SELECT unix_timestamp(timestamp_col) FROM tbl WHERE ... ```
115,431
<p>Suppose I have some XAML like this:</p> <pre><code>&lt;Window.Resources&gt; &lt;v:MyClass x:Key="whatever" Text="foo\nbar" /&gt; &lt;/Window.Resources&gt; </code></pre> <p>Obviously I want a newline character in the MyClass.Text property, but the XAML parser constructs the object with the literal string "foo\nbar".</p> <p>Is there (a) a way to convince the parser to translate escape sequences, or (b) a .NET method to interpret a string in the way that the C# compiler would?</p> <p>I realize that I can go in there looking for <code>\n</code> sequences, but it would be nicer to have a generic way to do this.</p>
[ { "answer_id": 115543, "author": "deepcode.co.uk", "author_id": 20524, "author_profile": "https://Stackoverflow.com/users/20524", "pm_score": 1, "selected": false, "text": "<p>Off the top of my head, try;</p>\n\n<ol>\n<li>A custom binding expression perhaps?</li>\n</ol>\n\n<blockquote>\n...
2008/09/22
[ "https://Stackoverflow.com/questions/115431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9591/" ]
Suppose I have some XAML like this: ``` <Window.Resources> <v:MyClass x:Key="whatever" Text="foo\nbar" /> </Window.Resources> ``` Obviously I want a newline character in the MyClass.Text property, but the XAML parser constructs the object with the literal string "foo\nbar". Is there (a) a way to convince the parser to translate escape sequences, or (b) a .NET method to interpret a string in the way that the C# compiler would? I realize that I can go in there looking for `\n` sequences, but it would be nicer to have a generic way to do this.
You can use XML character escaping ``` <TextBlock Text="Hello&#13;World!"/> ```
115,462
<p>I'm having a little bit of a problem scaling my images to a properly predefined size. I was wondering - since it is purely mathematics, if there's some sort of common logical algorithm that works in every language (PHP, ActionScript, Javascript etc.) to scale images proportionally.</p> <p>I'm using this at the moment: </p> <pre><code>var maxHeight = 300; var maxWidth = 300; var ratio:Number = height / width; if (height &gt; maxHeight) { height = maxHeight; width = Math.round(height / ratio); } else if(width &gt; maxWidth) { width = maxWidth; height = Math.round(width * ratio); } </code></pre> <p>But it doesn't work properly. The images scales proportionately, sure enough, but the size isn't set at 300 (either in width or in height). It kind of makes sense, but I was wondering if there's a fool-proof, easy way to scale images proportionally.</p>
[ { "answer_id": 115487, "author": "Alex Weinstein", "author_id": 16668, "author_profile": "https://Stackoverflow.com/users/16668", "pm_score": 2, "selected": false, "text": "<p>I'd recommend not writing this code yourself; there are myriads of pixel-level details that take a serious while...
2008/09/22
[ "https://Stackoverflow.com/questions/115462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17362/" ]
I'm having a little bit of a problem scaling my images to a properly predefined size. I was wondering - since it is purely mathematics, if there's some sort of common logical algorithm that works in every language (PHP, ActionScript, Javascript etc.) to scale images proportionally. I'm using this at the moment: ``` var maxHeight = 300; var maxWidth = 300; var ratio:Number = height / width; if (height > maxHeight) { height = maxHeight; width = Math.round(height / ratio); } else if(width > maxWidth) { width = maxWidth; height = Math.round(width * ratio); } ``` But it doesn't work properly. The images scales proportionately, sure enough, but the size isn't set at 300 (either in width or in height). It kind of makes sense, but I was wondering if there's a fool-proof, easy way to scale images proportionally.
``` ratio = MIN( maxWidth / width, maxHeight/ height ); width = ratio * width; height = ratio * height; ``` Make sure all divides are floating-point.
115,478
<p>The following code is in the <code>/Courses/Detail</code> action:</p> <pre><code> [AcceptVerbs("GET")] public ActionResult Detail(int id) { ViewData["Title"] = "A View Title"; return View(tmdc.GetCourseById(id)); } </code></pre> <p>The <code>tmdc.GetCourseById(id)</code> method returns an instance of type <code>Course</code> for the View. In the View I am using </p> <pre><code>&lt;%= HTML.TextBox("Title")%&gt; </code></pre> <p>to display the value of the <code>Title</code> property for the <code>Course</code> object. Instead the text box is displaying the string <code>A View Title</code>. Is this normal/expected behavior? What would be the best way to handle this?</p> <p><b>Update</b><br /> As a workaround, I've changed <code>ViewData["Title"]</code> to <code>ViewData["VIEW_TITLE"]</code> but would like a cleaner way to handle this collision or to know if this is an expected result.</p>
[ { "answer_id": 115704, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 1, "selected": false, "text": "<p>You have to wait for the IDE to parse the JavaScript code. Just wait a while and you should see the JavaScript code cha...
2008/09/22
[ "https://Stackoverflow.com/questions/115478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19251/" ]
The following code is in the `/Courses/Detail` action: ``` [AcceptVerbs("GET")] public ActionResult Detail(int id) { ViewData["Title"] = "A View Title"; return View(tmdc.GetCourseById(id)); } ``` The `tmdc.GetCourseById(id)` method returns an instance of type `Course` for the View. In the View I am using ``` <%= HTML.TextBox("Title")%> ``` to display the value of the `Title` property for the `Course` object. Instead the text box is displaying the string `A View Title`. Is this normal/expected behavior? What would be the best way to handle this? **Update** As a workaround, I've changed `ViewData["Title"]` to `ViewData["VIEW_TITLE"]` but would like a cleaner way to handle this collision or to know if this is an expected result.
I was experiencing the same behavior in Visual Studio 2008, and after spending several minutes trying to get the symbols to load I ended up using a workaround - adding a line with the "debugger;" command in my JavaScript file. After adding `debugger;` when you then reload the script in Internet Explorer it'll let you bring up a new instance of the script debugger, and it'll stop on your debugger command let you debug from there. In this scenario I was already debugging the JavaScript in [Firebug](http://en.wikipedia.org/wiki/Firebug_%28software%29), but I wanted to debug against Internet Explorer as well.
115,488
<p>I am having difficulty reliably creating / removing event sources during the installation of my .Net Windows Service.</p> <p>Here is the code from my ProjectInstaller class:</p> <pre><code>// Create Process Installer ServiceProcessInstaller spi = new ServiceProcessInstaller(); spi.Account = ServiceAccount.LocalSystem; // Create Service ServiceInstaller si = new ServiceInstaller(); si.ServiceName = Facade.GetServiceName(); si.Description = "Processes ..."; si.DisplayName = "Auto Checkout"; si.StartType = ServiceStartMode.Automatic; // Remove Event Source if already there if (EventLog.SourceExists("AutoCheckout")) EventLog.DeleteEventSource("AutoCheckout"); // Create Event Source and Event Log EventLogInstaller log = new EventLogInstaller(); log.Source = "AutoCheckout"; log.Log = "AutoCheckoutLog"; Installers.AddRange(new Installer[] { spi, si, log }); </code></pre> <p>The facade methods referenced just return the strings for the name of the log, service, etc.</p> <p>This code works most of the time, but recently after installing I started getting my log entries showing up in the Application Log instead of the custom log. And the following errors are in the log as well:</p> <blockquote> <p>The description for Event ID ( 0 ) in Source ( AutoCheckout ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. </p> </blockquote> <p>For some reason it either isn't properly removing the source during the uninstall or it isn't creating it during the install.</p> <p>Any help with best practices here is appreciated.</p> <p>Thanks!</p> <p>In addition, here is a sample of how I am writing exceptions to the log:</p> <pre><code>// Write to Log EventLog.WriteEntry(Facade.GetEventLogSource(), errorDetails, EventLogEntryType.Error, 99); </code></pre> <p><strong>Regarding stephbu's answer:</strong> The recommended path is an installer script and installutil, or a Windows Setup routine.</p> <p>I am using a Setup Project, which performs the installation of the service and sets up the log. Whether I use the installutil.exe or the windows setup project I believe they both call the same ProjectInstaller class I show above.</p> <p>I see how the state of my test machine could be causing the error if the log isn't truly removed until rebooting. I will experiment more to see if that solves the issue.</p> <p><strong>Edit:</strong> I'm interested in a sure fire way to register the source and the log name during the installation of the service. So if the service had previously been installed, it would remove the source, or reuse the source during subsequent installations.</p> <p>I haven't yet had an opportunity to learn WiX to try that route.</p>
[ { "answer_id": 116222, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 3, "selected": false, "text": "<p>Couple of things here</p>\n\n<p>Creating Event Logs and Sources on the fly is pretty frowned upon. primarily because o...
2008/09/22
[ "https://Stackoverflow.com/questions/115488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13368/" ]
I am having difficulty reliably creating / removing event sources during the installation of my .Net Windows Service. Here is the code from my ProjectInstaller class: ``` // Create Process Installer ServiceProcessInstaller spi = new ServiceProcessInstaller(); spi.Account = ServiceAccount.LocalSystem; // Create Service ServiceInstaller si = new ServiceInstaller(); si.ServiceName = Facade.GetServiceName(); si.Description = "Processes ..."; si.DisplayName = "Auto Checkout"; si.StartType = ServiceStartMode.Automatic; // Remove Event Source if already there if (EventLog.SourceExists("AutoCheckout")) EventLog.DeleteEventSource("AutoCheckout"); // Create Event Source and Event Log EventLogInstaller log = new EventLogInstaller(); log.Source = "AutoCheckout"; log.Log = "AutoCheckoutLog"; Installers.AddRange(new Installer[] { spi, si, log }); ``` The facade methods referenced just return the strings for the name of the log, service, etc. This code works most of the time, but recently after installing I started getting my log entries showing up in the Application Log instead of the custom log. And the following errors are in the log as well: > > The description for Event ID ( 0 ) in Source ( AutoCheckout ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. > > > For some reason it either isn't properly removing the source during the uninstall or it isn't creating it during the install. Any help with best practices here is appreciated. Thanks! In addition, here is a sample of how I am writing exceptions to the log: ``` // Write to Log EventLog.WriteEntry(Facade.GetEventLogSource(), errorDetails, EventLogEntryType.Error, 99); ``` **Regarding stephbu's answer:** The recommended path is an installer script and installutil, or a Windows Setup routine. I am using a Setup Project, which performs the installation of the service and sets up the log. Whether I use the installutil.exe or the windows setup project I believe they both call the same ProjectInstaller class I show above. I see how the state of my test machine could be causing the error if the log isn't truly removed until rebooting. I will experiment more to see if that solves the issue. **Edit:** I'm interested in a sure fire way to register the source and the log name during the installation of the service. So if the service had previously been installed, it would remove the source, or reuse the source during subsequent installations. I haven't yet had an opportunity to learn WiX to try that route.
The best recommendation would be to not use the Setup Project in Visual Studio. It has very severe limitations. I had very good results with [WiX](http://wix.sourceforge.net/)
115,503
<p>I recently asked a question about Oracle Encryption. Along the way to finding a solution for myself I decided to move the encryption (well, obfuscation) to the application side for certain tasks. </p> <p>My problem is that the database is already encrypting data a certain way and I need Java code to duplicate that functionality, so that text encrypted by one system can be decrypted by the other and vice versa.</p> <p>I want the encryption to be compatible with what the DB was already doing but couldn't find the documentation that describes exactly what Oracle is doing. How do I replicate this in Java?</p> <pre><code>dbms_obfuscation_toolkit.DESEncrypt( input_string =&gt; v_string, key_string =&gt; key_string, encrypted_string =&gt; encrypted_string ); RETURN UTL_RAW.CAST_TO_RAW(encrypted_string); </code></pre> <p>No matter what I try, it seems as if the Java DES encryption is different than Oracle's.</p>
[ { "answer_id": 115540, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 3, "selected": true, "text": "<p>I found this works:</p>\n\n<pre><code>KeySpec ks = new DESKeySpec(new byte[] {'s','e','c','r','e','t','!','!'...
2008/09/22
[ "https://Stackoverflow.com/questions/115503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867/" ]
I recently asked a question about Oracle Encryption. Along the way to finding a solution for myself I decided to move the encryption (well, obfuscation) to the application side for certain tasks. My problem is that the database is already encrypting data a certain way and I need Java code to duplicate that functionality, so that text encrypted by one system can be decrypted by the other and vice versa. I want the encryption to be compatible with what the DB was already doing but couldn't find the documentation that describes exactly what Oracle is doing. How do I replicate this in Java? ``` dbms_obfuscation_toolkit.DESEncrypt( input_string => v_string, key_string => key_string, encrypted_string => encrypted_string ); RETURN UTL_RAW.CAST_TO_RAW(encrypted_string); ``` No matter what I try, it seems as if the Java DES encryption is different than Oracle's.
I found this works: ``` KeySpec ks = new DESKeySpec(new byte[] {'s','e','c','r','e','t','!','!'}); SecretKeyFactory skf = SecretKeyFactory.getInstance("DES"); SecretKey sk = skf.generateSecret(ks); Cipher c = Cipher.getInstance("DES/CBC/NoPadding"); IvParameterSpec ips = new IvParameterSpec(new byte[] {0,0,0,0,0,0,0,0}); c.init(Cipher.ENCRYPT, sk, ips); // or c.init(Cipher.DECRYPT, sk, ips); ``` The missing piece was the Initialization Vector (ips) which must be 8 zeros. When you use null in Java you get something different.
115,526
<p>I'm running an c# .net app in an iframe of an asp page on an older site. Accessing the Asp page's session information is somewhat difficult, so I'd like to make my .net app simply verify that it's being called from an approved page, or else immediately halt.</p> <p>Is there a way for a page to find out the url of it's parent document?</p>
[ { "answer_id": 115533, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 5, "selected": true, "text": "<pre><code>top.location.href\n</code></pre>\n\n<p>But that will only work if both pages (the iframe and the main page) are bein...
2008/09/22
[ "https://Stackoverflow.com/questions/115526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12382/" ]
I'm running an c# .net app in an iframe of an asp page on an older site. Accessing the Asp page's session information is somewhat difficult, so I'd like to make my .net app simply verify that it's being called from an approved page, or else immediately halt. Is there a way for a page to find out the url of it's parent document?
``` top.location.href ``` But that will only work if both pages (the iframe and the main page) are being served from the same domain.
115,548
<p>This code in JS gives me a popup saying "i think null is a number", which I find slightly disturbing. What am I missing?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>if (isNaN(null)) { alert("null is not a number"); } else { alert("i think null is a number"); }</code></pre> </div> </div> </p> <p>I'm using Firefox 3. Is that a browser bug?</p> <p>Other tests:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(null == NaN); // false console.log(isNaN("text")); // true console.log(NaN == "text"); // false</code></pre> </div> </div> </p> <p>So, the problem seems not to be an exact comparison with NaN?</p> <p><i><b>Edit:</b> Now the question has been answered, I have cleaned up my post to have a better version for the archive. However, this renders some comments and even some answers a little incomprehensible. Don't blame their authors. Among the things I changed was:</p> <ul> <li>Removed a note saying that I had screwed up the headline in the first place by reverting its meaning</li> <li>Earlier answers showed that I didn't state clearly enough why I thought the behaviour was weird, so I added the examples that check a string and do a manual comparison. </i></li> </ul>
[ { "answer_id": 115559, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 2, "selected": false, "text": "<p>Null is not NaN, as well as a string is not NaN. isNaN() just test if you really have the NaN object.</p>\n" }, { "...
2008/09/22
[ "https://Stackoverflow.com/questions/115548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
This code in JS gives me a popup saying "i think null is a number", which I find slightly disturbing. What am I missing? ```js if (isNaN(null)) { alert("null is not a number"); } else { alert("i think null is a number"); } ``` I'm using Firefox 3. Is that a browser bug? Other tests: ```js console.log(null == NaN); // false console.log(isNaN("text")); // true console.log(NaN == "text"); // false ``` So, the problem seems not to be an exact comparison with NaN? ***Edit:** Now the question has been answered, I have cleaned up my post to have a better version for the archive. However, this renders some comments and even some answers a little incomprehensible. Don't blame their authors. Among the things I changed was:* * Removed a note saying that I had screwed up the headline in the first place by reverting its meaning * Earlier answers showed that I didn't state clearly enough why I thought the behaviour was weird, so I added the examples that check a string and do a manual comparison.
I believe the code is trying to ask, "is `x` numeric?" with the specific case here of `x = null`. The function `isNaN()` can be used to answer this question, but semantically it's referring specifically to the value `NaN`. From Wikipedia for [`NaN`](http://en.wikipedia.org/wiki/NaN): > > NaN (**N**ot **a** **N**umber) is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations. > > > In most cases we think the answer to "is null numeric?" should be no. However, `isNaN(null) == false` is semantically correct, because `null` is not `NaN`. Here's the algorithmic explanation: The function `isNaN(x)` attempts to convert the passed parameter to a number[1](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN) (equivalent to `Number(x)`) and then tests if the value is `NaN`. If the parameter can't be converted to a number, `Number(x)` will return `NaN`[2](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number). Therefore, if the conversion of parameter `x` to a number results in `NaN`, it returns true; otherwise, it returns false. So in the specific case `x = null`, `null` is converted to the number 0, (try evaluating `Number(null)` and see that it returns 0,) and `isNaN(0)` returns false. A string that is only digits can be converted to a number and isNaN also returns false. A string (e.g. `'abcd'`) that cannot be converted to a number will cause `isNaN('abcd')` to return true, specifically because `Number('abcd')` returns `NaN`. In addition to these apparent edge cases are the standard numerical reasons for returning NaN like 0/0. As for the seemingly inconsistent tests for equality shown in the question, the behavior of `NaN` is specified such that any comparison `x == NaN` is false, regardless of the other operand, including `NaN` itself[1](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN).
115,557
<p>We are struggling to configure our web app to be able to connect with web services via Spring WS. We have tried to use the example from the documentation of client-side Spring-WS, but we end up with a WebServiceTransportException. The XML config looks like this:</p> <pre><code>&lt;bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate"&gt; &lt;constructor-arg ref="messageFactory"/&gt; &lt;property name="messageSender"&gt; &lt;bean class="org.springframework.ws.transport.http.CommonsHttpMessageSender"&gt; &lt;property name="credentials"&gt; &lt;bean class="org.apache.commons.httpclient.UsernamePasswordCredentials"&gt; &lt;constructor-arg value="john"/&gt; &lt;constructor-arg value="secret"/&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>We have been able to configure the application programmatically, but this configuration was not possible to "transfer" to a Spring XML config because some setters did not use the format Spring expects. (HttpState.setCredentials(...) takes two parameters). The config was lifted from some other Spring-WS client code in the company.</p> <p>This is the configuration that works:</p> <pre><code> public List&lt;String&gt; getAll() { List&lt;String&gt; carTypes = new ArrayList&lt;String&gt;(); try { Source source = new ResourceSource(request); JDOMResult result = new JDOMResult(); SaajSoapMessageFactory soapMessageFactory = new SaajSoapMessageFactory(MessageFactory.newInstance()); WebServiceTemplate template = new WebServiceTemplate(soapMessageFactory); HttpClientParams clientParams = new HttpClientParams(); clientParams.setSoTimeout(60000); clientParams.setConnectionManagerTimeout(60000); clientParams.setAuthenticationPreemptive(true); HttpClient client = new HttpClient(clientParams); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password")); CommonsHttpMessageSender messageSender = new CommonsHttpMessageSender(client); template.setMessageSender(messageSender); template.sendSourceAndReceiveToResult(SERVICE_URI, source, result); // Handle the XML } catch (IOException e) { throw new RuntimeException(e); } catch (SOAPException e) { throw new RuntimeException(e); } return carTypes; } </code></pre> <p>Does anyone know how to solve my problem? Every tutorial I have see out there lists the first configuration. It seems that when I set the credentials on the messageSender object, they are just ignored...</p>
[ { "answer_id": 150178, "author": "Symbioxys", "author_id": 1841427, "author_profile": "https://Stackoverflow.com/users/1841427", "pm_score": 1, "selected": false, "text": "<p>How do you distinguish these:</p>\n\n<pre><code>&lt;constructor-arg value=\"john\"/&gt;\n&lt;constructor-arg valu...
2008/09/22
[ "https://Stackoverflow.com/questions/115557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20529/" ]
We are struggling to configure our web app to be able to connect with web services via Spring WS. We have tried to use the example from the documentation of client-side Spring-WS, but we end up with a WebServiceTransportException. The XML config looks like this: ``` <bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate"> <constructor-arg ref="messageFactory"/> <property name="messageSender"> <bean class="org.springframework.ws.transport.http.CommonsHttpMessageSender"> <property name="credentials"> <bean class="org.apache.commons.httpclient.UsernamePasswordCredentials"> <constructor-arg value="john"/> <constructor-arg value="secret"/> </bean> </property> </bean> </property> </bean> ``` We have been able to configure the application programmatically, but this configuration was not possible to "transfer" to a Spring XML config because some setters did not use the format Spring expects. (HttpState.setCredentials(...) takes two parameters). The config was lifted from some other Spring-WS client code in the company. This is the configuration that works: ``` public List<String> getAll() { List<String> carTypes = new ArrayList<String>(); try { Source source = new ResourceSource(request); JDOMResult result = new JDOMResult(); SaajSoapMessageFactory soapMessageFactory = new SaajSoapMessageFactory(MessageFactory.newInstance()); WebServiceTemplate template = new WebServiceTemplate(soapMessageFactory); HttpClientParams clientParams = new HttpClientParams(); clientParams.setSoTimeout(60000); clientParams.setConnectionManagerTimeout(60000); clientParams.setAuthenticationPreemptive(true); HttpClient client = new HttpClient(clientParams); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password")); CommonsHttpMessageSender messageSender = new CommonsHttpMessageSender(client); template.setMessageSender(messageSender); template.sendSourceAndReceiveToResult(SERVICE_URI, source, result); // Handle the XML } catch (IOException e) { throw new RuntimeException(e); } catch (SOAPException e) { throw new RuntimeException(e); } return carTypes; } ``` Does anyone know how to solve my problem? Every tutorial I have see out there lists the first configuration. It seems that when I set the credentials on the messageSender object, they are just ignored...
Override HttpClient with a constructor that takes the parameters and wire through Spring using constructor-args ``` public MyHttpClient(HttpClientParams params, UsernamePasswordCredentials usernamePasswordCredentials) { super(params); getState().setCredentials(AuthScope.ANY, usernamePasswordCredentials); } ```
115,573
<p>I'm sure we all have received the wonderfully vague "Object reference not set to instance of an Object" exception at some time or another. Identifying the object that is the problem is often a tedious task of setting breakpoints and inspecting all members in each statement. </p> <p>Does anyone have any tricks to easily and efficiently identify the object that causes the exception, either via programmatical means or otherwise?</p> <p>--edit</p> <p>It seems I was vague like the exception =). The point is to _not have to debug the app to find the errant object. The compiler/runtime does know that the object has been allocated/declared, and that the object has not yet been instantiated. Is there a way to extract / identify those details in a caught exception</p> <p>@ W. Craig Trader</p> <p>Your explanation that it is a result of a design problem is probably the best answer I could get. I am fairly compulsive with defensive coding and have managed to get rid of most of these errors after fixing my habits over time. The remaining ones just <strong><em>tweak</em></strong> me to no end, and lead me to posting this question to the community. </p> <p>Thanks for everyone's suggestions.</p>
[ { "answer_id": 115599, "author": "Oliver Mellet", "author_id": 12001, "author_profile": "https://Stackoverflow.com/users/12001", "pm_score": 1, "selected": false, "text": "<p>There's really not much you can do besides look at the stack trace; if you're dereferencing multiple object refer...
2008/09/22
[ "https://Stackoverflow.com/questions/115573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16391/" ]
I'm sure we all have received the wonderfully vague "Object reference not set to instance of an Object" exception at some time or another. Identifying the object that is the problem is often a tedious task of setting breakpoints and inspecting all members in each statement. Does anyone have any tricks to easily and efficiently identify the object that causes the exception, either via programmatical means or otherwise? --edit It seems I was vague like the exception =). The point is to \_not have to debug the app to find the errant object. The compiler/runtime does know that the object has been allocated/declared, and that the object has not yet been instantiated. Is there a way to extract / identify those details in a caught exception @ W. Craig Trader Your explanation that it is a result of a design problem is probably the best answer I could get. I am fairly compulsive with defensive coding and have managed to get rid of most of these errors after fixing my habits over time. The remaining ones just ***tweak*** me to no end, and lead me to posting this question to the community. Thanks for everyone's suggestions.
At the point where the NRE is thrown, there is no target object -- that's the point of the exception. The most you can hope for is to trap the file and line number where the exception occurred. If you're having problems identifying which object reference is causing the problem, then you might want to rethink your coding standards, because it sounds like you're doing too much on one line of code. A better solution to this sort of problem is [Design by Contract](http://en.wikipedia.org/wiki/Design_By_Contract), either through builtin language constructs, or via a library. DbC would suggest pre-checking any incoming arguments for a method for out-of-range data (ie: Null) and throwing exceptions because the method won't work with bad data. **[Edit to match question edit:]** I think the NRE description is misleading you. The problem that the CLR is having is that it was asked to dereference an object reference, when the object reference is Null. Take this example program: ``` public class NullPointerExample { public static void Main() { Object foo; System.Console.WriteLine( foo.ToString() ); } } ``` When you run this, it's going to throw an NRE on line 5, when it tried to evaluate the ToString() method on foo. There are no objects to debug, only an uninitialized object reference (foo). There's a class and a method, but no object. --- Re: Chris Marasti-Georg's [answer](https://stackoverflow.com/questions/115573/detecting-what-the-target-object-is-when-nullreferenceexception-is-thrown#115619): You should never throw NRE yourself -- that's a system exception with a specific meaning: the CLR (or JVM) has attempted to evaluate an object reference that wasn't initialized. If you pre-check an object reference, then either throw some sort of invalid argument exception or an application-specific exception, but not NRE, because you'll only confuse the next programmer who has to maintain your app.
115,643
<p>PowerShell is definitely in the category of dynamic languages, but would it be considered strongly typed? </p>
[ { "answer_id": 115676, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 3, "selected": false, "text": "<p>It can be if you need it to be.</p>\n\n<p>Like so:</p>\n\n<pre><code>[1] » [int]$x = 5\n[2] » $x\n5\n[3] » $x = 'h...
2008/09/22
[ "https://Stackoverflow.com/questions/115643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3289/" ]
PowerShell is definitely in the category of dynamic languages, but would it be considered strongly typed?
There is a certain amount of confusion around the terminlogy. [This article](http://eli.thegreenplace.net/2006/11/25/a-taxonomy-of-typing-systems/) explains a useful taxonomy of type systems. PowerShell is dynamically, implicit typed: ``` > $x=100 > $x=dir ``` No type errors - a variable can change its type at runtime. This is like [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), [Perl](http://en.wikipedia.org/wiki/Perl), [JavaScript](http://en.wikipedia.org/wiki/JavaScript) but different from [C++](http://en.wikipedia.org/wiki/C%2B%2B), [Java](http://en.wikipedia.org/wiki/Java_%28programming_language%29), [C#](http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29), etc. However: ``` > [int]$x = 100 > $x = dir Cannot convert "scripts-2.5" to "System.Int32". ``` So it also supports *explicit* typing of variables if you want. However, the type checking is done at runtime rather than compile time, so it's not *statically* typed. I have seen some say that PowerShell uses *type inference* (because you don't have to declare the type of a variable), but I think that is the wrong words. Type inference is a feature of systems that does type-checking at compile time (like "`var`" in C#). PowerShell only checks types at runtime, so it can check the actual value rather than do inference. However, there is some amount of automatic type-conversion going on: ``` > [int]$a = 1 > [string]$b = $a > $b 1 > $b.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object ``` So *some* types are converted on the fly. This will by most definitions make PowerShell a *weakly typed* language. It is certainly more weak than e.g. Python which (almost?) never convert types on the fly. But probably not at weak as Perl which will convert almost anything as needed.
115,649
<p>We have various servers that have many directories shared. It's easy enough to look at the share browser to see what the "top level" shares are, but underneath is a jumbled mess of custom permissions, none of which is documented.</p> <p>I'd like to enumerate all the shares on the domain (definitely all the 'servers', local PCs would be nice) and then recurse down each one and report any deviation from the parent. If the child has the same permissions, no need to report that back.</p> <p>I'd prefer a simple script-y solution to writing a big C# app, but any method that works will do (even existing software).</p> <p>For example, I'd like to get:</p> <pre><code>SERVER1\ \-- C: (EVERYONE: Total control, ADMINs, etc. etc.) \-- (skip anything that is not the same as above) \-- SuperSecretStuff (Everyone: NO access; Bob: Read access) SERVER2\ \-- Stuff (some people) </code></pre> <p>etc.</p>
[ { "answer_id": 115689, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 2, "selected": true, "text": "<p>According to the JEdit <a href=\"http://jedit.org/index.php?page=features\" rel=\"nofollow noreferrer\">features page<...
2008/09/22
[ "https://Stackoverflow.com/questions/115649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2590/" ]
We have various servers that have many directories shared. It's easy enough to look at the share browser to see what the "top level" shares are, but underneath is a jumbled mess of custom permissions, none of which is documented. I'd like to enumerate all the shares on the domain (definitely all the 'servers', local PCs would be nice) and then recurse down each one and report any deviation from the parent. If the child has the same permissions, no need to report that back. I'd prefer a simple script-y solution to writing a big C# app, but any method that works will do (even existing software). For example, I'd like to get: ``` SERVER1\ \-- C: (EVERYONE: Total control, ADMINs, etc. etc.) \-- (skip anything that is not the same as above) \-- SuperSecretStuff (Everyone: NO access; Bob: Read access) SERVER2\ \-- Stuff (some people) ``` etc.
According to the JEdit [features page](http://jedit.org/index.php?page=features) it already supports Objective C.
115,658
<p>In my C# application I am using the Microsoft Jet OLEDB data provider to read a CSV file. The connection string looks like this:</p> <pre><code>Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\Data;Extended Properties="text;HDR=Yes;FMT=Delimited </code></pre> <p>I open an ADO.NET OleDbConnection using that connection string and select all the rows from the CSV file with the command:</p> <pre><code>select * from Data.csv </code></pre> <p>When I open an OleDbDataReader and examine the data types of the columns it returns, I find that something in the stack has tried to guess at the data types based on the first row of data in the file. For example, suppose the CSV file contains:</p> <pre><code>House,Street,Town 123,Fake Street,Springfield 12a,Evergreen Terrace,Springfield </code></pre> <p>Calling the OleDbDataReader.GetDataTypeName method for the House column will reveal that the column has been given the data type "DBTYPE_I4", so all values read from it are interpreted as integers. My problem is that House should be a string - when I try to read the House value from the second row, the OleDbDataReader returns null.</p> <p>How can I tell either the Jet database provider or the OleDbDataReader to interpret a column as strings instead of numbers?</p>
[ { "answer_id": 115684, "author": "MarcE", "author_id": 7262, "author_profile": "https://Stackoverflow.com/users/7262", "pm_score": 4, "selected": true, "text": "<p>There's a schema file you can create that would tell ADO.NET how to interpret the CSV - in effect giving it a structure.</p>...
2008/09/22
[ "https://Stackoverflow.com/questions/115658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016/" ]
In my C# application I am using the Microsoft Jet OLEDB data provider to read a CSV file. The connection string looks like this: ``` Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\Data;Extended Properties="text;HDR=Yes;FMT=Delimited ``` I open an ADO.NET OleDbConnection using that connection string and select all the rows from the CSV file with the command: ``` select * from Data.csv ``` When I open an OleDbDataReader and examine the data types of the columns it returns, I find that something in the stack has tried to guess at the data types based on the first row of data in the file. For example, suppose the CSV file contains: ``` House,Street,Town 123,Fake Street,Springfield 12a,Evergreen Terrace,Springfield ``` Calling the OleDbDataReader.GetDataTypeName method for the House column will reveal that the column has been given the data type "DBTYPE\_I4", so all values read from it are interpreted as integers. My problem is that House should be a string - when I try to read the House value from the second row, the OleDbDataReader returns null. How can I tell either the Jet database provider or the OleDbDataReader to interpret a column as strings instead of numbers?
There's a schema file you can create that would tell ADO.NET how to interpret the CSV - in effect giving it a structure. Try this: [http://www.aspdotnetcodes.com/Importing\_CSV\_Database\_Schema.ini.aspx](https://web.archive.org/web/20081009034412/http://www.aspdotnetcodes.com/Importing_CSV_Database_Schema.ini.aspx) Or the most recent [MS Documentation](https://learn.microsoft.com/en-us/sql/odbc/microsoft/schema-ini-file-text-file-driver?view=sql-server-2017)
115,665
<p>I'm using the <code>cacheCounter</code> in <code>CakePHP</code>, which increments a counter for related fields.</p> <p>Example, I have a Person table a Source table. Person.source_id maps to a row in the Source table. Each person has one Source, and each Source has none or many Person rows.</p> <p><code>cacheCounter</code> is working great when I change the value of a source on a person. It increments <code>Source.Person_Count</code>. Cool.</p> <p>But when it increments, it adds it to the destination source for a person, but doesn't remove it from the old value. I tried <code>updateCacheControl()</code> in <code>afterSave</code>, but that didn't do anything.</p> <p>So then I wrote some code in my model for <code>afterSave</code> that would subtract the source source_id, but it always did this even when I wasn't even changing the <code>source_id</code>. (So the count went negative).</p> <p>My question: Is there a way to tell if a field was changed in the model in <code>CakePHP</code>?</p>
[ { "answer_id": 120009, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": -1, "selected": false, "text": "<p>See if the \"save\" uses some sort of DBAL call that returns \"affected rows\", usually this is how you can judge if the la...
2008/09/22
[ "https://Stackoverflow.com/questions/115665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43/" ]
I'm using the `cacheCounter` in `CakePHP`, which increments a counter for related fields. Example, I have a Person table a Source table. Person.source\_id maps to a row in the Source table. Each person has one Source, and each Source has none or many Person rows. `cacheCounter` is working great when I change the value of a source on a person. It increments `Source.Person_Count`. Cool. But when it increments, it adds it to the destination source for a person, but doesn't remove it from the old value. I tried `updateCacheControl()` in `afterSave`, but that didn't do anything. So then I wrote some code in my model for `afterSave` that would subtract the source source\_id, but it always did this even when I wasn't even changing the `source_id`. (So the count went negative). My question: Is there a way to tell if a field was changed in the model in `CakePHP`?
To monitor changes in a field, you can use this logic in your model with no changes elsewhere required: ``` function beforeSave() { $this->recursive = -1; $this->old = $this->find(array($this->primaryKey => $this->id)); if ($this->old){ $changed_fields = array(); foreach ($this->data[$this->alias] as $key =>$value) { if ($this->old[$this->alias][$key] != $value) { $changed_fields[] = $key; } } } // $changed_fields is an array of fields that changed return true; } ```
115,685
<p>I once wrote this line in a Java class. This compiled fine in Eclipse but not on the command line. </p> <p>This is on</p> <ul> <li>Eclipse 3.3</li> <li>JDK 1.5</li> <li>Windows XP Professional</li> </ul> <p>Any clues?</p> <p>Error given on the command line is:</p> <pre><code>Icons.java:16: code too large public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50, ^ </code></pre> <p>The code line in question is:</p> <pre><code>public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50, 0, 50, 0, -9, 0, 0, -1, -1, -1, -24, -72, -72, -24, -64, -64, -8, -16, -24, -8, -24, -24, -16, -24, -32, -1, -8, -8, 48, 72, -72, -24, -80, -80, 72, 96, -40, -24, -24, -8, 56, 88, -56, -24, -40, -48, -24, -48, -64, 56, 80, -64, 64, 88, -48, -56, -64, -64, -16, -24, -24, -32, -40, -40, -32, -88, -96, -72, -72, -72, -48, -56, -56, -24, -32, -32, -8, -8, -1, -24, -40, -56, -64, -72, -72, -16, -32, -40, 48, 80, -72, -40, -96, -104, -40, -96, -96, -56, -104, -104, 120, 88, -104, -40, -64, -80, -32, -88, -88, -32, -56, -72, -72, -80, -80, -32, -80, -88, 104, -96, -1, -40, -40, -40, -64, -104, -104, -32, -56, -64, -112, 104, 112, -48, -104, -112, -128, -112, -24, -72, -80, -88, -8, -8, -8, -64, -112, -120, 72, 104, -40, 120, 96, -96, -112, -96, -24, -112, -120, -72, -40, -88, -88, -48, -64, -72, -32, -72, -80, -48, -72, -88, -88, -72, -24, 64, 88, -56, -120, 96, 104, 88, -128, -72, 48, 56, 56, 104, 104, 120, 112, -120, -16, -128, 104, -88, -40, -48, -48, 88, -120, -24, 104, 88, -104, -40, -56, -72, -128, 112, -88, -128, 96, -88, -104, -88, -24, -96, -120, 120, -88, -128, -80, -56, -56, -64, 96, 120, -8, -96, -128, -88, -80, -96, -104, -32, -72, -72, 96, 104, 112, 96, -104, -8, -72, -112, -112, -64, -72, -80, 64, 64, 72, -128, -120, -96, -128, 88, 88, -56, -72, -80, 88, 96, 120, -72, -128, 112, 72, 112, -40, 96, 120, -56, 88, -112, -16, 64, 104, -48, -64, -80, -88, -88, -120, -80, 88, 88, 96, -56, -96, -120, -40, -56, -64, 96, 104, 120, -120, -80, -24, -104, -88, -40, -48, -72, -80, -64, -56, -16, -88, -112, -128, -32, -48, -56, -24, -16, -8, -64, -120, 120, -96, -96, -88, 80, -128, -24, -56, -72, -88, -96, 120, 88, -72, -112, 120, -64, -104, 120, -48, -56, -64, -120, -104, -32, -104, 120, -80, -96, -112, -120, 56, 88, -64, -128, 96, 64, 88, 120, -40, -80, -104, -120, -104, -128, 104, 96, -104, -24, -72, -120, -128, 56, 96, -56, -128, 112, 104, -48, -88, -112, 96, 96, 104, -104, -88, -72, -40, -88, -96, -72, -88, -96, -120, 120, 104, -80, -88, -96, 72, 72, 80, -120, 88, 96, 120, -120, -24, 96, -104, -16, 104, 80, 48, -56, -80, -96, -56, -88, -104, -104, 120, -88, -88, 120, 104, -72, -120, -120, -24, -32, -40, 112, 88, -104, 120, 96, -104, -32, -32, -32, -96, 96, 96, 80, 80, 88, 64, 88, 120, 72, 120, -40, 72, 88, 112, -88, -96, -104, -56, -80, -88, -72, -88, -104, -56, -64, -72, -80, -120, 104, -80, -120, -80, -112, 112, -88, 120, 112, 112, 112, -96, -24, -120, -120, -64, -120, 120, -80, 64, 96, -128, 96, 64, 64, 96, -128, -32, 80, 112, -24, 112, -120, -24, 104, -96, -8, 96, 120, -16, -88, 120, 120, -72, -56, -16, -128, -128, -128, -104, -120, -72, -64, -96, -120, -32, -64, -64, -40, -48, -56, -64, -88, -96, -64, -104, -72, -96, -88, -24, -104, -96, -40, -96, -128, 96, -128, -128, -96, 104, 88, 80, 112, -88, -8, -64, -104, -80, -96, -120, 112, 96, 120, -32, 56, 80, -72, -104, -88, -32, 104, -128, -24, -56, -88, -120, -80, -72, -8, -96, -128, -128, -64, -128, 96, -72, -96, -120, 72, 104, -32, -96, 96, 64, -72, -96, -112, -32, -40, -48, -64, -88, -112, -88, -128, 96, -88, -128, -88, -64, -64, -32, -128, -96, -32, -88, -104, -112, 32, 32, 64, -120, 104, -88, 120, -120, -16, -104, 120, -72, -24, -48, -56, -96, -96, -96, -64, 96, 96, 96, 64, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 0, 0, 0, 0, 50, 0, 50, 0, 0, 8, -1, 0, 1, 8, 28, 72, -80, -96, -63, -125, 8, 19, 42, 92, -120, 112, 0, 3, 6, 12, 23, 6, -104, 72, -79, -94, -59, -117, 19, 39, -124, 64, -128, -128, 3, -121, 9, 19, 48, -118, -92, 24, 81, 33, -118, 8, 40, 7, -88, 84, -55, -64, 12, 6, 6, 45, 74, -54, 52, 8, 73, -60, 24, 22, 25, 92, 73, 40, 64, -96, -64, 74, -121, 24, 94, -58, -100, 25, -79, -59, 47, 17, 3, 52, -120, 88, -125, 105, 73, 6, 42, -102, -68, 96, -16, -71, 18, 3, -118, 6, 13, 14, -114, -36, 26, -64, 69, 7, 18, 28, -61, -110, -32, -32, -62, -54, -94, 72, -61, -48, -88, -40, 72, 34, -60, 4, 21, 23, -119, 14, -92, 80, -58, 6, -108, 10, 18, 44, 68, -8, 57, -96, -128, 16, 98, 70, -24, -48, 97, -45, 6, 4, 6, 16, 67, -27, 18, 52, -79, -52, -89, -46, 49, -105, -74, -32, 109, -45, -85, -63, -49, 2, 13, 88, -51, -62, 5, 40, 80, 31, 91, 103, 20, 11, -116, 32, -124, -81, -54, 2, 40, -58, -40, -103, -59, -122, 13, 43, 51, 12, 122, 106, 96, -48, 0, -105, 40, 29, 106, 32, 17, 20, -64, -69, -73, -17, -33, -68, 25, 113, 13, 80, -125, 44, -102, 72, 108, -84, -88, 80, 49, -127, -61, -94, 28, -97, -108, -4, -98, -103, 102, 9, -127, -21, -40, -81, 23, -32, 35, -126, 39, -10, 2, 32, -116, 29, -1, 27, -74, 37, -40, 29, 60, 90, -60, -120, -90, 0, -122, -118, -23, -107, 54, -36, -72, -15, 2, 66, -61, -23, -39, 24, -8, -36, -7, -108, -27, -128, 44, -59, -112, -16, -64, 67, 3, -39, 21, 72, 0, 6, 34, 120, -31, -123, 124, 124, 52, 16, 84, 3, -119, -88, 82, -62, 28, -2, 21, 4, -36, -123, -83, -92, -96, 97, 13, 20, 117, 112, 2, -121, 24, 77, -128, 6, 48, -64, 72, -93, -62, 31, 104, -56, 48, 68, 16, 65, 112, 49, 29, 67, 82, 8, 24, 72, 118, 18, 84, 48, 66, 6, 63, 72, 96, 96, 1, 26, -128, 64, -97, 8, 50, 24, 114, -64, -112, -22, -51, -28, 7, 24, 77, 116, -15, 75, 1, 123, 53, 2, -63, 15, 22, 88, 0, 1, 5, 44, 72, 32, -127, 74, -78, -47, -122, -62, 27, -90, -24, 49, -28, 1, 69, -106, -108, 76, 21, -99, 8, -127, -119, 29, -81, 60, 41, -63, 15, 16, -116, 80, 65, -114, 22, -44, 40, 72, 6, 111, 60, 4, 77, 3, 34, -124, 1, -60, -105, 7, 40, 96, -31, -123, -68, 49, -111, 66, 30, 32, 102, -92, 66, 30, 86, 60, -47, -63, 12, 30, 42, 58, 67, 13, 51, 120, -32, 1, 35, 30, 112, 112, -62, 39, -114, -80, 24, -124, 116, 47, 30, 116, 6, 15, -120, 24, -104, 93, 3, -105, 44, -79, 12, 11, -103, -116, 112, 35, 20, 52, -96, 64, 3, 32, 91, -40, -1, 114, 5, -97, 126, -106, 36, 5, 24, -106, -67, 103, 26, 3, 32, -68, -14, 10, 20, 44, 88, -78, -124, 37, 91, -124, -47, -33, -105, 112, -56, -28, 7, -103, -70, -86, 116, -57, 29, 52, 80, 37, -101, 8, 54, 24, 99, -121, 17, 82, -108, -80, 0, -83, 7, 93, 56, 70, 14, 41, -96, -78, -107, 11, -117, -48, 97, -42, 12, 127, 32, 64, 66, 91, 19, -96, -88, -94, 35, -16, 110, 10, -88, 65, 103, 76, -62, 67, 19, 114, -120, -102, 93, 49, 107, -108, 65, -121, 29, -121, -36, 65, -116, 16, 24, -32, 121, -125, 33, -70, 108, -96, 112, -97, 37, 5, -127, 100, 23, -128, -4, 68, 65, 5, 123, -103, 102, -63, 24, 101, -20, 49, -51, 33, -121, -40, 80, 65, 9, 122, 40, -84, 112, -78, 17, 73, 81, 69, -110, -110, -28, -38, -105, 9, 84, -30, 69, 21, -106, 60, 106, 32, 68, 25, -127, -96, -96, -25, 6, 14, 56, -96, 112, -83, 90, 81, 116, 2, -72, 57, 16, 66, 8, 88, 28, 49, 26, 66, 8, 51, 60, -15, -60, 9, 51, -128, -75, -82, 91, 19, 116, 96, -87, 12, 31, 84, 93, -75, 18, 91, 13, 100, -126, -67, 125, 72, 50, 72, 45, 63, 89, -112, 1, 5, 20, -104, 96, 65, 1, 38, -4, 48, 49, 4, -82, 60, 84, 48, 13, -90, 92, -111, -13, -36, 60, 39, -44, 66, 40, 96, -12, -47, -59, 32, 81, -20, -1, -15, 19, 4, 18, 68, 80, 64, 5, 72, -80, 0, -127, 9, 17, 72, -112, 9, 20, -106, -48, -48, -86, -79, 56, -49, 77, -14, 66, -76, -100, -68, 119, 20, 59, 44, -15, 19, -53, 20, 0, 30, 103, -101, 110, -66, 97, -122, 25, 52, 44, 33, -125, -74, 11, -92, -98, 115, -35, 90, -55, 1, 52, 33, 83, 76, 33, -118, 10, 97, 73, -70, 81, 7, 29, 44, -35, 1, -46, 29, 76, -22, 2, 7, 30, -84, 50, -60, 7, 48, 60, 114, -11, 112, 0, -124, -95, 67, 21, -110, 96, -66, -61, 14, 12, -84, 36, -27, 8, -99, -101, 80, -128, 5, 72, -36, -104, -55, 23, -92, 83, -95, -116, 19, 14, -92, 46, 62, -21, 8, 21, 1, 68, 9, -93, -124, -78, 3, 51, 59, -68, -84, 82, -30, 72, 84, 64, 1, 18, 121, 85, 0, -123, 32, -126, -80, -112, 6, -56, 11, -32, 32, -2, -28, 10, -71, -64, 5, -80, 48, 7, 74, 56, -63, 16, 58, -40, 65, 45, -28, -16, 5, -108, 56, 16, 37, -112, -80, 17, 5, 70, -16, 6, 87, 124, -127, 5, -98, 0, -126, 3, 30, -128, -125, 14, -30, 64, 1, 2, 12, -95, 8, 67, 8, 0, -118, 108, -126, 8, 31, -16, 1, 40, 100, -96, -120, 20, 76, 33, 18, 121, -104, 64, 88, 102, 24, 2, -78, 48, 66, 5, -101, -96, 26, 12, 118, -72, 67, 100, 12, 103, 34, 4, 89, 65, 18, -1, 72, -127, -125, 2, 30, 80, 7, -107, -24, -37, 22, 26, -15, -66, 2, 20, -96, 17, 12, 64, 65, 52, -30, -74, -128, 7, 88, -47, -118, -28, 99, -120, 2, 122, -112, -124, 36, -100, 34, 1, 14, -48, -126, 26, 74, -128, -121, 80, 68, 33, 10, -127, -80, -127, 6, 98, -122, 1, 42, 120, 34, 11, 27, -72, -94, 21, 1, 56, 19, 50, 116, -47, -117, -89, 32, -59, 3, 28, 112, 5, 39, -108, 0, -119, 81, 16, -123, 17, 108, 96, 6, 42, -8, 65, 91, 15, 72, -128, 28, -77, -120, 16, -116, -64, -30, 25, 113, -120, 100, 36, -101, -15, 8, 24, -84, 80, 6, 46, -116, 93, 36, -124, -9, 1, 34, 120, -46, -109, 71, -8, 33, 73, 16, 66, -122, 21, -12, -32, -108, 61, 40, 5, 47, 18, 48, -121, 62, -2, 113, 18, 58, 112, -62, 6, 18, 64, -53, 90, 50, 82, 49, 10, 40, -62, 41, 11, -63, 75, 94, -68, 32, 117, 106, -16, -93, 30, 18, 89, -53, 4, -60, 64, 52, 10, 81, -128, 47, 86, -64, 76, 102, -106, 34, 23, 47, -48, -126, 22, 28, 80, 76, 90, -34, 82, 32, 6, -56, -90, 54, 69, 25, 0, 38, -64, -126, 11, 71, 8, -89, 56, -107, -96, 8, 31, -104, -45, 7, 68, -32, 2, 55, -127, 72, -108, 11, -112, -95, 8, 49, -120, -89, 60, 71, -15, -126, 122, 38, -32, -102, -56, 60, -120, 2, 110, 80, 51, -124, 126, -58, -94, 8, -62, -88, -25, 49, -13, 41, 23, 5, -112, -31, 6, 8, 93, 65, 64, -15, -39, -56, 117, 98, -124, 9, 51, -72, -59, 45, 56, -95, 78, -121, 6, -128, -96, 5, -39, 39, 67, 49, -54, -47, -114, 122, -44, 32, 1, 1, 0, 59 }; </code></pre>
[ { "answer_id": 115693, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 0, "selected": false, "text": "<p>Hard to say from what's provided, but guesses are</p>\n\n<ol>\n<li>Different JVM in Eclipse than command line.</li>\n...
2008/09/22
[ "https://Stackoverflow.com/questions/115685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9425/" ]
I once wrote this line in a Java class. This compiled fine in Eclipse but not on the command line. This is on * Eclipse 3.3 * JDK 1.5 * Windows XP Professional Any clues? Error given on the command line is: ``` Icons.java:16: code too large public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50, ^ ``` The code line in question is: ``` public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50, 0, 50, 0, -9, 0, 0, -1, -1, -1, -24, -72, -72, -24, -64, -64, -8, -16, -24, -8, -24, -24, -16, -24, -32, -1, -8, -8, 48, 72, -72, -24, -80, -80, 72, 96, -40, -24, -24, -8, 56, 88, -56, -24, -40, -48, -24, -48, -64, 56, 80, -64, 64, 88, -48, -56, -64, -64, -16, -24, -24, -32, -40, -40, -32, -88, -96, -72, -72, -72, -48, -56, -56, -24, -32, -32, -8, -8, -1, -24, -40, -56, -64, -72, -72, -16, -32, -40, 48, 80, -72, -40, -96, -104, -40, -96, -96, -56, -104, -104, 120, 88, -104, -40, -64, -80, -32, -88, -88, -32, -56, -72, -72, -80, -80, -32, -80, -88, 104, -96, -1, -40, -40, -40, -64, -104, -104, -32, -56, -64, -112, 104, 112, -48, -104, -112, -128, -112, -24, -72, -80, -88, -8, -8, -8, -64, -112, -120, 72, 104, -40, 120, 96, -96, -112, -96, -24, -112, -120, -72, -40, -88, -88, -48, -64, -72, -32, -72, -80, -48, -72, -88, -88, -72, -24, 64, 88, -56, -120, 96, 104, 88, -128, -72, 48, 56, 56, 104, 104, 120, 112, -120, -16, -128, 104, -88, -40, -48, -48, 88, -120, -24, 104, 88, -104, -40, -56, -72, -128, 112, -88, -128, 96, -88, -104, -88, -24, -96, -120, 120, -88, -128, -80, -56, -56, -64, 96, 120, -8, -96, -128, -88, -80, -96, -104, -32, -72, -72, 96, 104, 112, 96, -104, -8, -72, -112, -112, -64, -72, -80, 64, 64, 72, -128, -120, -96, -128, 88, 88, -56, -72, -80, 88, 96, 120, -72, -128, 112, 72, 112, -40, 96, 120, -56, 88, -112, -16, 64, 104, -48, -64, -80, -88, -88, -120, -80, 88, 88, 96, -56, -96, -120, -40, -56, -64, 96, 104, 120, -120, -80, -24, -104, -88, -40, -48, -72, -80, -64, -56, -16, -88, -112, -128, -32, -48, -56, -24, -16, -8, -64, -120, 120, -96, -96, -88, 80, -128, -24, -56, -72, -88, -96, 120, 88, -72, -112, 120, -64, -104, 120, -48, -56, -64, -120, -104, -32, -104, 120, -80, -96, -112, -120, 56, 88, -64, -128, 96, 64, 88, 120, -40, -80, -104, -120, -104, -128, 104, 96, -104, -24, -72, -120, -128, 56, 96, -56, -128, 112, 104, -48, -88, -112, 96, 96, 104, -104, -88, -72, -40, -88, -96, -72, -88, -96, -120, 120, 104, -80, -88, -96, 72, 72, 80, -120, 88, 96, 120, -120, -24, 96, -104, -16, 104, 80, 48, -56, -80, -96, -56, -88, -104, -104, 120, -88, -88, 120, 104, -72, -120, -120, -24, -32, -40, 112, 88, -104, 120, 96, -104, -32, -32, -32, -96, 96, 96, 80, 80, 88, 64, 88, 120, 72, 120, -40, 72, 88, 112, -88, -96, -104, -56, -80, -88, -72, -88, -104, -56, -64, -72, -80, -120, 104, -80, -120, -80, -112, 112, -88, 120, 112, 112, 112, -96, -24, -120, -120, -64, -120, 120, -80, 64, 96, -128, 96, 64, 64, 96, -128, -32, 80, 112, -24, 112, -120, -24, 104, -96, -8, 96, 120, -16, -88, 120, 120, -72, -56, -16, -128, -128, -128, -104, -120, -72, -64, -96, -120, -32, -64, -64, -40, -48, -56, -64, -88, -96, -64, -104, -72, -96, -88, -24, -104, -96, -40, -96, -128, 96, -128, -128, -96, 104, 88, 80, 112, -88, -8, -64, -104, -80, -96, -120, 112, 96, 120, -32, 56, 80, -72, -104, -88, -32, 104, -128, -24, -56, -88, -120, -80, -72, -8, -96, -128, -128, -64, -128, 96, -72, -96, -120, 72, 104, -32, -96, 96, 64, -72, -96, -112, -32, -40, -48, -64, -88, -112, -88, -128, 96, -88, -128, -88, -64, -64, -32, -128, -96, -32, -88, -104, -112, 32, 32, 64, -120, 104, -88, 120, -120, -16, -104, 120, -72, -24, -48, -56, -96, -96, -96, -64, 96, 96, 96, 64, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 0, 0, 0, 0, 50, 0, 50, 0, 0, 8, -1, 0, 1, 8, 28, 72, -80, -96, -63, -125, 8, 19, 42, 92, -120, 112, 0, 3, 6, 12, 23, 6, -104, 72, -79, -94, -59, -117, 19, 39, -124, 64, -128, -128, 3, -121, 9, 19, 48, -118, -92, 24, 81, 33, -118, 8, 40, 7, -88, 84, -55, -64, 12, 6, 6, 45, 74, -54, 52, 8, 73, -60, 24, 22, 25, 92, 73, 40, 64, -96, -64, 74, -121, 24, 94, -58, -100, 25, -79, -59, 47, 17, 3, 52, -120, 88, -125, 105, 73, 6, 42, -102, -68, 96, -16, -71, 18, 3, -118, 6, 13, 14, -114, -36, 26, -64, 69, 7, 18, 28, -61, -110, -32, -32, -62, -54, -94, 72, -61, -48, -88, -40, 72, 34, -60, 4, 21, 23, -119, 14, -92, 80, -58, 6, -108, 10, 18, 44, 68, -8, 57, -96, -128, 16, 98, 70, -24, -48, 97, -45, 6, 4, 6, 16, 67, -27, 18, 52, -79, -52, -89, -46, 49, -105, -74, -32, 109, -45, -85, -63, -49, 2, 13, 88, -51, -62, 5, 40, 80, 31, 91, 103, 20, 11, -116, 32, -124, -81, -54, 2, 40, -58, -40, -103, -59, -122, 13, 43, 51, 12, 122, 106, 96, -48, 0, -105, 40, 29, 106, 32, 17, 20, -64, -69, -73, -17, -33, -68, 25, 113, 13, 80, -125, 44, -102, 72, 108, -84, -88, 80, 49, -127, -61, -94, 28, -97, -108, -4, -98, -103, 102, 9, -127, -21, -40, -81, 23, -32, 35, -126, 39, -10, 2, 32, -116, 29, -1, 27, -74, 37, -40, 29, 60, 90, -60, -120, -90, 0, -122, -118, -23, -107, 54, -36, -72, -15, 2, 66, -61, -23, -39, 24, -8, -36, -7, -108, -27, -128, 44, -59, -112, -16, -64, 67, 3, -39, 21, 72, 0, 6, 34, 120, -31, -123, 124, 124, 52, 16, 84, 3, -119, -88, 82, -62, 28, -2, 21, 4, -36, -123, -83, -92, -96, 97, 13, 20, 117, 112, 2, -121, 24, 77, -128, 6, 48, -64, 72, -93, -62, 31, 104, -56, 48, 68, 16, 65, 112, 49, 29, 67, 82, 8, 24, 72, 118, 18, 84, 48, 66, 6, 63, 72, 96, 96, 1, 26, -128, 64, -97, 8, 50, 24, 114, -64, -112, -22, -51, -28, 7, 24, 77, 116, -15, 75, 1, 123, 53, 2, -63, 15, 22, 88, 0, 1, 5, 44, 72, 32, -127, 74, -78, -47, -122, -62, 27, -90, -24, 49, -28, 1, 69, -106, -108, 76, 21, -99, 8, -127, -119, 29, -81, 60, 41, -63, 15, 16, -116, 80, 65, -114, 22, -44, 40, 72, 6, 111, 60, 4, 77, 3, 34, -124, 1, -60, -105, 7, 40, 96, -31, -123, -68, 49, -111, 66, 30, 32, 102, -92, 66, 30, 86, 60, -47, -63, 12, 30, 42, 58, 67, 13, 51, 120, -32, 1, 35, 30, 112, 112, -62, 39, -114, -80, 24, -124, 116, 47, 30, 116, 6, 15, -120, 24, -104, 93, 3, -105, 44, -79, 12, 11, -103, -116, 112, 35, 20, 52, -96, 64, 3, 32, 91, -40, -1, 114, 5, -97, 126, -106, 36, 5, 24, -106, -67, 103, 26, 3, 32, -68, -14, 10, 20, 44, 88, -78, -124, 37, 91, -124, -47, -33, -105, 112, -56, -28, 7, -103, -70, -86, 116, -57, 29, 52, 80, 37, -101, 8, 54, 24, 99, -121, 17, 82, -108, -80, 0, -83, 7, 93, 56, 70, 14, 41, -96, -78, -107, 11, -117, -48, 97, -42, 12, 127, 32, 64, 66, 91, 19, -96, -88, -94, 35, -16, 110, 10, -88, 65, 103, 76, -62, 67, 19, 114, -120, -102, 93, 49, 107, -108, 65, -121, 29, -121, -36, 65, -116, 16, 24, -32, 121, -125, 33, -70, 108, -96, 112, -97, 37, 5, -127, 100, 23, -128, -4, 68, 65, 5, 123, -103, 102, -63, 24, 101, -20, 49, -51, 33, -121, -40, 80, 65, 9, 122, 40, -84, 112, -78, 17, 73, 81, 69, -110, -110, -28, -38, -105, 9, 84, -30, 69, 21, -106, 60, 106, 32, 68, 25, -127, -96, -96, -25, 6, 14, 56, -96, 112, -83, 90, 81, 116, 2, -72, 57, 16, 66, 8, 88, 28, 49, 26, 66, 8, 51, 60, -15, -60, 9, 51, -128, -75, -82, 91, 19, 116, 96, -87, 12, 31, 84, 93, -75, 18, 91, 13, 100, -126, -67, 125, 72, 50, 72, 45, 63, 89, -112, 1, 5, 20, -104, 96, 65, 1, 38, -4, 48, 49, 4, -82, 60, 84, 48, 13, -90, 92, -111, -13, -36, 60, 39, -44, 66, 40, 96, -12, -47, -59, 32, 81, -20, -1, -15, 19, 4, 18, 68, 80, 64, 5, 72, -80, 0, -127, 9, 17, 72, -112, 9, 20, -106, -48, -48, -86, -79, 56, -49, 77, -14, 66, -76, -100, -68, 119, 20, 59, 44, -15, 19, -53, 20, 0, 30, 103, -101, 110, -66, 97, -122, 25, 52, 44, 33, -125, -74, 11, -92, -98, 115, -35, 90, -55, 1, 52, 33, 83, 76, 33, -118, 10, 97, 73, -70, 81, 7, 29, 44, -35, 1, -46, 29, 76, -22, 2, 7, 30, -84, 50, -60, 7, 48, 60, 114, -11, 112, 0, -124, -95, 67, 21, -110, 96, -66, -61, 14, 12, -84, 36, -27, 8, -99, -101, 80, -128, 5, 72, -36, -104, -55, 23, -92, 83, -95, -116, 19, 14, -92, 46, 62, -21, 8, 21, 1, 68, 9, -93, -124, -78, 3, 51, 59, -68, -84, 82, -30, 72, 84, 64, 1, 18, 121, 85, 0, -123, 32, -126, -80, -112, 6, -56, 11, -32, 32, -2, -28, 10, -71, -64, 5, -80, 48, 7, 74, 56, -63, 16, 58, -40, 65, 45, -28, -16, 5, -108, 56, 16, 37, -112, -80, 17, 5, 70, -16, 6, 87, 124, -127, 5, -98, 0, -126, 3, 30, -128, -125, 14, -30, 64, 1, 2, 12, -95, 8, 67, 8, 0, -118, 108, -126, 8, 31, -16, 1, 40, 100, -96, -120, 20, 76, 33, 18, 121, -104, 64, 88, 102, 24, 2, -78, 48, 66, 5, -101, -96, 26, 12, 118, -72, 67, 100, 12, 103, 34, 4, 89, 65, 18, -1, 72, -127, -125, 2, 30, 80, 7, -107, -24, -37, 22, 26, -15, -66, 2, 20, -96, 17, 12, 64, 65, 52, -30, -74, -128, 7, 88, -47, -118, -28, 99, -120, 2, 122, -112, -124, 36, -100, 34, 1, 14, -48, -126, 26, 74, -128, -121, 80, 68, 33, 10, -127, -80, -127, 6, 98, -122, 1, 42, 120, 34, 11, 27, -72, -94, 21, 1, 56, 19, 50, 116, -47, -117, -89, 32, -59, 3, 28, 112, 5, 39, -108, 0, -119, 81, 16, -123, 17, 108, 96, 6, 42, -8, 65, 91, 15, 72, -128, 28, -77, -120, 16, -116, -64, -30, 25, 113, -120, 100, 36, -101, -15, 8, 24, -84, 80, 6, 46, -116, 93, 36, -124, -9, 1, 34, 120, -46, -109, 71, -8, 33, 73, 16, 66, -122, 21, -12, -32, -108, 61, 40, 5, 47, 18, 48, -121, 62, -2, 113, 18, 58, 112, -62, 6, 18, 64, -53, 90, 50, 82, 49, 10, 40, -62, 41, 11, -63, 75, 94, -68, 32, 117, 106, -16, -93, 30, 18, 89, -53, 4, -60, 64, 52, 10, 81, -128, 47, 86, -64, 76, 102, -106, 34, 23, 47, -48, -126, 22, 28, 80, 76, 90, -34, 82, 32, 6, -56, -90, 54, 69, 25, 0, 38, -64, -126, 11, 71, 8, -89, 56, -107, -96, 8, 31, -104, -45, 7, 68, -32, 2, 55, -127, 72, -108, 11, -112, -95, 8, 49, -120, -89, 60, 71, -15, -126, 122, 38, -32, -102, -56, 60, -120, 2, 110, 80, 51, -124, 126, -58, -94, 8, -62, -88, -25, 49, -13, 41, 23, 5, -112, -31, 6, 8, 93, 65, 64, -15, -39, -56, 117, 98, -124, 9, 51, -72, -59, 45, 56, -95, 78, -121, 6, -128, -96, 5, -39, 39, 67, 49, -54, -47, -114, 122, -44, 32, 1, 1, 0, 59 }; ```
Taking from [this forum on Sun's support site](http://forums.sun.com/thread.jspa?threadID=747860&messageID=4278559), no method can be more than 64 KB long: When you have code (pseudo) like the following... ``` class MyClass { private String[] s = { "a", "b", "c"} public MyClass() { } ``` The compiler ends up producing code that basically looks like the following. ``` class MyClass { private String[] s; private void FunnyName$Method() { s[0] = "a"; s[1] = "b"; s[2] = "c"; } public MyClass() { FunnyName$Method(); } ``` And as noted java limits all methods to 64k, even the ones the compiler creates. It may be that Eclipse is doing something sneaky to get around this, but I assure you this is still possible in Eclipse because I have seen the same error message. A better solution is to just read from a static file, like this: ``` public class Icons { public static final byte[] compileIcon; static { compileIcon = readFileToBytes("compileIcon.gif"); } //... (I assume there are several other icons) private static byte[] readFileToBytes(String filename) { try { File file = new File(filename); byte[] bytes = new byte[(int)file.length()]; FileInputStream fin = new FileInputStream(file); fin.read(bytes); fin.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } ```
115,691
<p>In every MVC framework I've tried (Rails, Merb, Waves, Spring, and Struts), the idea of a Request (and Response) is tied to the HTTP notion of a Request. That is, even if there is an AbstractRequest that is a superclass of Request, the AbstractRequest has things like headers, request method (GET, POST, etc.), and all of the other things tied to HTTP.</p> <p>I'd like to support a request-response cycle over SMS, Twitter, email, or any other medium for which I can make an adapter. Is there a framework that does this particularly well?</p> <p>The only other option I've thought of is creating, for example, a Twitter poller that runs in a separate thread and translates messages into local HTTP requests, then sends the responses back out.</p> <p>If there <em>were</em> a good framework for multiple request media, what would routing look like? In Rails, the HTTP routing looks something like:</p> <pre><code>map.connect 'some/path/with/:parameter_1/:paramter_2', :controller =&gt; 'foo', :action =&gt; 'bar' </code></pre> <p>How would a Twitter or SMS route look? Regular expressions to match keywords and parameters?</p>
[ { "answer_id": 115823, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 1, "selected": false, "text": "<p>I haven't seen one. The issue is that the request is also tied to the host, and the response is tied to the reque...
2008/09/22
[ "https://Stackoverflow.com/questions/115691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
In every MVC framework I've tried (Rails, Merb, Waves, Spring, and Struts), the idea of a Request (and Response) is tied to the HTTP notion of a Request. That is, even if there is an AbstractRequest that is a superclass of Request, the AbstractRequest has things like headers, request method (GET, POST, etc.), and all of the other things tied to HTTP. I'd like to support a request-response cycle over SMS, Twitter, email, or any other medium for which I can make an adapter. Is there a framework that does this particularly well? The only other option I've thought of is creating, for example, a Twitter poller that runs in a separate thread and translates messages into local HTTP requests, then sends the responses back out. If there *were* a good framework for multiple request media, what would routing look like? In Rails, the HTTP routing looks something like: ``` map.connect 'some/path/with/:parameter_1/:paramter_2', :controller => 'foo', :action => 'bar' ``` How would a Twitter or SMS route look? Regular expressions to match keywords and parameters?
You seem to be working mostly with Java and/or Ruby, so forgive me that this answer is based on Perl :-). I'm very fond of the Catalyst MVC Framework (<http://www.catalystframework.org/>). It delegates the actual mapping of requests (in the general, generic sense) to code via engines. Granted, all the engine classes are currently based on HTTP, but I have toyed with the idea of trying to write an engine class that wasn't based on HTTP (or was perhaps tied to something like Twitter, but was separated from the HTTP interactions that Twitter uses). At the very least, I'm convinced it can be done, even if I haven't gotten around to trying it yet.
115,692
<p>For example I have such query:</p> <pre><code>Query q = sess.createQuery("from Cat cat"); List cats = q.list(); </code></pre> <p>If I try to make something like this it shows the following warning </p> <pre><code>Type safety: The expression of type List needs unchecked conversion to conform to List&lt;Cat&gt; List&lt;Cat&gt; cats = q.list(); </code></pre> <p>Is there a way to avoid it?</p>
[ { "answer_id": 115714, "author": "tyshock", "author_id": 16448, "author_profile": "https://Stackoverflow.com/users/16448", "pm_score": 3, "selected": false, "text": "<p>In our code we annotate the calling methods with:</p>\n\n<p>@SuppressWarnings(\"unchecked\")</p>\n\n<p>I know it seems ...
2008/09/22
[ "https://Stackoverflow.com/questions/115692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
For example I have such query: ``` Query q = sess.createQuery("from Cat cat"); List cats = q.list(); ``` If I try to make something like this it shows the following warning ``` Type safety: The expression of type List needs unchecked conversion to conform to List<Cat> List<Cat> cats = q.list(); ``` Is there a way to avoid it?
Using `@SuppressWarnings` everywhere, as suggested, is a good way to do it, though it does involve a bit of finger typing each time you call `q.list()`. There are two other techniques I'd suggest: **Write a cast-helper** Simply refactor all your `@SuppressWarnings` into one place: ``` List<Cat> cats = MyHibernateUtils.listAndCast(q); ... public static <T> List<T> listAndCast(Query q) { @SuppressWarnings("unchecked") List list = q.list(); return list; } ``` **Prevent Eclipse from generating warnings for unavoidable problems** In Eclipse, go to Window>Preferences>Java>Compiler>Errors/Warnings and under Generic type, select the checkbox `Ignore unavoidable generic type problems due to raw APIs` This will turn off unnecessary warnings for similar problems like the one described above which are unavoidable. Some comments: * I chose to pass in the `Query` instead of the result of `q.list()` because that way this "cheating" method can only be used to cheat with Hibernate, and not for cheating any `List` in general. * You could add similar methods for `.iterate()` etc.
115,703
<p>I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example:</p> <p><strong>.h file</strong></p> <pre><code>class foo { public: template &lt;typename T&gt; void do(const T&amp; t); }; </code></pre> <p><strong>.cpp file</strong></p> <pre><code>template &lt;typename T&gt; void foo::do(const T&amp; t) { // Do something with t } template void foo::do&lt;int&gt;(const int&amp;); template void foo::do&lt;std::string&gt;(const std::string&amp;); </code></pre> <p>Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link.</p> <p>My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments.</p>
[ { "answer_id": 115731, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>Yes, that's the standard way to do <s>specializiation</s> explicit instantiation. As you stated, you cannot instantia...
2008/09/22
[ "https://Stackoverflow.com/questions/115703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example: **.h file** ``` class foo { public: template <typename T> void do(const T& t); }; ``` **.cpp file** ``` template <typename T> void foo::do(const T& t) { // Do something with t } template void foo::do<int>(const int&); template void foo::do<std::string>(const std::string&); ``` Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link. My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments.
The problem you describe can be solved by defining the template in the header, or via the approach you describe above. I recommend reading the following points from the [C++ FAQ Lite](https://isocpp.org/wiki/faq/templates): * [Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?](https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl) * [How can I avoid linker errors with my template functions?](https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl) * [How does the C++ keyword export help with template linker errors?](https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl-export-keyword) They go into a lot of detail about these (and other) template issues.
115,720
<p>Is there a command in classic ASP I can use to tell the browser not to pull the page from it's cache, or, to not cache, or clear the cache of my page?</p>
[ { "answer_id": 115734, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>If you put</p>\n\n<pre><code>Response.Expires = -1\n</code></pre>\n\n<p>in you classic ASP-page it will instruct the browser...
2008/09/22
[ "https://Stackoverflow.com/questions/115720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5836/" ]
Is there a command in classic ASP I can use to tell the browser not to pull the page from it's cache, or, to not cache, or clear the cache of my page?
You can use HTML meta tags: ``` <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="Fri, 01 Jan 1999 1:00:00 GMT" /> <meta http-equiv="Last-Modified" content="0" /> <meta http-equiv="Cache-Control" content="no-cache, must-revalidate" /> ``` Or you can use ASP response headers: ``` <% Response.CacheControl = "no-cache" Response.AddHeader "Pragma", "no-cache" Response.Expires = -1 %> ```
115,764
<p>I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file.</p> <p>The calendar object just has a method that adds events as they get parsed.</p> <p>Now I want to create a factory function that creates a calendar from a file object, path, or URL.</p> <p>I've been using the <a href="http://codespeak.net/icalendar/" rel="nofollow noreferrer">iCalendar python module</a>, which implements a factory function as a class method directly on the Class that it returns an instance of:</p> <pre><code>cal = icalendar.Calendar.from_string(data) </code></pre> <p>From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from.</p> <p>The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?</p>
[ { "answer_id": 115777, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 3, "selected": false, "text": "<p>It's pythonic not to think about esoteric difference in some pattern you read somewhere and now want to use every...
2008/09/22
[ "https://Stackoverflow.com/questions/115764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2900/" ]
I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file. The calendar object just has a method that adds events as they get parsed. Now I want to create a factory function that creates a calendar from a file object, path, or URL. I've been using the [iCalendar python module](http://codespeak.net/icalendar/), which implements a factory function as a class method directly on the Class that it returns an instance of: ``` cal = icalendar.Calendar.from_string(data) ``` From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from. The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?
[**Note**. Be very cautious about separating "Calendar" a collection of events, and "Event" - a single event on a calendar. In your question, it seems like there could be some confusion.] There are many variations on the Factory design pattern. 1. A stand-alone convenience function (e.g., calendarMaker(data)) 2. A separate class (e.g., CalendarParser) which builds your target class (Calendar). 3. A class-level method (e.g. Calendar.from\_string) method. These have different purposes. All are Pythonic, the questions are "what do you *mean*?" and "what's likely to change?" Meaning is everything; change is important. Convenience functions are Pythonic. Languages like Java can't have free-floating functions; you must wrap a lonely function in a class. Python allows you to have a lonely function without the overhead of a class. A function is relevant when your constructor has no state changes or alternate strategies or any memory of previous actions. Sometimes folks will define a class and then provide a convenience function that makes an instance of the class, sets the usual parameters for state and strategy and any other configuration, and then calls the single relevant method of the class. This gives you both the statefulness of class plus the flexibility of a stand-alone function. The class-level method pattern is used, but it has limitations. One, it's forced to rely on class-level variables. Since these can be confusing, a complex constructor as a static method runs into problems when you need to add features (like statefulness or alternative strategies.) Be sure you're never going to expand the static method. Two, it's more-or-less irrelevant to the rest of the class methods and attributes. This kind of `from_string` is just one of many alternative encodings for your Calendar objects. You might have a `from_xml`, `from_JSON`, `from_YAML` and on and on. None of this has the least relevance to what a Calendar IS or what it DOES. These methods are all about how a Calendar is encoded for transmission. What you'll see in the mature Python libraries is that factories are separate from the things they create. Encoding (as strings, XML, JSON, YAML) is subject to a great deal of more-or-less random change. The essential thing, however, rarely changes. Separate the two concerns. Keep encoding and representation as far away from state and behavior as you can.
115,773
<p>I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name. It could be a machine configuration difference or a newer version of CherryPy or Python. Any ideas how I can bind to the correct IP address?</p> <p>Edit: to make it clear, I currently don't have a config file at all.</p>
[ { "answer_id": 115826, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 5, "selected": true, "text": "<p>That depends on how you are running the cherrypy init.</p>\n\n<p>If using cherrypy 3.1 syntax, that wold do it:</p>\n\n<p...
2008/09/22
[ "https://Stackoverflow.com/questions/115773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/852/" ]
I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name. It could be a machine configuration difference or a newer version of CherryPy or Python. Any ideas how I can bind to the correct IP address? Edit: to make it clear, I currently don't have a config file at all.
That depends on how you are running the cherrypy init. If using cherrypy 3.1 syntax, that wold do it: ``` cherrypy.server.socket_host = 'www.machinename.com' cherrypy.engine.start() cherrypy.engine.block() ``` Of course you can have something more fancy, like subclassing the server class, or using config files. Those uses are covered in [the documentation](http://www.cherrypy.org/wiki/ServerAPI "Cherrypy Server API documentation"). But that should be enough. If not just tell us what you are doing and cherrypy version, and I will edit this answer.
115,789
<p>It's my understanding that nulls are not indexable in DB2, so assuming we have a huge table (Sales) with a date column (sold_on) which is normally a date, but is occasionally (10% of the time) null.</p> <p>Furthermore, let's assume that it's a legacy application that we can't change, so those nulls are staying there and mean something (let's say sales that were returned).</p> <p>We can make the following query fast by putting an index on the sold_on and total columns</p> <pre><code>Select * from Sales where Sales.sold_on between date1 and date2 and Sales.total = 9.99 </code></pre> <p>But an index won't make this query any faster:</p> <pre><code>Select * from Sales where Sales.sold_on is null and Sales.total = 9.99 </code></pre> <p>Because the indexing is done on the value.</p> <p>Can I index nulls? Maybe by changing the index type? Indexing the indicator column?</p>
[ { "answer_id": 115824, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 3, "selected": true, "text": "<p>I'm no DB2 expert, but if 10% of your values are null, I don't think an index on that column alone will ever help ...
2008/09/22
[ "https://Stackoverflow.com/questions/115789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9056/" ]
It's my understanding that nulls are not indexable in DB2, so assuming we have a huge table (Sales) with a date column (sold\_on) which is normally a date, but is occasionally (10% of the time) null. Furthermore, let's assume that it's a legacy application that we can't change, so those nulls are staying there and mean something (let's say sales that were returned). We can make the following query fast by putting an index on the sold\_on and total columns ``` Select * from Sales where Sales.sold_on between date1 and date2 and Sales.total = 9.99 ``` But an index won't make this query any faster: ``` Select * from Sales where Sales.sold_on is null and Sales.total = 9.99 ``` Because the indexing is done on the value. Can I index nulls? Maybe by changing the index type? Indexing the indicator column?
I'm no DB2 expert, but if 10% of your values are null, I don't think an index on that column alone will ever help your query. 10% is too many to bother using an index for -- it'll just do a table scan. If you were talking about 2-3%, I think it would actually use your index. Think about how many records are on a page/block -- say 20. The reason to use an index is to avoid fetching pages you don't need. The odds that a given page will contain 0 records that are null is (90%)^20, or 12%. Those aren't good odds -- you're going to need 88% of your pages to be fetched anyway, using the index isn't very helpful. If, however, your select clause only included a few columns (and not \*) -- say just salesid, you could probably get it to use an index on (sold\_on,salesid), as the read of the data page wouldn't be needed -- all the data would be in the index.
115,809
<p>Many beginning programmers write code like this:</p> <pre><code>sub copy_file ($$) { my $from = shift; my $to = shift; `cp $from $to`; } </code></pre> <p>Is this bad, and why? Should backticks ever be used? If so, how?</p>
[ { "answer_id": 115810, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": 3, "selected": false, "text": "<p>Backticks should be used if and only if you need to capture the output of a command. Otherwise, system() should be used. An...
2008/09/22
[ "https://Stackoverflow.com/questions/115809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
Many beginning programmers write code like this: ``` sub copy_file ($$) { my $from = shift; my $to = shift; `cp $from $to`; } ``` Is this bad, and why? Should backticks ever be used? If so, how?
A few people have already mentioned that you should only use backticks when: * You need to capture (or supress) the output. * There exists no built-in function or Perl module to do the same task, or you have a good reason not to use the module or built-in. * You sanitise your input. * You check the return value. Unfortunately, things like checking the return value *properly* can be quite challenging. Did it die to a signal? Did it run to completion, but return a funny exit status? The standard ways of trying to interpret `$?` are just awful. I'd recommend using the [IPC::System::Simple](http://search.cpan.org/perldoc?IPC::System::Simple) module's `capture()` and `system()` functions rather than backticks. The `capture()` function works just like backticks, except that: * It provides detailed diagnostics if the command doesn't start, is killed by a signal, or returns an unexpected exit value. * It provides detailed diagnostics if passed tainted data. * It provides an easy mechanism for specifying acceptable exit values. * It allows you to call backticks without the shell, if you want to. * It provides reliable mechanisms for avoiding the shell, even if you use a single argument. The commands also work consistently across operating systems and Perl versions, unlike Perl's built-in `system()` which may not check for tainted data when called with multiple arguments on older versions of Perl (eg, 5.6.0 with multiple arguments), or which may call the shell anyway under Windows. As an example, the following code snippet will save the results of a call to `perldoc` into a scalar, avoids the shell, and throws an exception if the page cannot be found (since perldoc returns 1). ``` #!/usr/bin/perl -w use strict; use IPC::System::Simple qw(capture); # Make sure we're called with command-line arguments. @ARGV or die "Usage: $0 arguments\n"; my $documentation = capture('perldoc', @ARGV); ``` [IPC::System::Simple](http://search.cpan.org/perldoc?IPC::System::Simple) is pure Perl, works on 5.6.0 and above, and doesn't have any dependencies that wouldn't normally come with your Perl distribution. (On Windows it depends upon a Win32:: module that comes with both ActiveState and Strawberry Perl). Disclaimer: I'm the author of [IPC::System::Simple](http://search.cpan.org/perldoc?IPC::System::Simple), so I may show some bias.
115,813
<p>I have been trying to produce a statically linked "single binary" version of my game for windows. I want to link with sdl, sdl_image and sdl_mixer which in turn pull in a few support libraries. Unfortunately I haven't found a way to get them all to compile and link using cygwin/mingw/gcc. As far as I can tell all existing public versions are only shared libraries / dlls.</p> <p>Please note that I'm not talking about licencing here. The source will be open thus the GPL/LGPLness of sdl is not relevant.</p>
[ { "answer_id": 115854, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 0, "selected": false, "text": "<p>That's because the SDL libs are under the LGPL-license.</p>\n\n<p>If you want to static link the libs (you can...
2008/09/22
[ "https://Stackoverflow.com/questions/115813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555/" ]
I have been trying to produce a statically linked "single binary" version of my game for windows. I want to link with sdl, sdl\_image and sdl\_mixer which in turn pull in a few support libraries. Unfortunately I haven't found a way to get them all to compile and link using cygwin/mingw/gcc. As far as I can tell all existing public versions are only shared libraries / dlls. Please note that I'm not talking about licencing here. The source will be open thus the GPL/LGPLness of sdl is not relevant.
When compiling your project, you need to make just a couple changes to your makefile. * Instead of `sdl-config --libs`, use `sdl-config --static-libs` * Surround the use of the above-mentioned `sdl-config --static-libs` with `-Wl,-Bstatic` and `-Wl,-Bdynamic`. This tells GCC to force static linking, but only for the libraries specified between them. If your makefile currently looks like: ``` SDLLIBS=`sdl-config --libs` ``` Change it to: ``` SDLLIBS=-Wl,-Bstatic `sdl-config --static-libs` -Wl,-Bdynamic ``` These are actually the same things you *should* do on Unix-like systems, but it usually doesn't cause as many errors on Unix-likes if you use the simpler `-static` flag to GCC, like it does on Windows.
115,835
<p>I am looking into an image processing problem for semi-real time detection of certain scenarios. My goal is to have the live video arrive as Motion JPEG frames in my Java code <em>somehow</em>. </p> <p>I am familiar with the <a href="http://java.sun.com/javase/technologies/desktop/media/jmf/" rel="noreferrer">Java Media Framework</a> and, sadly, I think we can consider that an effectively dead API. I am also familiar with <a href="http://www.axis.com/" rel="noreferrer">Axis boxes</a> and, while I really like their solution, I would appreciate any critical feedback on my specific points of interest. </p> <p>This is how I define "best" for the purpose of this discussion:</p> <ul> <li>Latency - if I'm controlling the camera using this video stream, I would like to keep my round-trip latency at less than 100 milliseconds if possible. That's measured as the time between my control input to the time when I see the visible change. EDIT some time later: another thing to keep in mind is that camera control is likely to be a combination of manual and automatic (event triggers). We need to see those pictures right away, even if the high quality feed is archived separately.</li> <li>Cost - free / open source is better than not free.</li> <li>Adjustable codec parameters - I need to be able to tune the codec for certain situations. Sometimes a high-speed low-resolution stream is actually easier to process.</li> <li>"Integration" with Java - how much trouble is it to hook this solution to my code? Am I sending packets over a socket? Hitting URLs? Installing Direct3D / JNI combinations?</li> <li>Windows / Linux / both? - I would prefer an operating system agnostic solution because I have to deliver to several flavors of OS but there may be a solution that is optimal for one but not the other.</li> </ul> <p>NOTE: I am aware of other image / video capture codecs and that is not the focus of this question. I am specifically <em>not</em> interested in streaming APIs (e.g., MPEG4) due to the loss of frame accuracy. However, if there is a solution to my question that delivers another frame-accurate data stream, please chime in.</p> <p>Follow-up to this question: at this point, I am strongly inclined to buy appliances such as the <a href="http://www.axis.com/products/video/video_server/index.htm" rel="noreferrer">Axis video encoders</a> rather than trying to capture the video in software or on the PC directly. However, if someone has alternatives, I'd love to hear them.</p>
[ { "answer_id": 117412, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": -1, "selected": false, "text": "<p>Have you ever looked at <a href=\"http://processing.org/\" rel=\"nofollow noreferrer\">Processing.org</a>? It's basic...
2008/09/22
[ "https://Stackoverflow.com/questions/115835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5812/" ]
I am looking into an image processing problem for semi-real time detection of certain scenarios. My goal is to have the live video arrive as Motion JPEG frames in my Java code *somehow*. I am familiar with the [Java Media Framework](http://java.sun.com/javase/technologies/desktop/media/jmf/) and, sadly, I think we can consider that an effectively dead API. I am also familiar with [Axis boxes](http://www.axis.com/) and, while I really like their solution, I would appreciate any critical feedback on my specific points of interest. This is how I define "best" for the purpose of this discussion: * Latency - if I'm controlling the camera using this video stream, I would like to keep my round-trip latency at less than 100 milliseconds if possible. That's measured as the time between my control input to the time when I see the visible change. EDIT some time later: another thing to keep in mind is that camera control is likely to be a combination of manual and automatic (event triggers). We need to see those pictures right away, even if the high quality feed is archived separately. * Cost - free / open source is better than not free. * Adjustable codec parameters - I need to be able to tune the codec for certain situations. Sometimes a high-speed low-resolution stream is actually easier to process. * "Integration" with Java - how much trouble is it to hook this solution to my code? Am I sending packets over a socket? Hitting URLs? Installing Direct3D / JNI combinations? * Windows / Linux / both? - I would prefer an operating system agnostic solution because I have to deliver to several flavors of OS but there may be a solution that is optimal for one but not the other. NOTE: I am aware of other image / video capture codecs and that is not the focus of this question. I am specifically *not* interested in streaming APIs (e.g., MPEG4) due to the loss of frame accuracy. However, if there is a solution to my question that delivers another frame-accurate data stream, please chime in. Follow-up to this question: at this point, I am strongly inclined to buy appliances such as the [Axis video encoders](http://www.axis.com/products/video/video_server/index.htm) rather than trying to capture the video in software or on the PC directly. However, if someone has alternatives, I'd love to hear them.
This JavaCV implementation works fine. **CODE:** ``` import com.googlecode.javacv.OpenCVFrameGrabber; import com.googlecode.javacv.cpp.opencv_core.IplImage; import static com.googlecode.javacv.cpp.opencv_highgui.*; public class CaptureImage { private static void captureFrame() { // 0-default camera, 1 - next...so on final OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0); try { grabber.start(); IplImage img = grabber.grab(); if (img != null) { cvSaveImage("capture.jpg", img); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { captureFrame(); } } ``` There is also [post on viewing live video](http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/javacv-capture-save-flip-show-live.html) from Camera .And [configuration for JavaCV :](http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/opencv-javacv-eclipse-project.html) I think this will meet your requirements.
115,862
<p>I'm not sure about what's the difference between opening a JS script with </p> <pre><code>&lt;SCRIPT language='JavaScript'&gt; </code></pre> <p>or with:</p> <pre><code>&lt;SCRIPT type="text/JavaScript"&gt; </code></pre> <p>Should JavaScript always be quoted (either with " " or with ' ') or that's not really important?</p> <p>Thank you for any clarification on this topic!</p>
[ { "answer_id": 115871, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>Use both:</p>\n\n<pre><code>&lt;script language=\"javascript\" type=\"text/javascript\"&gt;\n</code></pre>\n" },...
2008/09/22
[ "https://Stackoverflow.com/questions/115862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19159/" ]
I'm not sure about what's the difference between opening a JS script with ``` <SCRIPT language='JavaScript'> ``` or with: ``` <SCRIPT type="text/JavaScript"> ``` Should JavaScript always be quoted (either with " " or with ' ') or that's not really important? Thank you for any clarification on this topic!
The language attribute was used in HTML 3.2. HTML 4.0 introduced type (which is consistent with other elements that refer to external media, such as `<style>`) and made it required. It also [deprecated](http://www.w3.org/TR/html401/conform.html#deprecated) language. Use [type](http://www.w3.org/TR/html401/interact/scripts.html#adef-type-SCRIPT). Do not use [language](http://www.w3.org/TR/html401/interact/scripts.html#adef-language). In HTML (and XHTML), there is no difference between [attribute values delimited using single or double quotes](http://www.w3.org/TR/html401/intro/sgmltut.html#h-3.2.2) (except that you can't use the character used to delimit the value inside the value without representing it with an entity).
115,866
<p>Convert mysql timestamp to epoch time in python - is there an easy way to do this?</p>
[ { "answer_id": 115903, "author": "David Singer", "author_id": 4618, "author_profile": "https://Stackoverflow.com/users/4618", "pm_score": 5, "selected": false, "text": "<p>Why not let MySQL do the hard work?</p>\n\n<pre><code>select unix_timestamp(fieldname) from tablename;\n</code></pre...
2008/09/22
[ "https://Stackoverflow.com/questions/115866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Convert mysql timestamp to epoch time in python - is there an easy way to do this?
Why not let MySQL do the hard work? ``` select unix_timestamp(fieldname) from tablename; ```
115,868
<p>I'd like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#. </p>
[ { "answer_id": 115891, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 2, "selected": false, "text": "<p>Use the Windows API. Call <code>GetForegroundWindow()</code>.</p>\n\n<p><code>GetForegroundWindow()</code> will give you a ha...
2008/09/22
[ "https://Stackoverflow.com/questions/115868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039/" ]
I'd like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#.
See example on how you can do this with full source code here: <http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/> ``` [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count); private string GetActiveWindowTitle() { const int nChars = 256; StringBuilder Buff = new StringBuilder(nChars); IntPtr handle = GetForegroundWindow(); if (GetWindowText(handle, Buff, nChars) > 0) { return Buff.ToString(); } return null; } ``` --- **Edited** with @Doug McClean comments for better correctness.
115,916
<p>I'm trying to convert a VARIANT from VT_DATE to an <strong>invariant</strong> VT_BSTR. The following code works on Windows XP:</p> <pre><code>VARIANT va; ::VariantInit(&amp;va); // set the variant to VT_DATE SYSTEMTIME st; memset(&amp;st, 0, sizeof(SYSTEMTIME)); st.wYear = 2008; st.wMonth = 9; st.wDay = 22; st.wHour = 12; st.wMinute = 30; DATE date; SystemTimeToVariantTime(&amp;st, &amp;date); va.vt = VT_DATE; va.date = date; // change to a string err = ::VariantChangeTypeEx(&amp;va, &amp;va, LOCALE_INVARIANT, 0, VT_BSTR); </code></pre> <p>But on PPC 2003 and Windows Mobile 5, the above code returns E_FAIL. Can someone correct the above code or provide an alternative?</p> <p><strong>EDIT</strong>: After converting the date to a string, I'm using the string to do a SQL update. I want the update to work regardless of the device's regional settings, so that's why I'm trying to convert it to an "invariant" format.</p> <p>I'm now using the following to convert the date to a format that appears to work:</p> <pre><code>err = ::VariantTimeToSystemTime(va.date, &amp;time); if (FAILED(err)) goto cleanup; err = strDate.PrintF(_T("%04d-%02d-%02d %02d:%02d:%02d.%03d"), time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds); </code></pre>
[ { "answer_id": 118962, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 1, "selected": false, "text": "<p>This isn't really an answer, but changing a date to a string <em>isn't</em> a Locale-invariant task - it highly depends...
2008/09/22
[ "https://Stackoverflow.com/questions/115916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773/" ]
I'm trying to convert a VARIANT from VT\_DATE to an **invariant** VT\_BSTR. The following code works on Windows XP: ``` VARIANT va; ::VariantInit(&va); // set the variant to VT_DATE SYSTEMTIME st; memset(&st, 0, sizeof(SYSTEMTIME)); st.wYear = 2008; st.wMonth = 9; st.wDay = 22; st.wHour = 12; st.wMinute = 30; DATE date; SystemTimeToVariantTime(&st, &date); va.vt = VT_DATE; va.date = date; // change to a string err = ::VariantChangeTypeEx(&va, &va, LOCALE_INVARIANT, 0, VT_BSTR); ``` But on PPC 2003 and Windows Mobile 5, the above code returns E\_FAIL. Can someone correct the above code or provide an alternative? **EDIT**: After converting the date to a string, I'm using the string to do a SQL update. I want the update to work regardless of the device's regional settings, so that's why I'm trying to convert it to an "invariant" format. I'm now using the following to convert the date to a format that appears to work: ``` err = ::VariantTimeToSystemTime(va.date, &time); if (FAILED(err)) goto cleanup; err = strDate.PrintF(_T("%04d-%02d-%02d %02d:%02d:%02d.%03d"), time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds); ```
This isn't really an answer, but changing a date to a string *isn't* a Locale-invariant task - it highly depends on the locale. In this case, I'd convert the Variant Time to System Time, then use a sprintf-style function to convert it to a string
115,928
<p>I need to have a thread signal another if the user wishes to interrupt execution, however I'm unsure about how to implement the signaling/signal-checking mechanism. I wouldn't like to have a singleton in my project (like a global <code>bool</code>), but is there an alternative?</p> <p>In <a href="https://stackoverflow.com/questions/34151/c-thread-question-setting-a-value-to-indicate-the-thread-has-finished">this thread</a> people suggest proper structures for that in C++, but I don't know about anything similar in .NET. Could somebody please shed some light?</p>
[ { "answer_id": 115935, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>Look at the System.Runtime.Remoting namespace.</p>\n" }, { "answer_id": 115948, "author": "Statement",...
2008/09/22
[ "https://Stackoverflow.com/questions/115928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4850/" ]
I need to have a thread signal another if the user wishes to interrupt execution, however I'm unsure about how to implement the signaling/signal-checking mechanism. I wouldn't like to have a singleton in my project (like a global `bool`), but is there an alternative? In [this thread](https://stackoverflow.com/questions/34151/c-thread-question-setting-a-value-to-indicate-the-thread-has-finished) people suggest proper structures for that in C++, but I don't know about anything similar in .NET. Could somebody please shed some light?
Try out [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx). It supports progress updates and cancellation of a running task. If you want one thread to wait until another thread has finished doing its thing, then Monitor.Wait and Monitor.Pulse are good, as is ManualResetEvent. However, these are not really of any use for cancelling a running task. If you want to write your own cancellation code, you could just have a field somewhere which both threads have access to. Mark it volatile, e.g.: ``` private volatile bool cancelling; ``` Have the main thread set it to true, and have the worker thread check it periodically and set it to false when it has finished. This is not really comparable to having a 'global variable', as you can still limit the scope of the semaphore variable to be private to a class.
115,955
<p>I'm trying to run a LINQ to SQL query that returns a result in a grid view in a search engine style listing. </p> <p>In the simplified example below, is it possible to populate the collection with a comma-separated list of any children that the parent has (NAMESOFCHILDREN) in a single query?</p> <pre><code>var family = from p in db.Parents where p.ParentId == Convert.ToInt32(Request.QueryString["parentId"]) join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId join c in db.Children on pcl.ChildId equals c.ChildId select new { Family = "Name: " + p.ParentName + "&lt;br /&gt;" + "Children: " + NAMESOFCHILDREN? + "&lt;br /&gt;" }; </code></pre> <p>Thanks in advance.</p>
[ { "answer_id": 115965, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "<p>Your joins are going to screw up your cardinality! You don't have a list of Parents!</p>\n\n<p>Here's some untested free-ha...
2008/09/22
[ "https://Stackoverflow.com/questions/115955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2034/" ]
I'm trying to run a LINQ to SQL query that returns a result in a grid view in a search engine style listing. In the simplified example below, is it possible to populate the collection with a comma-separated list of any children that the parent has (NAMESOFCHILDREN) in a single query? ``` var family = from p in db.Parents where p.ParentId == Convert.ToInt32(Request.QueryString["parentId"]) join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId join c in db.Children on pcl.ChildId equals c.ChildId select new { Family = "Name: " + p.ParentName + "<br />" + "Children: " + NAMESOFCHILDREN? + "<br />" }; ``` Thanks in advance.
Your joins are going to screw up your cardinality! You don't have a list of Parents! Here's some untested free-hand code. Adding the relationships in the Linq designer gives you relationship properties. String.Join will put the list together. I've added two optional method calls. *Where ... Any* will filter the parents to only those parents that have children. I'm unsure of string.Join's behavior on an empty array. *ToList* will yank Parents into memory, the children will be accessed by further database calls. This may be necessary if you get a runtime *string.Join is not supported by SQL translator* exception. This exception would mean that LINQ tried to translate the method call into something that SQL Server can understand - and failed. ``` int parentID = Convert.ToInt32(Request.QueryString["parentId"]); List<string> result = db.Parents .Where(p => p.ParentId == parentID) //.Where(p => p.ParentChildLookup.Children.Any()) //.ToList() .Select(p => "Name: " + p.ParentName + "<br />" + "Children: " + String.Join(", ", p.ParentChildLookup.Children.Select(c => c.Name).ToArray() + "<br />" )).ToList(); ``` Also note: generally you do not want to mix data and markup until the data is properly escaped for markup.
115,974
<p>What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. </p>
[ { "answer_id": 115985, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Nohup\" rel=\"nofollow noreferrer\">nohup</a> </p>\n\n<p><a href=\"http://cod...
2008/09/22
[ "https://Stackoverflow.com/questions/115974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14262/" ]
What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools.
See [Stevens](http://www.kohala.com/start/) and also this [lengthy thread on activestate](http://code.activestate.com/recipes/278731/) which I found personally to be both mostly incorrect and much to verbose, and I came up with this: ``` from os import fork, setsid, umask, dup2 from sys import stdin, stdout, stderr if fork(): exit(0) umask(0) setsid() if fork(): exit(0) stdout.flush() stderr.flush() si = file('/dev/null', 'r') so = file('/dev/null', 'a+') se = file('/dev/null', 'a+', 0) dup2(si.fileno(), stdin.fileno()) dup2(so.fileno(), stdout.fileno()) dup2(se.fileno(), stderr.fileno()) ``` If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one ``` from os import getpid outfile = open(pid_file, 'w') outfile.write('%i' % getpid()) outfile.close() ``` For security reasons you might consider any of these after demonizing ``` from os import setuid, setgid, chdir from pwd import getpwnam from grp import getgrnam setuid(getpwnam('someuser').pw_uid) setgid(getgrnam('somegroup').gr_gid) chdir('/') ``` You could also use [nohup](http://en.wikipedia.org/wiki/Nohup) but that does not work well with [python's subprocess module](http://docs.python.org/lib/module-subprocess.html)
115,977
<p>I would very much like to integrate <a href="http://www.logilab.org/857" rel="noreferrer">pylint</a> into the build process for my python projects, but I have run into one show-stopper: One of the error types that I find extremely useful--:<code>E1101: *%s %r has no %r member*</code>--constantly reports errors when using common django fields, for example:</p> <pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member </code></pre> <p>which is caused by this code:</p> <pre><code>def get_user_tags(username): """ Gets all the tags that username has used. Returns a query set. """ return Tag.objects.filter( ## This line triggers the error. tagownership__users__username__exact=username).distinct() # Here is the Tag class, models.Model is provided by Django: class Tag(models.Model): """ Model for user-defined strings that help categorize Events on on a per-user basis. """ name = models.CharField(max_length=500, null=False, unique=True) def __unicode__(self): return self.name </code></pre> <p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p> <p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p> <p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/" rel="noreferrer">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
[ { "answer_id": 116025, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 4, "selected": false, "text": "<p>Because of how pylint works (it examines the source itself, without letting Python actually execute it) it's ver...
2008/09/22
[ "https://Stackoverflow.com/questions/115977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3446/" ]
I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for my python projects, but I have run into one show-stopper: One of the error types that I find extremely useful--:`E1101: *%s %r has no %r member*`--constantly reports errors when using common django fields, for example: ``` E1101:125:get_user_tags: Class 'Tag' has no 'objects' member ``` which is caused by this code: ``` def get_user_tags(username): """ Gets all the tags that username has used. Returns a query set. """ return Tag.objects.filter( ## This line triggers the error. tagownership__users__username__exact=username).distinct() # Here is the Tag class, models.Model is provided by Django: class Tag(models.Model): """ Model for user-defined strings that help categorize Events on on a per-user basis. """ name = models.CharField(max_length=500, null=False, unique=True) def __unicode__(self): return self.name ``` How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of `objects`, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.) **Edit:** The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :) See [here](http://creswick.github.io/blog/2008/09/05/wrestling-python/) for a summary of the problems I've had with `pychecker` and `pyflakes` -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)
Do not disable or weaken Pylint functionality by adding `ignores` or `generated-members`. Use an actively developed Pylint plugin that **understands** Django. [This Pylint plugin for Django](https://github.com/landscapeio/pylint-django) works quite well: ``` pip install pylint-django ``` and when running pylint add the following flag to the command: ``` --load-plugins pylint_django ``` Detailed blog post [here](https://blog.landscape.io/using-pylint-on-django-projects-with-pylint-django.html).
115,983
<p>How do I add an empty directory (that contains no files) to a Git repository?</p>
[ { "answer_id": 115992, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 10, "selected": false, "text": "<p>You can't. See the <a href=\"https://git.wiki.kernel.org/index.php/GitFaq#Can_I_add_empty_directories.3F\" rel=\"no...
2008/09/22
[ "https://Stackoverflow.com/questions/115983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
How do I add an empty directory (that contains no files) to a Git repository?
Another way to make a directory stay (almost) empty (in the repository) is to create a `.gitignore` file inside that directory that contains these four lines: ``` # Ignore everything in this directory * # Except this file !.gitignore ``` Then you don't have to get the order right the way that you have to do in m104's [solution](https://stackoverflow.com/a/180917/32453). This also gives the benefit that files in that directory won't show up as "untracked" when you do a git status. Making [@GreenAsJade](https://stackoverflow.com/users/554807/greenasjade)'s comment persistent: > > I think it's worth noting that this solution does precisely what the question asked for, but is not perhaps what many people looking at this question will have been looking for. This solution guarantees that the directory remains empty. It says "I truly never want files checked in here". As opposed to "I don't have any files to check in here, yet, but I need the directory here, files may be coming later". > > >
116,002
<p>We all know that RAW pointers need to be wrapped in some form of smart pointer to get Exception safe memory management. But when it comes to containers of pointers the issue becomes more thorny.</p> <p>The std containers insist on the contained object being copyable so this rules out the use of std::auto_ptr, though you can still use boost::shared_ptr etc.</p> <p>But there are also some boost containers designed explicitly to hold pointers safely:<br> See <a href="http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/reference.html" rel="nofollow noreferrer">Pointer Container Library</a><br></p> <p>The question is: Under what conditions should I prefer to use the ptr_containers over a container of smart_pointers?</p> <pre><code>boost::ptr_vector&lt;X&gt; or std::vector&lt;boost::shared_ptr&lt;X&gt; &gt; </code></pre>
[ { "answer_id": 116045, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<p>Well, overhead is one case.</p>\n\n<p>A vector of shared pointers will do a lot of extraneous copying that involves cr...
2008/09/22
[ "https://Stackoverflow.com/questions/116002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14065/" ]
We all know that RAW pointers need to be wrapped in some form of smart pointer to get Exception safe memory management. But when it comes to containers of pointers the issue becomes more thorny. The std containers insist on the contained object being copyable so this rules out the use of std::auto\_ptr, though you can still use boost::shared\_ptr etc. But there are also some boost containers designed explicitly to hold pointers safely: See [Pointer Container Library](http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/reference.html) The question is: Under what conditions should I prefer to use the ptr\_containers over a container of smart\_pointers? ``` boost::ptr_vector<X> or std::vector<boost::shared_ptr<X> > ```
Boost pointer containers have strict ownership over the resources they hold. A std::vector<boost::shared\_ptr<X>> has shared ownership. There are reasons why that may be necessary, but in case it isn't, I would default to boost::ptr\_vector<X>. YMMV.
116,032
<p>I've sometimes had a problem with my field-, table-, view- oder stored procedure names. Example:</p> <pre><code> SELECT from, to, rate FROM Table1 </code></pre> <p>The Problem is that <strong><em>from</em></strong> is a reserved word in SQL-92. You could put the fieldname in double quotes to fix this, but what if some other db tools wants to read your database? It is your database design and it is your fault if other applications have problems with your db.</p> <p>There are many other <a href="http://developer.mimer.com/validator/sql-reserved-words.tml" rel="nofollow noreferrer" title="SQL reserved words">reserved words</a> (~300) and we should avoid all of them. If you change the DBMS from manufacturer A to B, your application can fail, because a some fieldnames are now reserved words. A field called <strong><em>PERCENT</em></strong> may work for a oracle db, but on a MS SQL Server it must be treated as a reserved word.</p> <p>I have a tool to check my database design against these reserved words ; you too?</p> <p>Here are my rules</p> <ol> <li>don't use names longer than 32 chars (some DBMS can't handle longer names)</li> <li>use only a-z, A-Z, 0-9 and the underscore (:-;,/&amp;!=?+- are not allowed)</li> <li>don't start a name with a digit</li> <li>avoid these reserved words</li> </ol>
[ { "answer_id": 116033, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>Easy way: just make sure <em>every</em> field name is quoted.</p>\n\n<p>Edit: Any sensible DB tool worth its salt should be...
2008/09/22
[ "https://Stackoverflow.com/questions/116032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573/" ]
I've sometimes had a problem with my field-, table-, view- oder stored procedure names. Example: ``` SELECT from, to, rate FROM Table1 ``` The Problem is that ***from*** is a reserved word in SQL-92. You could put the fieldname in double quotes to fix this, but what if some other db tools wants to read your database? It is your database design and it is your fault if other applications have problems with your db. There are many other [reserved words](http://developer.mimer.com/validator/sql-reserved-words.tml "SQL reserved words") (~300) and we should avoid all of them. If you change the DBMS from manufacturer A to B, your application can fail, because a some fieldnames are now reserved words. A field called ***PERCENT*** may work for a oracle db, but on a MS SQL Server it must be treated as a reserved word. I have a tool to check my database design against these reserved words ; you too? Here are my rules 1. don't use names longer than 32 chars (some DBMS can't handle longer names) 2. use only a-z, A-Z, 0-9 and the underscore (:-;,/&!=?+- are not allowed) 3. don't start a name with a digit 4. avoid these reserved words
Easy way: just make sure *every* field name is quoted. Edit: Any sensible DB tool worth its salt should be doing the same thing, I have certainly never encountered any problems (outside of my own code, at least!)
116,038
<p>How do I read a file into a <code>std::string</code>, i.e., read the whole file at once?</p> <p>Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.</p> <p>One way to do this would be to stat the filesize, resize the <code>std::string</code> and <code>fread()</code> into the <code>std::string</code>'s <code>const_cast&lt;char*&gt;()</code>'ed <code>data()</code>. This requires the <code>std::string</code>'s data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the <code>std::string</code>'s size may not equal the file's size.</p> <p>A fully correct, standard-compliant and portable solutions could be constructed using <code>std::ifstream</code>'s <code>rdbuf()</code> into a <code>std::ostringstream</code> and from there into a <code>std::string</code>. However, this could copy the string data and/or needlessly reallocate memory. </p> <ul> <li>Are all relevant standard library implementations smart enough to avoid all unnecessary overhead? </li> <li>Is there another way to do it? </li> <li>Did I miss some hidden Boost function that already provides the desired functionality?</li> </ul> <p><br></p> <pre><code>void slurp(std::string&amp; data, bool is_binary) </code></pre>
[ { "answer_id": 116083, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 5, "selected": false, "text": "<p>Use </p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;sstream&gt;\n#include &lt;fstream&gt;\n\nint main()\n{...
2008/09/22
[ "https://Stackoverflow.com/questions/116038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I read a file into a `std::string`, i.e., read the whole file at once? Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string. One way to do this would be to stat the filesize, resize the `std::string` and `fread()` into the `std::string`'s `const_cast<char*>()`'ed `data()`. This requires the `std::string`'s data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the `std::string`'s size may not equal the file's size. A fully correct, standard-compliant and portable solutions could be constructed using `std::ifstream`'s `rdbuf()` into a `std::ostringstream` and from there into a `std::string`. However, this could copy the string data and/or needlessly reallocate memory. * Are all relevant standard library implementations smart enough to avoid all unnecessary overhead? * Is there another way to do it? * Did I miss some hidden Boost function that already provides the desired functionality? ``` void slurp(std::string& data, bool is_binary) ```
One way is to flush the stream buffer into a separate memory stream, and then convert that to `std::string` (error handling omitted): ``` std::string slurp(std::ifstream& in) { std::ostringstream sstr; sstr << in.rdbuf(); return sstr.str(); } ``` This is nicely concise. However, as noted in the question this performs a redundant copy and unfortunately there is fundamentally no way of eliding this copy. The only real solution that avoids redundant copies is to do the reading manually in a loop, unfortunately. Since C++ now has guaranteed contiguous strings, one could write the following (≥C++17, error handling included): ``` auto read_file(std::string_view path) -> std::string { constexpr auto read_size = std::size_t(4096); auto stream = std::ifstream(path.data()); stream.exceptions(std::ios_base::badbit); auto out = std::string(); auto buf = std::string(read_size, '\0'); while (stream.read(& buf[0], read_size)) { out.append(buf, 0, stream.gcount()); } out.append(buf, 0, stream.gcount()); return out; } ```
116,050
<p>How do I programatically (Using C#) find out what the path is of my My Pictures folder? </p> <p>Does this work on XP and Vista?</p>
[ { "answer_id": 116057, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": 3, "selected": false, "text": "<p>Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);</p>\n" }, { "answer_id": 116061, "auth...
2008/09/22
[ "https://Stackoverflow.com/questions/116050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5147/" ]
How do I programatically (Using C#) find out what the path is of my My Pictures folder? Does this work on XP and Vista?
The following will return a full-path to the location of the users picture folder (Username\My Documents\My Pictures on XP, Username\Pictures on Vista) ``` Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); ```
116,053
<p>I'd like to show/hide a column at runtime based on a particular condition. I'm using "Print when expression" to conditionally show/hide this column (and it's header) in my report. When the column is hidden, the space it would have occupied is left blank, which is not particularly attractive.</p> <p>I would prefer if the extra space was used in a more effective manner, possibilities include:</p> <ul> <li>the width of the report is reduced by the width of the hidden column</li> <li>the extra space is distributed among the remaining columns</li> </ul> <p>In theory, I could achieve the first by setting the width of the column (and header) to 0, but also indicate that the column should resize to fit its contents. But JasperReports does not provide a "resize width to fit contents" option.</p> <p>Another possibility is to generate reports using the Jasper API instead of defining the report template in XML. But that seems like a lot of effort for such a simple requirement.</p>
[ { "answer_id": 117847, "author": "Jacob Schoen", "author_id": 3340, "author_profile": "https://Stackoverflow.com/users/3340", "pm_score": 0, "selected": false, "text": "<p>If it is just one column, is it possible to place this column to the far right, and then use the print when expressi...
2008/09/22
[ "https://Stackoverflow.com/questions/116053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I'd like to show/hide a column at runtime based on a particular condition. I'm using "Print when expression" to conditionally show/hide this column (and it's header) in my report. When the column is hidden, the space it would have occupied is left blank, which is not particularly attractive. I would prefer if the extra space was used in a more effective manner, possibilities include: * the width of the report is reduced by the width of the hidden column * the extra space is distributed among the remaining columns In theory, I could achieve the first by setting the width of the column (and header) to 0, but also indicate that the column should resize to fit its contents. But JasperReports does not provide a "resize width to fit contents" option. Another possibility is to generate reports using the Jasper API instead of defining the report template in XML. But that seems like a lot of effort for such a simple requirement.
In later version (v5 or above) of jasper reports you can use the `jr:table` component and **truly** achieve this (without the use of java code as using dynamic-jasper or dynamic-reports). The method is using a `<printWhenExpression/>` under the `<jr:column/>` Example ======= **Sample Data** ``` +----------------+--------+ | User | Rep | +----------------+--------+ | Jon Skeet | 854503 | | Darin Dimitrov | 652133 | | BalusC | 639753 | | Hans Passant | 616871 | | Me | 6487 | +----------------+--------+ ``` **Sample jrxml** **Note**: the parameter `$P{displayRecordNumber}` and the `<printWhenExpression>` under first `jr:column` ``` <?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="reputation" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a88bd694-4f90-41fc-84d0-002b90b2d73e"> <style name="table"> <box> <pen lineWidth="1.0" lineColor="#000000"/> </box> </style> <style name="table_TH" mode="Opaque" backcolor="#F0F8FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table_CH" mode="Opaque" backcolor="#BFE1FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table_TD" mode="Opaque" backcolor="#FFFFFF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <subDataset name="tableDataset" uuid="7a53770f-0350-4a73-bfc1-48a5f6386594"> <field name="User" class="java.lang.String"/> <field name="Rep" class="java.math.BigDecimal"/> </subDataset> <parameter name="displayRecordNumber" class="java.lang.Boolean"> <defaultValueExpression><![CDATA[true]]></defaultValueExpression> </parameter> <queryString> <![CDATA[]]> </queryString> <title> <band height="50"> <componentElement> <reportElement key="table" style="table" x="0" y="0" width="555" height="47" uuid="76ab08c6-e757-4785-a43d-b65ad4ab1dd5"/> <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd"> <datasetRun subDataset="tableDataset" uuid="07e5f1c2-af7f-4373-b653-c127c47c9fa4"> <dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></dataSourceExpression> </datasetRun> <jr:column width="90" uuid="918270fe-25c8-4a9b-a872-91299cddbc31"> <printWhenExpression><![CDATA[$P{displayRecordNumber}]]></printWhenExpression> <jr:columnHeader style="table_CH" height="30" rowSpan="1"> <staticText> <reportElement x="0" y="0" width="90" height="30" uuid="5cd6da41-01d5-4f74-99c2-06784f891d1e"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <text><![CDATA[Record number]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table_TD" height="30" rowSpan="1"> <textField> <reportElement x="0" y="0" width="90" height="30" uuid="5fe48359-0e7e-44b2-93ac-f55404189832"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$V{REPORT_COUNT}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> <jr:column width="90" uuid="7979d8a2-4e3c-42a7-9ff9-86f8e0b164bc"> <jr:columnHeader style="table_CH" height="30" rowSpan="1"> <staticText> <reportElement x="0" y="0" width="90" height="30" uuid="61d5f1b6-7677-4511-a10c-1fb8a56a4b2a"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <text><![CDATA[Username]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table_TD" height="30" rowSpan="1"> <textField> <reportElement x="0" y="0" width="90" height="30" uuid="a3cdb99d-3bf6-4c66-b50c-259b9aabfaef"/> <box leftPadding="3" rightPadding="3"/> <textElement verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{User}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> <jr:column width="90" uuid="625e4e5e-5057-4eab-b4a9-c5b22844d25c"> <jr:columnHeader style="table_CH" height="30" rowSpan="1"> <staticText> <reportElement x="0" y="0" width="90" height="30" uuid="e1c07cb8-a44c-4a8d-8566-5c86d6671282"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <text><![CDATA[Reputation]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table_TD" height="30" rowSpan="1"> <textField pattern="#,##0"> <reportElement x="0" y="0" width="90" height="30" uuid="6be2d79f-be82-4c7b-afd9-0039fb8b3189"/> <box leftPadding="3" rightPadding="3"/> <textElement textAlignment="Right" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{Rep}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> </jr:table> </componentElement> </band> </title> </jasperReport> ``` **Output with $P{displayRecordNumber}=true** [![true](https://i.stack.imgur.com/B4Lwv.png)](https://i.stack.imgur.com/B4Lwv.png) **Output with $P{displayRecordNumber}=false** [![false](https://i.stack.imgur.com/UsUo9.png)](https://i.stack.imgur.com/UsUo9.png) *As you can see the columns adapts nicely on the basis of which are displayed.*
116,074
<p>I just started using SVN, and I have a cache directory that I don't need under source control. How can I ignore the whole directory/folder with SVN?</p> <p>I am using <a href="https://en.wikipedia.org/wiki/Comparison_of_Subversion_clients#Standalone_Subversion_clients_comparison_table" rel="noreferrer">Versions</a> and <a href="http://en.wikipedia.org/wiki/TextMate" rel="noreferrer">TextMate</a> on OS&nbsp;X and commandline.</p>
[ { "answer_id": 116075, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 11, "selected": true, "text": "<p>Set the <code>svn:ignore</code> property of the parent directory:</p>\n\n<pre><code>svn propset svn:ignore dirname .\...
2008/09/22
[ "https://Stackoverflow.com/questions/116074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6305/" ]
I just started using SVN, and I have a cache directory that I don't need under source control. How can I ignore the whole directory/folder with SVN? I am using [Versions](https://en.wikipedia.org/wiki/Comparison_of_Subversion_clients#Standalone_Subversion_clients_comparison_table) and [TextMate](http://en.wikipedia.org/wiki/TextMate) on OS X and commandline.
Set the `svn:ignore` property of the parent directory: ``` svn propset svn:ignore dirname . ``` If you have multiple things to ignore, separate by newlines in the property value. In that case it's easier to edit the property value using an external editor: ``` svn propedit svn:ignore . ```
116,090
<p>I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code. </p> <p>Does any one have any straight-forward code for killing a process using vb.net or c#?</p>
[ { "answer_id": 116098, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 8, "selected": true, "text": "<p>You'll want to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx\" rel=\...
2008/09/22
[ "https://Stackoverflow.com/questions/116090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13337/" ]
I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code. Does any one have any straight-forward code for killing a process using vb.net or c#?
You'll want to use the [System.Diagnostics.Process.Kill](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx) method. You can obtain the process you want using [System.Diagnostics.Proccess.GetProcessesByName](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx). Examples have already been posted here, but I found that the non-.exe version worked better, so something like: ``` foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") ) { try { p.Kill(); p.WaitForExit(); // possibly with a timeout } catch ( Win32Exception winException ) { // process was terminating or can't be terminated - deal with it } catch ( InvalidOperationException invalidException ) { // process has already exited - might be able to let this one go } } ``` You probably don't have to deal with `NotSupportedException`, which suggests that the process is remote.
116,140
<p>I've got several AssemblyInfo.cs files as part of many projects in a single solution that I'm building automatically as part of TeamCity.</p> <p>To make the msbuild script more maintainable I'd like to be able to use the AssemblyInfo community task in conjunction with an ItemGroup e.g.</p> <pre><code>&lt;ItemGroup&gt; &lt;AllAssemblyInfos Include="..\**\AssemblyInfo.cs" /&gt; &lt;/ItemGroup&gt; &lt;AssemblyInfo AssemblyTitle="" AssemblyProduct="$(Product)" AssemblyCompany="$(Company)" AssemblyCopyright="$(Copyright)" ComVisible="false" CLSCompliant="false" CodeLanguage="CS" AssemblyDescription="$(Revision)$(BranchName)" AssemblyVersion="$(FullVersion)" AssemblyFileVersion="$(FullVersion)" OutputFile="@(AllAssemblyInfos)" /&gt; </code></pre> <p>Which blatently doesn't work because OutputFile cannot be a referenced ItemGroup.</p> <p>Anyone know how to make this work?</p>
[ { "answer_id": 116182, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 4, "selected": false, "text": "<p>We use \"linked\" files in project.\nSolution Explorer -> Add Existin Item -> .. select_file .. -> arrow_on_left_of_add_bu...
2008/09/22
[ "https://Stackoverflow.com/questions/116140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5777/" ]
I've got several AssemblyInfo.cs files as part of many projects in a single solution that I'm building automatically as part of TeamCity. To make the msbuild script more maintainable I'd like to be able to use the AssemblyInfo community task in conjunction with an ItemGroup e.g. ``` <ItemGroup> <AllAssemblyInfos Include="..\**\AssemblyInfo.cs" /> </ItemGroup> <AssemblyInfo AssemblyTitle="" AssemblyProduct="$(Product)" AssemblyCompany="$(Company)" AssemblyCopyright="$(Copyright)" ComVisible="false" CLSCompliant="false" CodeLanguage="CS" AssemblyDescription="$(Revision)$(BranchName)" AssemblyVersion="$(FullVersion)" AssemblyFileVersion="$(FullVersion)" OutputFile="@(AllAssemblyInfos)" /> ``` Which blatently doesn't work because OutputFile cannot be a referenced ItemGroup. Anyone know how to make this work?
Try changing the @ to a % as below ``` <ItemGroup> <AllAssemblyInfos Include="..\**\AssemblyInfo.cs" /> </ItemGroup> <AssemblyInfo AssemblyTitle="" AssemblyProduct="$(Product)" AssemblyCompany="$(Company)" AssemblyCopyright="$(Copyright)" ComVisible="false" CLSCompliant="false" CodeLanguage="CS" AssemblyDescription="$(Revision)$(BranchName)" AssemblyVersion="$(FullVersion)" AssemblyFileVersion="$(FullVersion)" OutputFile="%(AllAssemblyInfos)" /> ``` This creates a call for every entry in AllAssemblyInfos. Have a look at this article too, should help. <http://blogs.msdn.com/aaronhallberg/archive/2006/09/05/msbuild-batching-generating-a-cross-product.aspx>
116,154
<p>I would like to have something like this:</p> <pre><code>class Foo { private: int bar; public: void setBar(int bar); int getBar() const; } class MyDialog : public CDialogImpl&lt;MyDialog&gt; { BEGIN_MODEL_MAPPING() MAP_INT_EDITOR(m_editBar, m_model, getBar, setBar); END_MODEL_MAPPING() // other methods and message map private: Foo * m_model; CEdit m_editBar; } </code></pre> <p>Also it would be great if I could provide my custom validations:</p> <pre><code>MAP_VALIDATED_INT_EDITOR(m_editBar, m_model, getBar, setBar, validateBar) ... bool validateBar (int value) { // custom validation } </code></pre> <p>Have anybody seen something like this?</p> <p>P.S. I don't like DDX because it's old and it's not flexible, and I cannot use getters and setters.</p>
[ { "answer_id": 120133, "author": "vog", "author_id": 19163, "author_profile": "https://Stackoverflow.com/users/19163", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaBindings/CocoaBindings.html\" rel=\"nofollow n...
2008/09/22
[ "https://Stackoverflow.com/questions/116154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14535/" ]
I would like to have something like this: ``` class Foo { private: int bar; public: void setBar(int bar); int getBar() const; } class MyDialog : public CDialogImpl<MyDialog> { BEGIN_MODEL_MAPPING() MAP_INT_EDITOR(m_editBar, m_model, getBar, setBar); END_MODEL_MAPPING() // other methods and message map private: Foo * m_model; CEdit m_editBar; } ``` Also it would be great if I could provide my custom validations: ``` MAP_VALIDATED_INT_EDITOR(m_editBar, m_model, getBar, setBar, validateBar) ... bool validateBar (int value) { // custom validation } ``` Have anybody seen something like this? P.S. I don't like DDX because it's old and it's not flexible, and I cannot use getters and setters.
The DDX map is just a series of `if` statements, so you can easily write your own DDX macro. ``` #define DDX_MAP_VALIDATED_INT_EDITOR(control, variable, getter, setter, validator)\ if(nCtlID==control.GetDlgCtrlID())\ {\ if(bSaveAndValidate)\ {\ int const value=control.GetDlgItemInt();\ if(validator(value))\ {\ variable->setter(value);\ }\ else\ {\ return false;\ }\ }\ else\ {\ control.SetDlgItemInt(variable->getter());\ }\ } ``` This is untested, but should work as per your example, if you put it in the DDX map. It should give you the idea. Of course you could extract this into a function, which is what the standard DDX macros do: they just do the outer `if` and then call a function. This would allow you to overload the function for different types of the `variable` (e.g. pointer vs reference/value)
116,163
<p>I have a paradox table from a legacy system I need to run a single query on. The field names have spaces in them - i.e. "Street 1". When I try and formulate a query in delphi for only the "Street 1" field, I get an error - Invalid use of keyword. Token: 1, Line Number: 1</p> <p>Delphi V7 - object pascal, standard Tquery object name query1.</p>
[ { "answer_id": 116257, "author": "Jeremy Mullin", "author_id": 7893, "author_profile": "https://Stackoverflow.com/users/7893", "pm_score": 2, "selected": false, "text": "<p>You normally need to quote the field name in this case. For example:</p>\n\n<p>select * from t1 where \"street 1\" ...
2008/09/22
[ "https://Stackoverflow.com/questions/116163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a paradox table from a legacy system I need to run a single query on. The field names have spaces in them - i.e. "Street 1". When I try and formulate a query in delphi for only the "Street 1" field, I get an error - Invalid use of keyword. Token: 1, Line Number: 1 Delphi V7 - object pascal, standard Tquery object name query1.
You need to prefix the string with the table name in the query. For example: field name is 'Street 1', table is called customers the select is: ``` SELECT customers."Street 1" FROM customers WHERE ... ```
116,188
<p>I need to do the following for the purposes of paging a query in nHibernate:</p> <pre><code>Select count(*) from (Select e.ID,e.Name from Object as e where...) </code></pre> <p>I have tried the following, </p> <pre><code>select count(*) from Object e where e = (Select distinct e.ID,e.Name from ...) </code></pre> <p>and I get an nHibernate Exception saying I cannot convert Object to int32.</p> <p>Any ideas on the required syntax?</p> <p><strong>EDIT</strong></p> <p>The Subquery uses a distinct clause, I cannot replace the e.ID,e.Name with <code>Count(*)</code> because <code>Count(*) distinct</code> is not a valid syntax, and <code>distinct count(*)</code> is meaningless.</p>
[ { "answer_id": 116285, "author": "user8456", "author_id": 8456, "author_profile": "https://Stackoverflow.com/users/8456", "pm_score": 0, "selected": false, "text": "<p>If you just need <code>e.Id</code>,<code>e.Name</code>:</p>\n\n<p><code>select count(*) from Object where</code>.....</p...
2008/09/22
[ "https://Stackoverflow.com/questions/116188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14833/" ]
I need to do the following for the purposes of paging a query in nHibernate: ``` Select count(*) from (Select e.ID,e.Name from Object as e where...) ``` I have tried the following, ``` select count(*) from Object e where e = (Select distinct e.ID,e.Name from ...) ``` and I get an nHibernate Exception saying I cannot convert Object to int32. Any ideas on the required syntax? **EDIT** The Subquery uses a distinct clause, I cannot replace the e.ID,e.Name with `Count(*)` because `Count(*) distinct` is not a valid syntax, and `distinct count(*)` is meaningless.
``` var session = GetSession(); var criteria = session.CreateCriteria(typeof(Order)) .Add(Restrictions.Eq("Product", product)) .SetProjection(Projections.CountDistinct("Price")); return (int) criteria.UniqueResult(); ```
116,276
<p>I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class.</p> <p>Two Questions:</p> <ol> <li><p>I can't seem to get the input loop to work out, what's the best practice for doing so.</p></li> <li><p>What is the object-type going to be for the reading method? A double[], or an ArrayList?</p> <ol> <li><p>How do I declare method-type to be an arraylist?</p></li> <li><p>How do I prevent the array from having more than 1000 values stored within it?</p></li> </ol></li> </ol> <p>Let me show what I have so far:</p> <pre><code>public static java.util.ArrayList readRange(double end_signal){ //read in the range and stop at end_signal ArrayList input = new ArrayList(); Scanner kbd = new Scanner( System.in ); int count = 0; do{ input.add(kbd.nextDouble()); System.out.println(input); //debugging ++count; } while(input(--count) != end_signal); return input; } </code></pre> <p>Any help would be appreciated, pardon my newbieness...</p>
[ { "answer_id": 116283, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 3, "selected": false, "text": "<p>What you need in your loop condition is:</p>\n\n<pre><code>while ( input.get( input.size()-1 ) != end_signal );\n</co...
2008/09/22
[ "https://Stackoverflow.com/questions/116276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10636/" ]
I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class. Two Questions: 1. I can't seem to get the input loop to work out, what's the best practice for doing so. 2. What is the object-type going to be for the reading method? A double[], or an ArrayList? 1. How do I declare method-type to be an arraylist? 2. How do I prevent the array from having more than 1000 values stored within it? Let me show what I have so far: ``` public static java.util.ArrayList readRange(double end_signal){ //read in the range and stop at end_signal ArrayList input = new ArrayList(); Scanner kbd = new Scanner( System.in ); int count = 0; do{ input.add(kbd.nextDouble()); System.out.println(input); //debugging ++count; } while(input(--count) != end_signal); return input; } ``` Any help would be appreciated, pardon my newbieness...
Answers: *>1. I can't seem to get the input loop to work out, what's the best practice for doing so.* I would rather have a simple while loop instead of a do{}while... and place the condition in the while... In my example it read: *while the read number is not end signal and count is lower than limit: do.* *>2. What is the object-type going to be for the reading method? A double[], or an ArrayList?* An ArrayList, however I would strongly recommend you to use List ( java.util.List ) interface instead. It is a good OO practice to program to the interface rather to the implementation. *>2.1How do I declare method-type to be an arraylist?* See code below. *>2.2. How do I prevent the array from having more than 1000 values stored within it?* By adding this restriction in the while condition. ``` import java.util.Scanner; import java.util.List; import java.util.ArrayList; public class InputTest{ private int INPUT_LIMIT = 10000; public static void main( String [] args ) { InputTest test = new InputTest(); System.out.println("Start typing numbers..."); List list = test.readRange( 2.0 ); System.out.println("The input was " + list ); } /** * Read from the standar input until endSignal number is typed. * Also limits the amount of entered numbers to 10000; * @return a list with the numbers. */ public List readRange( double endSignal ) { List<Double> input = new ArrayList<Double>(); Scanner kdb = new Scanner( System.in ); int count = 0; double number = 0; while( ( number = kdb.nextDouble() ) != endSignal && count < INPUT_LIMIT ){ System.out.println( number ); input.add( number ); } return input; } } ``` Final remarks: It is preferred to have "instance methods" than class methods. This way if needed the "readRange" could be handled by a subclass without having to change the signature, thus In the sample I've removed the "static" keyword an create an instance of "InputTest" class In java code style the variable names should go in cammel case like in "endSignal" rather than "end\_signal"
116,289
<p>I have VB6 application , I want to put some good error handling finction in it which can tell me what was the error and exact place when it happened , can anyone suggest the good way to do this </p>
[ { "answer_id": 116312, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 5, "selected": false, "text": "<p>First of all, go get <a href=\"http://www.mztools.com/v3/mztools3.aspx\" rel=\"noreferrer\">MZTools for Visual Basi...
2008/09/22
[ "https://Stackoverflow.com/questions/116289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14299/" ]
I have VB6 application , I want to put some good error handling finction in it which can tell me what was the error and exact place when it happened , can anyone suggest the good way to do this
ON ERROR GOTO and the ``` Err ``` object. There is a tutorial [here](http://web.archive.org/web/20171020040908/http://www.vb6.us:80/tutorials/error-handling).
116,402
<p>I was given a task to display when a record in the database was added, however the previous developers never made a field for this, and I can't go back and make up dates for all the existing records. Is there an easy way to extract out a record Creation date from a <code>SQL server 2000</code> query. </p> <pre><code>SELECT RECORD_CREATED_DATE FROM tblSomething WHERE idField = 1 </code></pre> <p>The <code>RECORD_CREATED_DATE</code> isn't a field in the existing table. Is there some sort of SQL Function to get this information ?</p>
[ { "answer_id": 116407, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": true, "text": "<p>If it's not stored as a field, the info is <em>lost</em> after the transaction log recycles (typically daily), and m...
2008/09/22
[ "https://Stackoverflow.com/questions/116402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893/" ]
I was given a task to display when a record in the database was added, however the previous developers never made a field for this, and I can't go back and make up dates for all the existing records. Is there an easy way to extract out a record Creation date from a `SQL server 2000` query. ``` SELECT RECORD_CREATED_DATE FROM tblSomething WHERE idField = 1 ``` The `RECORD_CREATED_DATE` isn't a field in the existing table. Is there some sort of SQL Function to get this information ?
If it's not stored as a field, the info is *lost* after the transaction log recycles (typically daily), and maybe even sooner.
116,403
<p>Let's say I have a string holding a mess of text and (x)HTML tags. I want to remove all instances of a given tag (and any attributes of that tag), leaving all other tags and text along. What's the best Regex to get this done?</p> <p>Edited to add: Oh, I appreciate that using a Regex for this particular issue is not the best solution. However, for the sake of discussion can we assume that that particular technical decision was made a few levels over my pay grade? ;)</p>
[ { "answer_id": 116417, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 5, "selected": true, "text": "<p>Attempting to parse HTML with regular expressions is generally an <em>extremely</em> bad idea. Use a parser instead, there s...
2008/09/22
[ "https://Stackoverflow.com/questions/116403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
Let's say I have a string holding a mess of text and (x)HTML tags. I want to remove all instances of a given tag (and any attributes of that tag), leaving all other tags and text along. What's the best Regex to get this done? Edited to add: Oh, I appreciate that using a Regex for this particular issue is not the best solution. However, for the sake of discussion can we assume that that particular technical decision was made a few levels over my pay grade? ;)
Attempting to parse HTML with regular expressions is generally an *extremely* bad idea. Use a parser instead, there should be one available for your chosen language. You **might** be able to get away with something like this: ``` </?tag[^>]*?> ``` But it depends on exactly what you're doing. For example, that won't remove the tag's content, and it may leave your HTML in an invalid state, depending on which tag you're trying to remove. It also copes badly with invalid HTML (and there's a lot of that about). Use a parser instead :)
116,423
<p>I've been reading a little about temporary tables in MySQL but I'm an admitted newbie when it comes to databases in general and MySQL in particular. I've looked at some examples and the MySQL documentation on how to create a temporary table, but I'm trying to determine just how temporary tables might benefit my applications and I guess secondly what sorts of issues I can run into. Granted, each situation is different, but I guess what I'm looking for is some general advice on the topic.</p> <p>I did a little googling but didn't find exactly what I was looking for on the topic. If you have any experience with this, I'd love to hear about it.</p> <p>Thanks, Matt</p>
[ { "answer_id": 116443, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": 1, "selected": false, "text": "<p>I've used them in the past when I needed to create evaluated data. That was before the time of views and sub selec...
2008/09/22
[ "https://Stackoverflow.com/questions/116423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7862/" ]
I've been reading a little about temporary tables in MySQL but I'm an admitted newbie when it comes to databases in general and MySQL in particular. I've looked at some examples and the MySQL documentation on how to create a temporary table, but I'm trying to determine just how temporary tables might benefit my applications and I guess secondly what sorts of issues I can run into. Granted, each situation is different, but I guess what I'm looking for is some general advice on the topic. I did a little googling but didn't find exactly what I was looking for on the topic. If you have any experience with this, I'd love to hear about it. Thanks, Matt
Temporary tables are often valuable when you have a fairly complicated SELECT you want to perform and then perform a bunch of queries on that... You can do something like: ``` CREATE TEMPORARY TABLE myTopCustomers SELECT customers.*,count(*) num from customers join purchases using(customerID) join items using(itemID) GROUP BY customers.ID HAVING num > 10; ``` And then do a bunch of queries against myTopCustomers without having to do the joins to purchases and items on each query. Then when your application no longer needs the database handle, no cleanup needs to be done. Almost always you'll see temporary tables used for derived tables that were expensive to create.