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
147,468
<p><a href="https://pmd.github.io/" rel="noreferrer">PMD</a> would report a violation for:</p> <pre><code>ArrayList&lt;Object&gt; list = new ArrayList&lt;Object&gt;(); </code></pre> <p>The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead".</p> <p>The following line would correct the violation:</p> <pre><code>List&lt;Object&gt; list = new ArrayList&lt;Object&gt;(); </code></pre> <p>Why should the latter with <code>List</code> be used instead of <code>ArrayList</code>?</p>
[ { "answer_id": 147472, "author": "AdamC", "author_id": 16476, "author_profile": "https://Stackoverflow.com/users/16476", "pm_score": 5, "selected": false, "text": "<p>This is preferred because you decouple your code from the implementation of the list. Using the interface lets you easil...
2008/09/29
[ "https://Stackoverflow.com/questions/147468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22807/" ]
[PMD](https://pmd.github.io/) would report a violation for: ``` ArrayList<Object> list = new ArrayList<Object>(); ``` The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead". The following line would correct the violation: ``` List<Object> list = new ArrayList<Object>(); ``` Why should the latter with `List` be used instead of `ArrayList`?
Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code. It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implementation if needed in the future. Here's a [good article](http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html) on the subject. Hope it helps!
147,486
<p>Given the following XML structure</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt; &lt;span&gt;Test: Text2&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;span&gt;Test: Text3&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;span&gt;Test: Text5&lt;/span&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What is the best XPath query to locate any <code>span</code> with text that starts with <code>Test</code>?</p>
[ { "answer_id": 147497, "author": "A. Rex", "author_id": 3508, "author_profile": "https://Stackoverflow.com/users/3508", "pm_score": 6, "selected": true, "text": "<pre><code>//span[starts-with(.,'Test')]\n</code></pre>\n\n<p><br>References:</p>\n\n<p><a href=\"http://www.w3.org/TR/xpath/#...
2008/09/29
[ "https://Stackoverflow.com/questions/147486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10673/" ]
Given the following XML structure ``` <html> <body> <div> <span>Test: Text2</span> </div> <div> <span>Test: Text3</span> </div> <div> <span>Test: Text5</span> </div> </body> </html> ``` What is the best XPath query to locate any `span` with text that starts with `Test`?
``` //span[starts-with(.,'Test')] ``` References: <http://www.w3.org/TR/xpath/#function-starts-with> <https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/starts-with>
147,491
<p>I have the function below ENCRYPT.</p> <pre><code>Public Function Encrypt(ByVal plainText As String) As Byte() Dim key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} Dim iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219} ' Declare a UTF8Encoding object so we may use the GetByte ' method to transform the plainText into a Byte array. Dim utf8encoder As UTF8Encoding = New UTF8Encoding() Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText) ' Create a new TripleDES service provider Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() ' The ICryptTransform interface uses the TripleDES ' crypt provider along with encryption key and init vector ' information Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv) ' All cryptographic functions need a stream to output the ' encrypted information. Here we declare a memory stream ' for this purpose. Dim encryptedStream As MemoryStream = New MemoryStream() Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write) ' Write the encrypted information to the stream. Flush the information ' when done to ensure everything is out of the buffer. cryptStream.Write(inputInBytes, 0, inputInBytes.Length) cryptStream.FlushFinalBlock() encryptedStream.Position = 0 ' Read the stream back into a Byte array and return it to the calling ' method. Dim result(encryptedStream.Length - 1) As Byte encryptedStream.Read(result, 0, encryptedStream.Length) cryptStream.Close() Return result End Function </code></pre> <p>How do i see the byte value of the text?</p>
[ { "answer_id": 147502, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx\" rel=\"nofollow noreferrer\">Encodin...
2008/09/29
[ "https://Stackoverflow.com/questions/147491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
I have the function below ENCRYPT. ``` Public Function Encrypt(ByVal plainText As String) As Byte() Dim key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} Dim iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219} ' Declare a UTF8Encoding object so we may use the GetByte ' method to transform the plainText into a Byte array. Dim utf8encoder As UTF8Encoding = New UTF8Encoding() Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText) ' Create a new TripleDES service provider Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() ' The ICryptTransform interface uses the TripleDES ' crypt provider along with encryption key and init vector ' information Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv) ' All cryptographic functions need a stream to output the ' encrypted information. Here we declare a memory stream ' for this purpose. Dim encryptedStream As MemoryStream = New MemoryStream() Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write) ' Write the encrypted information to the stream. Flush the information ' when done to ensure everything is out of the buffer. cryptStream.Write(inputInBytes, 0, inputInBytes.Length) cryptStream.FlushFinalBlock() encryptedStream.Position = 0 ' Read the stream back into a Byte array and return it to the calling ' method. Dim result(encryptedStream.Length - 1) As Byte encryptedStream.Read(result, 0, encryptedStream.Length) cryptStream.Close() Return result End Function ``` How do i see the byte value of the text?
You can use [Encoding](http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx) class. To convert array of bytes to a string you can use [Encoding.GetString](http://msdn.microsoft.com/en-us/library/system.text.encoding.getstring.aspx) method There is a special version for UTF8: [UTF8Encoding.GetString](http://msdn.microsoft.com/en-us/library/system.text.utf8encoding.getstring.aspx)
147,500
<p>Is it possible to include one CSS file in another?</p>
[ { "answer_id": 147508, "author": "Kevin Read", "author_id": 23303, "author_profile": "https://Stackoverflow.com/users/23303", "pm_score": 11, "selected": true, "text": "<p>Yes:</p>\n\n<pre><code>@import url(\"base.css\");\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li>The <a href=\"https://...
2008/09/29
[ "https://Stackoverflow.com/questions/147500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460927/" ]
Is it possible to include one CSS file in another?
Yes: ``` @import url("base.css"); ``` Note: * The [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) rule [must precede](https://drafts.csswg.org/css-cascade-3/#at-import) all other rules (except `@charset`). * Additional `@import` statements require additional server requests. As an alternative, concatenate all CSS into one file to avoid multiple HTTP requests. For example, copy the contents of `base.css` and `special.css` into `base-special.css` and reference only `base-special.css`.
147,505
<p>I am trying to get a Flex application to communicate with a custom python webserver I have developed. </p> <p>I am noticing that I cannot read the postdata received because Flex does not seem to include the Content-Length in the HTTP headers. (My webserver work when posted to from plain HTML)</p> <p>Is this a known problem? any ideas how to set the content-length header? </p> <p>Here is the current headers being sent:</p> <pre> Host: localhost:7070 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0 .3 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive </pre>
[ { "answer_id": 147540, "author": "A. Rex", "author_id": 3508, "author_profile": "https://Stackoverflow.com/users/3508", "pm_score": 0, "selected": false, "text": "<p>I don't believe this is a known problem.</p>\n\n<p>Are you sure no Content-Length is being sent? You've posted the reques...
2008/09/29
[ "https://Stackoverflow.com/questions/147505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I am trying to get a Flex application to communicate with a custom python webserver I have developed. I am noticing that I cannot read the postdata received because Flex does not seem to include the Content-Length in the HTTP headers. (My webserver work when posted to from plain HTML) Is this a known problem? any ideas how to set the content-length header? Here is the current headers being sent: ``` Host: localhost:7070 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0 .3 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive ```
It should, so long as you set your HTTPService's method property to POST. If you omit it, it will default to GET, and the parameters will be sent as part of the query string, not as POST data. I set up this scenario using this Flex code: ``` <?xml version="1.0" encoding="utf-8"?> <mx:Application layout="absolute" xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()"> <mx:HTTPService id="service" url="http://localhost:8000/" method="POST" resultFormat="text" result="response.htmlText=ResultEvent(event).result.toString()"/> <mx:Text id="response" width="100%" height="100%"/> <mx:Script> <![CDATA[ import mx.rpc.events.ResultEvent; private function init() : void { service.send({ foo: "Fred", bar: "Barney" }); } ]]> </mx:Script> </mx:Application> ``` And this python server code: ``` #!/usr/bin/env python import SimpleHTTPServer, BaseHTTPServer, string class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_POST(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write("<html><body>") self.wfile.write("<b>METHOD:</b> " + self.command) # Write out Headers header_keys = self.headers.dict.keys() for key in header_keys: self.wfile.write("<br><b>" + key + "</b>: ") self.wfile.write(self.headers.dict[key]) # Write out any POST data if self.headers.dict.has_key("content-length"): content_length = string.atoi(self.headers.dict["content-length"]) raw_post_data = self.rfile.read(content_length) self.wfile.write("<br><b>Post Data:</b> " + raw_post_data) self.wfile.write("</body></html>") def do_GET(self): self.do_POST() try: BaseHTTPServer.test(MyHandler, BaseHTTPServer.HTTPServer) except KeyboardInterrupt: print 'Exiting...' ``` And got this result: ``` METHOD: POST content-length: 19 accept-language: en-us,en;q=0.5 accept-encoding: gzip,deflate connection: keep-alive keep-alive: 300 accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 user-agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1 accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 host: 10.0.7.61:8000 content-type: application/x-www-form-urlencoded Post Data: bar=Barney&foo=Fred ``` So it should work.
147,507
<p>Given a string with a module name, how do you import everything in the module as if you had called:</p> <pre><code>from module import * </code></pre> <p>i.e. given string S="module", how does one get the equivalent of the following:</p> <pre><code>__import__(S, fromlist="*") </code></pre> <p>This doesn't seem to perform as expected (as it doesn't import anything).</p>
[ { "answer_id": 147541, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 6, "selected": true, "text": "<p>Please reconsider. The only thing worse than <code>import *</code> is <em>magic</em> <code>import *</code>.</p>\n\n<...
2008/09/29
[ "https://Stackoverflow.com/questions/147507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
Given a string with a module name, how do you import everything in the module as if you had called: ``` from module import * ``` i.e. given string S="module", how does one get the equivalent of the following: ``` __import__(S, fromlist="*") ``` This doesn't seem to perform as expected (as it doesn't import anything).
Please reconsider. The only thing worse than `import *` is *magic* `import *`. If you really want to: ``` m = __import__ (S) try: attrlist = m.__all__ except AttributeError: attrlist = dir (m) for attr in attrlist: globals()[attr] = getattr (m, attr) ```
147,515
<p>How do you calculate the least common multiple of multiple numbers?</p> <p>So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers.</p> <p>So far this is how I did it </p> <pre><code>LCM = num1 * num2 / gcd ( num1 , num2 ) </code></pre> <p>With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm</p> <p>But I can't figure out how to calculate it for 3 or more numbers.</p>
[ { "answer_id": 147523, "author": "A. Rex", "author_id": 3508, "author_profile": "https://Stackoverflow.com/users/3508", "pm_score": 9, "selected": true, "text": "<p>You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e.</p>\n\n<pre><code>lc...
2008/09/29
[ "https://Stackoverflow.com/questions/147515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2976/" ]
How do you calculate the least common multiple of multiple numbers? So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers. So far this is how I did it ``` LCM = num1 * num2 / gcd ( num1 , num2 ) ``` With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm But I can't figure out how to calculate it for 3 or more numbers.
You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e. ``` lcm(a,b,c) = lcm(a,lcm(b,c)) ```
147,528
<p>In the markup shown below, I'm trying to get the content div to stretch all the way to the bottom of the page but it's only stretching if there's content to display. The reason I want to do this is so the vertical border still appears down the page even if there isn't any content to display.</p> <p>Here is my <strong>DEMO</strong>:</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-css lang-css prettyprint-override"><code>body { font-family: Trebuchet MS, Verdana, MS Sans Serif; font-size:0.9em; margin:0; padding:0; } div#header { width: 100%; height: 100px; } #header a { background-position: 100px 30px; background: transparent url(site-style-images/sitelogo.jpg) no-repeat fixed 100px 30px; height: 80px; display: block; } #header, #menuwrapper { background-repeat: repeat; background-image: url(site-style-images/darkblue_background_color.jpg); } #menu #menuwrapper { height:25px; } div#menuwrapper { width:100% } #menu, #content { width:1024px; margin: 0 auto; } div#menu { height: 25px; background-color:#50657a; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form id="form1"&gt; &lt;div id="header"&gt; &lt;a title="Home" href="index.html" /&gt; &lt;/div&gt; &lt;div id="menuwrapper"&gt; &lt;div id="menu"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="content"&gt; &lt;/div&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 147537, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": false, "text": "<p>you can kinda hack it with the <a href=\"http://www.w3schools.com/CSS/pr_dim_min-height.asp\" rel=\"noreferrer\">min-height<...
2008/09/29
[ "https://Stackoverflow.com/questions/147528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
In the markup shown below, I'm trying to get the content div to stretch all the way to the bottom of the page but it's only stretching if there's content to display. The reason I want to do this is so the vertical border still appears down the page even if there isn't any content to display. Here is my **DEMO**: ```css body { font-family: Trebuchet MS, Verdana, MS Sans Serif; font-size:0.9em; margin:0; padding:0; } div#header { width: 100%; height: 100px; } #header a { background-position: 100px 30px; background: transparent url(site-style-images/sitelogo.jpg) no-repeat fixed 100px 30px; height: 80px; display: block; } #header, #menuwrapper { background-repeat: repeat; background-image: url(site-style-images/darkblue_background_color.jpg); } #menu #menuwrapper { height:25px; } div#menuwrapper { width:100% } #menu, #content { width:1024px; margin: 0 auto; } div#menu { height: 25px; background-color:#50657a; } ``` ```html <form id="form1"> <div id="header"> <a title="Home" href="index.html" /> </div> <div id="menuwrapper"> <div id="menu"> </div> </div> <div id="content"> </div> </form> ```
Your problem is not that the div is not at 100% height, but that the container around it is not.This will help in the browser I suspect you are using: ``` html,body { height:100%; } ``` You may need to adjust padding and margins as well, but this will get you 90% of the way there.If you need to make it work with all browsers you will have to mess around with it a bit. This site has some excellent examples: <http://www.brunildo.org/test/html_body_0.html> <http://www.brunildo.org/test/html_body_11b.html> <http://www.brunildo.org/test/index.html> I also recommend going to <http://quirksmode.org/>
147,557
<p>I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#.</p> <p>In my C++ source I can write</p> <p>LOGERR("Some error"); or LOGERR("Error with inputs %s and %d", stringvar, intvar);</p> <p>The macro &amp; supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user.</p> <p>Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging?</p> <p><strong>Edit:</strong> At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)</p>
[ { "answer_id": 147574, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 3, "selected": false, "text": "<p>Even though I personally hate it, <a href=\"http://logging.apache.org/log4net/index.html\" rel=\"nofollow noreferre...
2008/09/29
[ "https://Stackoverflow.com/questions/147557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6188/" ]
I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#. In my C++ source I can write LOGERR("Some error"); or LOGERR("Error with inputs %s and %d", stringvar, intvar); The macro & supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user. Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging? **Edit:** At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)
Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference: ``` System.Diagnostics.Trace ``` This includes listeners that listen for your `Trace()` methods, and then write to a log file/output window/event log, ones in the framework that are included are `DefaultTraceListener`, `TextWriterTraceListener` and the `EventLogTraceListener`. It allows you to specify levels (Warning,Error,Info) and categories. [Trace class on MSDN](http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.aspx) [Writing to the Event Log in a Web Application](https://stackoverflow.com/questions/286060/what-do-i-need-to-change-to-alllow-my-iis7-asp-net-3-5-application-to-create-an/7848414#7848414) [UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console](http://www.anotherchris.net/log4net/udptracelistener-a-udp-tracelistener-compatible-with-log4netlog4j/)
147,572
<pre><code>class someclass {}; class base { int a; int *pint; someclass objsomeclass; someclass* psomeclass; public: base() { objsomeclass = someclass(); psomeclass = new someclass(); pint = new int(); throw "constructor failed"; a = 43; } } int main() { base temp(); } </code></pre> <p>In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?</p> <pre><code>int main() { base *temp = new base(); } </code></pre> <p>How about in the above code? How can the memory leaks be avoided after the constructor throws?</p>
[ { "answer_id": 147578, "author": "Colen", "author_id": 13500, "author_profile": "https://Stackoverflow.com/users/13500", "pm_score": -1, "selected": false, "text": "<p>Everything you \"new\" needs to be deleted, or you'll cause a memory leak. So these two lines:</p>\n\n<pre><code>psomecl...
2008/09/29
[ "https://Stackoverflow.com/questions/147572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
``` class someclass {}; class base { int a; int *pint; someclass objsomeclass; someclass* psomeclass; public: base() { objsomeclass = someclass(); psomeclass = new someclass(); pint = new int(); throw "constructor failed"; a = 43; } } int main() { base temp(); } ``` In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided? ``` int main() { base *temp = new base(); } ``` How about in the above code? How can the memory leaks be avoided after the constructor throws?
Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don't show a destructor that frees the dynamically allocated objects, but lets assume you had one). This is a major reason to use smart pointers - since the smart poitners are full fledged objects, they will get destructors called during the exception's stack unwind and have the opportunity to free the memory. If you use something like Boost's scoped\_ptr<> template, your class could look more like: ``` class base{ int a; scoped_ptr<int> pint; someclass objsomeclass; scoped_ptr<someclass> psomeclass; base() : pint( new int), objsomeclass( someclass()), psomeclass( new someclass()) { throw "constructor failed"; a = 43; } } ``` And you would have no memory leaks (and the default dtor would also clean up the dynamic memory allocations). --- To sum up (and hopefully this also answers the question about the ``` base* temp = new base(); ``` statement): When an exception is thrown inside a constructor there are several things that you should take note of in terms of properly handling resource allocations that may have occured in the aborted construction of the object: 1. the destructor for the object being constructed will **not** be called. 2. destructors for member objects contained in that object's class will be called 3. the memory for the object that was being constructed will be freed. This means that if your object owns resources, you have 2 methods available to clean up those resources that might have already been acquired when the constructor throws: 1. catch the exception, release the resources, then rethrow. This can be difficult to get correct and can become a maintenance problem. 2. use objects to manage the resource lifetimes (RAII) and use those objects as the members. When the constructor for your object throws an exception, the member objects will have desctructors called and will have an opportunity to free the resource whose lifetimes they are responsible for.
147,626
<p>in Javascript, the following:</p> <pre><code>var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/".*?"/g); alert(result); </code></pre> <p>yields "the quick","brown fox","jumps over","the lazy dog"</p> <p>I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog</p> <p>what regexp will do this?</p>
[ { "answer_id": 147644, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<p>You can use the <a href=\"http://www.w3schools.com/jsref/jsref_replace.asp\" rel=\"nofollow noreferrer\">Javascript repla...
2008/09/29
[ "https://Stackoverflow.com/questions/147626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11397/" ]
in Javascript, the following: ``` var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/".*?"/g); alert(result); ``` yields "the quick","brown fox","jumps over","the lazy dog" I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog what regexp will do this?
This seems to work: ``` var test = '"the quick" "brown fox" "jumps over" "the lazy dog"'; var result = test.match(/[^"]+(?=(" ")|"$)/g); alert(result); ``` Note: This doesn't match empty elements (i.e. ""). Also, it won't work in browsers that don't support JavaScript 1.5 (lookaheads are a 1.5 feature). See <http://www.javascriptkit.com/javatutors/redev2.shtml> for more info.
147,646
<p>What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading. </p> <p>What is the best way to achieve this?</p>
[ { "answer_id": 147656, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 7, "selected": true, "text": "<p>There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing prima...
2008/09/29
[ "https://Stackoverflow.com/questions/147646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9107/" ]
What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading. What is the best way to achieve this?
There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than). However; if you just want it to work, then in .NET 3.5 there are some options... I have put together a library [here](http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html) that allows efficient and simple access to operators with generics - such as: ``` T result = Operator.Add(first, second); // implicit <T>; here ``` It can be downloaded as part of [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/) Additionally, in C# 4.0, this becomes possible via `dynamic`: ``` static T Add<T>(T x, T y) { dynamic dx = x, dy = y; return dx + dy; } ``` I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as ``` interface ICalc<T> { T Add(T,T)() T Subtract(T,T)() } ``` etc, but then you need to pass an `ICalc<T>;` through all the methods, which gets messy.
147,649
<p>I am using a very intrinsic database with a CakePHP application and so far my multi-models views and controllers are working fine. I have a singular table (<code>Entity</code>) that have it's <code>id</code> on several other tables as the Foreign Key <code>entity_id</code></p> <p>Some tables are one to one relations (Like a <code>Company</code> is one <code>Entity</code>) and some are one to many (<code>Entity</code> can have several <code>Addresses</code>) and so on.</p> <p><em>I won't/can't change the database model</em>, so this is the structure.</p> <p>I have been using <code>saveAll()</code> to save data on those tables with input names like:</p> <pre><code>Entity.type='x' (hidden inside the view) Company.name Address.0.street Address.0.city Address.1.street Address.1.city ... and so on ... </code></pre> <p>and my save all is doing all the hard job, <code>BEGIN TRANSACTION</code>, all <code>INSERT</code>s and a final <code>COMMIT</code> ...</p> <p>But now I've created a <code>EntityCategory</code> that is a n to n relation and created the full <code>HABTM</code> relation inside the model.</p> <p>It works when I <code>save()</code> it but just the <code>HABTM</code> relation, and it saves everthing when I use <code>saveAll()</code> (just as before) except for the <code>HABTM</code> relation.</p> <p>Am I missing something ? How I make this work correctly ? I am using the following code today:</p> <pre><code>if (!empty($this-&gt;data)) { $this-&gt;Entity-&gt;saveAll($this-&gt;data); $this-&gt;Entity-&gt;save($this-&gt;data); } </code></pre> <p>The <code>saveAll()</code> saves all data in several tables, saves the id in <code>Entity-&gt;id</code> and the <code>save()</code> saves the <code>HABTM</code> relations, but I am not sure if it is correct or if it can bring me problems if I change some structure/model.</p> <p>Is this the best way to use it? Is there a <em>correct</em> way to save that relations inside CakePHP ? What your experience/knowledge can tell me ?</p>
[ { "answer_id": 147788, "author": "Jacob", "author_id": 22107, "author_profile": "https://Stackoverflow.com/users/22107", "pm_score": 0, "selected": false, "text": "<p>The problem with saveAll() and HABTM associations is a known CakePHP <a href=\"https://trac.cakephp.org/ticket/4389\" rel...
2008/09/29
[ "https://Stackoverflow.com/questions/147649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
I am using a very intrinsic database with a CakePHP application and so far my multi-models views and controllers are working fine. I have a singular table (`Entity`) that have it's `id` on several other tables as the Foreign Key `entity_id` Some tables are one to one relations (Like a `Company` is one `Entity`) and some are one to many (`Entity` can have several `Addresses`) and so on. *I won't/can't change the database model*, so this is the structure. I have been using `saveAll()` to save data on those tables with input names like: ``` Entity.type='x' (hidden inside the view) Company.name Address.0.street Address.0.city Address.1.street Address.1.city ... and so on ... ``` and my save all is doing all the hard job, `BEGIN TRANSACTION`, all `INSERT`s and a final `COMMIT` ... But now I've created a `EntityCategory` that is a n to n relation and created the full `HABTM` relation inside the model. It works when I `save()` it but just the `HABTM` relation, and it saves everthing when I use `saveAll()` (just as before) except for the `HABTM` relation. Am I missing something ? How I make this work correctly ? I am using the following code today: ``` if (!empty($this->data)) { $this->Entity->saveAll($this->data); $this->Entity->save($this->data); } ``` The `saveAll()` saves all data in several tables, saves the id in `Entity->id` and the `save()` saves the `HABTM` relations, but I am not sure if it is correct or if it can bring me problems if I change some structure/model. Is this the best way to use it? Is there a *correct* way to save that relations inside CakePHP ? What your experience/knowledge can tell me ?
This is fixed if you download the [nightly](http://cakephp.org/downloads/index/nightly/1.2.x.x). Be careful though, something else might break.
147,657
<p>According to MSDN </p> <pre><code>form.RightToLeftLayout = True; form.RightToLeft = ifWeWantRTL() ? RightToLeft.True : RightToLeft.False; </code></pre> <p>is enough to mirrow the form content for RTL languages.</p> <p>But controls placement gets mirrowed only for controls immediately on the form,<br> those inside a GroupBox or a Panel <strong>are not mirrowed</strong>, unless I put them on a TableLayoutPanel or a FlowLayoutPanel fisrt.</p> <p>This is a lot of manual work to place a TableLayoutPanel inside each GroupBox, and especially to rearrange the controls (one control per table cell, padding, margin, etc)</p> <p>Is there an easier way to make mirrowing work for all controls? </p> <p>Or at least, how can I bypass the rearranging step, for it is quite a task with our number of forms?</p> <hr> <p><strong>Edit</strong>: RightToLeft property for each control on the form by default is inherited,<br> so Panels and GroupBoxes always have the needed RightToLeft setting.<br> Nevertheless, I tryed to reassign it for them both programmatically and from designer, it did not help.</p>
[ { "answer_id": 148001, "author": "eugensk", "author_id": 17495, "author_profile": "https://Stackoverflow.com/users/17495", "pm_score": 1, "selected": false, "text": "<p>According to the article \n<a href=\"http://www.microsoft.com/middleeast/msdn/WinFormsAndArabic.aspx#_Toc136842131\" re...
2008/09/29
[ "https://Stackoverflow.com/questions/147657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17495/" ]
According to MSDN ``` form.RightToLeftLayout = True; form.RightToLeft = ifWeWantRTL() ? RightToLeft.True : RightToLeft.False; ``` is enough to mirrow the form content for RTL languages. But controls placement gets mirrowed only for controls immediately on the form, those inside a GroupBox or a Panel **are not mirrowed**, unless I put them on a TableLayoutPanel or a FlowLayoutPanel fisrt. This is a lot of manual work to place a TableLayoutPanel inside each GroupBox, and especially to rearrange the controls (one control per table cell, padding, margin, etc) Is there an easier way to make mirrowing work for all controls? Or at least, how can I bypass the rearranging step, for it is quite a task with our number of forms? --- **Edit**: RightToLeft property for each control on the form by default is inherited, so Panels and GroupBoxes always have the needed RightToLeft setting. Nevertheless, I tryed to reassign it for them both programmatically and from designer, it did not help.
It does seen that you have quite a nasty problem on your hands. Have played with it for a while and come up with the following: Making use of a little recursion you can run though all the controls and do the manaul RTL conversion for those controls trapped in Pannels and GroupBoxes. This is a *quick* little mock of code that I slapped together. I would suggest you put this in your BaseForm (heres hoping you have one of these) and call on base form load. ``` private void SetRTL (bool setRTL) { ApplyRTL(setRTL, this); } private void ApplyRTL(bool yes, Control startControl) { if ((startControl is Panel ) || (startControl is GroupBox)) { foreach (Control control in startControl.Controls) { control.Location = CalculateRTL(control.Location, startControl.Size, control.Size); } } foreach (Control control in startControl.Controls) ApplyRTL(yes, control); } private Point CalculateRTL (Point currentPoint, Size parentSize, Size currentSize) { return new Point(parentSize.Width - currentSize.Width - currentPoint.X, currentPoint.Y); } ```
147,659
<p>How can I get the list of available databases on a SQL Server instance? I'm planning to make a list of them in a combo box in VB.NET.</p>
[ { "answer_id": 147662, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 11, "selected": true, "text": "<p>Execute: </p>\n\n<p><code>SELECT name FROM master.sys.databases</code> </p>\n\n<p>This the preferred approach now, ...
2008/09/29
[ "https://Stackoverflow.com/questions/147659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
How can I get the list of available databases on a SQL Server instance? I'm planning to make a list of them in a combo box in VB.NET.
Execute: `SELECT name FROM master.sys.databases` This the preferred approach now, rather than `dbo.sysdatabases`, which has been deprecated for some time. --- Execute this query: ``` SELECT name FROM master.dbo.sysdatabases ``` or if you prefer ``` EXEC sp_databases ```
147,669
<p>I've got a c# assembly which I'm invoking via COM from a Delphi (win32 native) application.</p> <p>This works on all the machines I've tested it on, except one.</p> <p>The problem is that the Delphi application gets "Class not registered" when trying to create the COM object.</p> <p>Now, when I look in the registry under <code>HKEY_CLASSES_ROOT\DelphiToCSharp\CLSID</code>, the GUID listed there is not the same as the assembly Guid in AssemblyInfo.cs. It should be the same - it IS the same on all the other computers where it's installed.</p> <p>I have tried <code>regasm /unregister delphitocsharp.dll</code>, and that removes the registry key. Then if I do <code>regasm delphitocsharp.dll</code>, the registry key returns, but the GUID is the same as before (ie. wrong), and Delphi still gets "Class not registered".</p> <p>DelphiToCSharp.dll on the working machine is identical (verified with md5) to the version on the non-working machine.</p> <p>All I can think of is that an old version of the dll was registered before, and there still exists some remnant of that file which is making regasm confused.</p> <p>How can I fix or at least further diagnose this issue?</p>
[ { "answer_id": 147730, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>Maybe you have an old version of the assembly somewhere? Maybe in the GAC? Regasm is probably picking that up an...
2008/09/29
[ "https://Stackoverflow.com/questions/147669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
I've got a c# assembly which I'm invoking via COM from a Delphi (win32 native) application. This works on all the machines I've tested it on, except one. The problem is that the Delphi application gets "Class not registered" when trying to create the COM object. Now, when I look in the registry under `HKEY_CLASSES_ROOT\DelphiToCSharp\CLSID`, the GUID listed there is not the same as the assembly Guid in AssemblyInfo.cs. It should be the same - it IS the same on all the other computers where it's installed. I have tried `regasm /unregister delphitocsharp.dll`, and that removes the registry key. Then if I do `regasm delphitocsharp.dll`, the registry key returns, but the GUID is the same as before (ie. wrong), and Delphi still gets "Class not registered". DelphiToCSharp.dll on the working machine is identical (verified with md5) to the version on the non-working machine. All I can think of is that an old version of the dll was registered before, and there still exists some remnant of that file which is making regasm confused. How can I fix or at least further diagnose this issue?
The GUID in AssemblyInfo becomes the "Type-Library" GUID and usually is not what you'd be looking for. I'm going to assume you're trying to access a class, and you need to define a Guid attribute and ComVisible for the class. For example: ``` [Guid("00001111-2222-3333-4444-555566667777"), ComVisible(true)] public class MyCOMRegisteredClass ``` If you don't, then the class either a) won't be registered, or b) if you've defined COMVisible(true) at the assembly level, will be assigned a guid that .NET bakes up for you.
147,670
<p>How can I extract the list of available SQL servers in an SQL server group? I'm planning to put that list in a combo box in VB.NET.</p>
[ { "answer_id": 147680, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 4, "selected": true, "text": "<p>The only way I knew to do it was using the command line:</p>\n\n<pre><code>osql -L\n</code></pre>\n\n<p>But I found ...
2008/09/29
[ "https://Stackoverflow.com/questions/147670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
How can I extract the list of available SQL servers in an SQL server group? I'm planning to put that list in a combo box in VB.NET.
The only way I knew to do it was using the command line: ``` osql -L ``` But I found the below article which seems to solve your specific goal filling a combobox: <http://www.sqldbatips.com/showarticle.asp?ID=45>
147,684
<p>I have a page which is largely created by DOM script, which generates a table of images (normal img elements) from several webcams (helping out a friend with a pet boarding and my HTML/DOM is a bit rusty).</p> <p>It works fine in FF3 or Chrome, but not in IE7, In fact, the whole table is not visible in IE (but the body background-color is applied).</p> <p>Looking at the page in IE, there are no script errors, the CSS appears to be applied OK, and the DOM appears to show all the cells and rows in the table, which are all generated.</p> <p>Using the IE Developer Toolbar, running the Image report even shows the images (even though they don't appear in the table and there is no evidence of the table in the page as rendered - even the text in the cells isn't rendered)</p> <p>In looking at the img elements and using the trace style feature, at one time, I saw that the img elements all had display : none, and it said inline style, but there's nothing in my code or stylesheet which does this. That problem appears to have gone away as I started to add explicit entries for every table element in my stylesheet.</p> <p>Where to start?</p> <pre><code>body { background-color : gray ; color : white ; margin : 0 ; font-family : Verdana, "lucida console", arial, sans-serif ; } #CameraPreviewParent { text-align : center ; width : 100% ; } #CameraTable { text-align : center ; width : 100% ; } #CameraLiveParent { text-align : center ; margin : 50px ; } #CameraLiveHeading { color : white ; } td.CameraCell { text-align : center ; } img.CameraImage { border : none ; } a:link, a:visited, a:active, a:hover { text-decoration : none ; color : inherit ; } table#CameraTable { color : white ; background-color : gray ; } td.CameraCell { color : white ; background-color : gray ; } </code></pre> <p>Removing the stylesheet completely has no effect.</p> <p>Here's the code of the page after generation (I apologize for the formatting from the DOM toolbar - I've tried to put in some linefeeds to make it easier to read):</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML Strict//EN"&gt;&lt;META http-equiv="Content-Type" content="text/html; charset=windows-1252"&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;&lt;/TITLE&gt; &lt;SCRIPT src="cameras.js" type="text/javascript"&gt; &lt;/SCRIPT&gt; &lt;SCRIPT type="text/javascript"&gt; function CallOnLoad() { document.title = PreviewPageTitle ; BuildPreview(document.getElementById("CameraPreviewParent")) ; } &lt;/SCRIPT&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;!-- Any HTML can go here to modify page content/layout --&gt; &lt;DIV id="CameraPreviewParent"&gt; &lt;TABLE id="CameraTable" class="CameraTable"&gt; &lt;TR id="CameraRow0" class="CameraRow"&gt; &lt;TD id="CameraCell0" class="CameraCell"&gt;&lt;A id="CameraNameLink0" href="http://192.168.4.3:801" class="CameraNameLink"&gt;Luxury Suite 1 (1)&lt;/A&gt;&lt;BR /&gt;&lt;A id="CameraLink0" href="camlive.html?camIndex=0" class="CameraLink"&gt;&lt;IMG id="CameraImage0" title="Click For Live Video from Luxury Suite 1 (1)" height="0" alt="Click For Live Video from Luxury Suite 1 (1)" src="http://192.168.4.3:801/IMAGE.JPG" width="0" class="CameraImage" /&gt;&lt;/A&gt;&lt;/TD&gt; &lt;TD id="CameraCell1" class="CameraCell"&gt;&lt;A id="CameraNameLink1" href="http://192.168.4.3:802" class="CameraNameLink"&gt;Luxury Suite 2 (2)&lt;/A&gt;&lt;BR /&gt;&lt;A id="CameraLink1" href="camlive.html?camIndex=1" class="CameraLink"&gt;&lt;IMG id="CameraImage1" title="Click For Live Video from Luxury Suite 2 (2)" height="0" alt="Click For Live Video from Luxury Suite 2 (2)" src="http://192.168.4.3:802/IMAGE.JPG" width="0" class="CameraImage" /&gt;&lt;/A&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; &lt;/DIV&gt;&lt;!-- This element is used to hold the preview --&gt; &lt;!-- Any HTML can go here to modify page content/layout --&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>Apparently the DOM code which inserts with width and height of the images is not working right in IE:</p> <pre><code>var PhotoWidth = 320 ; var PhotoHeight = 240 ; var image = document.createElement("img") ; image.setAttribute("id", "CameraImage" + camIndex) ; image.setAttribute("class", "CameraImage") ; image.setAttribute("src", thisCam.ImageURL()) ; image.setAttribute("width", PhotoWidth) ; image.setAttribute("height", PhotoHeight) ; image.setAttribute("alt", thisCam.PreviewAction()) ; image.setAttribute("title", thisCam.PreviewAction()) ; link.appendChild(image) ; </code></pre> <p><strong>The response about the require TBODY element when dynamically building tables appears to be the entire problem - this appears to even set the image width and height to 0 in the DOM!</strong></p>
[ { "answer_id": 147690, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>The gotcha that always gets me is IE's mishandling of the <code>&lt;script&gt;</code> tag when it's used like <code>&l...
2008/09/29
[ "https://Stackoverflow.com/questions/147684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18255/" ]
I have a page which is largely created by DOM script, which generates a table of images (normal img elements) from several webcams (helping out a friend with a pet boarding and my HTML/DOM is a bit rusty). It works fine in FF3 or Chrome, but not in IE7, In fact, the whole table is not visible in IE (but the body background-color is applied). Looking at the page in IE, there are no script errors, the CSS appears to be applied OK, and the DOM appears to show all the cells and rows in the table, which are all generated. Using the IE Developer Toolbar, running the Image report even shows the images (even though they don't appear in the table and there is no evidence of the table in the page as rendered - even the text in the cells isn't rendered) In looking at the img elements and using the trace style feature, at one time, I saw that the img elements all had display : none, and it said inline style, but there's nothing in my code or stylesheet which does this. That problem appears to have gone away as I started to add explicit entries for every table element in my stylesheet. Where to start? ``` body { background-color : gray ; color : white ; margin : 0 ; font-family : Verdana, "lucida console", arial, sans-serif ; } #CameraPreviewParent { text-align : center ; width : 100% ; } #CameraTable { text-align : center ; width : 100% ; } #CameraLiveParent { text-align : center ; margin : 50px ; } #CameraLiveHeading { color : white ; } td.CameraCell { text-align : center ; } img.CameraImage { border : none ; } a:link, a:visited, a:active, a:hover { text-decoration : none ; color : inherit ; } table#CameraTable { color : white ; background-color : gray ; } td.CameraCell { color : white ; background-color : gray ; } ``` Removing the stylesheet completely has no effect. Here's the code of the page after generation (I apologize for the formatting from the DOM toolbar - I've tried to put in some linefeeds to make it easier to read): ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML Strict//EN"><META http-equiv="Content-Type" content="text/html; charset=windows-1252"> <HTML> <HEAD> <TITLE></TITLE> <SCRIPT src="cameras.js" type="text/javascript"> </SCRIPT> <SCRIPT type="text/javascript"> function CallOnLoad() { document.title = PreviewPageTitle ; BuildPreview(document.getElementById("CameraPreviewParent")) ; } </SCRIPT> </HEAD> <BODY> <!-- Any HTML can go here to modify page content/layout --> <DIV id="CameraPreviewParent"> <TABLE id="CameraTable" class="CameraTable"> <TR id="CameraRow0" class="CameraRow"> <TD id="CameraCell0" class="CameraCell"><A id="CameraNameLink0" href="http://192.168.4.3:801" class="CameraNameLink">Luxury Suite 1 (1)</A><BR /><A id="CameraLink0" href="camlive.html?camIndex=0" class="CameraLink"><IMG id="CameraImage0" title="Click For Live Video from Luxury Suite 1 (1)" height="0" alt="Click For Live Video from Luxury Suite 1 (1)" src="http://192.168.4.3:801/IMAGE.JPG" width="0" class="CameraImage" /></A></TD> <TD id="CameraCell1" class="CameraCell"><A id="CameraNameLink1" href="http://192.168.4.3:802" class="CameraNameLink">Luxury Suite 2 (2)</A><BR /><A id="CameraLink1" href="camlive.html?camIndex=1" class="CameraLink"><IMG id="CameraImage1" title="Click For Live Video from Luxury Suite 2 (2)" height="0" alt="Click For Live Video from Luxury Suite 2 (2)" src="http://192.168.4.3:802/IMAGE.JPG" width="0" class="CameraImage" /></A></TD> </TR> </TABLE> </DIV><!-- This element is used to hold the preview --> <!-- Any HTML can go here to modify page content/layout --> </BODY> </HTML> ``` Apparently the DOM code which inserts with width and height of the images is not working right in IE: ``` var PhotoWidth = 320 ; var PhotoHeight = 240 ; var image = document.createElement("img") ; image.setAttribute("id", "CameraImage" + camIndex) ; image.setAttribute("class", "CameraImage") ; image.setAttribute("src", thisCam.ImageURL()) ; image.setAttribute("width", PhotoWidth) ; image.setAttribute("height", PhotoHeight) ; image.setAttribute("alt", thisCam.PreviewAction()) ; image.setAttribute("title", thisCam.PreviewAction()) ; link.appendChild(image) ; ``` **The response about the require TBODY element when dynamically building tables appears to be the entire problem - this appears to even set the image width and height to 0 in the DOM!**
One gotcha I found is that in IE, if you dynamically create tables using `document.createElement()`, you need `table(tbody(tr(tds)))`. Without a `tbody`, the table will not show.
147,703
<p>I have a generic list, i.e. <code>List&lt;myclass&gt;</code>. Here <code>myclass</code> contains two string properties. </p> <p>How can I assign a datasource to the list collection?</p>
[ { "answer_id": 147717, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>You got it the other way around. Databound objects like grids and the like could set generic lists as their data source....
2008/09/29
[ "https://Stackoverflow.com/questions/147703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a generic list, i.e. `List<myclass>`. Here `myclass` contains two string properties. How can I assign a datasource to the list collection?
Mirmal, I guess English is not your first language, this question is not very clear. I think that what you are asking is given a list of your class how do you then bind that list to something (a listbox or combobox etc) Here is a simple code snippet of how to do this... ``` private void button2_Click(object sender, EventArgs e) { List<MyClass> list = new List<MyClass>(); list.Add(new MyClass() { FirstName = "Tim", Lastname = "Jarvis"}); list.Add(new MyClass() { FirstName = "John", Lastname = "Doe" }); listBox1.DataSource = list; listBox1.DisplayMember = "FirstName"; // or override MyClass's ToString() method. } ``` I hope this has answered your question.
147,713
<p>In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:</p> <pre><code>unsigned long value = 0xdeadbeef; value &amp;= ~(1&lt;&lt;10); </code></pre> <p>How do I do that in Python ?</p>
[ { "answer_id": 147716, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<pre><code>value = 0xdeadbeef\nvalue &amp;= ~(1&lt;&lt;10)\n</code></pre>\n" }, { "answer_id": 147718, "autho...
2008/09/29
[ "https://Stackoverflow.com/questions/147713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16144/" ]
In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so: ``` unsigned long value = 0xdeadbeef; value &= ~(1<<10); ``` How do I do that in Python ?
Bitwise operations on Python ints work much like in C. The `&`, `|` and `^` operators in Python work just like in C. The `~` operator works as for a signed integer in C; that is, `~x` computes `-x-1`. You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain the low order bits. For example, to do the equivalent of shift of a 32-bit integer do `(x << 5) & 0xffffffff`.
147,714
<p>I would like to refer HTML templates designed/developed especially for form based Web Applications.</p> <p>I have been searching them but am not able to find out which I find better.</p> <p>Regards, Jatan</p>
[ { "answer_id": 147770, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 1, "selected": false, "text": "<p>Here are a few catalogs of template designs:</p>\n\n<ul>\n<li><a href=\"http://www.opendesigns.org/\" rel=\"nofoll...
2008/09/29
[ "https://Stackoverflow.com/questions/147714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/959/" ]
I would like to refer HTML templates designed/developed especially for form based Web Applications. I have been searching them but am not able to find out which I find better. Regards, Jatan
Much of the choice in this sort of thing is going to be defined by your choice of server tech / platform, e.g. .NET has in built widgets you can use, as do many web application frameworks. The django admin layouts are extremely well designed, you could download [Django](http://www.djangoproject.com/) and check it out. Similar forms are also implemented for Rails by the [Streamlined framwork](http://streamlinedframework.org/), not to mention the inbuilt scaffolding generators. Tthe YUI framework has a bunch of different widgets with a consistent style, as does the ExtJS framework, and are server technology agnostic. These can be dynamically created using json as the data source, rather than html/xml You could also use a CSS framework such as BlueprintCSS, and combine it with the suggested HTML, and add effects + interactions with jQuery, and build that on top of your html. Modifying an existing layout is not too hard, for a simple CRUD application you probably just need a large area for forms and lists/tables and a menu. If you need anything more particular than that, its probably time to invest in a design, or learn to do it yourself. The simplest possible layout is going to be a header with a menu inside (& maybe a heading), and a content area for your forms. --- ``` <style type="text/css" media="screen"> div#page { width:900px; margin:0; auto; } </style> <body> <div id="page"> <div id="header"> <!-- Menu Goes Here! --> </div> <div id="content"> <!-- Put some Forms n stuff here --> </div> </div> </body> ```
147,719
<p>Is there a Delphi equivalent of the C# #if(DEBUG) compiler directive?</p>
[ { "answer_id": 147725, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 6, "selected": true, "text": "<p>Use this:</p>\n\n<pre><code>{$IFDEF DEBUG}\n...\n{$ENDIF}\n</code></pre>\n" }, { "answer_id": 147855, "...
2008/09/29
[ "https://Stackoverflow.com/questions/147719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
Is there a Delphi equivalent of the C# #if(DEBUG) compiler directive?
Use this: ``` {$IFDEF DEBUG} ... {$ENDIF} ```
147,741
<p>In a text file, there is a string "I don't like this".</p> <p>However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use </p> <pre><code>f1 = open (file1, "r") text = f1.read() </code></pre> <p>command to do the reading.</p> <p>Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?</p> <p>Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?</p>
[ { "answer_id": 147751, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "<p>Actually, U+2018 is the Unicode representation of the special character ‘ . If you want, you can convert instances ...
2008/09/29
[ "https://Stackoverflow.com/questions/147741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
In a text file, there is a string "I don't like this". However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use ``` f1 = open (file1, "r") text = f1.read() ``` command to do the reading. Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"? Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?
Ref: <http://docs.python.org/howto/unicode> *Reading Unicode from a file is therefore simple:* ``` import codecs with codecs.open('unicode.rst', encoding='utf-8') as f: for line in f: print repr(line) ``` *It's also possible to open files in update mode, allowing both reading and writing:* ``` with codecs.open('test', encoding='utf-8', mode='w+') as f: f.write(u'\u4500 blah blah blah\n') f.seek(0) print repr(f.readline()[:1]) ``` **EDIT**: I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII. If you're trying to convert to an ASCII string, try one of the following: 1. Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example 2. Use the `unicodedata` module's `normalize()` and the `string.encode()` method to convert as best you can to the next closest ASCII equivalent (Ref <https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python>): ``` >>> teststr u'I don\xe2\x80\x98t like this' >>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore') 'I donat like this' ```
147,747
<p>OK, probably best to give an example here of what I mean.</p> <p>Imagine a web based forum system, where the user authentication is done by some external method, which the system is aware of.</p> <p>Now, say for example, a user enters the URL for a thread that they do not have access to. For this should I return a 403 (Forbidden), letting the user know that they should try another authentication method, or a 404, not letting them know that there is something there to access.</p> <p>Assuming I return a 403, should I also return a 403 when they access a URL for a topic that doesn't exist yet?</p> <p>Edit: the example above was more of an example that something IRL.</p> <p>Another Example, say I expose something like</p> <pre><code>/adminnotes/user </code></pre> <p>if there are Administrator notes about the user. Now, returning a 403 would let the user know that there is something there being said about them. A 404 would say nothing.</p> <p>But, if I were to return a 403 - I could return it for adminnotes/* - which would resolve that issue.</p> <p>Edit 2: Another example. Soft deleted Questions here return a 404. Yet, with the right authentication and access, you can still see them (I'd presume)</p>
[ { "answer_id": 147754, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>No website in the world does what you are suggesting, so by this example we see that it is probably best to foll...
2008/09/29
[ "https://Stackoverflow.com/questions/147747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20010/" ]
OK, probably best to give an example here of what I mean. Imagine a web based forum system, where the user authentication is done by some external method, which the system is aware of. Now, say for example, a user enters the URL for a thread that they do not have access to. For this should I return a 403 (Forbidden), letting the user know that they should try another authentication method, or a 404, not letting them know that there is something there to access. Assuming I return a 403, should I also return a 403 when they access a URL for a topic that doesn't exist yet? Edit: the example above was more of an example that something IRL. Another Example, say I expose something like ``` /adminnotes/user ``` if there are Administrator notes about the user. Now, returning a 403 would let the user know that there is something there being said about them. A 404 would say nothing. But, if I were to return a 403 - I could return it for adminnotes/\* - which would resolve that issue. Edit 2: Another example. Soft deleted Questions here return a 404. Yet, with the right authentication and access, you can still see them (I'd presume)
Above everything else, **comply with HTTP spec.** Returning 403 in place of 404 is not a good thing. Returning 404 in place of 403 probably is ok (or not a big blunder), but I would just **let the software tell the truth**. If user only knows the ID of a topic, it's not much anyway. And he could try *timing attacks* to determine whether this topic exists.
147,752
<p>In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:</p> <pre><code>APPROVAL_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ('cancelled', 'Cancelled'), ) client_approved = models.CharField(choices=APPROVAL_CHOICES) </code></pre> <p>to create a drop down box in your form and force the user to choose one of those options.</p> <p>I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.</p>
[ { "answer_id": 147793, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 7, "selected": true, "text": "<p>In terms of the forms library, you would use the <a href=\"http://docs.djangoproject.com/en/dev/ref/forms/fields/#m...
2008/09/29
[ "https://Stackoverflow.com/questions/147752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23366/" ]
In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this: ``` APPROVAL_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ('cancelled', 'Cancelled'), ) client_approved = models.CharField(choices=APPROVAL_CHOICES) ``` to create a drop down box in your form and force the user to choose one of those options. I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.
In terms of the forms library, you would use the [MultipleChoiceField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#multiplechoicefield) field with a [CheckboxSelectMultiple](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxSelectMultiple) widget to do that. You could validate the number of choices which were made by writing a validation method for the field: ``` class MyForm(forms.Form): my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple()) def clean_my_field(self): if len(self.cleaned_data['my_field']) > 3: raise forms.ValidationError('Select no more than 3.') return self.cleaned_data['my_field'] ``` To get this in the admin application, you'd need to customise a ModelForm and [override the form used in the appropriate ModelAdmin](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin).
147,816
<p>Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.</p> <p>Here is an example:</p> <pre><code>def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) return g @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z &gt;&gt;&gt; funny_function("3", 4.0, z="5") 22 </code></pre> <p>Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function:</p> <pre><code>&gt;&gt;&gt; help(funny_function) Help on function g in module __main__: g(*args, **kwargs) </code></pre> <p>Fortunately, there is a workaround:</p> <pre><code>def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z </code></pre> <p>This time, the function name and documentation are correct:</p> <pre><code>&gt;&gt;&gt; help(funny_function) Help on function funny_function in module __main__: funny_function(*args, **kwargs) Computes x*y + 2*z </code></pre> <p>But there is still a problem: the function signature is wrong. The information "*args, **kwargs" is next to useless.</p> <p>What to do? I can think of two simple but flawed workarounds:</p> <p>1 -- Include the correct signature in the docstring:</p> <pre><code>def funny_function(x, y, z=3): """funny_function(x, y, z=3) -- computes x*y + 2*z""" return x*y + 2*z </code></pre> <p>This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [<i>And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny_function is just a random example.</i>]</p> <p>2 -- Not use a decorator, or use a special-purpose decorator for every specific signature:</p> <pre><code>def funny_functions_decorator(f): def g(x, y, z=3): return f(int(x), int(y), z=int(z)) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g </code></pre> <p>This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically.</p> <p>I'm looking for a solution that is fully general, and automatic.</p> <p>So the question is: is there a way to edit the decorated function signature after it has been created?</p> <p>Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "*kwargs, **kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec?</p> <p>Any other approaches?</p>
[ { "answer_id": 147835, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "<p>Take a look at the <a href=\"http://www.phyast.pitt.edu/~micheles/python/documentation.html\" rel=\"noreferrer\">decorator<...
2008/09/29
[ "https://Stackoverflow.com/questions/147816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1163767/" ]
Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc. Here is an example: ``` def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) return g @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z >>> funny_function("3", 4.0, z="5") 22 ``` Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function: ``` >>> help(funny_function) Help on function g in module __main__: g(*args, **kwargs) ``` Fortunately, there is a workaround: ``` def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z ``` This time, the function name and documentation are correct: ``` >>> help(funny_function) Help on function funny_function in module __main__: funny_function(*args, **kwargs) Computes x*y + 2*z ``` But there is still a problem: the function signature is wrong. The information "\*args, \*\*kwargs" is next to useless. What to do? I can think of two simple but flawed workarounds: 1 -- Include the correct signature in the docstring: ``` def funny_function(x, y, z=3): """funny_function(x, y, z=3) -- computes x*y + 2*z""" return x*y + 2*z ``` This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [*And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny\_function is just a random example.*] 2 -- Not use a decorator, or use a special-purpose decorator for every specific signature: ``` def funny_functions_decorator(f): def g(x, y, z=3): return f(int(x), int(y), z=int(z)) g.__name__ = f.__name__ g.__doc__ = f.__doc__ return g ``` This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically. I'm looking for a solution that is fully general, and automatic. So the question is: is there a way to edit the decorated function signature after it has been created? Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "\*kwargs, \*\*kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec? Any other approaches?
1. Install [decorator](http://www.phyast.pitt.edu/~micheles/python/documentation.html#the-solution) module: ``` $ pip install decorator ``` 2. Adapt definition of `args_as_ints()`: ``` import decorator @decorator.decorator def args_as_ints(f, *args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z print funny_function("3", 4.0, z="5") # 22 help(funny_function) # Help on function funny_function in module __main__: # # funny_function(x, y, z=3) # Computes x*y + 2*z ``` --- ### Python 3.4+ [`functools.wraps()` from stdlib](https://docs.python.org/3/library/functools.html#functools.wraps) preserves signatures since Python 3.4: ``` import functools def args_as_ints(func): @functools.wraps(func) def wrapper(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return func(*args, **kwargs) return wrapper @args_as_ints def funny_function(x, y, z=3): """Computes x*y + 2*z""" return x*y + 2*z print(funny_function("3", 4.0, z="5")) # 22 help(funny_function) # Help on function funny_function in module __main__: # # funny_function(x, y, z=3) # Computes x*y + 2*z ``` `functools.wraps()` is available [at least since Python 2.5](https://docs.python.org/2.5/lib/module-functools.html) but it does not preserve the signature there: ``` help(funny_function) # Help on function funny_function in module __main__: # # funny_function(*args, **kwargs) # Computes x*y + 2*z ``` Notice: `*args, **kwargs` instead of `x, y, z=3`.
147,824
<p>To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it would be for English or ASCII. Anyone has a clue?</p>
[ { "answer_id": 147854, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "<p>Why not let the window resize itself based on the runtime height/width?</p>\n\n<p>Run something like this in your pop-up:</...
2008/09/29
[ "https://Stackoverflow.com/questions/147824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23373/" ]
To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it would be for English or ASCII. Anyone has a clue?
JavaScript holds text internally as UCS-2, which can encode a fairly extensive subset of Unicode. But that's not really germane to your question. One solution might be to loop through the string and examine the character codes at each position: ``` function isDoubleByte(str) { for (var i = 0, n = str.length; i < n; i++) { if (str.charCodeAt( i ) > 255) { return true; } } return false; } ``` This might not be as fast as you would like.
147,837
<p>I am already excited about document databases and especially about CouchDB's simplicity. But I have a hard time understanding if such databases are a viable option for multi user systems. Since those systems require some kind of relations between records which document databases do not provide.</p> <p>Is it completely the wrong tool for such cases? Or some tagging and temporary views are the way to accomplish this? Or else...</p> <p>UPDATE:<br> I understand the answers so far. But let me rephrase the question a bit. Lets say I have a load of semi-structured data which is normally a fit for CouchDB. I can tag them like "type=post" and "year=2008". My question is how far can I go with this type of tagging? Say can I create an array field with 10.000 names in it? Or is there a better way of doing this? It is a matter of understanding how to think in this document based sense.</p>
[ { "answer_id": 147932, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 2, "selected": false, "text": "<p>Multi-user systems do not <em>require</em> relational databases, though RDBMSs are a staple technology for data st...
2008/09/29
[ "https://Stackoverflow.com/questions/147837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3812/" ]
I am already excited about document databases and especially about CouchDB's simplicity. But I have a hard time understanding if such databases are a viable option for multi user systems. Since those systems require some kind of relations between records which document databases do not provide. Is it completely the wrong tool for such cases? Or some tagging and temporary views are the way to accomplish this? Or else... UPDATE: I understand the answers so far. But let me rephrase the question a bit. Lets say I have a load of semi-structured data which is normally a fit for CouchDB. I can tag them like "type=post" and "year=2008". My question is how far can I go with this type of tagging? Say can I create an array field with 10.000 names in it? Or is there a better way of doing this? It is a matter of understanding how to think in this document based sense.
There was a discussion on the [mailing list](http://couchdb.markmail.org/search/?q=twitter%20follower#query:twitter%20follower+page:1+mid:l4ibup6xoftffvrs+state:results) awhile back that fits this question fairly well. The rule of thumb was to only store data in a document that is likely to change vs. grow. If the data is more likely to grow then you most likely want to store separate docs. So in the case of a multi-user system one way of implementing ACL based permissions could be to create 'permission docs' that would be a mapping of user\_id to doc\_id with the appropriate permission indicated. ``` { _id: "permission_doc_1", type: "acl", user: "John", docid: "John's Account Info", read: true, write: true } ``` And your views would be something along the lines of ``` function(doc) { emit([doc.user, doc.docid], {"read": doc.read, "write": doc.write}); } ``` And given a docid and userid, checking for permissions would be: ``` http://localhost:5984/db/_view/permissions/all?key=["John", "John's Account Info"] ``` Obviously, this would require having some intermediary between the client and couch to make sure permissions were enforced.
147,850
<p>I have the problem that an specific step in Ant can only be executed when we have Java 1.5 installed in the build computer. The task definition uses uses a jar file that was compiled using 1.5, so running with a 1.4 virtual machine will throw an IncompatibleClassVersion exception.</p> <p>I have to find a solution meanwhile to have this task working for this specific project that requires 1.4, but a question came to me. How can I avoid defining this task and executing this optional step if I don't have a specific java version?</p> <p>I could use the "if" or "unless" tags on the target tag, but those only check if a property is set or not. I also would like to have a solution that doesn't require extra libraries, but I don't know if the build-in functionality in standard is enough to perform such a task.</p>
[ { "answer_id": 147890, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 4, "selected": true, "text": "<p>The Java version is exposed via the <em>ant.java.version</em> property. Use a <em>condition</em> to set a property and exec...
2008/09/29
[ "https://Stackoverflow.com/questions/147850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309/" ]
I have the problem that an specific step in Ant can only be executed when we have Java 1.5 installed in the build computer. The task definition uses uses a jar file that was compiled using 1.5, so running with a 1.4 virtual machine will throw an IncompatibleClassVersion exception. I have to find a solution meanwhile to have this task working for this specific project that requires 1.4, but a question came to me. How can I avoid defining this task and executing this optional step if I don't have a specific java version? I could use the "if" or "unless" tags on the target tag, but those only check if a property is set or not. I also would like to have a solution that doesn't require extra libraries, but I don't know if the build-in functionality in standard is enough to perform such a task.
The Java version is exposed via the *ant.java.version* property. Use a *condition* to set a property and execute the task only if it is true. ``` <?xml version="1.0" encoding="UTF-8"?> <project name="project" default="default"> <target name="default" depends="javaCheck" if="isJava6"> <echo message="Hello, World!" /> </target> <target name="javaCheck"> <echo message="ant.java.version=${ant.java.version}" /> <condition property="isJava6"> <equals arg1="${ant.java.version}" arg2="1.6" /> </condition> </target> </project> ```
147,891
<p>In Firefox I can get the stack trace of an exception by using <code>exception.stack</code>.</p> <p>Is there a way to get that in other browsers, too?</p> <p><b>Edit:</b> I actually want to save the stack trace automatically (if possible) and not debug it at the time (i.e. I know how to get the stack trace in a debugger).</p>
[ { "answer_id": 147895, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 0, "selected": false, "text": "<p>Not really, at least not easily.</p>\n\n<p>In IE, you can debug the browser process with MS Script Debugger (which for some...
2008/09/29
[ "https://Stackoverflow.com/questions/147891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4936/" ]
In Firefox I can get the stack trace of an exception by using `exception.stack`. Is there a way to get that in other browsers, too? **Edit:** I actually want to save the stack trace automatically (if possible) and not debug it at the time (i.e. I know how to get the stack trace in a debugger).
Place this line where you want to print the stack trace: ``` console.log(new Error().stack); ``` **Note:** tested by me on **Chrome 24** and **Firefox 18** May be worth taking a look at [this tool](https://github.com/ebobby/tracing.js) as well.
147,897
<p>I want to generate some XML in a stored procedure based on data in a table.</p> <p>The following insert allows me to add many nodes but they have to be hard-coded or use variables (sql:variable):</p> <pre><code>SET @MyXml.modify(' insert &lt;myNode&gt; {sql:variable("@MyVariable")} &lt;/myNode&gt; into (/root[1]) ') </code></pre> <p>So I could loop through each record in my table, put the values I need into variables and execute the above statement.</p> <p>But is there a way I can do this by just combining with a select statement and avoiding the loop?</p> <p><strong>Edit</strong> I have used <code>SELECT FOR XML</code> to do similar stuff before but I always find it hard to read when working with a hierarchy of data from multiple tables. I was hoping there would be something using the <code>modify</code> where the XML generated is more explicit and more controllable.</p>
[ { "answer_id": 148113, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 0, "selected": false, "text": "<p>Can you tell a bit more about what exactly you are planning to do.\nIs it simply generating XML data based on a content o...
2008/09/29
[ "https://Stackoverflow.com/questions/147897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107/" ]
I want to generate some XML in a stored procedure based on data in a table. The following insert allows me to add many nodes but they have to be hard-coded or use variables (sql:variable): ``` SET @MyXml.modify(' insert <myNode> {sql:variable("@MyVariable")} </myNode> into (/root[1]) ') ``` So I could loop through each record in my table, put the values I need into variables and execute the above statement. But is there a way I can do this by just combining with a select statement and avoiding the loop? **Edit** I have used `SELECT FOR XML` to do similar stuff before but I always find it hard to read when working with a hierarchy of data from multiple tables. I was hoping there would be something using the `modify` where the XML generated is more explicit and more controllable.
Have you tried **nesting** FOR XML PATH scalar valued functions? With the nesting technique, you can brake your SQL into very managable/readable elemental pieces Disclaimer: the following, while adapted from a working example, has not itself been literally tested Some reference links for the general audience * <http://msdn2.microsoft.com/en-us/library/ms178107(SQL.90).aspx> * <http://msdn2.microsoft.com/en-us/library/ms189885(SQL.90).aspx> The simplest, lowest level nested node example Consider the following invocation ``` DECLARE @NestedInput_SpecificDogNameId int SET @NestedInput_SpecificDogNameId = 99 SELECT [dbo].[udfGetLowestLevelNestedNode_SpecificDogName] (@NestedInput_SpecificDogNameId) ``` Let's say had udfGetLowestLevelNestedNode\_SpecificDogName had been written without the FOR XML PATH clause, and for @NestedInput\_SpecificDogName = 99 it returns the single rowset record: ``` @SpecificDogNameId DogName 99 Astro ``` But with the FOR XML PATH clause, ``` CREATE FUNCTION dbo.udfGetLowestLevelNestedNode_SpecificDogName ( @NestedInput_SpecificDogNameId ) RETURNS XML AS BEGIN -- Declare the return variable here DECLARE @ResultVar XML -- Add the T-SQL statements to compute the return value here SET @ResultVar = ( SELECT @SpecificDogNameId as "@SpecificDogNameId", t.DogName FROM tblDogs t FOR XML PATH('Dog') ) -- Return the result of the function RETURN @ResultVar END ``` the user-defined function produces the following XML (the @ signs causes the SpecificDogNameId field to be returned as an attribute) ``` <Dog SpecificDogNameId=99>Astro</Dog> ``` Nesting User-defined Functions of XML Type User-defined functions such as the above udfGetLowestLevelNestedNode\_SpecificDogName can be nested to provide a powerful method to produce complex XML. For example, the function ``` CREATE FUNCTION [dbo].[udfGetDogCollectionNode]() RETURNS XML AS BEGIN -- Declare the return variable here DECLARE @ResultVar XML -- Add the T-SQL statements to compute the return value here SET @ResultVar = ( SELECT [dbo].[udfGetLowestLevelNestedNode_SpecificDogName] (t.SpecificDogNameId) FROM tblDogs t FOR XML PATH('DogCollection') ELEMENTS ) -- Return the result of the function RETURN @ResultVar END ``` when invoked as ``` SELECT [dbo].[udfGetDogCollectionNode]() ``` might produce the complex XML node (given the appropriate underlying data) ``` <DogCollection> <Dog SpecificDogNameId="88">Dino</Dog> <Dog SpecificDogNameId="99">Astro</Dog> </DogCollection> ``` From here, you could keep working upwards in the nested tree to build as complex an XML structure as you please ``` CREATE FUNCTION [dbo].[udfGetAnimalCollectionNode]() RETURNS XML AS BEGIN DECLARE @ResultVar XML SET @ResultVar = ( SELECT dbo.udfGetDogCollectionNode(), dbo.udfGetCatCollectionNode() FOR XML PATH('AnimalCollection'), ELEMENTS XSINIL ) RETURN @ResultVar END ``` when invoked as ``` SELECT [dbo].[udfGetAnimalCollectionNode]() ``` the udf might produce the more complex XML node (given the appropriate underlying data) ``` <AnimalCollection> <DogCollection> <Dog SpecificDogNameId="88">Dino</Dog> <Dog SpecificDogNameId="99">Astro</Dog> </DogCollection> <CatCollection> <Cat SpecificCatNameId="11">Sylvester</Cat> <Cat SpecificCatNameId="22">Tom</Cat> <Cat SpecificCatNameId="33">Felix</Cat> </CatCollection> </AnimalCollection> ```
147,908
<p>Under the View-Model-ViewModel pattern for WPF, I am trying to databind the Heights and Widths of various definitions for grid controls, so I can store the values the user sets them to after using a GridSplitter. However, the normal pattern doesn't seem to work for these particular properties.</p> <p><em>Note: I'm posting this as a reference question that I'm posting as Google failed me and I had to work this out myself. My own answer to follow.</em></p>
[ { "answer_id": 147928, "author": "Nidonocu", "author_id": 483, "author_profile": "https://Stackoverflow.com/users/483", "pm_score": 6, "selected": true, "text": "<p>There were a number of gotchas I discovered:</p>\n\n<ol>\n<li>Although it may appear like a double in XAML, the actual valu...
2008/09/29
[ "https://Stackoverflow.com/questions/147908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483/" ]
Under the View-Model-ViewModel pattern for WPF, I am trying to databind the Heights and Widths of various definitions for grid controls, so I can store the values the user sets them to after using a GridSplitter. However, the normal pattern doesn't seem to work for these particular properties. *Note: I'm posting this as a reference question that I'm posting as Google failed me and I had to work this out myself. My own answer to follow.*
There were a number of gotchas I discovered: 1. Although it may appear like a double in XAML, the actual value for a \*Definition's Height or Width is a 'GridLength' struct. 2. All the properties of GridLength are readonly, you have to create a new one each time you change it. 3. Unlike every other property in WPF, Width and Height don't default their databinding mode to 'TwoWay', you have to manually set this. Thusly, I used the following code: ``` private GridLength myHorizontalInputRegionSize = new GridLength(0, GridUnitType.Auto) public GridLength HorizontalInputRegionSize { get { // If not yet set, get the starting value from the DataModel if (myHorizontalInputRegionSize.IsAuto) myHorizontalInputRegionSize = new GridLength(ConnectionTabDefaultUIOptions.HorizontalInputRegionSize, GridUnitType.Pixel); return myHorizontalInputRegionSize; } set { myHorizontalInputRegionSize = value; if (ConnectionTabDefaultUIOptions.HorizontalInputRegionSize != myHorizontalInputRegionSize.Value) { // Set the value in the DataModel ConnectionTabDefaultUIOptions.HorizontalInputRegionSize = value.Value; } OnPropertyChanged("HorizontalInputRegionSize"); } } ``` And the XAML: ``` <Grid.RowDefinitions> <RowDefinition Height="*" MinHeight="100" /> <RowDefinition Height="Auto" /> <RowDefinition Height="{Binding Path=HorizontalInputRegionSize,Mode=TwoWay}" MinHeight="50" /> </Grid.RowDefinitions> ```
147,920
<p>I miss it so much (used it a lot in C#). can you do it in C++?</p>
[ { "answer_id": 147954, "author": "Matt Hanson", "author_id": 5473, "author_profile": "https://Stackoverflow.com/users/5473", "pm_score": 5, "selected": true, "text": "<p>Yes, you can. See <a href=\"http://msdn.microsoft.com/en-us/library/b6xkz944(VS.80).aspx\" rel=\"noreferrer\">here</a>...
2008/09/29
[ "https://Stackoverflow.com/questions/147920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18426/" ]
I miss it so much (used it a lot in C#). can you do it in C++?
Yes, you can. See [here](http://msdn.microsoft.com/en-us/library/b6xkz944(VS.80).aspx). ``` #pragma region Region_Name //Your content. #pragma endregion Region_Name ```
147,924
<p>Can share with me any of this script?</p>
[ { "answer_id": 147963, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "<p>The default one is called commit-email.pl and is included when you install Subversion. But <a href=\"http://blog.hungrymachi...
2008/09/29
[ "https://Stackoverflow.com/questions/147924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17147/" ]
Can share with me any of this script?
The default one is called commit-email.pl and is included when you install Subversion. But [here](http://blog.hungrymachine.com/2007/11/5/pretty-svn-commit-emails) is one in ruby: ``` #!/usr/bin/ruby -w # A Subversion post-commit hook. Edit the configurable stuff below, and # copy into your repository's hooks/ directory as "post-commit". Don't # forget to "chmod a+x post-commit". # ------------------------------------------------------------------------ # You *will* need to change these. address="FOO@SOME_DOMAIN.com" sendmail="/usr/sbin/sendmail" svnlook="/usr/bin/svnlook" # ------------------------------------------------------------------------ require 'cgi' # Subversion's commit-email.pl suggests that svnlook might create files. Dir.chdir("/tmp") # What revision in what repository? repo = ARGV.shift() rev = ARGV.shift() # Get the overview information. info=`#{svnlook} info #{repo} -r #{rev}` info_lines=info.split("\n") author=info_lines.shift date=info_lines.shift info_lines.shift comment=info_lines # Output the overview. body = "<p><b>#{author}</b> #{date}</p>" body << "<p>" comment.each { |line| body << "#{CGI.escapeHTML(line)}<br/>\n" } body << "</p>" body << "<hr noshade>" # Get and output the patch. changes=`#{svnlook} diff #{repo} -r #{rev}` body << "<pre>" changes.each do |top_line| top_line.split("\n").each do |line| color = case when line =~ /^Modified: / || line =~ /^=+$/ || line =~ /^@@ /: "gray" when line =~ /^-/: "red" when line =~ /^\+/: "blue" else "black" end body << %Q{<font style="color:#{color}">#{CGI.escapeHTML(line)}</font><br/>\n} end end body << "</pre>" # Write the header. header = "" header << "To: #{address}\n" header << "From: #{address}\n" header << "Subject: [SVN] #{repo} revision #{rev}\n" header << "Reply-to: #{address}\n" header << "MIME-Version: 1.0\n" header << "Content-Type: text/html; charset=UTF-8\n" header << "Content-Transfer-Encoding: 8bit\n" header << "\n" # Send the mail. begin fd = open("|#{sendmail} #{address}", "w") fd.print(header) fd.print(body) rescue exit(1) end fd.close # We're done. exit(0) ```
147,929
<p>I've been searching around, and I haven't found how I would do this from C#.</p> <p>I was wanting to make it so I could tell Google Chrome to go <strong>Forward</strong>, <strong>Back</strong>, <strong>Open New Tab</strong>, <strong>Close Tab</strong>, <strong>Open New Window</strong>, and <strong>Close Window</strong> from my C# application.</p> <p>I did something similar with WinAmp using</p> <pre><code>[DllImport("user32", EntryPoint = "SendMessageA")] private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam); </code></pre> <p>and a a few others. But I don't know what message to send or how to find what window to pass it to, or anything. </p> <p>So could someone show me how I would send those 6 commands to Chrome from C#? thanks</p> <p>EDIT: Ok, I'm getting voted down, so maybe I wasn't clear enough, or people are assuming I didn't try to figure this out on my own.</p> <p>First off, I'm not very good with the whole DllImport stuff. I'm still learning how it all works.</p> <p>I found how to do the same idea in winamp a few years ago, and I was looking at my code. I made it so I could skip a song, go back, play, pause, and stop winamp from my C# code. I started by importing:</p> <pre><code> [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr FindWindow([MarshalAs(UnmanagedType.LPTStr)] string lpClassName, [MarshalAs(UnmanagedType.LPTStr)] string lpWindowName); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern int SendMessageA(IntPtr hwnd, int wMsg, int wParam, uint lParam); [DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int GetWindowText(IntPtr hwnd, string lpString, int cch); [DllImport("user32", EntryPoint = "FindWindowExA")] private static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2); [DllImport("user32", EntryPoint = "SendMessageA")] private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam); </code></pre> <p>Then the code I found to use this used these constants for the messages I send.</p> <pre><code> const int WM_COMMAND = 0x111; const int WA_NOTHING = 0; const int WA_PREVTRACK = 40044; const int WA_PLAY = 40045; const int WA_PAUSE = 40046; const int WA_STOP = 40047; const int WA_NEXTTRACK = 40048; const int WA_VOLUMEUP = 40058; const int WA_VOLUMEDOWN = 40059; const int WINAMP_FFWD5S = 40060; const int WINAMP_REW5S = 40061; </code></pre> <p>I would get the <em>hwnd</em> (the program to send the message to) by:</p> <pre><code>IntPtr hwnd = FindWindow(m_windowName, null); </code></pre> <p>then I would send a message to that program:</p> <pre><code>SendMessageA(hwnd, WM_COMMAND, WA_STOP, WA_NOTHING); </code></pre> <p>I assume that I would do something very similar to this for Google Chrome. but I don't know what some of those values should be, and I googled around trying to find the answer, but I couldn't, which is why I asked here. So my question is how do I get the values for:</p> <p><strong>m_windowName</strong> and <strong>WM_COMMAND</strong></p> <p>and then, the values for the different commands, <strong>forward</strong>, <strong>back</strong>, <strong>new tab</strong>, <strong>close tab</strong>, <strong>new window</strong>, <strong>close window</strong>?</p>
[ { "answer_id": 147950, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 4, "selected": true, "text": "<p>Start your research at <a href=\"http://dev.chromium.org/developers\" rel=\"noreferrer\">http://dev.chromium.org/developers<...
2008/09/29
[ "https://Stackoverflow.com/questions/147929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13713/" ]
I've been searching around, and I haven't found how I would do this from C#. I was wanting to make it so I could tell Google Chrome to go **Forward**, **Back**, **Open New Tab**, **Close Tab**, **Open New Window**, and **Close Window** from my C# application. I did something similar with WinAmp using ``` [DllImport("user32", EntryPoint = "SendMessageA")] private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam); ``` and a a few others. But I don't know what message to send or how to find what window to pass it to, or anything. So could someone show me how I would send those 6 commands to Chrome from C#? thanks EDIT: Ok, I'm getting voted down, so maybe I wasn't clear enough, or people are assuming I didn't try to figure this out on my own. First off, I'm not very good with the whole DllImport stuff. I'm still learning how it all works. I found how to do the same idea in winamp a few years ago, and I was looking at my code. I made it so I could skip a song, go back, play, pause, and stop winamp from my C# code. I started by importing: ``` [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr FindWindow([MarshalAs(UnmanagedType.LPTStr)] string lpClassName, [MarshalAs(UnmanagedType.LPTStr)] string lpWindowName); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern int SendMessageA(IntPtr hwnd, int wMsg, int wParam, uint lParam); [DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern int GetWindowText(IntPtr hwnd, string lpString, int cch); [DllImport("user32", EntryPoint = "FindWindowExA")] private static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2); [DllImport("user32", EntryPoint = "SendMessageA")] private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam); ``` Then the code I found to use this used these constants for the messages I send. ``` const int WM_COMMAND = 0x111; const int WA_NOTHING = 0; const int WA_PREVTRACK = 40044; const int WA_PLAY = 40045; const int WA_PAUSE = 40046; const int WA_STOP = 40047; const int WA_NEXTTRACK = 40048; const int WA_VOLUMEUP = 40058; const int WA_VOLUMEDOWN = 40059; const int WINAMP_FFWD5S = 40060; const int WINAMP_REW5S = 40061; ``` I would get the *hwnd* (the program to send the message to) by: ``` IntPtr hwnd = FindWindow(m_windowName, null); ``` then I would send a message to that program: ``` SendMessageA(hwnd, WM_COMMAND, WA_STOP, WA_NOTHING); ``` I assume that I would do something very similar to this for Google Chrome. but I don't know what some of those values should be, and I googled around trying to find the answer, but I couldn't, which is why I asked here. So my question is how do I get the values for: **m\_windowName** and **WM\_COMMAND** and then, the values for the different commands, **forward**, **back**, **new tab**, **close tab**, **new window**, **close window**?
Start your research at <http://dev.chromium.org/developers> --- **EDIT**: Sending a message to a window is only half of the work. The window has to respond to that message and act accordingly. If that window doesn't know about a message or doesn't care at all you have no chance to control it by sending window messages. You're looking at an implementation detail on how you remote controlled Winamp. Sending messages is just one way to do it and it's the way the Winamp developers chose. Those messages you're using are user defined messages that have a specific meaning *only* to Winamp. What you have to do in the first step is to find out *if* Chromium supports some kind of remote controlling and what those mechanisms are.
147,941
<p>I am trying to read an Http response stream twice via the following:</p> <pre><code>HttpWebResponse response = (HttpWebResponse)request.GetResponse(); stream = response.GetResponseStream(); RssReader reader = new RssReader(stream); do { element = reader.Read(); if (element is RssChannel) { feed.Channels.Add((RssChannel)element); } } while (element != null); StreamReader sr = new StreamReader(stream); feed._FeedRawData = sr.ReadToEnd(); </code></pre> <p>However when the StreamReader code executes there is no data returned because the stream has now reached the end. I tried to reset the stream via stream.Position = 0 but this throws an exception (I think because the stream can't have its position changed manually).</p> <p>Basically, I would like to parse the stream for XML and have access to the raw data (in string format).</p> <p>Any ideas?</p>
[ { "answer_id": 147948, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": -1, "selected": false, "text": "<p>have you tried resetting the stream position?\nif this does not work you can copy the stream to a MemoryS...
2008/09/29
[ "https://Stackoverflow.com/questions/147941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10505/" ]
I am trying to read an Http response stream twice via the following: ``` HttpWebResponse response = (HttpWebResponse)request.GetResponse(); stream = response.GetResponseStream(); RssReader reader = new RssReader(stream); do { element = reader.Read(); if (element is RssChannel) { feed.Channels.Add((RssChannel)element); } } while (element != null); StreamReader sr = new StreamReader(stream); feed._FeedRawData = sr.ReadToEnd(); ``` However when the StreamReader code executes there is no data returned because the stream has now reached the end. I tried to reset the stream via stream.Position = 0 but this throws an exception (I think because the stream can't have its position changed manually). Basically, I would like to parse the stream for XML and have access to the raw data (in string format). Any ideas?
Copy it into a new MemoryStream first. Then you can re-read the MemoryStream as many times as you like: ``` Stream responseStream = CopyAndClose(resp.GetResponseStream()); // Do something with the stream responseStream.Position = 0; // Do something with the stream again private static Stream CopyAndClose(Stream inputStream) { const int readSize = 256; byte[] buffer = new byte[readSize]; MemoryStream ms = new MemoryStream(); int count = inputStream.Read(buffer, 0, readSize); while (count > 0) { ms.Write(buffer, 0, count); count = inputStream.Read(buffer, 0, readSize); } ms.Position = 0; inputStream.Close(); return ms; } ```
147,953
<p>In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company, Region, Area, Site, Room, Till. For a particular company I need to write some MDX that lists all regions, areas and sites (but not any levels below Site). Currently I am achieving this with the following MDX</p> <pre><code>HIERARCHIZE({ [Location].[Test Company], Descendants([Location].[Test Company], [Location].[Region]), Descendants([Location].[Test Company], [Location].[Area]), Descendants([Location].[Test Company], [Location].[Site]) }) </code></pre> <p>Because my knowledge of MDX is limited, I was wondering if there was a simpler way to do this, with a single command rather that four? Is there a less verbose way of achieveing this, or is my example the only real way of achieving this?</p>
[ { "answer_id": 147978, "author": "Magnus Smith", "author_id": 11461, "author_profile": "https://Stackoverflow.com/users/11461", "pm_score": 2, "selected": false, "text": "<p>The command you want is DESCENDANTS. Keep the 'family tree' analogy in mind, and you can see that this will list t...
2008/09/29
[ "https://Stackoverflow.com/questions/147953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ]
In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company, Region, Area, Site, Room, Till. For a particular company I need to write some MDX that lists all regions, areas and sites (but not any levels below Site). Currently I am achieving this with the following MDX ``` HIERARCHIZE({ [Location].[Test Company], Descendants([Location].[Test Company], [Location].[Region]), Descendants([Location].[Test Company], [Location].[Area]), Descendants([Location].[Test Company], [Location].[Site]) }) ``` Because my knowledge of MDX is limited, I was wondering if there was a simpler way to do this, with a single command rather that four? Is there a less verbose way of achieveing this, or is my example the only real way of achieving this?
``` DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE) ```
147,962
<p>I have a big load of documents, text-files, that I want to search for relevant content. I've seen a searching tool, can't remeber where, that implemented a nice method as I describe in my requirement below.</p> <p>My requirement is as follows:</p> <ul> <li>I need an optimised search function: I supply this search function with a list (one or more) partially-complete (or complete) words separated with spaces. </li> <li>The function then finds all the documents containing words starting or equal to the first word, then search these found documents in the same way using the second word, and so on, at the end of which it returns a list containing the actual words found linked with the documents (name &amp; location) containing them, for the complete the list of words. </li> <li>The documents must contain <strong>all</strong> the words in the list.</li> <li>I want to use this function to do an as-you-type search so that I can display and update the results in a tree-like structure in real-time.</li> </ul> <p>A possible approach to a solution I came up with is as follows: I create a database (most likely using mysql) with three tables: 'Documents', 'Words' and 'Word_Docs'.</p> <ul> <li>'Documents' will have (idDoc, Name, Location) of all documents.</li> <li>'Words' will have (idWord, Word) , and be a list of unique words from all the documents (a specific word appears only once).</li> <li>'Word_Docs' will have (idWord, idDoc) , and be a list of unique id-combinations for each word and document it appears in.</li> </ul> <p>The function is then called with the content of an editbox on each keystroke (except space):</p> <ul> <li>the string is tokenized</li> <li>(here my wheels spin a bit): I am sure a single SQL statement can be constructed to return the required dataset: (actual_words, doc_name, doc_location); (I'm not a hot-number with SQL), alternatively a sequence of calls for each token and parse-out the non-repeating idDocs?</li> <li>this dataset (/list/array) is then returned </li> </ul> <p>The returned list-content is then displayed:</p> <p>e.g.: called with: "seq sta cod" displays:</p> <pre><code>sequence - start - code - Counting Sequences [file://docs/sample/con_seq.txt] - stop - code - Counting Sequences [file://docs/sample/con_seq.txt] sequential - statement - code - SQL intro [file://somewhere/sql_intro.doc] </code></pre> <p>(and-so-on)</p> <p>Is this an optimal way of doing it? The function needs to be fast, or should it be called only when a space is hit? Should it offer word-completion? (Got the words in the database) At least this would prevent useless calls to the function for words that does not exist. If word-completion: how would that be implemented?</p> <p>(Maybe SO could also use this type of search-solution for browsing the tags? (In top-right of main page))</p>
[ { "answer_id": 147989, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>Not sure about the syntax (this is sql server syntax), but:</p>\n\n<pre><code>-- N is the number of elements in the list\...
2008/09/29
[ "https://Stackoverflow.com/questions/147962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15161/" ]
I have a big load of documents, text-files, that I want to search for relevant content. I've seen a searching tool, can't remeber where, that implemented a nice method as I describe in my requirement below. My requirement is as follows: * I need an optimised search function: I supply this search function with a list (one or more) partially-complete (or complete) words separated with spaces. * The function then finds all the documents containing words starting or equal to the first word, then search these found documents in the same way using the second word, and so on, at the end of which it returns a list containing the actual words found linked with the documents (name & location) containing them, for the complete the list of words. * The documents must contain **all** the words in the list. * I want to use this function to do an as-you-type search so that I can display and update the results in a tree-like structure in real-time. A possible approach to a solution I came up with is as follows: I create a database (most likely using mysql) with three tables: 'Documents', 'Words' and 'Word\_Docs'. * 'Documents' will have (idDoc, Name, Location) of all documents. * 'Words' will have (idWord, Word) , and be a list of unique words from all the documents (a specific word appears only once). * 'Word\_Docs' will have (idWord, idDoc) , and be a list of unique id-combinations for each word and document it appears in. The function is then called with the content of an editbox on each keystroke (except space): * the string is tokenized * (here my wheels spin a bit): I am sure a single SQL statement can be constructed to return the required dataset: (actual\_words, doc\_name, doc\_location); (I'm not a hot-number with SQL), alternatively a sequence of calls for each token and parse-out the non-repeating idDocs? * this dataset (/list/array) is then returned The returned list-content is then displayed: e.g.: called with: "seq sta cod" displays: ``` sequence - start - code - Counting Sequences [file://docs/sample/con_seq.txt] - stop - code - Counting Sequences [file://docs/sample/con_seq.txt] sequential - statement - code - SQL intro [file://somewhere/sql_intro.doc] ``` (and-so-on) Is this an optimal way of doing it? The function needs to be fast, or should it be called only when a space is hit? Should it offer word-completion? (Got the words in the database) At least this would prevent useless calls to the function for words that does not exist. If word-completion: how would that be implemented? (Maybe SO could also use this type of search-solution for browsing the tags? (In top-right of main page))
What you're talking about is known as an [inverted index](http://en.wikipedia.org/wiki/Inverted_index) or posting list, and operates similary to what you propose and what Mecki proposes. There's a lot of literature about inverted indexes out there; the Wikipedia article is a good place to start. Better, rather than trying to build it yourself, use an existing inverted index implementation. Both MySQL and recent versions of PostgreSQL have full text indexing by default. You may also want to check out [Lucene](http://lucene.apache.org/) for an independent solution. There are a lot of things to consider in writing a *good* inverted index, including tokenisation, stemming, multi-word queries, etc, etc, and a prebuilt solution will do all this for you.
147,969
<p>I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it?</p> <p>BTW, <em>I know of the existence of the various Unit frameworks in Ruby</em> - this is an exercise to learn the Ruby idioms, rather than to "get something done".</p>
[ { "answer_id": 148938, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 4, "selected": false, "text": "<p>What's your reason for adding the assert method to the Kernel module? Why not just use another module called...
2008/09/29
[ "https://Stackoverflow.com/questions/147969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2455/" ]
I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it? BTW, *I know of the existence of the various Unit frameworks in Ruby* - this is an exercise to learn the Ruby idioms, rather than to "get something done".
No it's not a best practice. The best analogy to assert() in Ruby is just raising ``` raise "This is wrong" unless expr ``` and you can implement your own exceptions if you want to provide for more specific exception handling
147,976
<p>I'm making a simple jquery command:</p> <p><code>element.html("&amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;");</code></p> <p>using the attributes/html method: <a href="http://docs.jquery.com/Attributes/html" rel="nofollow noreferrer">http://docs.jquery.com/Attributes/html</a></p> <p>It works on my local app engine server, but it doesn't work once I push to the Google server. The element empties but doesn't fill with spaces.</p> <p>So instead of <code>" "</code> <em>(6 spaces)</em> it's just <code>""</code>. </p> <p>Once again, this is running on App Engine, but I don't think that should matter...</p>
[ { "answer_id": 148387, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 1, "selected": false, "text": "<p>Have you tried using <code>&amp;nbsp;</code> instead of spaces? The <code>html()</code> method just pumps the string ...
2008/09/29
[ "https://Stackoverflow.com/questions/147976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9106/" ]
I'm making a simple jquery command: `element.html("&nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;");` using the attributes/html method: <http://docs.jquery.com/Attributes/html> It works on my local app engine server, but it doesn't work once I push to the Google server. The element empties but doesn't fill with spaces. So instead of `" "` *(6 spaces)* it's just `""`. Once again, this is running on App Engine, but I don't think that should matter...
You could try generating the space during run-time, so it won't be trimmed or whatever happens during transport: ``` element.html(String.fromCharCode(32)); ```
147,988
<p>I want to split an arithmetic expression into tokens, to convert it into RPN.</p> <p>Java has the StringTokenizer, which can optionally keep the delimiters. That way, I could use the operators as delimiters. Unfortunately, I need to do this in PHP, which has strtok, but that throws away the delimiters, so I need to brew something myself.</p> <p>This sounds like a classic textbook example for Compiler Design 101, but I'm afraid I'm lacking some formal education here. Is there a standard algorithm you can point me to?</p> <p>My other options are to read up on <a href="http://en.wikipedia.org/wiki/Lexical_analysis" rel="nofollow noreferrer">Lexical Analysis</a> or to roll up something quick and dirty with the available string functions.</p>
[ { "answer_id": 148014, "author": "Shoan", "author_id": 17404, "author_profile": "https://Stackoverflow.com/users/17404", "pm_score": 2, "selected": false, "text": "<p>This might help.</p>\n\n<p><a href=\"http://c7y.phparch.com/c/entry/1/art,practical_uses_tokenizer\" rel=\"nofollow noref...
2008/09/29
[ "https://Stackoverflow.com/questions/147988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
I want to split an arithmetic expression into tokens, to convert it into RPN. Java has the StringTokenizer, which can optionally keep the delimiters. That way, I could use the operators as delimiters. Unfortunately, I need to do this in PHP, which has strtok, but that throws away the delimiters, so I need to brew something myself. This sounds like a classic textbook example for Compiler Design 101, but I'm afraid I'm lacking some formal education here. Is there a standard algorithm you can point me to? My other options are to read up on [Lexical Analysis](http://en.wikipedia.org/wiki/Lexical_analysis) or to roll up something quick and dirty with the available string functions.
As often, I would just use a regular expression to do this: ``` $expr = '(5*(7 + 2 * -9.3) - 8 )/ 11'; $tokens = preg_split('/([*\/^+-]+)\s*|([\d.]+)\s*/', $expr, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $tts = print_r($tokens, true); echo "<pre>x=$tts</pre>"; ``` It needs a little more work to accept numbers with exponent (like -9.2e-8).
147,995
<p>When using the paginator helper in cakephp views, it doesnt remember parts of the url that are custom for my useage.</p> <p>For example: </p> <pre><code>http://example.org/users/index/moderators/page:2/sort:name/dir:asc </code></pre> <p>here <strong>moderators</strong> is a parameter that helps me filter by that type. But pressing a paginator link will not include this link.</p>
[ { "answer_id": 147998, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 4, "selected": false, "text": "<p>The secret is adding this line to your view:</p>\n\n<p><strong>$paginator->options(array('url'=>$this->passedAr...
2008/09/29
[ "https://Stackoverflow.com/questions/147995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
When using the paginator helper in cakephp views, it doesnt remember parts of the url that are custom for my useage. For example: ``` http://example.org/users/index/moderators/page:2/sort:name/dir:asc ``` here **moderators** is a parameter that helps me filter by that type. But pressing a paginator link will not include this link.
To add to Alexander Morland's answer above, it's worth remembering that the syntax has changed in CakePHP 1.3 and is now: ``` $this->Paginator->options(array('url' => $this->passedArgs)); ``` This is described further in the [pagination in views](http://book.cakephp.org/1.3/en/The-Manual/Common-Tasks-With-CakePHP/Pagination.html#pagination-in-views) section of the CakePHP book.
148,003
<p>I have an array of a few million numbers.</p> <pre><code>double* const data = new double (3600000); </code></pre> <p>I need to iterate through the array and find the range (the largest value in the array minus the smallest value). However, there is a catch. I only want to find the range where the smallest and largest values are within 1,000 samples of each other.</p> <p>So I need to find the maximum of: range(data + 0, data + 1000), range(data + 1, data + 1001), range(data + 2, data + 1002), ...., range(data + 3599000, data + 3600000).</p> <p>I hope that makes sense. Basically I could do it like above, but I'm looking for a more efficient algorithm if one exists. I think the above algorithm is O(n), but I feel that it's possible to optimize. An idea I'm playing with is to keep track of the most recent maximum and minimum and how far back they are, then only backtrack when necessary.</p> <p>I'll be coding this in C++, but a nice algorithm in pseudo code would be just fine. Also, if this number I'm trying to find has a name, I'd love to know what it is.</p> <p>Thanks.</p>
[ { "answer_id": 148030, "author": "Drakosha", "author_id": 19868, "author_profile": "https://Stackoverflow.com/users/19868", "pm_score": 4, "selected": true, "text": "<p>The algorithm you describe is really O(N), but i think the constant is too high. Another solution which looks reasonabl...
2008/09/29
[ "https://Stackoverflow.com/questions/148003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
I have an array of a few million numbers. ``` double* const data = new double (3600000); ``` I need to iterate through the array and find the range (the largest value in the array minus the smallest value). However, there is a catch. I only want to find the range where the smallest and largest values are within 1,000 samples of each other. So I need to find the maximum of: range(data + 0, data + 1000), range(data + 1, data + 1001), range(data + 2, data + 1002), ...., range(data + 3599000, data + 3600000). I hope that makes sense. Basically I could do it like above, but I'm looking for a more efficient algorithm if one exists. I think the above algorithm is O(n), but I feel that it's possible to optimize. An idea I'm playing with is to keep track of the most recent maximum and minimum and how far back they are, then only backtrack when necessary. I'll be coding this in C++, but a nice algorithm in pseudo code would be just fine. Also, if this number I'm trying to find has a name, I'd love to know what it is. Thanks.
The algorithm you describe is really O(N), but i think the constant is too high. Another solution which looks reasonable is to use O(N\*log(N)) algorithm the following way: ``` * create sorted container (std::multiset) of first 1000 numbers * in loop (j=1, j<(3600000-1000); ++j) - calculate range - remove from the set number which is now irrelevant (i.e. in index *j - 1* of the array) - add to set new relevant number (i.e. in index *j+1000-1* of the array) ``` I believe it should be faster, because the constant is much lower.
148,005
<p>In SQL, how do update a table, setting a column to a different value for each row?</p> <p>I want to update some rows in a PostgreSQL database, setting one column to a number from a sequence, where that column has a unique constraint. I hoped that I could just use:</p> <pre><code>update person set unique_number = (select nextval('number_sequence') ); </code></pre> <p>but it seems that <em>nextval</em> is only called once, so the update uses the same number for every row, and I get a 'duplicate key violates unique constraint' error. What should I do instead?</p>
[ { "answer_id": 148017, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": 6, "selected": true, "text": "<p>Don't use a subselect, rather use the nextval function directly, like this:</p>\n\n<pre><code>update person set uniqu...
2008/09/29
[ "https://Stackoverflow.com/questions/148005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2670/" ]
In SQL, how do update a table, setting a column to a different value for each row? I want to update some rows in a PostgreSQL database, setting one column to a number from a sequence, where that column has a unique constraint. I hoped that I could just use: ``` update person set unique_number = (select nextval('number_sequence') ); ``` but it seems that *nextval* is only called once, so the update uses the same number for every row, and I get a 'duplicate key violates unique constraint' error. What should I do instead?
Don't use a subselect, rather use the nextval function directly, like this: ``` update person set unique_number = nextval('number_sequence'); ```
148,024
<p>I have got a C function in a static library, let's call it A, with the following interface :</p> <pre><code>int A(unsigned int a, unsigned long long b, unsigned int *y, unsigned char *z); </code></pre> <p>This function will change the value of y an z (this is for sure). I use it from within a dynamic C++ library, using extern "C".</p> <p>Now, here is what stune me : </p> <ul> <li>y is properly set, z is not changed. What I exactly mean is that if both are initialized with a (pointed) value of 666, the value pointed by y will have changed after the call but not the value pointed by z (still 666).</li> <li>when called from a C binary, this function works seamlessly (value pointed by z is modified).</li> <li>if I create a dummy C library with a function having the same prototype, and I use it from within my dynamic C++ library, it works very well. If I re-use the same variables to call A(..), I get the same result as before, z is not changed.</li> </ul> <p>I think that the above points show that it is not a stupid mistake with the declaration of my variables. </p> <p>I am clearly stuck, and I can't change the C library. Do you have any clue on what can be the problem ? I was thinking about a problem on the C/C++ interface, per instance the way a char* is interpreted.</p> <p>Edit : I finally found out what was the problem. See below my answer.</p>
[ { "answer_id": 148041, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 1, "selected": false, "text": "<p>As far as I know, long long is not part of standard C++, maybe that is the source of your problem.</p>\n" }, { ...
2008/09/29
[ "https://Stackoverflow.com/questions/148024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20986/" ]
I have got a C function in a static library, let's call it A, with the following interface : ``` int A(unsigned int a, unsigned long long b, unsigned int *y, unsigned char *z); ``` This function will change the value of y an z (this is for sure). I use it from within a dynamic C++ library, using extern "C". Now, here is what stune me : * y is properly set, z is not changed. What I exactly mean is that if both are initialized with a (pointed) value of 666, the value pointed by y will have changed after the call but not the value pointed by z (still 666). * when called from a C binary, this function works seamlessly (value pointed by z is modified). * if I create a dummy C library with a function having the same prototype, and I use it from within my dynamic C++ library, it works very well. If I re-use the same variables to call A(..), I get the same result as before, z is not changed. I think that the above points show that it is not a stupid mistake with the declaration of my variables. I am clearly stuck, and I can't change the C library. Do you have any clue on what can be the problem ? I was thinking about a problem on the C/C++ interface, per instance the way a char\* is interpreted. Edit : I finally found out what was the problem. See below my answer.
First of all, I am very grateful to everyone for your help. Thanks to the numerous ideas and clues you gave me, I have been able to finally sort out this problem. Your advices helped me to question what I took for granted. Short answer to my problem : The problem was that my C++ library used an old version of the C library. This old version missed the 4th argument. As a consequence, the 4th argument was obviously never changed. I am a bit ashamed now that I realised this was the problem. However, I was misslead by the fact that my code was compiling fine. This was due to the fact that the C++ library compiled against the correct version of the C lib, but at runtime it used the old version statically linked with another library that I was using. ``` C++ Lib (M) ---> dyn C++ lib (N) ---> C lib (P) v.1.0 | ------> C lib (P) v.1.1 ``` (N) is a dynamic library which is statically linked with (P) version 1.0. The compiler accepted the call from (M) to the function with 4 arguments because I linked against (P) version 1.1, but at runtime it used the old version of (P). Feel free to edit this answer or the question or to ask me to do so.
148,042
<p>When using IF statements in Python, you have to do the following to make the "cascade" work correctly.</p> <pre><code>if job == "mechanic" or job == "tech": print "awesome" elif job == "tool" or job == "rock": print "dolt" </code></pre> <p>Is there a way to make Python accept multiple values when checking for "equals to"? For example,</p> <pre><code>if job == "mechanic" or "tech": print "awesome" elif job == "tool" or "rock": print "dolt" </code></pre>
[ { "answer_id": 148048, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<pre><code>if job in (\"mechanic\", \"tech\"):\n print \"awesome\"\nelif job in (\"tool\", \"rock\"):\n print \"dolt...
2008/09/29
[ "https://Stackoverflow.com/questions/148042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
When using IF statements in Python, you have to do the following to make the "cascade" work correctly. ``` if job == "mechanic" or job == "tech": print "awesome" elif job == "tool" or job == "rock": print "dolt" ``` Is there a way to make Python accept multiple values when checking for "equals to"? For example, ``` if job == "mechanic" or "tech": print "awesome" elif job == "tool" or "rock": print "dolt" ```
``` if job in ("mechanic", "tech"): print "awesome" elif job in ("tool", "rock"): print "dolt" ``` The values in parentheses are a tuple. The `in` operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple. Note that when Python searches a tuple or list using the `in` operator, it does a linear search. If you have a large number of items on the right hand side, this could be a performance bottleneck. A larger-scale way of doing this would be to use a [`frozenset`](http://docs.python.org/lib/types-set.html): ``` AwesomeJobs = frozenset(["mechanic", "tech", ... lots of others ]) def func(): if job in AwesomeJobs: print "awesome" ``` The use of `frozenset` over `set` is preferred if the list of awesome jobs does not need to be changed during the operation of your program.
148,056
<p>I have created my own Tree implementation for <a href="https://stackoverflow.com/questions/144642/tree-directed-acyclic-graph-implementation">various reasons</a> and have come up with two classes, a 'base' class that is a generic tree node that is chock full of logic and another class that extends that one which is more specialised.</p> <p>In my base class certain methods involve instantiating new tree nodes (e.g. adding children). These instantations are inside logic (in a nested loop, say) which makes the logic hard to separate from the instantation.</p> <p>So, if I don't override these instantations in the specific class the wrong type of node will be created. However, I don't <em>want</em> to override those methods because they also contained shared logic that shouldn't be duplicated!</p> <p>The problem can be boiled down to this:</p> <pre><code>public class Foo { public String value() { return "foo"; } public Foo doStuff() { // Logic logic logic.. return new Foo(); } } class Bar extends Foo { public String value() { return "bar"; } } new Bar().doStuff().value(); // returns 'foo', we want 'bar' </code></pre> <p>The first thing that popped into my head would have a 'create hook' that extending classes could override:</p> <pre><code>public Foo createFooHook(/* required parameters */) { return new Foo(); } </code></pre> <p>Now. while it was a fine first thought, there is a stench coming off that code something awful. There is something very... <em>wrong</em> about it. </p> <p>It's like cooking while naked-- it feels dangerous and <em>unnecessary</em>.</p> <p>So, <strong>how would you deal with this situation?</strong></p>
[ { "answer_id": 148072, "author": "mitchnull", "author_id": 18645, "author_profile": "https://Stackoverflow.com/users/18645", "pm_score": 0, "selected": false, "text": "<p>I don't think there's a better approach. Just be careful not to call these hooks from the constructor.</p>\n" }, ...
2008/09/29
[ "https://Stackoverflow.com/questions/148056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
I have created my own Tree implementation for [various reasons](https://stackoverflow.com/questions/144642/tree-directed-acyclic-graph-implementation) and have come up with two classes, a 'base' class that is a generic tree node that is chock full of logic and another class that extends that one which is more specialised. In my base class certain methods involve instantiating new tree nodes (e.g. adding children). These instantations are inside logic (in a nested loop, say) which makes the logic hard to separate from the instantation. So, if I don't override these instantations in the specific class the wrong type of node will be created. However, I don't *want* to override those methods because they also contained shared logic that shouldn't be duplicated! The problem can be boiled down to this: ``` public class Foo { public String value() { return "foo"; } public Foo doStuff() { // Logic logic logic.. return new Foo(); } } class Bar extends Foo { public String value() { return "bar"; } } new Bar().doStuff().value(); // returns 'foo', we want 'bar' ``` The first thing that popped into my head would have a 'create hook' that extending classes could override: ``` public Foo createFooHook(/* required parameters */) { return new Foo(); } ``` Now. while it was a fine first thought, there is a stench coming off that code something awful. There is something very... *wrong* about it. It's like cooking while naked-- it feels dangerous and *unnecessary*. So, **how would you deal with this situation?**
So, after getting my copy of [Design Patterns](https://rads.stackoverflow.com/amzn/click/com/0201633612) and opening it for what I'm fairly sure is the first time ever I discovered what I want. It's called the [Factory Method](http://en.wikipedia.org/wiki/Factory_method) and it's mostly a perfect fit. It's still a bit ugly because my super class (`Foo` in the above example) is not abstract which means subclasses are not forced to implement the hook. That can be fixed with some refactoring though, and I'll end up with something to the effect of: ``` abstract class AbstractFoo { public String value() { return "Foo"; } public AbstractFoo doStuff() { // Logic logic logic return hook(); } protected abstract AbstractFoo hook(); } class Foo extends AbstractFoo { protected AbstractFoo hook() { return new Foo(); } } class Bar extends AbstractFoo { public String value() { return "Bar"; } protected AbstractFoo hook() { return new Bar(); } } new Bar().doStuff().value(); // Returns 'Bar'! ```
148,057
<p>If you have Mathematica code in foo.m, Mathematica can be invoked with <code>-noprompt</code> and with <code>-initfile foo.m</code> (or <code>-run "&lt;&lt;foo.m"</code>) and the command line arguments are available in <code>$CommandLine</code> (with extra junk in there) but is there a way to just have some mathematica code like</p> <pre><code>#!/usr/bin/env MathKernel x = 2+2; Print[x]; Print["There were ", Length[ARGV], " args passed in on the command line."]; linesFromStdin = readList[]; etc. </code></pre> <p>and chmod it executable and run it? In other words, how does one use Mathematica like any other scripting language (Perl, Python, Ruby, etc)?</p>
[ { "answer_id": 148085, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 2, "selected": false, "text": "<p>Try<br>\n-initfile <em>filename</em><br>\nAnd put the exit command into your program</p>\n" }, { "answer_id": 151656,...
2008/09/29
[ "https://Stackoverflow.com/questions/148057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
If you have Mathematica code in foo.m, Mathematica can be invoked with `-noprompt` and with `-initfile foo.m` (or `-run "<<foo.m"`) and the command line arguments are available in `$CommandLine` (with extra junk in there) but is there a way to just have some mathematica code like ``` #!/usr/bin/env MathKernel x = 2+2; Print[x]; Print["There were ", Length[ARGV], " args passed in on the command line."]; linesFromStdin = readList[]; etc. ``` and chmod it executable and run it? In other words, how does one use Mathematica like any other scripting language (Perl, Python, Ruby, etc)?
MASH -- Mathematica Scripting Hack -- will do this. Since Mathematica version 6, the following perl script suffices: <http://ai.eecs.umich.edu/people/dreeves/mash/mash.pl> For previous Mathematica versions, a C program is needed: <http://ai.eecs.umich.edu/people/dreeves/mash/pre6> UPDATE: At long last, Mathematica 8 supports this natively with the "-script" command-line option: <http://www.wolfram.com/mathematica/new-in-8/mathematica-shell-scripts/>
148,078
<p>I have a method which should be executed in an exclusive fashion. Basically, it's a multi threaded application where the method is invoked periodically by a timer, but which could also be manually triggered by a user action.</p> <p>Let's take an example :</p> <ol> <li><p>The timer elapses, so the method is called. The task could take a few seconds.</p></li> <li><p>Right after, the user clicks on some button, which should trigger the same task : BAM. It does nothing since the method is already running.</p></li> </ol> <p>I used the following solution :</p> <pre><code>public void DoRecurentJob() { if(!Monitor.TryEnter(this.lockObject)) { return; } try { // Do work } finally { Monitor.Exit(this.lockObject); } } </code></pre> <p>Where <code>lockObject</code> is declared like that:</p> <pre><code>private readonly object lockObject = new object(); </code></pre> <p><strong>Edit</strong> : There will be only one instance of the object which holds this method, so I updated the lock object to be non-static.</p> <p>Is there a better way to do that ? Or maybe this one is just wrong for any reason ?</p>
[ { "answer_id": 148104, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 3, "selected": true, "text": "<p>This looks reasonable if you are just interested in not having the method run in parallel. There's nothing to sto...
2008/09/29
[ "https://Stackoverflow.com/questions/148078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ]
I have a method which should be executed in an exclusive fashion. Basically, it's a multi threaded application where the method is invoked periodically by a timer, but which could also be manually triggered by a user action. Let's take an example : 1. The timer elapses, so the method is called. The task could take a few seconds. 2. Right after, the user clicks on some button, which should trigger the same task : BAM. It does nothing since the method is already running. I used the following solution : ``` public void DoRecurentJob() { if(!Monitor.TryEnter(this.lockObject)) { return; } try { // Do work } finally { Monitor.Exit(this.lockObject); } } ``` Where `lockObject` is declared like that: ``` private readonly object lockObject = new object(); ``` **Edit** : There will be only one instance of the object which holds this method, so I updated the lock object to be non-static. Is there a better way to do that ? Or maybe this one is just wrong for any reason ?
This looks reasonable if you are just interested in not having the method run in parallel. There's nothing to stop it from running immediately after each other, say that you pushed the button half a microsecond after the timer executed the Monitor.Exit(). And having the lock object as readonly static also make sense.
148,116
<p>So, In a Flex app I add a new GUI component by creating it and calling <code>parent.addChild()</code>. However in some cases, this causes an error in the bowels of Flex. Turns out, addChild actually does:</p> <pre><code>return addChildAt(child, numChildren); </code></pre> <p>In the cases where it breaks, somehow the numChildren is off by one. Leading to this error:</p> <blockquote> <p>RangeError: Error #2006: The supplied index is out of bounds. at flash.display::DisplayObjectContainer/addChildAt() at mx.core::Container/addChildAt() at mx.core::Container/addChild() . . at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at mx.core::UIComponent/dispatchEvent() at mx.controls::SWFLoader::contentLoaderInfo_completeEventHandler()</p> </blockquote> <p>Is this a bug in Flex or in how I am using it? It kind of looks like it could be a threading bug, but since Flex doesn't support threads that is a bit confusing.</p>
[ { "answer_id": 148250, "author": "user23405", "author_id": 23405, "author_profile": "https://Stackoverflow.com/users/23405", "pm_score": 1, "selected": false, "text": "<p>I have noticed that it most often occurs when re-parenting a UIComponent that is already on the display list. Are yo...
2008/09/29
[ "https://Stackoverflow.com/questions/148116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
So, In a Flex app I add a new GUI component by creating it and calling `parent.addChild()`. However in some cases, this causes an error in the bowels of Flex. Turns out, addChild actually does: ``` return addChildAt(child, numChildren); ``` In the cases where it breaks, somehow the numChildren is off by one. Leading to this error: > > RangeError: Error #2006: The supplied > index is out of bounds. at > flash.display::DisplayObjectContainer/addChildAt() > at > mx.core::Container/addChildAt() > at > mx.core::Container/addChild() > . . at > flash.events::EventDispatcher/dispatchEventFunction() > at > flash.events::EventDispatcher/dispatchEvent() > at > mx.core::UIComponent/dispatchEvent() > at > mx.controls::SWFLoader::contentLoaderInfo\_completeEventHandler() > > > Is this a bug in Flex or in how I am using it? It kind of looks like it could be a threading bug, but since Flex doesn't support threads that is a bit confusing.
I have noticed that it most often occurs when re-parenting a UIComponent that is already on the display list. Are you re-parenting in this situation?
148,130
<p>Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this?</p> <p><strong>Answer</strong> - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus.</p>
[ { "answer_id": 148135, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 7, "selected": true, "text": "<p>For a general InputStream, I would wrap it in a BufferedInputStream and do something like this:</p>\n\n<pre><code>Buf...
2008/09/29
[ "https://Stackoverflow.com/questions/148130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this? **Answer** - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus.
For a general InputStream, I would wrap it in a BufferedInputStream and do something like this: ``` BufferedInputStream bis = new BufferedInputStream(inputStream); bis.mark(2); int byte1 = bis.read(); int byte2 = bis.read(); bis.reset(); // note: you must continue using the BufferedInputStream instead of the inputStream ```
148,136
<p>I'm currently generating SQL insert statements from more than one tables, and in the generated data I need to use a CASE statement, like this:</p> <pre><code>select 'INSERT INTO TABLE1 (f1, f2, f3, f4 ...) values (' ||t.f1||',' ||CASE WHEN t.f2 &gt; 0 THEN '1' ELSE '0' END CASE from table2 t , table3 t3 </code></pre> <p>But at this point if I want to continue my statement with <code>... END CASE||','|| ....</code> I can't run the query anymore, as TOAD complains about not finding the FROM keyword.</p> <p>A quick solution was to separate the ouput into fields, then save it to text, and edit, but there must be a better way.</p>
[ { "answer_id": 148150, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 1, "selected": false, "text": "<p>For some similar situations, the \"decode\" function works quite well. </p>\n\n<p>You might be able to feed the e...
2008/09/29
[ "https://Stackoverflow.com/questions/148136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11621/" ]
I'm currently generating SQL insert statements from more than one tables, and in the generated data I need to use a CASE statement, like this: ``` select 'INSERT INTO TABLE1 (f1, f2, f3, f4 ...) values (' ||t.f1||',' ||CASE WHEN t.f2 > 0 THEN '1' ELSE '0' END CASE from table2 t , table3 t3 ``` But at this point if I want to continue my statement with `... END CASE||','|| ....` I can't run the query anymore, as TOAD complains about not finding the FROM keyword. A quick solution was to separate the ouput into fields, then save it to text, and edit, but there must be a better way.
Use END instead of END CASE ``` select 'INSERT INTO TABLE1 (f1, f2, f3, f4 ...) values (' ||t.f1||',' ||CASE WHEN t.f2 > 0 THEN '1' ELSE '0' END||','||t.f2 from table2 t , table3 t3 ```
148,143
<p>When you open a solution in Visual Studio 2008 (or ealier versions for that matter), it opens all the documents that you did not close before you closed Visual Studio. Is there anyway to turn this functionality off, or a plugin that fixes this behavior? It takes forever to load a solution with 50 files open?</p>
[ { "answer_id": 148166, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": false, "text": "<p>Have you tried deleting the <strong>.suo</strong> file?</p>\n\n<p>It's a hidden file that lives beside your solution (s...
2008/09/29
[ "https://Stackoverflow.com/questions/148143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11559/" ]
When you open a solution in Visual Studio 2008 (or ealier versions for that matter), it opens all the documents that you did not close before you closed Visual Studio. Is there anyway to turn this functionality off, or a plugin that fixes this behavior? It takes forever to load a solution with 50 files open?
You can automate the process of closing all the files prior to closing a solution by adding a handler for the BeforeClosing event of EnvDTE.SolutionEvents -- this will get invoked when VS is exiting. In VS2005, adding the following to the EnvironmentEvents macro module will close all open documents: ``` Private Sub SolutionEvents_BeforeClosing() Handles SolutionEvents.BeforeClosing DTE.ExecuteCommand("Window.CloseAllDocuments") End Sub ``` Visual Studio 2008 appears to support the same events so I'm sure this would work there too. I'm sure you could also delete the .suo file for your project in the handler if you wanted, but you'd probably want the AfterClosing event.
148,157
<p>I am working on a Sharepoint Server 2007 State machine Workflow. Until now I have a few states and a custom Association/InitiationForm which I created with InfoPath 2007. In Addition I have a few modification forms. I have a Problem with the removing of the modification link in the state-page of my workflow. </p> <p>I have a state and in the initialize block of this state my EnableWorkflowModification Activity appears. So at the beginning of the state the modification is active. In the same state I have an OnWorkflowModification activity, which catches the event raised by the EnableWorkflowModification activity. After this state my modification is over and the link should disappear in the state-page. But this is not the case. Both activities have the same correlation token (modification) and the same owner (the owning state). Has anybody an idea why the link is not removed and how to remove the modification link?</p> <p>Thank you in advance, Stefan!</p>
[ { "answer_id": 148166, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": false, "text": "<p>Have you tried deleting the <strong>.suo</strong> file?</p>\n\n<p>It's a hidden file that lives beside your solution (s...
2008/09/29
[ "https://Stackoverflow.com/questions/148157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21729/" ]
I am working on a Sharepoint Server 2007 State machine Workflow. Until now I have a few states and a custom Association/InitiationForm which I created with InfoPath 2007. In Addition I have a few modification forms. I have a Problem with the removing of the modification link in the state-page of my workflow. I have a state and in the initialize block of this state my EnableWorkflowModification Activity appears. So at the beginning of the state the modification is active. In the same state I have an OnWorkflowModification activity, which catches the event raised by the EnableWorkflowModification activity. After this state my modification is over and the link should disappear in the state-page. But this is not the case. Both activities have the same correlation token (modification) and the same owner (the owning state). Has anybody an idea why the link is not removed and how to remove the modification link? Thank you in advance, Stefan!
You can automate the process of closing all the files prior to closing a solution by adding a handler for the BeforeClosing event of EnvDTE.SolutionEvents -- this will get invoked when VS is exiting. In VS2005, adding the following to the EnvironmentEvents macro module will close all open documents: ``` Private Sub SolutionEvents_BeforeClosing() Handles SolutionEvents.BeforeClosing DTE.ExecuteCommand("Window.CloseAllDocuments") End Sub ``` Visual Studio 2008 appears to support the same events so I'm sure this would work there too. I'm sure you could also delete the .suo file for your project in the handler if you wanted, but you'd probably want the AfterClosing event.
148,178
<p>I've got a really odd error message that only occurs when I add the following line to my project:</p> <pre><code>std::list&lt;CRect&gt; myVar; </code></pre> <p>It's worth noting that it doesn't have to be a std::list, it can be std::vector or any other STL container I assume.</p> <p>Here is the error message:</p> <blockquote> <p>Error 1 error LNK2005: "public: __thiscall std::list</p> <blockquote> <p>::list >(void)" (??0?$list@VCRect@@V?$allocator@VCRect@@@std@@@std@@QAE@XZ) already defined in SomeLowLevelLibrary.lib</p> </blockquote> </blockquote> <p>The low level library that's referenced in the error message has no idea about the project I am building, it only has core low level functionality and doesn't deal with high level MFC GUIs.</p> <p>I can get the linker error to go away if I change the line of code to:</p> <pre><code>std::list&lt;CRect*&gt; myVar; </code></pre> <p>But I don't want to hack it for the sake of it.</p> <p>Also, it doesn't matter if I create the variable on the stack or the heap, I still get the same error.</p> <p>Does anyone have any ideas whatsoever about this? I'm using Microsoft Visual Studio 2008 SP1 on Vista Enterprise.</p> <p><strong>Edit:</strong> The linker error above is for the std::list&lt;> constructor, I also get an error for the destructor, _Nextnode and clear functions.</p> <p><strong>Edit:</strong> In other files in the project, std::vector won't link, in other files it might be std::list. I can't work out why some containers work, and some don't. MFC linkage is static across both libraries. In the low level library we have 1 class that inherits from std::list.</p> <p><strong>Edit:</strong> The low level library doesn't have any classes that inherit from CRect, but it does make use of STL.</p>
[ { "answer_id": 148899, "author": "jeffm", "author_id": 1544, "author_profile": "https://Stackoverflow.com/users/1544", "pm_score": 0, "selected": false, "text": "<p>This doesn't sound like the exact symptom, but to be sure you should check that your main project and all your included lib...
2008/09/29
[ "https://Stackoverflow.com/questions/148178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
I've got a really odd error message that only occurs when I add the following line to my project: ``` std::list<CRect> myVar; ``` It's worth noting that it doesn't have to be a std::list, it can be std::vector or any other STL container I assume. Here is the error message: > > Error 1 error LNK2005: "public: > \_\_thiscall std::list > > > > > > > ::list >(void)" > > (??0?$list@VCRect@@V?$allocator@VCRect@@@std@@@std@@QAE@XZ) > > already defined in > > SomeLowLevelLibrary.lib > > > > > > > > > The low level library that's referenced in the error message has no idea about the project I am building, it only has core low level functionality and doesn't deal with high level MFC GUIs. I can get the linker error to go away if I change the line of code to: ``` std::list<CRect*> myVar; ``` But I don't want to hack it for the sake of it. Also, it doesn't matter if I create the variable on the stack or the heap, I still get the same error. Does anyone have any ideas whatsoever about this? I'm using Microsoft Visual Studio 2008 SP1 on Vista Enterprise. **Edit:** The linker error above is for the std::list<> constructor, I also get an error for the destructor, \_Nextnode and clear functions. **Edit:** In other files in the project, std::vector won't link, in other files it might be std::list. I can't work out why some containers work, and some don't. MFC linkage is static across both libraries. In the low level library we have 1 class that inherits from std::list. **Edit:** The low level library doesn't have any classes that inherit from CRect, but it does make use of STL.
I recently stumbled across this error again in our project and decided to have a more thorough investigation compared to just patching it up with a hack like last time (swap std::list for CArray). It turns out that one of our low level libraries was inheriting from std::list, e.g. ``` class LIB_EXPORT CRectList : public std::list<CRect> { }; ``` This is not just bad practice, but it also was the cause of the linker errors in the main application. I change CRectList to wrap std::list rather than inherit from it and the error went away.
148,185
<p>C++ preprocessor <code>#define</code> is totally different.</p> <p>Is the PHP <code>define()</code> any different than just creating a var?</p> <pre><code>define("SETTING", 0); $something = SETTING; </code></pre> <p>vs</p> <pre><code>$setting = 0; $something = $setting; </code></pre>
[ { "answer_id": 148191, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 2, "selected": false, "text": "<p>Here are the differences, from the <a href=\"http://uk3.php.net/manual/en/language.constants.php\" rel=\"nofollow nore...
2008/09/29
[ "https://Stackoverflow.com/questions/148185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21240/" ]
C++ preprocessor `#define` is totally different. Is the PHP `define()` any different than just creating a var? ``` define("SETTING", 0); $something = SETTING; ``` vs ``` $setting = 0; $something = $setting; ```
'define' operation itself is rather slow - confirmed by xdebug profiler. Here is benchmarks from <http://t3.dotgnu.info/blog/php/my-first-php-extension.html>: * pure 'define' 380.785 fetches/sec 14.2647 mean msecs/first-response * constants defined with 'hidef' extension 930.783 fetches/sec 6.30279 mean msecs/first-response --- **broken link update** The blog post referenced above has left the internet. It can still be viewed [here via Wayback Machine](http://web.archive.org/web/20100504144640/http://t3.dotgnu.info/blog/php/my-first-php-extension.html). Here is another [similar article](http://shwup.blogspot.com/2010/04/about-constants.html). The libraries the author references can be found [here (apc\_define\_constants)](http://sg.php.net/manual/en/function.apc-define-constants.php) and [here (hidef extension)](http://pecl.php.net/package/hidef).
148,202
<p>Microsoft <a href="http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx" rel="nofollow noreferrer">recently announced</a> that the Javascript/HTML DOM library <strong>jQuery will be integrated</strong> into the ASP.NET MVC framework and into ASP.NET / Visual Studio.</p> <p>What is the best practice or strategy adopting jQuery using <strong>ASP.NET 2.0</strong>? I'd like to prepare a large, existing ASP.NET Web Application (<strong>not</strong> MVC) for jQuery. How would I deal with versioning and related issues?</p> <p>Are the any caveats integrating jQuery and <strong>ASP.NET Ajax</strong>? Or <strong>3rd party components</strong> like Telerik or Intersoft controls?</p>
[ { "answer_id": 148241, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 1, "selected": false, "text": "<p>There's a small issue which is mentioned by David Ward here: <a href=\"http://encosia.com/2008/09/28/avoid-this-tr...
2008/09/29
[ "https://Stackoverflow.com/questions/148202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
Microsoft [recently announced](http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx) that the Javascript/HTML DOM library **jQuery will be integrated** into the ASP.NET MVC framework and into ASP.NET / Visual Studio. What is the best practice or strategy adopting jQuery using **ASP.NET 2.0**? I'd like to prepare a large, existing ASP.NET Web Application (**not** MVC) for jQuery. How would I deal with versioning and related issues? Are the any caveats integrating jQuery and **ASP.NET Ajax**? Or **3rd party components** like Telerik or Intersoft controls?
For me, problems arise when using UpdatePanels and jQuery (no problem with MVC, which doesn't have a Page Life-Cycle and is truly stateless). For instance, the useful jQuery idiom ``` $(function() { // some actions }); ``` used to enhance your DOM or attach events to the DOM elements may not interact very well with the ASP.NET PostBack model if there are UpdatePanels in the page. By now, I circumvent it with the following code snippet ``` if (Sys.WebForms.PageRequestManager) { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function() { $('#updateListView1').trigger("gridLoaded"); }); } ``` where `gridLoaded` will be the replacement of `$(document).ready`. I think you have to take extra care and know very well the ASP.NET Page/Controls Life-Cycle in order to mix both technologies.
148,225
<p>Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.</p> <p>Particular order doesn't matter much here.</p> <p>I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask.</p>
[ { "answer_id": 148230, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "<pre><code>#include &lt;stdint.h&gt;\n#include &lt;stdio.h&gt;\n\nunion ui64 {\n uint64_t one;\n uint16_t four[4];\n};\...
2008/09/29
[ "https://Stackoverflow.com/questions/148225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it. Particular order doesn't matter much here. I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask.
``` #include <stdint.h> #include <stdio.h> union ui64 { uint64_t one; uint16_t four[4]; }; int main() { union ui64 number = {0x123456789abcdef0}; printf("%x %x %x %x\n", number.four[0], number.four[1], number.four[2], number.four[3]); return 0; } ```
148,251
<p>My favorite equation for centering an xhtml element using only CSS is as follows:</p> <pre><code>display: block; position: absolute; width: _insert width here_; left: 50%; margin-left: _insert width divided by two &amp; multiplied by negative one here_ </code></pre> <p>There's also the simpler margin:auto method in browsers that support it. Does anyone else have tricky ways to force content to display centered in its container? (bonus points for vertical centering)</p> <p>edit - oops, forgot the 'negative' part of one in the margin-left. fixed.</p>
[ { "answer_id": 148265, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "<p>Well that seems like massive overkill, I've got to say. I tend to set the container to <code>text-align:center;</code> for ...
2008/09/29
[ "https://Stackoverflow.com/questions/148251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14026/" ]
My favorite equation for centering an xhtml element using only CSS is as follows: ``` display: block; position: absolute; width: _insert width here_; left: 50%; margin-left: _insert width divided by two & multiplied by negative one here_ ``` There's also the simpler margin:auto method in browsers that support it. Does anyone else have tricky ways to force content to display centered in its container? (bonus points for vertical centering) edit - oops, forgot the 'negative' part of one in the margin-left. fixed.
Stick with Margin: 0 auto; for horizontal alignment; If you need vertical alignment as well use position: absolute; top: 50%; margin-top: -(width/2)px; Be aware though, If your container has more width than your screen a part of it will fall off screen on the left side using the Position: absolute method.
148,262
<p>In Oracle, I have set the <code>log_archive_dest1='D:\app\administrator\orcl\archive'</code> parameter and shutdown the database. When I tried to start up the db, I got the following error:</p> <pre><code>SQL&gt; startup mount; ORA-16032: parameter LOG_ARCHIVE_DEST_1 destination string cannot be translated ORA-09291: sksachk: invalid device specified for archive destination OSD-04018: Unable to access the specified directory or device. O/S-Error: (OS 3) The system cannot find the path specified. </code></pre> <p>Does anyone have any ideas of how I might fix this?</p>
[ { "answer_id": 148285, "author": "sparklewhiskers", "author_id": 23402, "author_profile": "https://Stackoverflow.com/users/23402", "pm_score": 1, "selected": false, "text": "<p>I've never used Oracle but some things you might try are</p>\n\n<ul>\n<li>Make sure the permissions on the file...
2008/09/29
[ "https://Stackoverflow.com/questions/148262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In Oracle, I have set the `log_archive_dest1='D:\app\administrator\orcl\archive'` parameter and shutdown the database. When I tried to start up the db, I got the following error: ``` SQL> startup mount; ORA-16032: parameter LOG_ARCHIVE_DEST_1 destination string cannot be translated ORA-09291: sksachk: invalid device specified for archive destination OSD-04018: Unable to access the specified directory or device. O/S-Error: (OS 3) The system cannot find the path specified. ``` Does anyone have any ideas of how I might fix this?
You probably need a trailing \ on the dir name ie D:\app\administrator\orcl\archive\
148,275
<p>I want to draw DirectX content so that it appears to be floating over top of the desktop and any other applications that are running. I also need to be able to make the directx content semi-transparent, so other things show through. Is there a way of doing this?</p> <p>I am using Managed DX with C#.</p>
[ { "answer_id": 148288, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 2, "selected": false, "text": "<p>I guess that will be hard without using the Desktop Window Manager, i.e. if you want to support Windows XP. With th...
2008/09/29
[ "https://Stackoverflow.com/questions/148275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23407/" ]
I want to draw DirectX content so that it appears to be floating over top of the desktop and any other applications that are running. I also need to be able to make the directx content semi-transparent, so other things show through. Is there a way of doing this? I am using Managed DX with C#.
I found a solution which works on Vista, starting from the link provided by OregonGhost. This is the basic process, in C# syntax. This code is in a class inheriting from Form. It doesn't seem to work if in a UserControl: ``` //this will allow you to import the necessary functions from the .dll using System.Runtime.InteropServices; //this imports the function used to extend the transparent window border. [DllImport("dwmapi.dll")] static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins); //this is used to specify the boundaries of the transparent area internal struct Margins { public int Left, Right, Top, Bottom; } private Margins marg; //Do this every time the form is resized. It causes the window to be made transparent. marg.Left = 0; marg.Top = 0; marg.Right = this.Width; marg.Bottom = this.Height; DwmExtendFrameIntoClientArea(this.Handle, ref marg); //This initializes the DirectX device. It needs to be done once. //The alpha channel in the backbuffer is critical. PresentParameters presentParameters = new PresentParameters(); presentParameters.Windowed = true; presentParameters.SwapEffect = SwapEffect.Discard; presentParameters.BackBufferFormat = Format.A8R8G8B8; Device device = new Device(0, DeviceType.Hardware, this.Handle, CreateFlags.HardwareVertexProcessing, presentParameters); //the OnPaint functions maked the background transparent by drawing black on it. //For whatever reason this results in transparency. protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; // black brush for Alpha transparency SolidBrush blackBrush = new SolidBrush(Color.Black); g.FillRectangle(blackBrush, 0, 0, Width, Height); blackBrush.Dispose(); //call your DirectX rendering function here } //this is the dx rendering function. The Argb clearing function is important, //as it makes the directx background transparent. protected void dxrendering() { device.Clear(ClearFlags.Target, Color.FromArgb(0, 0, 0, 0), 1.0f, 0); device.BeginScene(); //draw stuff here. device.EndScene(); device.Present(); } ``` Lastly, a Form with default setting will have a glassy looking partially transparent background. Set the FormBorderStyle to "none" and it will be 100% transparent with only your content floating above everything.
148,281
<p>The output we get when printing C++ sources from Eclipse is rather ugly. </p> <p>Is there are way/a plugin to pretty print C++ source code like e.g. with a2ps (which is probably using yet another filter for C source code)?</p>
[ { "answer_id": 148313, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 2, "selected": false, "text": "<p>See this <a href=\"http://www.ddj.com/cpp/197002115?pgno=4\" rel=\"nofollow noreferrer\">DDJ</a> article which uses <em>ensc...
2008/09/29
[ "https://Stackoverflow.com/questions/148281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19734/" ]
The output we get when printing C++ sources from Eclipse is rather ugly. Is there are way/a plugin to pretty print C++ source code like e.g. with a2ps (which is probably using yet another filter for C source code)?
I also use `enscript` for this. Here's an alias I often use: ``` alias cpp2ps='enscript --color --pretty-print=cpp --language=PostScript' ``` and I use it like this: ``` cpp2ps -P main.ps main.cpp ``` There are several other great options in `enscript` including rotating, 2-column output, line numbers, headers/footers, etc. Check out the [enscript man page](http://linux.die.net/man/1/enscript). Also, on Macs, XCode prints C++ code very nicely.
148,298
<p>Okay, we know that the following two lines are equivalent - </p> <ol> <li><code>(0 == i)</code></li> <li><code>(i == 0)</code></li> </ol> <p>Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='.</p> <p>My question is - in today's generation of pretty slick IDE's and intelligent compilers, do you still recommend the first method? </p> <p>In particular, this question popped into my mind when I saw the following code - </p> <pre><code>if(DialogResult.OK == MessageBox.Show("Message")) ... </code></pre> <p>In my opinion, I would never recommend the above. Any second opinions?</p>
[ { "answer_id": 148299, "author": "Hans Sjunnesson", "author_id": 8683, "author_profile": "https://Stackoverflow.com/users/8683", "pm_score": 2, "selected": false, "text": "<p>I think it's just a matter of style. And it does help with accidentally using assignment operator.</p>\n\n<p>I ab...
2008/09/29
[ "https://Stackoverflow.com/questions/148298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621/" ]
Okay, we know that the following two lines are equivalent - 1. `(0 == i)` 2. `(i == 0)` Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='. My question is - in today's generation of pretty slick IDE's and intelligent compilers, do you still recommend the first method? In particular, this question popped into my mind when I saw the following code - ``` if(DialogResult.OK == MessageBox.Show("Message")) ... ``` In my opinion, I would never recommend the above. Any second opinions?
I prefer the second one, (i == 0), because it feel much more natural when reading it. You ask people, "Are you 21 or older?", not, "Is 21 less than or equal to your age?"
148,305
<p>I'm working on a SaaS application where each customer will have different configurations depending on the edition they have purchased, additional features they have purchased, etc. For example, a customer might have a limit of 3 custom reports.</p> <p>Obviously I want to store this configuration in the database, but I am unsure of the best approach. We want to be able to add additional features in the future without requiring a change to the database schema, so a single table with a column per configuration option isn't sensible.</p> <p>Possible options are a table with one entry per customer, with an XML field containing the entire configuration for that customer, but that adds complexity when the XML schema changes to add additional features.</p> <p>We could use a table with key value pairs, and store all configuration settings as strings and then parse to the correct data type, but that seems a bit of a cludge, as does having a seperate table for string config options, integer config options, etc.</p> <p>Is there a good pattern for this type of scenario which people are using?</p>
[ { "answer_id": 148331, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>The key value pair table, but with everything is stored as a string and with another column (if necessary) saying...
2008/09/29
[ "https://Stackoverflow.com/questions/148305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048/" ]
I'm working on a SaaS application where each customer will have different configurations depending on the edition they have purchased, additional features they have purchased, etc. For example, a customer might have a limit of 3 custom reports. Obviously I want to store this configuration in the database, but I am unsure of the best approach. We want to be able to add additional features in the future without requiring a change to the database schema, so a single table with a column per configuration option isn't sensible. Possible options are a table with one entry per customer, with an XML field containing the entire configuration for that customer, but that adds complexity when the XML schema changes to add additional features. We could use a table with key value pairs, and store all configuration settings as strings and then parse to the correct data type, but that seems a bit of a cludge, as does having a seperate table for string config options, integer config options, etc. Is there a good pattern for this type of scenario which people are using?
I think this would depend on how your product was sold to the customer. If you only sell it in packages... ``` PACKAGE 1 -> 3 reports, date entry, some other stuff. PACKAGE 2 -> 6 reports, more stuff PACKAGE 3 -> 12 reports, almost all the stuff UBER PACKAGE -> everything ``` I would think it would be easier to setup a table of those packages and link to that. If you sell each module by itself with variations... ``` Customer wants 4 reports a week with an additional report every other tuesday if it's a full moon. ``` Then I would -- ``` Create a table with all the product features. Create a link table for customers and the features they want. In that link table add an additional field for modification if needed. ``` CUSTOMERS ``` customer_id (pk) ``` MODULES ``` module_id (pk) module_name (reports!) ``` CUSTOMER\_MODULES ``` module_id (pk) (fk -> modules) customer_id (pk) (fk -> customers) customization (configuration file or somesuch?) ``` This makes the most sense to me.
148,314
<p>I have integrated SRM 5.0 into Portal. Most of the iviews are IAC i.e., all are ITS based services.</p> <p>The issue is that the Portal Theme does not get reflected on these services after integration.</p> <p>When a BSP or Webdynpro is integrated then the application reflects the Portal Theme when executed from Portal but the ITS services are not getting this.</p> <p>I tried using SE80 and editing EBPApplication.css. In BBPGLOBAL i changed all color attributes to custom colour but no effect.</p> <p>Whch property should i change to remove the blue colour.</p>
[ { "answer_id": 148331, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>The key value pair table, but with everything is stored as a string and with another column (if necessary) saying...
2008/09/29
[ "https://Stackoverflow.com/questions/148314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have integrated SRM 5.0 into Portal. Most of the iviews are IAC i.e., all are ITS based services. The issue is that the Portal Theme does not get reflected on these services after integration. When a BSP or Webdynpro is integrated then the application reflects the Portal Theme when executed from Portal but the ITS services are not getting this. I tried using SE80 and editing EBPApplication.css. In BBPGLOBAL i changed all color attributes to custom colour but no effect. Whch property should i change to remove the blue colour.
I think this would depend on how your product was sold to the customer. If you only sell it in packages... ``` PACKAGE 1 -> 3 reports, date entry, some other stuff. PACKAGE 2 -> 6 reports, more stuff PACKAGE 3 -> 12 reports, almost all the stuff UBER PACKAGE -> everything ``` I would think it would be easier to setup a table of those packages and link to that. If you sell each module by itself with variations... ``` Customer wants 4 reports a week with an additional report every other tuesday if it's a full moon. ``` Then I would -- ``` Create a table with all the product features. Create a link table for customers and the features they want. In that link table add an additional field for modification if needed. ``` CUSTOMERS ``` customer_id (pk) ``` MODULES ``` module_id (pk) module_name (reports!) ``` CUSTOMER\_MODULES ``` module_id (pk) (fk -> modules) customer_id (pk) (fk -> customers) customization (configuration file or somesuch?) ``` This makes the most sense to me.
148,350
<p>I want to be able to access custom URLs with apache httpclient. Something like this:</p> <pre><code>HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("media:///squishy.jpg"); int statusCode = client.executeMethod(method); </code></pre> <p>Can I somehow register a custom URL handler? Or should I just register one with Java, using</p> <pre><code>URL.setURLStreamHandlerFactory(...) </code></pre> <p>Regards.</p>
[ { "answer_id": 148390, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 1, "selected": true, "text": "<p>I don't think there's a way to do this in commons httpclient. It doesn't make a whole lot of sense either, after all it is a H...
2008/09/29
[ "https://Stackoverflow.com/questions/148350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11384/" ]
I want to be able to access custom URLs with apache httpclient. Something like this: ``` HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("media:///squishy.jpg"); int statusCode = client.executeMethod(method); ``` Can I somehow register a custom URL handler? Or should I just register one with Java, using ``` URL.setURLStreamHandlerFactory(...) ``` Regards.
I don't think there's a way to do this in commons httpclient. It doesn't make a whole lot of sense either, after all it is a HTTP client and "media:///squishy.jpg" is not HTTP, so all the code to implement the HTTP protocol probably couldn't be used anyways. ``` URL.setURLStreamHandlerFactory(...) ``` could be the way to go, but you'll probably have to do a lot of protocol coding by hand, depending on your "media"-protocol.
148,361
<p>I am building an application where I want to be able to click a rectangle represented by a DIV, and then use the keyboard to move that DIV by listing for keyboard events.</p> <p>Rather than using an event listener for those keyboard events at the document level, can I listen for keyboard events at the DIV level, perhaps by giving it keyboard focus?</p> <p>Here's a simplified sample to illustrate the problem:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="outer" style="background-color:#eeeeee;padding:10px"&gt; outer &lt;div id="inner" style="background-color:#bbbbbb;width:50%;margin:10px;padding:10px;"&gt; want to be able to focus this element and pick up keypresses &lt;/div&gt; &lt;/div&gt; &lt;script language="Javascript"&gt; function onClick() { document.getElementById('inner').innerHTML="clicked"; document.getElementById('inner').focus(); } //this handler is never called function onKeypressDiv() { document.getElementById('inner').innerHTML="keypress on div"; } function onKeypressDoc() { document.getElementById('inner').innerHTML="keypress on doc"; } //install event handlers document.getElementById('inner').addEventListener("click", onClick, false); document.getElementById('inner').addEventListener("keypress", onKeypressDiv, false); document.addEventListener("keypress", onKeypressDoc, false); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>On clicking the inner DIV I try to give it focus, but subsequent keyboard events are always picked up at the document level, not my DIV level event listener.</p> <p>Do I simply need to implement an application-specific notion of keyboard focus?</p> <p>I should add I only need this to work in Firefox.</p>
[ { "answer_id": 148444, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 8, "selected": true, "text": "<p>Sorted - I added tabindex attribute to the target DIV, which causes it to pick up keyboard events, for example</p>\n\n<...
2008/09/29
[ "https://Stackoverflow.com/questions/148361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6521/" ]
I am building an application where I want to be able to click a rectangle represented by a DIV, and then use the keyboard to move that DIV by listing for keyboard events. Rather than using an event listener for those keyboard events at the document level, can I listen for keyboard events at the DIV level, perhaps by giving it keyboard focus? Here's a simplified sample to illustrate the problem: ``` <html> <head> </head> <body> <div id="outer" style="background-color:#eeeeee;padding:10px"> outer <div id="inner" style="background-color:#bbbbbb;width:50%;margin:10px;padding:10px;"> want to be able to focus this element and pick up keypresses </div> </div> <script language="Javascript"> function onClick() { document.getElementById('inner').innerHTML="clicked"; document.getElementById('inner').focus(); } //this handler is never called function onKeypressDiv() { document.getElementById('inner').innerHTML="keypress on div"; } function onKeypressDoc() { document.getElementById('inner').innerHTML="keypress on doc"; } //install event handlers document.getElementById('inner').addEventListener("click", onClick, false); document.getElementById('inner').addEventListener("keypress", onKeypressDiv, false); document.addEventListener("keypress", onKeypressDoc, false); </script> </body> </html> ``` On clicking the inner DIV I try to give it focus, but subsequent keyboard events are always picked up at the document level, not my DIV level event listener. Do I simply need to implement an application-specific notion of keyboard focus? I should add I only need this to work in Firefox.
Sorted - I added tabindex attribute to the target DIV, which causes it to pick up keyboard events, for example ``` <div id="inner" tabindex="0"> this div can now have focus and receive keyboard events </div> ``` Information gleaned from <http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html>
148,373
<p>I wrote a sample program at <a href="http://codepad.org/ko8vVCDF" rel="noreferrer">http://codepad.org/ko8vVCDF</a> that uses a template function.</p> <p>How do I retrict the template function to only use numbers? (int, double etc.)</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; T sum(vector&lt;T&gt;&amp; a) { T result = 0; int size = a.size(); for(int i = 0; i &lt; size; i++) { result += a[i]; } return result; } int main() { vector&lt;int&gt; int_values; int_values.push_back(2); int_values.push_back(3); cout &lt;&lt; "Integer: " &lt;&lt; sum(int_values) &lt;&lt; endl; vector&lt;double&gt; double_values; double_values.push_back(1.5); double_values.push_back(2.1); cout &lt;&lt; "Double: " &lt;&lt; sum(double_values); return 0; } </code></pre>
[ { "answer_id": 148377, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>Why would you want to restrict the types in this case? Templates allow \"static duck typing\", so anything allowed by wha...
2008/09/29
[ "https://Stackoverflow.com/questions/148373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22040/" ]
I wrote a sample program at <http://codepad.org/ko8vVCDF> that uses a template function. How do I retrict the template function to only use numbers? (int, double etc.) ``` #include <vector> #include <iostream> using namespace std; template <typename T> T sum(vector<T>& a) { T result = 0; int size = a.size(); for(int i = 0; i < size; i++) { result += a[i]; } return result; } int main() { vector<int> int_values; int_values.push_back(2); int_values.push_back(3); cout << "Integer: " << sum(int_values) << endl; vector<double> double_values; double_values.push_back(1.5); double_values.push_back(2.1); cout << "Double: " << sum(double_values); return 0; } ```
The only way to restrict a template is to make it so that it uses something from the types that you want, that other types don't have. So, you construct with an int, use + and +=, call a copy constructor, etc. Any type that has all of these will work with your function -- so, if I create a new type that has these features, your function will work on it -- which is great, isn't it? If you want to restrict it more, use more functions that only are defined for the type you want. Another way to implement this is by creating a traits template -- something like this ``` template<class T> SumTraits { public: const static bool canUseSum = false; } ``` And then specialize it for the classes you want to be ok: ``` template<> class SumTraits<int> { public: const static bool canUseSum = true; }; ``` Then in your code, you can write ``` if (!SumTraits<T>::canUseSum) { // throw something here } ``` edit: as mentioned in the comments, you can use BOOST\_STATIC\_ASSERT to make it a compile-time check instead of a run-time one
148,403
<p>Is it possible to convert UTF8 string in a std::string to std::wstring and vice versa in a platform independent manner? In a Windows application I would use MultiByteToWideChar and WideCharToMultiByte. However, the code is compiled for multiple OSes and I'm limited to standard C++ library.</p>
[ { "answer_id": 148419, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"http://en.cppreference.com/w/cpp/locale/codecvt\" rel=\"nofollow noreferrer\"><code>codecvt</co...
2008/09/29
[ "https://Stackoverflow.com/questions/148403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22764/" ]
Is it possible to convert UTF8 string in a std::string to std::wstring and vice versa in a platform independent manner? In a Windows application I would use MultiByteToWideChar and WideCharToMultiByte. However, the code is compiled for multiple OSes and I'm limited to standard C++ library.
I've asked this question 5 years ago. This thread was very helpful for me back then, I came to a conclusion, then I moved on with my project. It is funny that I needed something similar recently, totally unrelated to that project from the past. As I was researching for possible solutions, I stumbled upon my own question :) The solution I chose now is based on C++11. The boost libraries that Constantin mentions in [his answer](https://stackoverflow.com/a/148665/22764) are now part of the standard. If we replace std::wstring with the new string type std::u16string, then the conversions will look like this: *UTF-8 to UTF-16* ``` std::string source; ... std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert; std::u16string dest = convert.from_bytes(source); ``` *UTF-16 to UTF-8* ``` std::u16string source; ... std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert; std::string dest = convert.to_bytes(source); ``` As seen from the other answers, there are multiple approaches to the problem. That's why I refrain from picking an accepted answer.
148,407
<p>Why does the code below return true only for a = 1?</p> <pre><code>main(){ int a = 10; if (true == a) cout&lt;&lt;"Why am I not getting executed"; } </code></pre>
[ { "answer_id": 148411, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 2, "selected": false, "text": "<p>Because true is 1. If you want to test a for a non-zero value, just write if(a).</p>\n" }, { "answer_id": 1...
2008/09/29
[ "https://Stackoverflow.com/questions/148407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
Why does the code below return true only for a = 1? ``` main(){ int a = 10; if (true == a) cout<<"Why am I not getting executed"; } ```
When a Bool true is converted to an int, it's always converted to 1. Your code is thus, equivalent to: ``` main(){ int a = 10; if (1 == a) cout<<"y i am not getting executed"; } ``` This is part of the [C++ standard](http://www.bond.id.au/~gnb/wp/cd2/conv.html), so it's something you would expect to happen with every C++ standards compliant compiler.
148,421
<p>I have a button on an ASP.NET wep application form and when clicked goes off and posts information a third party web service. </p> <p>I have an UpdateProgress associated with the button. </p> <p>how do disable/hide the button while the progress is visible (i.e. the server has not completed the operation) </p> <p>I am looking at doing this to stop users clicking again when the information is being sent (as this results in duplicate information being sent) </p>
[ { "answer_id": 148426, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>Easiest way it to put a semi-transparent png over the entire page -- then they can't send events to the page below. I...
2008/09/29
[ "https://Stackoverflow.com/questions/148421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
I have a button on an ASP.NET wep application form and when clicked goes off and posts information a third party web service. I have an UpdateProgress associated with the button. how do disable/hide the button while the progress is visible (i.e. the server has not completed the operation) I am looking at doing this to stop users clicking again when the information is being sent (as this results in duplicate information being sent)
You'll have to hook a javascript method to the page request manager (Sys.WebForms.PageRequestManager.getInstance().add\_initializeRequest). Here is the code I would use to hide the buttons, I would prefer the disable them (see how that's done in the link at the bottom). ASP.NET ------- ``` <div id="ButtonBar"> <asp:Button id= ............ </div> ``` Javascript ---------- ``` <script language="javascript"> // Get a reference to the PageRequestManager. var prm = Sys.WebForms.PageRequestManager.getInstance(); // Using that prm reference, hook _initializeRequest // and _endRequest, to run our code at the begin and end // of any async postbacks that occur. prm.add_initializeRequest(InitializeRequest); prm.add_endRequest(EndRequest); // Executed anytime an async postback occurs. function InitializeRequest(sender, args) { $get('ButtonBar').style.visibility = "hidden"; } // Executed when the async postback completes. function EndRequest(sender, args) { $get('ButtonBar').style.visibility = "visible"; } </script> ``` See more about this at [Why my ASP.NET AJAX forms are never submitted twice by Dave Ward](http://encosia.com/2008/03/04/why-my-aspnet-ajax-forms-are-never-submitted-twice/).
148,441
<p>If I have a script tag like this:</p> <pre><code>&lt;script id = "myscript" src = "http://www.example.com/script.js" type = "text/javascript"&gt; &lt;/script&gt; </code></pre> <p>I would like to get the content of the "script.js" file. I'm thinking about something like <code>document.getElementById("myscript").text</code> but it doesn't work in this case.</p>
[ { "answer_id": 148447, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 5, "selected": true, "text": "<p>Do you want to get the contents of the file <a href=\"http://www.example.com/script.js\" rel=\"nofollow noreferrer\">http://...
2008/09/29
[ "https://Stackoverflow.com/questions/148441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23423/" ]
If I have a script tag like this: ``` <script id = "myscript" src = "http://www.example.com/script.js" type = "text/javascript"> </script> ``` I would like to get the content of the "script.js" file. I'm thinking about something like `document.getElementById("myscript").text` but it doesn't work in this case.
Do you want to get the contents of the file <http://www.example.com/script.js>? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.
148,451
<p>I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file. </p> <p>How do I get <code>sed</code> to replace just the first occurrence of a string in a file rather than replacing every occurrence?</p> <p>If I use</p> <pre><code>sed s/#include/#include "newfile.h"\n#include/ </code></pre> <p>it replaces all #includes. </p> <p>Alternative suggestions to achieve the same thing are also welcome.</p>
[ { "answer_id": 148473, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 8, "selected": true, "text": "<pre><code> # sed script to change \"foo\" to \"bar\" only on the first occurrence\n 1{x;s/^/first/;x;}\n 1,/foo/{x;/fi...
2008/09/29
[ "https://Stackoverflow.com/questions/148451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5022/" ]
I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file. How do I get `sed` to replace just the first occurrence of a string in a file rather than replacing every occurrence? If I use ``` sed s/#include/#include "newfile.h"\n#include/ ``` it replaces all #includes. Alternative suggestions to achieve the same thing are also welcome.
``` # sed script to change "foo" to "bar" only on the first occurrence 1{x;s/^/first/;x;} 1,/foo/{x;/first/s///;x;s/foo/bar/;} #---end of script--- ``` or, if you prefer: Editor's note: works with *GNU* `sed` only. ```sh sed '0,/foo/s//bar/' file ``` [Source](http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_004.html)
148,503
<p>I am trying to upload a file using to Flickr using JQuery. I have a form (which works if I dont use JQuery) which I am submitting using the Form Plugin. My code is as follows:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Test Upload&lt;/title&gt; &lt;script type="text/javascript" src="jquery-1.2.6.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.form.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $('#myForm').bind('submit', function() { $(this).ajaxSubmit({ dataType: 'xml', success: processXml }); return false; // &lt;-- important! }); }); function processXml(responseXML) { var message = $('message', responseXML).text(); document.getElementById('output').innerHTML = message; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="myForm" method="post" action="http://api.flickr.com/services/upload/" enctype="multipart/form-data"&gt; &lt;input type="file" name="photo" id="photo"/&gt; &lt;input type="text" name="api_key" id="api_key" value="..snip.."/&gt; &lt;input type="text" name="auth_token" id="auth_token" value="..snip.."/&gt; &lt;input type="text" name="api_sig" id="api_sig" value="..snip.."/&gt; &lt;input type="submit" value="Upload"/&gt; &lt;/form&gt; &lt;div id="output"&gt;AJAX response will replace this content.&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The problem is I get the following text as a response:</p> <pre><code>&lt;rsp stat="fail"&gt; &lt;err code="100" msg="Invalid API Key (Key not found)" /&gt; &lt;/rsp&gt; </code></pre> <p>even though the file uploads with no problems. This means my div is not updated as it doesnt run the success function. Any one have any ideas.</p> <p>Thanks</p>
[ { "answer_id": 148534, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 0, "selected": false, "text": "<p>You will not be able to upload a file via AJAX this way.</p>\n\n<p>A pure AJAX file upload system is not possible because...
2008/09/29
[ "https://Stackoverflow.com/questions/148503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to upload a file using to Flickr using JQuery. I have a form (which works if I dont use JQuery) which I am submitting using the Form Plugin. My code is as follows: ``` <html> <head> <title>Test Upload</title> <script type="text/javascript" src="jquery-1.2.6.js"></script> <script type="text/javascript" src="jquery.form.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#myForm').bind('submit', function() { $(this).ajaxSubmit({ dataType: 'xml', success: processXml }); return false; // <-- important! }); }); function processXml(responseXML) { var message = $('message', responseXML).text(); document.getElementById('output').innerHTML = message; } </script> </head> <body> <form id="myForm" method="post" action="http://api.flickr.com/services/upload/" enctype="multipart/form-data"> <input type="file" name="photo" id="photo"/> <input type="text" name="api_key" id="api_key" value="..snip.."/> <input type="text" name="auth_token" id="auth_token" value="..snip.."/> <input type="text" name="api_sig" id="api_sig" value="..snip.."/> <input type="submit" value="Upload"/> </form> <div id="output">AJAX response will replace this content.</div> </body> </html> ``` The problem is I get the following text as a response: ``` <rsp stat="fail"> <err code="100" msg="Invalid API Key (Key not found)" /> </rsp> ``` even though the file uploads with no problems. This means my div is not updated as it doesnt run the success function. Any one have any ideas. Thanks
See this other thread about uploading files with AJAX: [How can I upload files asynchronously?](https://stackoverflow.com/questions/166221/how-to-upload-file-jquery) I've never tried it, but it seems that you can't get the server response (not easily, anyway)
148,511
<p>Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such:</p> <pre><code>LimitedValue&lt; float, 0, 360 &gt; someAngle( 45.0 ); someTrigFunction( someAngle ); </code></pre> <p>so that 'someTrigFunction' knows that it is guaranteed to be supplied a valid input (The constructor would throw an exception if the parameter is invalid).</p> <p>Copy-construction and assignment are limited to exactly equal types, though. I'd like to be able to do:</p> <pre><code>LimitedValue&lt; float, 0, 90 &gt; smallAngle( 45.0 ); LimitedValue&lt; float, 0, 360 &gt; anyAngle( smallAngle ); </code></pre> <p>and have that operation checked at compile-time, so this next example gives an error:</p> <pre><code>LimitedValue&lt; float, -90, 0 &gt; negativeAngle( -45.0 ); LimitedValue&lt; float, 0, 360 &gt; postiveAngle( negativeAngle ); // ERROR! </code></pre> <p>Is this possible? Is there some practical way of doing this, or any examples out there which approach this?</p>
[ { "answer_id": 148539, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 1, "selected": false, "text": "<p>At the moment, that is impossible in a portable manner due to the C++ rules on how methods (and by extension, construc...
2008/09/29
[ "https://Stackoverflow.com/questions/148511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23434/" ]
Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such: ``` LimitedValue< float, 0, 360 > someAngle( 45.0 ); someTrigFunction( someAngle ); ``` so that 'someTrigFunction' knows that it is guaranteed to be supplied a valid input (The constructor would throw an exception if the parameter is invalid). Copy-construction and assignment are limited to exactly equal types, though. I'd like to be able to do: ``` LimitedValue< float, 0, 90 > smallAngle( 45.0 ); LimitedValue< float, 0, 360 > anyAngle( smallAngle ); ``` and have that operation checked at compile-time, so this next example gives an error: ``` LimitedValue< float, -90, 0 > negativeAngle( -45.0 ); LimitedValue< float, 0, 360 > postiveAngle( negativeAngle ); // ERROR! ``` Is this possible? Is there some practical way of doing this, or any examples out there which approach this?
You can do this using templates -- try something like this: ``` template< typename T, int min, int max >class LimitedValue { template< int min2, int max2 >LimitedValue( const LimitedValue< T, min2, max2 > &other ) { static_assert( min <= min2, "Parameter minimum must be >= this minimum" ); static_assert( max >= max2, "Parameter maximum must be <= this maximum" ); // logic } // rest of code }; ```
148,513
<p>Using <a href="http://en.wikipedia.org/wiki/Apache_Ant" rel="nofollow noreferrer">Ant</a> I could unzip an archive before proceeding with the build per-se ... Is this possible using nmake? Could I call an external application? Or even a batch script?</p>
[ { "answer_id": 148560, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 0, "selected": false, "text": "<p>You can call an external application from nmake Makefiles, just as from any other Makefile.</p>\n\n<p>However, what to ...
2008/09/29
[ "https://Stackoverflow.com/questions/148513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ]
Using [Ant](http://en.wikipedia.org/wiki/Apache_Ant) I could unzip an archive before proceeding with the build per-se ... Is this possible using nmake? Could I call an external application? Or even a batch script?
Any variant on make has the ability to perform any task that can be done from the command line. Indeed, most of the build functionality of any makefile is going to depend upon the onvocation of external processes such as the compiler, linker, librarian, etc. The only downside to make is that there are so many variations of syntax (nmake, borland make, GNU make, etc.) that make it practically impossible to write a single cross-platform makefile. In answer to your particular question consider the following: > > > ``` > > main.cpp: archive.zip > unzip archive.zip > > ``` > > This basically states that main.cpp depends upon archive.zip and states that this dependency can be satisfied by invoking the "unzip" command.
148,518
<p>It seems the .NET Regex.Replace method automatically replaces all matching occurrences. I could provide a MatchEvaluator delegate that returns the matched string after the first replacement, rendering no change, but that sounds very inefficient to me.</p> <p>What is the most efficient way to stop after the first replacement?</p>
[ { "answer_id": 148526, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 6, "selected": true, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx\" rel=\"noreferrer\"...
2008/09/29
[ "https://Stackoverflow.com/questions/148518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347/" ]
It seems the .NET Regex.Replace method automatically replaces all matching occurrences. I could provide a MatchEvaluator delegate that returns the matched string after the first replacement, rendering no change, but that sounds very inefficient to me. What is the most efficient way to stop after the first replacement?
From [MSDN](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx): ``` Replace(String, String, Int32) ``` > > Within a specified input string, replaces a specified maximum number of strings that > match a regular expression pattern with a specified replacement string. > > > Isn't this what you want?
148,587
<p>I am currently getting exceptions when modifying an IBindingList on multiple threads. Does anyone have a threadsafe version before I write my own?</p>
[ { "answer_id": 148639, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 2, "selected": false, "text": "<p>I think you'll find this an incredibly difficult task. The easier path would be to prevent multiple-thread access with...
2008/09/29
[ "https://Stackoverflow.com/questions/148587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23385/" ]
I am currently getting exceptions when modifying an IBindingList on multiple threads. Does anyone have a threadsafe version before I write my own?
I think you'll find this an incredibly difficult task. The easier path would be to prevent multiple-thread access with a `lock`: ``` void AddItemToList(object o) { lock(myBindingList) { myBindingList.Add(o); } } ``` Look at the [lock statement docs](http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx) for more info.
148,594
<p>Suppose I have a non-recurring event that needs to be raised X seconds from now such as a timeout. Intuitively it would make sense to create a System.Timers.Timer, set its interval to X*1000, wire its tick up to the event and start it. Since this is a non-recurring event and you only want it raised once you would then have to stop the timer after it ticks.</p> <p>The fact that Timers are inherently recurring however makes me distrustful if this is indeed the best way of doing it. Would it be better/more accurate/safer to save the time started, set the timer to tick every second (or even millisecond) and on tick poll the system for time and manually raise the target event only once the requisite time has elapsed?</p> <p>Can anyone weigh in on which if either method is best (perhaps there is another option I didn't think of too). Does one method become better than the other if the timespan that I need to wait is measured in milliseconds?</p>
[ { "answer_id": 148602, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 3, "selected": false, "text": "<p>just use a normal timer and disable it after it has elapsed once.\nthat should solve your problem.</p>\n\n...
2008/09/29
[ "https://Stackoverflow.com/questions/148594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
Suppose I have a non-recurring event that needs to be raised X seconds from now such as a timeout. Intuitively it would make sense to create a System.Timers.Timer, set its interval to X\*1000, wire its tick up to the event and start it. Since this is a non-recurring event and you only want it raised once you would then have to stop the timer after it ticks. The fact that Timers are inherently recurring however makes me distrustful if this is indeed the best way of doing it. Would it be better/more accurate/safer to save the time started, set the timer to tick every second (or even millisecond) and on tick poll the system for time and manually raise the target event only once the requisite time has elapsed? Can anyone weigh in on which if either method is best (perhaps there is another option I didn't think of too). Does one method become better than the other if the timespan that I need to wait is measured in milliseconds?
This [constructor](http://msdn.microsoft.com/en-us/library/ah1h85ch.aspx) for the System.Threading.Timer allows you to specify a **period**. If you set this parameter to -1, it will disable periodic signaling and only execute once. ``` public Timer( TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period ) ```
148,601
<p>Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template?</p> <p>I would like to be able to write something like this:</p> <pre><code>#if ($a lt Long.MAX_VALUE) </code></pre> <p>but this is apparently not the right syntax.</p>
[ { "answer_id": 148650, "author": "Angelo van der Sijpt", "author_id": 19144, "author_profile": "https://Stackoverflow.com/users/19144", "pm_score": 3, "selected": false, "text": "<p>Velocity can only use anything it finds in its context, after e.g.</p>\n\n<pre><code>context.put(\"MaxLong...
2008/09/29
[ "https://Stackoverflow.com/questions/148601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4728/" ]
Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template? I would like to be able to write something like this: ``` #if ($a lt Long.MAX_VALUE) ``` but this is apparently not the right syntax.
There are a number of ways. 1) You can put the values directly in the context. 2) You can use the [FieldMethodizer](http://velocity.apache.org/engine/devel/apidocs/org/apache/velocity/app/FieldMethodizer.html) to make all public static fields in a class available. 3) You can use a custom Uberspect implementation that includes public static fields in the lookup order. 4) You can use the [FieldTool](http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/FieldTool.html) from VelocityTools. I recommend 1 for a few values, 2 for a few classes, 3 for lots of classes and values, and 4 if you are already using VelocityTools and would otherwise use 1 or 2.
148,662
<p>Suppose I have one list:</p> <pre><code>IList&lt;int&gt; originalList = new List&lt;int&gt;(); originalList.add(1); originalList.add(5); originalList.add(10); </code></pre> <p>And another list... </p> <pre><code>IList&lt;int&gt; newList = new List&lt;int&gt;(); newList.add(1); newList.add(5); newList.add(7); newList.add(11); </code></pre> <p>How can I update originalList so that: </p> <ol> <li>If the int appears in newList, keep</li> <li>If the int does not appear in newList, remove</li> <li>Add any ints from newList into originalList that aren't there already</li> </ol> <p>Thus - making the contents of originalList:</p> <pre><code>{ 1, 5, 7, 11 } </code></pre> <p>The reason I'm asking is because I have an object with a collection of children. When the user updates this collection, instead of just deleting all children, then inserting their selections, I think it would be more efficient if I just acted on the children that were added or removed, rather than tearing down the whole collection, and inserting the newList children as if they are all new.</p> <p>EDIT - Sorry - I wrote a horrible title... I should have written 'least amount of code' instead of 'efficient'. I think that threw off alot of the answers I've gotten. They are all great... thank you!</p>
[ { "answer_id": 148684, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<pre><code>originalList = newList;\n</code></pre>\n\n<p>Or if you prefer them being distinct lists:</p>\n\n<pre><code...
2008/09/29
[ "https://Stackoverflow.com/questions/148662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ]
Suppose I have one list: ``` IList<int> originalList = new List<int>(); originalList.add(1); originalList.add(5); originalList.add(10); ``` And another list... ``` IList<int> newList = new List<int>(); newList.add(1); newList.add(5); newList.add(7); newList.add(11); ``` How can I update originalList so that: 1. If the int appears in newList, keep 2. If the int does not appear in newList, remove 3. Add any ints from newList into originalList that aren't there already Thus - making the contents of originalList: ``` { 1, 5, 7, 11 } ``` The reason I'm asking is because I have an object with a collection of children. When the user updates this collection, instead of just deleting all children, then inserting their selections, I think it would be more efficient if I just acted on the children that were added or removed, rather than tearing down the whole collection, and inserting the newList children as if they are all new. EDIT - Sorry - I wrote a horrible title... I should have written 'least amount of code' instead of 'efficient'. I think that threw off alot of the answers I've gotten. They are all great... thank you!
Sorry, wrote my first response before I saw your last paragraph. ``` for(int i = originalList.length-1; i >=0; --i) { if (!newList.Contains(originalList[i]) originalList.RemoveAt(i); } foreach(int n in newList) { if (!originaList.Contains(n)) originalList.Add(n); } ```
148,669
<p>This <strike>is clearly not</strike> appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated.</p> <pre><code>//The constructor public Page_Index() { //create a local value string currentValue = "This is the FIRST value"; //use the local variable in a delegate that fires later this.Load += delegate(object sender, EventArgs e) { Response.Write(currentValue); }; //change it again currentValue = "This is the MODIFIED value"; } </code></pre> <p>The value that is output is the second value <em>"Modified"</em>. What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later?</p> <p>[Edit]: Given some of the comments, changing the original sentence some...</p>
[ { "answer_id": 148688, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>currentValue is no longer a local variable: it is a <em>captured</em> variable. This compiles to something like:</p...
2008/09/29
[ "https://Stackoverflow.com/questions/148669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17091/" ]
This is clearly not appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated. ``` //The constructor public Page_Index() { //create a local value string currentValue = "This is the FIRST value"; //use the local variable in a delegate that fires later this.Load += delegate(object sender, EventArgs e) { Response.Write(currentValue); }; //change it again currentValue = "This is the MODIFIED value"; } ``` The value that is output is the second value *"Modified"*. What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later? [Edit]: Given some of the comments, changing the original sentence some...
currentValue is no longer a local variable: it is a *captured* variable. This compiles to something like: ``` class Foo { public string currentValue; // yes, it is a field public void SomeMethod(object sender, EventArgs e) { Response.Write(currentValue); } } ... public Page_Index() { Foo foo = new Foo(); foo.currentValue = "This is the FIRST value"; this.Load += foo.SomeMethod; foo.currentValue = "This is the MODIFIED value"; } ``` Jon Skeet has a really good write up of this in [C# in Depth](http://www.manning.com/skeet/), and a separate (not as detailed) discussion [here](http://csharpindepth.com/Articles/Chapter5/Closures.aspx). Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers. This is different to java: in java the *value* of a variable is captured. In C#, the *variable itself* is captured.
148,704
<p>I've got the following user control:</p> <pre><code>&lt;TabItem x:Name="Self" x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" &gt; &lt;TabItem.Header&gt; &lt;!-- This works --&gt; &lt;TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/&gt; &lt;/TabItem.Header&gt; &lt;TabItem.ContentTemplate&gt; &lt;DataTemplate&gt; &lt;!-- This binds to "Self" in the surrounding window's namespace --&gt; &lt;TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/&gt; </code></pre> <p>This custom TabItem defines a <code>DependencyProperty</code> 'ShortLabel' to implement an interface. I would like to bind to this and other properties from within the <code>TabItem</code>'s <code>DataTemplate</code>. But due to strange interactions, the <code>TextBlock</code> within the <code>DataTemplate</code> gets bound to the <strong>parent container</strong> of the <code>TabItem</code>, which also is called "Self", but defined in another Xaml file.</p> <h2>Question</h2> <p>Why does the Binding work in the TabItem.Header, but not from within TabItem.ContentTemplate, and how should I proceed to get to the user control's properties from within the DataTemplate?</p> <h2>What I already tried</h2> <ul> <li><code>TemplateBinding</code>: Tries to bind to the ContentPresenter within the guts of the <code>TabItem</code>.</li> <li><code>FindAncestor, AncestorType={x:Type TabItem}</code>: Doesn't find the <code>TabItem</code> parent. This doesn't work either, when I specify the <code>MyTabItem</code> type.</li> <li><code>ElementName=Self</code>: Tries to bind to a control with that name in the wrong scope (parent container, not <code>TabItem</code>). I think that gives a hint, why this isn't working: the DataTemplate is not created at the point where it is defined in XAML, but apparently by the parent container.</li> </ul> <p>I assume I could replace the whole <code>ControlTemplate</code> to achieve the effect I'm looking for, but since I want to preserve the default look and feel of the <code>TabItem</code> without having to maintain the whole <code>ControlTemplate</code>, I'm very reluctant to do so.</p> <h2>Edit</h2> <p>Meanwhile I have found out that the problem is: <code>TabControl</code>s can't have (any) <code>ItemsTemplate</code> (that includes the <code>DisplayMemberPath</code>) if the <code>ItemsSource</code> contains <code>Visual</code>s. There <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/956eaba3-53bd-4683-b3dd-28b20e4b7526/" rel="nofollow noreferrer">a thread on MSDN Forum explaining why</a>. </p> <p>Since this seems to be a fundamental issue with WPF's TabControl, I'm closing the question. Thanks for all your help!</p>
[ { "answer_id": 184582, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 1, "selected": false, "text": "<p>Try this. I'm not sure if it will work or not, but </p>\n\n<pre><code>&lt;TabItem \n x:Name=\"Self\"\n x:Class=\"A...
2008/09/29
[ "https://Stackoverflow.com/questions/148704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4918/" ]
I've got the following user control: ``` <TabItem x:Name="Self" x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" > <TabItem.Header> <!-- This works --> <TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/> </TabItem.Header> <TabItem.ContentTemplate> <DataTemplate> <!-- This binds to "Self" in the surrounding window's namespace --> <TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/> ``` This custom TabItem defines a `DependencyProperty` 'ShortLabel' to implement an interface. I would like to bind to this and other properties from within the `TabItem`'s `DataTemplate`. But due to strange interactions, the `TextBlock` within the `DataTemplate` gets bound to the **parent container** of the `TabItem`, which also is called "Self", but defined in another Xaml file. Question -------- Why does the Binding work in the TabItem.Header, but not from within TabItem.ContentTemplate, and how should I proceed to get to the user control's properties from within the DataTemplate? What I already tried -------------------- * `TemplateBinding`: Tries to bind to the ContentPresenter within the guts of the `TabItem`. * `FindAncestor, AncestorType={x:Type TabItem}`: Doesn't find the `TabItem` parent. This doesn't work either, when I specify the `MyTabItem` type. * `ElementName=Self`: Tries to bind to a control with that name in the wrong scope (parent container, not `TabItem`). I think that gives a hint, why this isn't working: the DataTemplate is not created at the point where it is defined in XAML, but apparently by the parent container. I assume I could replace the whole `ControlTemplate` to achieve the effect I'm looking for, but since I want to preserve the default look and feel of the `TabItem` without having to maintain the whole `ControlTemplate`, I'm very reluctant to do so. Edit ---- Meanwhile I have found out that the problem is: `TabControl`s can't have (any) `ItemsTemplate` (that includes the `DisplayMemberPath`) if the `ItemsSource` contains `Visual`s. There [a thread on MSDN Forum explaining why](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/956eaba3-53bd-4683-b3dd-28b20e4b7526/). Since this seems to be a fundamental issue with WPF's TabControl, I'm closing the question. Thanks for all your help!
What appears to be the problem is that you are using a ContentTemplate without actualy using the content property. The default DataContext for the ContentTemplate's DataTemplate is the Content property of TabItem. However, none of what I said actually explains **why** the binding doesn't work. Unfortunately I can't give you a definitive answer, but my best guess is that it is due to the fact that the TabControl reuses a ContentPresenter to display the content property for all tab items. So, in your case I would change the code to look something like this: ``` <TabItem x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" Header="{Binding ShortLabel, RelativeSource={RelativeSource Self}}" Content="{Binding ShortLabel, RelativeSource={RelativeSource Self}}" /> ``` If ShortLabel is a more complex object and not just a string then you would want to indroduce a ContentTemplate: ``` <TabItem x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" Header="{Binding ShortLabel, RelativeSource={RelativeSource Self}}" Content="{Binding ComplexShortLabel, RelativeSource={RelativeSource Self}}"> <TabItem.ContentTemplate> <DataTemplate TargetType="{x:Type ComplexType}"> <TextBlock Text="{Binding Property}" /> </DataTemplate> </TabItem.ContentTemplate> </TabItem> ```
148,729
<p>I have a couple of buttons of which I modified how they look. I have set them as flat buttons with a background and a custom border so they look all pretty and nothing like normal buttons anymore (actually, they look like Office 2003 buttons now ;-). The buttons have a border of one pixel.</p> <p>However when the button gets selected (gets the focus through either a click or a keyboard action like pressing the tab key) the button suddenly gets and extra border around it of the same colour, so making it a two pixel border. Moreover when I disable the one pixel border, the button does not get a one pixel border on focus.</p> <p>On the net this question is asked a lot like 'How can I disable focus on a Button', but that's not what I want: the focus should still <em>exist</em>, just not <em>display</em> in the way it does now.</p> <p>Any suggestions? :-)</p>
[ { "answer_id": 148774, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "<p>Certainly you can draw the button yourself. One of the state flags is focused.</p>\n\n<p>So on the draw event if the...
2008/09/29
[ "https://Stackoverflow.com/questions/148729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a couple of buttons of which I modified how they look. I have set them as flat buttons with a background and a custom border so they look all pretty and nothing like normal buttons anymore (actually, they look like Office 2003 buttons now ;-). The buttons have a border of one pixel. However when the button gets selected (gets the focus through either a click or a keyboard action like pressing the tab key) the button suddenly gets and extra border around it of the same colour, so making it a two pixel border. Moreover when I disable the one pixel border, the button does not get a one pixel border on focus. On the net this question is asked a lot like 'How can I disable focus on a Button', but that's not what I want: the focus should still *exist*, just not *display* in the way it does now. Any suggestions? :-)
Is this the effect you are looking for? ``` public class NoFocusCueButton : Button { protected override bool ShowFocusCues { get { return false; } } } ``` You can use this custom button class just like a regular button, but it won't give you an extra rectangle on focus.
148,742
<p>In C# how do you detect is a specific drive is a Hard Drive, Network Drive, CDRom, or floppy?</p>
[ { "answer_id": 148753, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.driveinfo.drivetype.aspx\" rel=\"nofollow noreferrer\">DriveI...
2008/09/29
[ "https://Stackoverflow.com/questions/148742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13341/" ]
In C# how do you detect is a specific drive is a Hard Drive, Network Drive, CDRom, or floppy?
The method GetDrives() returns a DriveInfo class which has a property DriveType that corresponds to the enumeration of System.IO.DriveType: ``` public enum DriveType { Unknown, // The type of drive is unknown. NoRootDirectory, // The drive does not have a root directory. Removable, // The drive is a removable storage device, // such as a floppy disk drive or a USB flash drive. Fixed, // The drive is a fixed disk. Network, // The drive is a network drive. CDRom, // The drive is an optical disc device, such as a CD // or DVD-ROM. Ram // The drive is a RAM disk. } ``` Here is a slightly adjusted example from MSDN that displays information for all drives: ``` DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Drive {0}, Type {1}", d.Name, d.DriveType); } ```
148,764
<p>In the vxWorks shell, there are a number of routines you can use to display information about the system. </p> <p>These routines are usually referred to as <strong>show</strong> routines because they tend to have the form of "xxxShow".</p> <p>Is there a list of these routines available?</p>
[ { "answer_id": 148773, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 2, "selected": false, "text": "<p>There is no comprehensive list of all the show routines available. This will depend on your kernel configuration and wh...
2008/09/29
[ "https://Stackoverflow.com/questions/148764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
In the vxWorks shell, there are a number of routines you can use to display information about the system. These routines are usually referred to as **show** routines because they tend to have the form of "xxxShow". Is there a list of these routines available?
I work with VxWorks 5.5 and use the symbol lookup function "lkup" to find functions and/or variables that I may be interested in. Execute the following command where ">" is the VxWorks shell prompt. ``` > lkup "Show" ``` This will output a list of symbols that include the "Show" in their name, including all of the "Show" functions. The lkup command is interactive and will prompt you if there is more than one console screen worth of symbols before continuing.
148,795
<p>Selecting the union:</p> <pre><code>select * from table1 union select * from table1_backup </code></pre> <p>What is the query to select the intersection?</p>
[ { "answer_id": 148803, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 3, "selected": false, "text": "<p>In SQL Server <a href=\"http://msdn.microsoft.com/en-us/library/ms188055.aspx\" rel=\"noreferrer\">intersect</a></p>\n...
2008/09/29
[ "https://Stackoverflow.com/questions/148795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
Selecting the union: ``` select * from table1 union select * from table1_backup ``` What is the query to select the intersection?
In SQL Server [intersect](http://msdn.microsoft.com/en-us/library/ms188055.aspx) > > > ``` > select * from table1 > intersect > select * from table1_backup > > ``` > >
148,817
<p>Is there a component available list FileUpload which shows files on the server, not the client? </p> <p>I am basically looking for a clean dialog box to select server side files, like the one used in FileUpload.</p>
[ { "answer_id": 148913, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 1, "selected": false, "text": "<p>Nope. There's not. That said, you can use a listbox, and load the files into it.</p>\n\n<pre><code>public sub f...
2008/09/29
[ "https://Stackoverflow.com/questions/148817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5836/" ]
Is there a component available list FileUpload which shows files on the server, not the client? I am basically looking for a clean dialog box to select server side files, like the one used in FileUpload.
Nope. There's not. That said, you can use a listbox, and load the files into it. ``` public sub file_DatabindListbox(directoryPath as string) for each fName as string in io.directory(directorypath).getfilenames() dim li as new listitem li.text = io.path.getfilename(fName) li.value = fName myFileListbox.Items.Add(li) next end sub ```
148,828
<p>There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the <code>as</code> operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?</p>
[ { "answer_id": 148841, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": false, "text": "<p>You can use the <code>instanceof</code> keyword in place of C#'s <code>is</code>, but there is nothing like <code...
2008/09/29
[ "https://Stackoverflow.com/questions/148828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23424/" ]
There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the `as` operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?
Here's an implementation of as, as suggested by @Omar Kooheji: ``` public static <T> T as(Class<T> clazz, Object o){ if(clazz.isInstance(o)){ return clazz.cast(o); } return null; } as(A.class, new Object()) --> null as(B.class, new B()) --> B ```
148,838
<p>I'm trying to get started writing some Ruby on Rails apps and have been successful with Mongrel but, I'd like to deploy my apps to my Apache 2.2 instance on Windows? All the tutorials I've found seem out of date and are for older versions of Apache/Rails.</p> <p>Does anyone know of a good, current tutorial for configuring Apache 2.2 for Ruby on Rails apps?</p>
[ { "answer_id": 148947, "author": "Dave Nolan", "author_id": 9474, "author_profile": "https://Stackoverflow.com/users/9474", "pm_score": 5, "selected": true, "text": "<p><strong>EDIT:</strong> At least until there's a Phusion Passenger for Win, Apache + Mongrel is the way to go. You can u...
2008/09/29
[ "https://Stackoverflow.com/questions/148838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2109/" ]
I'm trying to get started writing some Ruby on Rails apps and have been successful with Mongrel but, I'd like to deploy my apps to my Apache 2.2 instance on Windows? All the tutorials I've found seem out of date and are for older versions of Apache/Rails. Does anyone know of a good, current tutorial for configuring Apache 2.2 for Ruby on Rails apps?
**EDIT:** At least until there's a Phusion Passenger for Win, Apache + Mongrel is the way to go. You can use Apache + FastCGI without Mongrel, but under real loads you will get (more) zombie processes and (more) memory leaks. You could also look at proxying to [Thin](http://code.macournoyer.com/thin/) in the same way as detailed below. However, I've had some instabilities with Thin on Win, even though it's appreciably quicker. AB (Apache Benchmark) is your friend here! Configuring Apache + Mongrel on Windows is not significantly different from \*nix. Essentially, you need to proxy requests coming into Apache to Mongrel. What this boils down to is something like this: ``` LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so <VirtualHost localhost:80> ServerName www.myapp.comm DocumentRoot "C:/web/myapp/public" ProxyPass / http://www.myapp.com:3000/ ProxyPassReverse / http://www.myapp.com:3000/ ProxyPreserveHost On </VirtualHost> ``` Stick this in your `httpd.conf` (or `httpd-vhost.conf` if you're including it). It assumes you're going to run mongrel on port 3000, your Rails root is in `C:\web\myapp`, and you'll access the app at www.myapp.com. To run the rails app in production mode: ``` mongrel_rails start -p 3000 -e production ``` And away you go (actually mongrel defaults to port 3000 so you could skip `-p 3000` if you want). The main difference is that you cannot daemonize mongrel on Windows (i.e. make it run in the background). Instead you can install it as a service using the `mongrel_service` gem. Also, running a cluster is more complicated and you won't be able to use Capistrano. Let me know if you want more info.
148,853
<p>Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?</p>
[ { "answer_id": 148891, "author": "danivovich", "author_id": 17583, "author_profile": "https://Stackoverflow.com/users/17583", "pm_score": 3, "selected": false, "text": "<p>This ActiveState Python recipe might be helpful:\n<a href=\"http://code.activestate.com/recipes/491261/\" rel=\"nofo...
2008/09/29
[ "https://Stackoverflow.com/questions/148853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17865/" ]
Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?
You could use a decorator function such as: ``` class cache(object): def __init__(self, fun): self.fun = fun self.cache = {} def __call__(self, *args, **kwargs): key = str(args) + str(kwargs) try: return self.cache[key] except KeyError: self.cache[key] = rval = self.fun(*args, **kwargs) return rval except TypeError: # incase key isn't a valid key - don't cache return self.fun(*args, **kwargs) ``` and define a function along the lines of: ``` @cache def get_url_src(url): return urllib.urlopen(url).read() ``` This is assuming you're not paying attention to HTTP Cache Controls, but just want to cache the page for the duration of the application
148,854
<p>I have a <code>DataGridView</code> with several created columns. I've add some rows and they get displayed correctly; however, when I click on a cell, the content disappears.</p> <p>What am I doing wrong?</p> <p>The code is as follows:</p> <pre><code>foreach (SaleItem item in this.Invoice.SaleItems) { DataGridViewRow row = new DataGridViewRow(); gridViewParts.Rows.Add(row); DataGridViewCell cellQuantity = new DataGridViewTextBoxCell(); cellQuantity.Value = item.Quantity; row.Cells["colQuantity"] = cellQuantity; DataGridViewCell cellDescription = new DataGridViewTextBoxCell(); cellDescription.Value = item.Part.Description; row.Cells["colDescription"] = cellDescription; DataGridViewCell cellCost = new DataGridViewTextBoxCell(); cellCost.Value = item.Price; row.Cells["colUnitCost1"] = cellCost; DataGridViewCell cellTotal = new DataGridViewTextBoxCell(); cellTotal.Value = item.Quantity * item.Price; row.Cells["colTotal"] = cellTotal; DataGridViewCell cellPartNumber = new DataGridViewTextBoxCell(); cellPartNumber.Value = item.Part.Number; row.Cells["colPartNumber"] = cellPartNumber; } </code></pre> <p>Thanks!</p>
[ { "answer_id": 887025, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><em>Edit: oops! made a mistake on the second line of code. - fixed it.</em></p>\n\n<p>Sometimes, I hate defining the dataso...
2008/09/29
[ "https://Stackoverflow.com/questions/148854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3086/" ]
I have a `DataGridView` with several created columns. I've add some rows and they get displayed correctly; however, when I click on a cell, the content disappears. What am I doing wrong? The code is as follows: ``` foreach (SaleItem item in this.Invoice.SaleItems) { DataGridViewRow row = new DataGridViewRow(); gridViewParts.Rows.Add(row); DataGridViewCell cellQuantity = new DataGridViewTextBoxCell(); cellQuantity.Value = item.Quantity; row.Cells["colQuantity"] = cellQuantity; DataGridViewCell cellDescription = new DataGridViewTextBoxCell(); cellDescription.Value = item.Part.Description; row.Cells["colDescription"] = cellDescription; DataGridViewCell cellCost = new DataGridViewTextBoxCell(); cellCost.Value = item.Price; row.Cells["colUnitCost1"] = cellCost; DataGridViewCell cellTotal = new DataGridViewTextBoxCell(); cellTotal.Value = item.Quantity * item.Price; row.Cells["colTotal"] = cellTotal; DataGridViewCell cellPartNumber = new DataGridViewTextBoxCell(); cellPartNumber.Value = item.Part.Number; row.Cells["colPartNumber"] = cellPartNumber; } ``` Thanks!
Just to extend this question, there's also another way to add a row to a `DataGridView`, especially if the columns are always the same: ``` object[] buffer = new object[5]; List<DataGridViewRow> rows = new List<DataGridViewRow>(); foreach (SaleItem item in this.Invoice.SaleItems) { buffer[0] = item.Quantity; buffer[1] = item.Part.Description; buffer[2] = item.Price; buffer[3] = item.Quantity * item.Price; buffer[4] = item.Part.Number; rows.Add(new DataGridViewRow()); rows[rows.Count - 1].CreateCells(gridViewParts, buffer); } gridViewParts.Rows.AddRange(rows.ToArray()); ``` Or if you like ParamArrays: ``` List<DataGridViewRow> rows = new List<DataGridViewRow>(); foreach (SaleItem item in this.Invoice.SaleItems) { rows.Add(new DataGridViewRow()); rows[rows.Count - 1].CreateCells(gridViewParts, item.Quantity, item.Part.Description, item.Price, item.Quantity * item.Price, item.Part.Number ); } gridViewParts.Rows.AddRange(rows.ToArray()); ``` The values in the buffer need to be in the same order as the columns (including hidden ones) obviously. This is the fastest way I found to get data into a `DataGridView` without binding the grid against a `DataSource`. Binding the grid will actually speed it up by a significant amount of time, and if you have more then 500 rows in a grid, I strongly recommend to bind it instead of filling it by hand. Binding does also come with the bonus that you can keep the Object in tact, f.e. if you want to operate on the selected row, you can do this is the DatagridView is bound: ``` if(gridViewParts.CurrentRow != null) { SaleItem item = (SalteItem)(gridViewParts.CurrentRow.DataBoundItem); // You can use item here without problems. } ``` It is advised that your classes which get bound do implement the `System.ComponentModel.INotifyPropertyChanged` interface, which allows it to tell the grid about changes.
148,856
<p>I need to call an external dll from c#. This is the header definition:</p> <pre><code>enum WatchMode { WATCH_MODE_SYSTEM = 0, WATCH_MODE_APPLICATION = 1 }; LONG ADS_API WDT_GetMode ( LONG i_hHandle, WatchMode * o_pWatchMode ); </code></pre> <p>I've added the enum and the call in C#:</p> <pre><code>public enum WatchMode { WATCH_MODE_SYSTEM = 0, WATCH_MODE_APPLICATION = 1 } [DllImport("AdsWatchdog.dll")] internal static extern long WDT_GetMode(long hHandle, ref WatchMode watchmode); </code></pre> <p>This generates an AccessViolationException. I know the dll is 'working' because I've also added a call to <code>GetHandle</code> which returns the <code>hHandle</code> mentioned above. I've tried to change the param to an <code>int</code> (<code>ref int watchmode</code>) but get the same error. Doesn anyone know how I can PInvoke the above call?</p>
[ { "answer_id": 150019, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 4, "selected": true, "text": "<p>You're running into a parameter size problem difference between C# and C++. In the C++/windows world LONG is a 4 byte ...
2008/09/29
[ "https://Stackoverflow.com/questions/148856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6399/" ]
I need to call an external dll from c#. This is the header definition: ``` enum WatchMode { WATCH_MODE_SYSTEM = 0, WATCH_MODE_APPLICATION = 1 }; LONG ADS_API WDT_GetMode ( LONG i_hHandle, WatchMode * o_pWatchMode ); ``` I've added the enum and the call in C#: ``` public enum WatchMode { WATCH_MODE_SYSTEM = 0, WATCH_MODE_APPLICATION = 1 } [DllImport("AdsWatchdog.dll")] internal static extern long WDT_GetMode(long hHandle, ref WatchMode watchmode); ``` This generates an AccessViolationException. I know the dll is 'working' because I've also added a call to `GetHandle` which returns the `hHandle` mentioned above. I've tried to change the param to an `int` (`ref int watchmode`) but get the same error. Doesn anyone know how I can PInvoke the above call?
You're running into a parameter size problem difference between C# and C++. In the C++/windows world LONG is a 4 byte signed integer. In the C# world long is a 8 byte signed integer. You should change your C# signature to take an int. ffpf is wrong in saying that you should use an IntPtr here. It will fix this particular problem on a 32 bit machine since an IntPtr will marshal as a int. If you run this on a 64 bit machine it will marshal as a 8 byte signed integer again and will crash.
148,867
<p>I have been googling for a good time on how to move a file with c# using the TFS API. The idea is to have a folder on which the developers drop database upgrade scripts and the build process get's to the folder creates a build script and moves all the files on the folder to a new folder with the database build version that we just created. </p> <p>I cannot seriously find any reference about moving files programatically in TFS... (aside of the cmd command line) </p> <p>does anybody know of a good guide / msdn starting point for learning TFS source control files manipulation via c#? </p>
[ { "answer_id": 149071, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 4, "selected": false, "text": "<p>Its pretty simple :).</p>\n\n<pre><code>Microsoft.TeamFoundation.VersionControl.Client.Workspace workspace = GetMyTfsWorks...
2008/09/29
[ "https://Stackoverflow.com/questions/148867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23460/" ]
I have been googling for a good time on how to move a file with c# using the TFS API. The idea is to have a folder on which the developers drop database upgrade scripts and the build process get's to the folder creates a build script and moves all the files on the folder to a new folder with the database build version that we just created. I cannot seriously find any reference about moving files programatically in TFS... (aside of the cmd command line) does anybody know of a good guide / msdn starting point for learning TFS source control files manipulation via c#?
Its pretty simple :). ``` Microsoft.TeamFoundation.VersionControl.Client.Workspace workspace = GetMyTfsWorkspace(); workspace.PendRename( oldPath, newPath ); ``` Then you need CheckIn it of course. Use a "workspace.GetPendingChanges()" and "workspace.CheckIn()" methods to do it.
148,875
<p>In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company -> Region -> Area -> Site -> Room. I am using the following MDX to get all the descendants of a particular member at company level.</p> <pre><code>DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE) </code></pre> <p>I now have a requirement to exclude a particular Region, named "Redundant", from the report. How can I change the above MDX to exclude this particular Region (and all its descendants)? I know this Region will be called "Redundant" but I do not want to hard-code any of the other Region names, as these may change.</p>
[ { "answer_id": 148897, "author": "Magnus Smith", "author_id": 11461, "author_profile": "https://Stackoverflow.com/users/11461", "pm_score": 6, "selected": true, "text": "<p>The EXCEPT function will take a set, and remove the members you dont want. In your case you need to say:</p>\n\n<pr...
2008/09/29
[ "https://Stackoverflow.com/questions/148875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ]
In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company -> Region -> Area -> Site -> Room. I am using the following MDX to get all the descendants of a particular member at company level. ``` DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE) ``` I now have a requirement to exclude a particular Region, named "Redundant", from the report. How can I change the above MDX to exclude this particular Region (and all its descendants)? I know this Region will be called "Redundant" but I do not want to hard-code any of the other Region names, as these may change.
The EXCEPT function will take a set, and remove the members you dont want. In your case you need to say: ``` EXCEPT( {DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)}, {DESCENDANTS([Location].[Whatever].[Redundant],[Location].[Site], SELF_AND_BEFORE)} ) ``` This gives you everything in the first set except what you've mentioned in the second. It's easier to understand like this: ``` EXCEPT({the set i want}, {a set of members i dont want}) ``` You shouldnt need to worry about the third (optional) argument: <http://msdn.microsoft.com/en-us/library/ms144900.aspx>
148,879
<p>My .NET application fails when run from a network drive even when the very same executable runs perfectly fine from a local hard drive?</p> <p>I tried checking for "Full trust" like so:</p> <pre><code>try { // Demand full trust permissions PermissionSet fullTrust = new PermissionSet( PermissionState.Unrestricted ); fullTrust.Demand(); // Perform normal application logic } catch( SecurityException ) { // Report that permissions were not full trust MessageBox.Show( "This application requires full-trust security permissions to execute." ); } </code></pre> <p>However, this isn't helping, by which I mean the application starts up and the catch block is never entered. However, a debug build shows that the exception thrown is a SecurityException caused by an InheritanceDemand. Any ideas?</p>
[ { "answer_id": 148886, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 4, "selected": false, "text": "<p>Did you try Using <a href=\"http://blogs.msdn.com/shawnfa/archive/2004/12/30/344554.aspx\" rel=\"noreferrer\">CasPol...
2008/09/29
[ "https://Stackoverflow.com/questions/148879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23461/" ]
My .NET application fails when run from a network drive even when the very same executable runs perfectly fine from a local hard drive? I tried checking for "Full trust" like so: ``` try { // Demand full trust permissions PermissionSet fullTrust = new PermissionSet( PermissionState.Unrestricted ); fullTrust.Demand(); // Perform normal application logic } catch( SecurityException ) { // Report that permissions were not full trust MessageBox.Show( "This application requires full-trust security permissions to execute." ); } ``` However, this isn't helping, by which I mean the application starts up and the catch block is never entered. However, a debug build shows that the exception thrown is a SecurityException caused by an InheritanceDemand. Any ideas?
It indeed has to do with the fact the apps on a network location are less trusted then on your local hdd (due to the default policy of the .NET framework). If I'm not mistaken Microsoft finally corrected this annoyance in .NET 3.5 SP1 (after a lot of developers complaining). I google'd it: [.NET Framework 3.5 SP1 Allows managed code to be launched from a network share!](http://blogs.msdn.com/vancem/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-be-launched-from-a-network-share.aspx)
148,882
<p>I'm working on some code that uses a pattern in its business and data tiers that uses events to signal errors e.g. </p> <pre><code>resource = AllocateLotsOfMemory(); if (SomeCondition()) { OnOddError(new OddErrorEventArgs(resource.StatusProperty)); resource.FreeLotsOfMemory(); return; } </code></pre> <p>This looked superficially rather odd, especially as the code that calls this needs to hook into the events (there are four or five different ones!).</p> <p>The developer tells me that this way they can refer to the properties of the allocated resource in the error handling code, and that responsibility for cleaning up after the error is kept by this tier. </p> <p>Which makes some kind of sense. </p> <p>The alternative might be something like</p> <pre><code>resource = AllocateLotsOfMemory(); if (SomeCondition()) { BigObject temporary = resource.StatusProperty; resource.FreeLotsOfMemory(); throw new OddException(temporary); } </code></pre> <p>My questions are:</p> <ol> <li><p>As this "<code>BigObject</code>" is freed when the exception object is released, do we need this pattern?</p></li> <li><p>Has anyone else experience of this pattern? If so, what pitfalls did you find? What advantages are there?</p></li> </ol> <p>Thanks!</p>
[ { "answer_id": 148892, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>If you think in terms of \"Errors\" and \"Warnings\", I've had lots of luck when reserving events for the \"Warning...
2008/09/29
[ "https://Stackoverflow.com/questions/148882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3546/" ]
I'm working on some code that uses a pattern in its business and data tiers that uses events to signal errors e.g. ``` resource = AllocateLotsOfMemory(); if (SomeCondition()) { OnOddError(new OddErrorEventArgs(resource.StatusProperty)); resource.FreeLotsOfMemory(); return; } ``` This looked superficially rather odd, especially as the code that calls this needs to hook into the events (there are four or five different ones!). The developer tells me that this way they can refer to the properties of the allocated resource in the error handling code, and that responsibility for cleaning up after the error is kept by this tier. Which makes some kind of sense. The alternative might be something like ``` resource = AllocateLotsOfMemory(); if (SomeCondition()) { BigObject temporary = resource.StatusProperty; resource.FreeLotsOfMemory(); throw new OddException(temporary); } ``` My questions are: 1. As this "`BigObject`" is freed when the exception object is released, do we need this pattern? 2. Has anyone else experience of this pattern? If so, what pitfalls did you find? What advantages are there? Thanks!
Take a look at [this post](http://www.udidahan.com/2008/08/25/domain-events-take-2/) by Udi Dahan. Its an elegant approach for dispatching domain events. The previous poster is correct in saying that you should not be using an event mechanism to recover from fatal errors, but it is a very useful pattern for notification in loosely coupled systems: ``` public class DomainEventStorage<ActionType> { public List<ActionType> Actions { get { var k = string.Format("Domain.Event.DomainEvent.{0}.{1}", GetType().Name, GetType().GetGenericArguments()[0]); if (Local.Data[k] == null) Local.Data[k] = new List<ActionType>(); return (List<ActionType>) Local.Data[k]; } } public IDisposable Register(ActionType callback) { Actions.Add(callback); return new DomainEventRegistrationRemover(() => Actions.Remove(callback) ); } } public class DomainEvent<T1> : IDomainEvent where T1 : class { private readonly DomainEventStorage<Action<T1>> _impl = new DomainEventStorage<Action<T1>>(); internal List<Action<T1>> Actions { get { return _impl.Actions; } } public IDisposable Register(Action<T1> callback) { return _impl.Register(callback); } public void Raise(T1 args) { foreach (var action in Actions) { action.Invoke(args); } } } ``` And to consume: ``` var fail = false; using(var ev = DomainErrors.SomethingHappened.Register(c => fail = true) { //Do something with your domain here } ```
148,901
<p>I've always handled optional parameters in JavaScript like this:</p> <pre><code>function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff } </code></pre> <p>Is there a better way to do it?</p> <p>Are there any cases where using <code>||</code> like that is going to fail?</p>
[ { "answer_id": 148918, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 11, "selected": true, "text": "<p>Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative</p>\n\n<pre><code>if (t...
2008/09/29
[ "https://Stackoverflow.com/questions/148901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
I've always handled optional parameters in JavaScript like this: ``` function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff } ``` Is there a better way to do it? Are there any cases where using `||` like that is going to fail?
Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative ``` if (typeof optionalArg === 'undefined') { optionalArg = 'default'; } ``` Or an alternative idiom: ``` optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg; ``` Use whichever idiom communicates the intent best to you!
148,902
<p>I have some commits that I've decided, after the fact, are going to be more branch work then trunk work. How do I create the branch and revert the trunk while still ensuring merging isn't painful later?</p> <p>Is it as simple as copying the current trunk to a branch and reverting the trunk? Or will this create headaches later?</p>
[ { "answer_id": 148922, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 2, "selected": false, "text": "<p>There's nothing wrong with following Philip's method, other than it leaves some \"cruft\" in the revision history. If ...
2008/09/29
[ "https://Stackoverflow.com/questions/148902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
I have some commits that I've decided, after the fact, are going to be more branch work then trunk work. How do I create the branch and revert the trunk while still ensuring merging isn't painful later? Is it as simple as copying the current trunk to a branch and reverting the trunk? Or will this create headaches later?
I think Philips method would be something like the following, assuming the last "good" revision was at 100 and you are now at 130, to create the new branch: ``` svn copy -r100 svn://repos/trunk svn://repos/branches/newbranch svn merge -r 100:130 svn://repos/trunk svn://repos/branches/newbranch ``` Note the idea is to preserve the changes made in those revisions so you can apply them back to trunk. To revert trunk: ``` svn merge -r130:100 . svn ci -m 'reverting to r100 (undoing changes in r100-130)' . ``` (It wouldn't matter which order you performed these in, so you could revert trunk before creating the branch.) Then you could switch to the new branch you created in the repo: ``` svn switch svn://repos/branches/newbranch workdir ```
148,945
<p>We let users create ad-hoc queries in our website. We would like to have the user select their criteria, then click submit and have the results streamed automatically to Excel. I have the application populating a DataTable, then using the datatable to create a tab delimited string. The problem is getting that to excel.</p> <p>What is the best way to stream data to Excel? Preferrably, we wouldn't have to make users close an empty window after clicking the submit button.</p>
[ { "answer_id": 148962, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 4, "selected": true, "text": "<p>Change the page's file type to excel, and only stream the HTML necessary to build a table to the page. code from ...
2008/09/29
[ "https://Stackoverflow.com/questions/148945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
We let users create ad-hoc queries in our website. We would like to have the user select their criteria, then click submit and have the results streamed automatically to Excel. I have the application populating a DataTable, then using the datatable to create a tab delimited string. The problem is getting that to excel. What is the best way to stream data to Excel? Preferrably, we wouldn't have to make users close an empty window after clicking the submit button.
Change the page's file type to excel, and only stream the HTML necessary to build a table to the page. code from [here](http://www.eggheadcafe.com/tutorials/aspnet/6e1ae1a8-8285-4b2a-a89b-fafc7668a782/aspnet-download-as-wor.aspx) ``` //for demo purpose, lets create a small datatable & populate it with dummy data System.Data.DataTable workTable = new System.Data.DataTable(); //The tablename specified here will be set as the worksheet name of the generated Excel file. workTable.TableName = "Customers"; workTable.Columns.Add("Id"); workTable.Columns.Add("Name"); System.Data.DataRow workRow; for (int i = 0; i <= 9; i++) { workRow = workTable.NewRow(); workRow[0] = i; workRow[1] = "CustName" + i.ToString(); workTable.Rows.Add(workRow); } //...and lets put DataTable2ExcelString to work string strBody = DataTable2ExcelString(workTable); Response.AppendHeader("Content-Type", "application/vnd.ms-excel"); Response.AppendHeader("Content-disposition", "attachment; filename=my.xls"); Response.Write(strBody); ```